gurudesh/pytracebugs huggingface dataset:
# Buggy code
def append(path, *args):
    """
    .. versionadded:: 0.9.5

    Append text to the end of a file

    CLI Example:

    .. code-block:: bash

        salt '*' file.append /etc/motd \\
                "With all thine offerings thou shalt offer salt." \\
                "Salt is what makes things taste bad when it isn't in them."
    """
    # Largely inspired by Fabric's contrib.files.append()

    with salt.utils.fopen(path, "a") as ofile:
        for line in args:
            ofile.write("{0}\n".format(line))

    return 'Wrote {0} lines to "{1}"'.format(len(args), path)


# Traceback (AttributeError)
[ERROR   ] Error in function _master_opts:
Traceback (most recent call last):
File "/usr/lib/pymodules/python2.7/salt/master.py", line 1444, in run_func
ret = getattr(self, func)(load)
File "/usr/lib/pymodules/python2.7/salt/master.py", line 891, in _master_opts
envs = self._file_envs()
File "/usr/lib/pymodules/python2.7/salt/fileserver/__init__.py", line 153, in envs
ret.update(self.servers[fstr]())
File "/usr/lib/pymodules/python2.7/salt/fileserver/hgfs.py", line 176, in envs
tags = repo.get_tags()
AttributeError: 'hgclient' object has no attribute 'get_tags'

# Fixed code
def append(path, *args):
    """
    .. versionadded:: 0.9.5

    Append text to the end of a file

    CLI Example:

    .. code-block:: bash

        salt '*' file.append /etc/motd \\
                "With all thine offerings thou shalt offer salt." \\
                "Salt is what makes things taste bad when it isn't in them."
    """
    # Largely inspired by Fabric's contrib.files.append()

    with salt.utils.fopen(path, "r+") as ofile:
        # Make sure we have a newline at the end of the file
        try:
            ofile.seek(-1, os.SEEK_END)
        except IOError as exc:
            if exc.errno == errno.EINVAL:
                # Empty file, simply append lines at the beginning of the file
                pass
            else:
                raise
        else:
            if ofile.read(1) != "\n":
                ofile.seek(0, os.SEEK_END)
                ofile.write("\n")
            else:
                ofile.seek(0, os.SEEK_END)
        # Append lines
        for line in args:
            ofile.write("{0}\n".format(line))

    return 'Wrote {0} lines to "{1}"'.format(len(args), path)
# Buggy code
def _lxc_profile(profile):
    """
    Gather the lxc profile from the config or apply the default (empty).

    Profiles can be defined in the config or pillar, e.g.:

    .. code-block:: yaml

        lxc:
          profile:
            ubuntu:
              template: ubuntu
              backing: lvm
              vgname: lxc
              size: 1G
    """
    return __salt__["config.option"]("lxc.profile", {}).get(profile, {})


# Traceback (AttributeError)
[ERROR   ] Error in function _master_opts:
Traceback (most recent call last):
File "/usr/lib/pymodules/python2.7/salt/master.py", line 1444, in run_func
ret = getattr(self, func)(load)
File "/usr/lib/pymodules/python2.7/salt/master.py", line 891, in _master_opts
envs = self._file_envs()
File "/usr/lib/pymodules/python2.7/salt/fileserver/__init__.py", line 153, in envs
ret.update(self.servers[fstr]())
File "/usr/lib/pymodules/python2.7/salt/fileserver/hgfs.py", line 176, in envs
tags = repo.get_tags()
AttributeError: 'hgclient' object has no attribute 'get_tags'

# Fixed code
def _lxc_profile(profile):
    """
    Gather the lxc profile from the config or apply the default (empty).

    Profiles can be defined in the config or pillar, e.g.:

    .. code-block:: yaml

        lxc.profile:
          ubuntu:
            template: ubuntu
            backing: lvm
            vgname: lxc
            size: 1G
    """
    return __salt__["config.option"]("lxc.profile", {}).get(profile, {})
# Buggy code
def _nic_profile(nic):
    """
    Gather the nic profile from the config or apply the default.

    This is the ``default`` profile, which can be overridden in the
    configuration:

    .. code-block:: yaml

        lxc:
          nic:
            default:
              eth0:
                link: br0
                type: veth
    """
    default = {"eth0": {"link": "br0", "type": "veth"}}
    return __salt__["config.option"]("lxc.nic", {}).get(nic, default)


# Traceback (AttributeError)
[ERROR   ] Error in function _master_opts:
Traceback (most recent call last):
File "/usr/lib/pymodules/python2.7/salt/master.py", line 1444, in run_func
ret = getattr(self, func)(load)
File "/usr/lib/pymodules/python2.7/salt/master.py", line 891, in _master_opts
envs = self._file_envs()
File "/usr/lib/pymodules/python2.7/salt/fileserver/__init__.py", line 153, in envs
ret.update(self.servers[fstr]())
File "/usr/lib/pymodules/python2.7/salt/fileserver/hgfs.py", line 176, in envs
tags = repo.get_tags()
AttributeError: 'hgclient' object has no attribute 'get_tags'

# Fixed code
def _nic_profile(nic):
    """
    Gather the nic profile from the config or apply the default.

    This is the ``default`` profile, which can be overridden in the
    configuration:

    .. code-block:: yaml

        lxc.nic:
          default:
            eth0:
              link: br0
              type: veth
    """
    default = {"eth0": {"link": "br0", "type": "veth"}}
    return __salt__["config.option"]("lxc.nic", {}).get(nic, default)
# Buggy code
def destroy(name):
    """
    Destroy the named container.
    WARNING: Destroys all data associated with the container.

    .. code-block:: bash

        salt '*' lxc.destroy name
    """
    return _change_state("lxc-destroy", name, None)


# Traceback (AttributeError)
[ERROR   ] Error in function _master_opts:
Traceback (most recent call last):
File "/usr/lib/pymodules/python2.7/salt/master.py", line 1444, in run_func
ret = getattr(self, func)(load)
File "/usr/lib/pymodules/python2.7/salt/master.py", line 891, in _master_opts
envs = self._file_envs()
File "/usr/lib/pymodules/python2.7/salt/fileserver/__init__.py", line 153, in envs
ret.update(self.servers[fstr]())
File "/usr/lib/pymodules/python2.7/salt/fileserver/hgfs.py", line 176, in envs
tags = repo.get_tags()
AttributeError: 'hgclient' object has no attribute 'get_tags'

# Fixed code
def destroy(name, stop=True):
    """
    Destroy the named container.
    WARNING: Destroys all data associated with the container.

    .. code-block:: bash

        salt '*' lxc.destroy name [stop=(true|false)]
    """
    if stop:
        _change_state("lxc-stop", name, "stopped")
    return _change_state("lxc-destroy", name, None)
# Buggy code
def exists(name):
    """
    Returns whether the named container exists.

    .. code-block:: bash

        salt '*' lxc.exists name
    """
    l = list()
    return name in (l["running"] + l["stopped"] + l["frozen"])


# Traceback (AttributeError)
[ERROR   ] Error in function _master_opts:
Traceback (most recent call last):
File "/usr/lib/pymodules/python2.7/salt/master.py", line 1444, in run_func
ret = getattr(self, func)(load)
File "/usr/lib/pymodules/python2.7/salt/master.py", line 891, in _master_opts
envs = self._file_envs()
File "/usr/lib/pymodules/python2.7/salt/fileserver/__init__.py", line 153, in envs
ret.update(self.servers[fstr]())
File "/usr/lib/pymodules/python2.7/salt/fileserver/hgfs.py", line 176, in envs
tags = repo.get_tags()
AttributeError: 'hgclient' object has no attribute 'get_tags'

# Fixed code
def exists(name):
    """
    Returns whether the named container exists.

    .. code-block:: bash

        salt '*' lxc.exists name
    """
    l = list_()
    return name in (l["running"] + l["stopped"] + l["frozen"])
# Buggy code
def info(name):
    """
    Returns information about a container.

    .. code-block:: bash

        salt '*' lxc.info name
    """
    f = "/var/lib/lxc/{0}/config".format(name)
    cgroup_dir = "/sys/fs/cgroup/memory/lxc/{0}/".format(name)
    if not os.path.isfile(f):
        return None

    ret = {}

    config = [
        (v[0].strip(), v[1].strip())
        for v in [l.split("#", 1)[0].strip().split("=", 1) for l in open(f).readlines()]
        if len(v) == 2
    ]

    ifaces = []
    current = None

    for k, v in config:
        if k == "lxc.network.type":
            current = {"type": v}
            ifaces.append(current)
        elif not current:
            continue
        elif k.startswith("lxc.network."):
            current[k.replace("lxc.network.", "", 1)] = v
    if ifaces:
        ret["ifaces"] = ifaces

    ret["rootfs"] = next((i[1] for i in config if i[0] == "lxc.rootfs"), None)
    ret["state"] = state(name)

    if ret["state"] == "running":
        with open(cgroup_dir + "memory.limit_in_bytes") as f:
            limit = int(f.read())
        with open(cgroup_dir + "memory.usage_in_bytes") as f:
            memory = int(f.read())
        free = limit - memory
        ret["memory_limit"] = limit
        ret["memory_free"] = free

    return ret


# Traceback (AttributeError)
[ERROR   ] Error in function _master_opts:
Traceback (most recent call last):
File "/usr/lib/pymodules/python2.7/salt/master.py", line 1444, in run_func
ret = getattr(self, func)(load)
File "/usr/lib/pymodules/python2.7/salt/master.py", line 891, in _master_opts
envs = self._file_envs()
File "/usr/lib/pymodules/python2.7/salt/fileserver/__init__.py", line 153, in envs
ret.update(self.servers[fstr]())
File "/usr/lib/pymodules/python2.7/salt/fileserver/hgfs.py", line 176, in envs
tags = repo.get_tags()
AttributeError: 'hgclient' object has no attribute 'get_tags'

# Fixed code
def info(name):
    """
    Returns information about a container.

    .. code-block:: bash

        salt '*' lxc.info name
    """
    f = "/var/lib/lxc/{0}/config".format(name)
    if not os.path.isfile(f):
        return None

    ret = {}

    config = [
        (v[0].strip(), v[1].strip())
        for v in [l.split("#", 1)[0].strip().split("=", 1) for l in open(f).readlines()]
        if len(v) == 2
    ]

    ifaces = []
    current = None

    for k, v in config:
        if k == "lxc.network.type":
            current = {"type": v}
            ifaces.append(current)
        elif not current:
            continue
        elif k.startswith("lxc.network."):
            current[k.replace("lxc.network.", "", 1)] = v
    if ifaces:
        ret["nics"] = ifaces

    ret["rootfs"] = next((i[1] for i in config if i[0] == "lxc.rootfs"), None)
    ret["state"] = state(name)

    if ret["state"] == "running":
        limit = int(
            get_parameter(name, "memory.limit_in_bytes").get("memory.limit_in_bytes")
        )
        usage = int(
            get_parameter(name, "memory.usage_in_bytes").get("memory.usage_in_bytes")
        )
        free = limit - usage
        ret["memory_limit"] = limit
        ret["memory_free"] = free

    return ret
# Buggy code
def __grant_generate(
    grant, database, user, host="localhost", grant_option=False, escape=True
):
    # TODO: Re-order the grant so it is according to the
    #       SHOW GRANTS for xxx@yyy query (SELECT comes first, etc)
    grant = re.sub(r"\s*,\s*", ", ", grant).upper()

    # MySQL normalizes ALL to ALL PRIVILEGES, we do the same so that
    # grant_exists and grant_add ALL work correctly
    if grant == "ALL":
        grant = "ALL PRIVILEGES"

    db_part = database.rpartition(".")
    dbc = db_part[0]
    table = db_part[2]

    if escape:
        if dbc is not "*":
            dbc = "`{0}`".format(dbc)
        if table is not "*":
            table = "`{0}`".format(table)
    qry = "GRANT {0} ON {1}.{2} TO {3!r}@{4!r}".format(grant, dbc, table, user, host)
    if grant_option:
        qry += " WITH GRANT OPTION"
    log.debug("Query generated: {0}".format(qry))
    return qry


# Traceback (AttributeError)
[ERROR   ] Error in function _master_opts:
Traceback (most recent call last):
File "/usr/lib/pymodules/python2.7/salt/master.py", line 1444, in run_func
ret = getattr(self, func)(load)
File "/usr/lib/pymodules/python2.7/salt/master.py", line 891, in _master_opts
envs = self._file_envs()
File "/usr/lib/pymodules/python2.7/salt/fileserver/__init__.py", line 153, in envs
ret.update(self.servers[fstr]())
File "/usr/lib/pymodules/python2.7/salt/fileserver/hgfs.py", line 176, in envs
tags = repo.get_tags()
AttributeError: 'hgclient' object has no attribute 'get_tags'

# Fixed code
def __grant_generate(
    grant, database, user, host="localhost", grant_option=False, escape=True
):
    # TODO: Re-order the grant so it is according to the
    #       SHOW GRANTS for xxx@yyy query (SELECT comes first, etc)
    grant = re.sub(r"\s*,\s*", ", ", grant).upper()

    # MySQL normalizes ALL to ALL PRIVILEGES, we do the same so that
    # grant_exists and grant_add ALL work correctly
    if grant == "ALL":
        grant = "ALL PRIVILEGES"

    db_part = database.rpartition(".")
    dbc = db_part[0]
    table = db_part[2]

    if escape:
        if dbc is not "*":
            dbc = "`{0}`".format(dbc)
        if table is not "*":
            table = "`{0}`".format(table)
    qry = "GRANT {0} ON {1}.{2} TO {3!r}@{4!r}".format(grant, dbc, table, user, host)
    if salt.utils.is_true(grant_option):
        qry += " WITH GRANT OPTION"
    log.debug("Query generated: {0}".format(qry))
    return qry
# Buggy code
def arp():
    """
    Return the arp table from the minion

    CLI Example:

    .. code-block:: bash

        salt '*' '*' network.arp
    """
    ret = {}
    out = __salt__["cmd.run"]("arp -an")
    for line in out.splitlines():
        comps = line.split()
        if len(comps) < 4:
            continue
        ret[comps[3]] = comps[1].strip("(").strip(")")
    return ret


# Traceback (AttributeError)
[ERROR   ] Error in function _master_opts:
Traceback (most recent call last):
File "/usr/lib/pymodules/python2.7/salt/master.py", line 1444, in run_func
ret = getattr(self, func)(load)
File "/usr/lib/pymodules/python2.7/salt/master.py", line 891, in _master_opts
envs = self._file_envs()
File "/usr/lib/pymodules/python2.7/salt/fileserver/__init__.py", line 153, in envs
ret.update(self.servers[fstr]())
File "/usr/lib/pymodules/python2.7/salt/fileserver/hgfs.py", line 176, in envs
tags = repo.get_tags()
AttributeError: 'hgclient' object has no attribute 'get_tags'

# Fixed code
def arp():
    """
    Return the arp table from the minion

    CLI Example:

    .. code-block:: bash

        salt '*' network.arp
    """
    ret = {}
    out = __salt__["cmd.run"]("arp -an")
    for line in out.splitlines():
        comps = line.split()
        if len(comps) < 4:
            continue
        ret[comps[3]] = comps[1].strip("(").strip(")")
    return ret
# Buggy code
def _format_response(response, msg):
    if "Error" in response:
        msg = "Error"

    return {msg: response.replace("\n", "")}


# Traceback (AttributeError)
[ERROR   ] Error in function _master_opts:
Traceback (most recent call last):
File "/usr/lib/pymodules/python2.7/salt/master.py", line 1444, in run_func
ret = getattr(self, func)(load)
File "/usr/lib/pymodules/python2.7/salt/master.py", line 891, in _master_opts
envs = self._file_envs()
File "/usr/lib/pymodules/python2.7/salt/fileserver/__init__.py", line 153, in envs
ret.update(self.servers[fstr]())
File "/usr/lib/pymodules/python2.7/salt/fileserver/hgfs.py", line 176, in envs
tags = repo.get_tags()
AttributeError: 'hgclient' object has no attribute 'get_tags'

# Fixed code
def _format_response(response, msg):
    if "Error" in response:
        msg = "Error"

    return {msg: response}
# Buggy code
def enable():
    """
    Enable RDP the service on the server

    CLI Example:

    .. code-block:: bash

        salt '*' rdp.enable
    """

    cmd = '-InputFormat None -Command "& { $RDP = Get-WmiObject -Class Win32_TerminalServiceSetting -Namespace root\\CIMV2\\TerminalServices -Computer . -Authentication 6 -ErrorAction Stop ; $RDP.SetAllowTsConnections(1,1) }"'
    cmd = "{0} {1}".format(POWERSHELL, cmd)
    return _parse_return_code_powershell(__salt__["cmd.run"](cmd)) == 0


# Traceback (AttributeError)
[ERROR   ] Error in function _master_opts:
Traceback (most recent call last):
File "/usr/lib/pymodules/python2.7/salt/master.py", line 1444, in run_func
ret = getattr(self, func)(load)
File "/usr/lib/pymodules/python2.7/salt/master.py", line 891, in _master_opts
envs = self._file_envs()
File "/usr/lib/pymodules/python2.7/salt/fileserver/__init__.py", line 153, in envs
ret.update(self.servers[fstr]())
File "/usr/lib/pymodules/python2.7/salt/fileserver/hgfs.py", line 176, in envs
tags = repo.get_tags()
AttributeError: 'hgclient' object has no attribute 'get_tags'

# Fixed code
def enable():
    """
    Enable RDP the service on the server

    CLI Example:

    .. code-block:: bash

        salt '*' rdp.enable
    """

    return _parse_return_code_powershell(_psrdp("$RDP.SetAllowTsConnections(1,1)")) == 0
# Buggy code
def disable():
    """
    Disable RDP the service on the server

    CLI Example:

    .. code-block:: bash

        salt '*' rdp.disable
    """

    cmd = '-InputFormat None -Command "& { $RDP = Get-WmiObject -Class Win32_TerminalServiceSetting -Namespace root\\CIMV2\\TerminalServices -Computer . -Authentication 6 -ErrorAction Stop ; $RDP.SetAllowTsConnections(0,1) }"'
    cmd = "{0} {1}".format(POWERSHELL, cmd)
    return _parse_return_code_powershell(__salt__["cmd.run"](cmd)) == 0


# Traceback (AttributeError)
[ERROR   ] Error in function _master_opts:
Traceback (most recent call last):
File "/usr/lib/pymodules/python2.7/salt/master.py", line 1444, in run_func
ret = getattr(self, func)(load)
File "/usr/lib/pymodules/python2.7/salt/master.py", line 891, in _master_opts
envs = self._file_envs()
File "/usr/lib/pymodules/python2.7/salt/fileserver/__init__.py", line 153, in envs
ret.update(self.servers[fstr]())
File "/usr/lib/pymodules/python2.7/salt/fileserver/hgfs.py", line 176, in envs
tags = repo.get_tags()
AttributeError: 'hgclient' object has no attribute 'get_tags'

# Fixed code
def disable():
    """
    Disable RDP the service on the server

    CLI Example:

    .. code-block:: bash

        salt '*' rdp.disable
    """

    return _parse_return_code_powershell(_psrdp("$RDP.SetAllowTsConnections(0,1)")) == 0
# Buggy code
def status():
    """
    Show if rdp is enabled on the server

    CLI Example:

    .. code-block:: bash

        salt '*' rdp.status
    """

    cmd = '-InputFormat None -Command "& { $RDP = Get-WmiObject -Class Win32_TerminalServiceSetting -Namespace root\\CIMV2\\TerminalServices -Computer . -Authentication 6 -ErrorAction Stop ; echo $RDP.AllowTSConnections }"'
    cmd = "{0} {1}".format(POWERSHELL, cmd)
    out = int(__salt__["cmd.run"](cmd).strip())
    return out != 0


# Traceback (AttributeError)
[ERROR   ] Error in function _master_opts:
Traceback (most recent call last):
File "/usr/lib/pymodules/python2.7/salt/master.py", line 1444, in run_func
ret = getattr(self, func)(load)
File "/usr/lib/pymodules/python2.7/salt/master.py", line 891, in _master_opts
envs = self._file_envs()
File "/usr/lib/pymodules/python2.7/salt/fileserver/__init__.py", line 153, in envs
ret.update(self.servers[fstr]())
File "/usr/lib/pymodules/python2.7/salt/fileserver/hgfs.py", line 176, in envs
tags = repo.get_tags()
AttributeError: 'hgclient' object has no attribute 'get_tags'

# Fixed code
def status():
    """
    Show if rdp is enabled on the server

    CLI Example:

    .. code-block:: bash

        salt '*' rdp.status
    """

    out = int(_psrdp("echo $RDP.AllowTSConnections").strip())
    return out != 0
# Buggy code
def __virtual__():
    """
    Only work on systems which default to SMF
    """
    # Don't let this work on Solaris 9 since SMF doesn't exist on it.
    enable = set(("Solaris",))
    if __grains__["os"] in enable:
        if __grains__["os"] == "Solaris" and __grains__["kernelrelease"] == "5.9":
            return False
        return "service"
    return False


# Traceback (AttributeError)
[ERROR   ] Error in function _master_opts:
Traceback (most recent call last):
File "/usr/lib/pymodules/python2.7/salt/master.py", line 1444, in run_func
ret = getattr(self, func)(load)
File "/usr/lib/pymodules/python2.7/salt/master.py", line 891, in _master_opts
envs = self._file_envs()
File "/usr/lib/pymodules/python2.7/salt/fileserver/__init__.py", line 153, in envs
ret.update(self.servers[fstr]())
File "/usr/lib/pymodules/python2.7/salt/fileserver/hgfs.py", line 176, in envs
tags = repo.get_tags()
AttributeError: 'hgclient' object has no attribute 'get_tags'

# Fixed code
def __virtual__():
    """
    Only work on systems which default to SMF
    """
    # Don't let this work on Solaris 9 since SMF doesn't exist on it.
    enable = set(
        (
            "Solaris",
            "SmartOS",
        )
    )
    if __grains__["os"] in enable:
        if __grains__["os"] == "Solaris" and __grains__["kernelrelease"] == "5.9":
            return False
        return "service"
    return False
# Buggy code
def _prepare_serial_port_xml(
    serial_type="pty", telnet_port="", console=True, **kwargs_sink
):
    """
    Prepares the serial and console sections of the VM xml

    serial_type: presently 'pty' or 'tcp'(telnet)

    telnet_port: When selecting tcp, which port to listen on

    console: Is this serial device the console or for some other purpose

    Returns string representing the serial and console devices suitable for
    insertion into the VM XML definition
    """
    fn_ = "serial_port_{0}.jinja".format(serial_type)
    try:
        template = JINJA.get_template(fn_)
    except jinja2.exceptions.TemplateNotFound:
        log.error("Could not load template {0}".format(fn_))
        return ""
    return template.render(
        serial_type=serial_type, telnet_port=telnet_port, console=console
    )


# Traceback (AttributeError)
[ERROR   ] Error in function _master_opts:
Traceback (most recent call last):
File "/usr/lib/pymodules/python2.7/salt/master.py", line 1444, in run_func
ret = getattr(self, func)(load)
File "/usr/lib/pymodules/python2.7/salt/master.py", line 891, in _master_opts
envs = self._file_envs()
File "/usr/lib/pymodules/python2.7/salt/fileserver/__init__.py", line 153, in envs
ret.update(self.servers[fstr]())
File "/usr/lib/pymodules/python2.7/salt/fileserver/hgfs.py", line 176, in envs
tags = repo.get_tags()
AttributeError: 'hgclient' object has no attribute 'get_tags'

# Fixed code
def _prepare_serial_port_xml(serial_type="pty", telnet_port="", console=True, **sink):  # pylint: disable=unused-argument
    """
    Prepares the serial and console sections of the VM xml

    serial_type: presently 'pty' or 'tcp'(telnet)

    telnet_port: When selecting tcp, which port to listen on

    console: Is this serial device the console or for some other purpose

    Returns string representing the serial and console devices suitable for
    insertion into the VM XML definition
    """
    fn_ = "serial_port_{0}.jinja".format(serial_type)
    try:
        template = JINJA.get_template(fn_)
    except jinja2.exceptions.TemplateNotFound:
        log.error("Could not load template {0}".format(fn_))
        return ""
    return template.render(
        serial_type=serial_type, telnet_port=telnet_port, console=console
    )
# Buggy code
def _qemu_image_info(path):
    """
    Detect information for the image at path
    """
    ret = {}
    out = __salt__["cmd.run"]("qemu-img info {0}".format(path))

    match_map = {
        "size": r"virtual size: \w+ \((\d+) byte[s]?\)",
        "format": r"file format: (\w+)",
    }

    for info, search in match_map.items():
        m = re.search(search, out)
        if m:
            ret[info] = m.group(1)
    return ret


# Traceback (AttributeError)
[ERROR   ] Error in function _master_opts:
Traceback (most recent call last):
File "/usr/lib/pymodules/python2.7/salt/master.py", line 1444, in run_func
ret = getattr(self, func)(load)
File "/usr/lib/pymodules/python2.7/salt/master.py", line 891, in _master_opts
envs = self._file_envs()
File "/usr/lib/pymodules/python2.7/salt/fileserver/__init__.py", line 153, in envs
ret.update(self.servers[fstr]())
File "/usr/lib/pymodules/python2.7/salt/fileserver/hgfs.py", line 176, in envs
tags = repo.get_tags()
AttributeError: 'hgclient' object has no attribute 'get_tags'

# Fixed code
def _qemu_image_info(path):
    """
    Detect information for the image at path
    """
    ret = {}
    out = __salt__["cmd.run"]("qemu-img info {0}".format(path))

    match_map = {
        "size": r"virtual size: \w+ \((\d+) byte[s]?\)",
        "format": r"file format: (\w+)",
    }

    for info, search in match_map.items():
        try:
            ret[info] = re.search(search, out).group(1)
        except AttributeError:
            continue
    return ret
# Buggy code
def _srvmgr(func):
    """
    Execute a function from the ServerManager PS module and return the STDOUT
    """
    return __salt__["cmd.run"](
        'powershell -InputFormat None -Command "& {{ Import-Module ServerManager ; {0} }}"'.format(
            func
        )
    )


# Traceback (AttributeError)
[ERROR   ] Error in function _master_opts:
Traceback (most recent call last):
File "/usr/lib/pymodules/python2.7/salt/master.py", line 1444, in run_func
ret = getattr(self, func)(load)
File "/usr/lib/pymodules/python2.7/salt/master.py", line 891, in _master_opts
envs = self._file_envs()
File "/usr/lib/pymodules/python2.7/salt/fileserver/__init__.py", line 153, in envs
ret.update(self.servers[fstr]())
File "/usr/lib/pymodules/python2.7/salt/fileserver/hgfs.py", line 176, in envs
tags = repo.get_tags()
AttributeError: 'hgclient' object has no attribute 'get_tags'

# Fixed code
def _srvmgr(func):
    """
    Execute a function from the ServerManager PS module and return the STDOUT
    """
    return __salt__["cmd.run"](
        "Import-Module ServerManager ; {0}".format(func), shell="powershell"
    )
# Buggy code
def install(feature, recurse=False):
    """
    Install a feature

    Note:
    Some features requires reboot after un/installation, if so until the server is restarted
    Other features can not be installed !

    Note:
    Some features takes a long time to complete un/installation, set -t with a long timeout

    CLI Example:

    .. code-block:: bash

        salt '*' win_servermanager.install Telnet-Client
        salt '*' win_servermanager.install SNMP-Services True
    """
    sub = ""
    if recurse:
        sub = "-IncludeAllSubFeature"
    out = _srvmgr(
        "Add-WindowsFeature -Name {0} {1} -erroraction silentlycontinue | format-list".format(
            feature, sub
        )
    )
    return _parse_powershell_list(out)


# Traceback (AttributeError)
[ERROR   ] Error in function _master_opts:
Traceback (most recent call last):
File "/usr/lib/pymodules/python2.7/salt/master.py", line 1444, in run_func
ret = getattr(self, func)(load)
File "/usr/lib/pymodules/python2.7/salt/master.py", line 891, in _master_opts
envs = self._file_envs()
File "/usr/lib/pymodules/python2.7/salt/fileserver/__init__.py", line 153, in envs
ret.update(self.servers[fstr]())
File "/usr/lib/pymodules/python2.7/salt/fileserver/hgfs.py", line 176, in envs
tags = repo.get_tags()
AttributeError: 'hgclient' object has no attribute 'get_tags'

# Fixed code
def install(feature, recurse=False):
    """
    Install a feature

    Note:
    Some features requires reboot after un/installation, if so until the server is restarted
    Other features can not be installed !

    Note:
    Some features takes a long time to complete un/installation, set -t with a long timeout

    CLI Example:

    .. code-block:: bash

        salt '*' win_servermanager.install Telnet-Client
        salt '*' win_servermanager.install SNMP-Services True
    """
    sub = ""
    if recurse:
        sub = "-IncludeAllSubFeature"
    out = _srvmgr(
        '"Add-WindowsFeature -Name {0} {1} -erroraction silentlycontinue | format-list"'.format(
            feature, sub
        )
    )
    return _parse_powershell_list(out)
# Buggy code
def remove(feature):
    """
    Remove an installed feature

    .. note::
        Some features require a reboot after installation/uninstallation. If
        one of these features are modified, then other features cannot be
        installed until the server is restarted. Additionally, some features
        take a while to complete installation/uninstallation, so it is a good
        idea to use the ``-t`` option to set a longer timeout.

    CLI Example:

    .. code-block:: bash

        salt -t 600 '*' win_servermanager.remove Telnet-Client
    """
    out = _srvmgr(
        "Remove-WindowsFeature -Name {0} -erroraction silentlycontinue | format-list".format(
            feature
        )
    )
    return _parse_powershell_list(out)


# Traceback (AttributeError)
[ERROR   ] Error in function _master_opts:
Traceback (most recent call last):
File "/usr/lib/pymodules/python2.7/salt/master.py", line 1444, in run_func
ret = getattr(self, func)(load)
File "/usr/lib/pymodules/python2.7/salt/master.py", line 891, in _master_opts
envs = self._file_envs()
File "/usr/lib/pymodules/python2.7/salt/fileserver/__init__.py", line 153, in envs
ret.update(self.servers[fstr]())
File "/usr/lib/pymodules/python2.7/salt/fileserver/hgfs.py", line 176, in envs
tags = repo.get_tags()
AttributeError: 'hgclient' object has no attribute 'get_tags'

# Fixed code
def remove(feature):
    """
    Remove an installed feature

    .. note::
        Some features require a reboot after installation/uninstallation. If
        one of these features are modified, then other features cannot be
        installed until the server is restarted. Additionally, some features
        take a while to complete installation/uninstallation, so it is a good
        idea to use the ``-t`` option to set a longer timeout.

    CLI Example:

    .. code-block:: bash

        salt -t 600 '*' win_servermanager.remove Telnet-Client
    """
    out = _srvmgr(
        '"Remove-WindowsFeature -Name {0} -erroraction silentlycontinue | format-list"'.format(
            feature
        )
    )
    return _parse_powershell_list(out)
# Buggy code
def restart(name):
    """
    Restart the named service

    CLI Example:

    .. code-block:: bash

        salt '*' service.restart <service name>
    """
    stopcmd = 'sc stop "{0}"'.format(name)
    __salt__["cmd.run"](stopcmd)
    servicestate = status(name)
    while True:
        servicestate = status(name)
        if servicestate == "":
            break
        else:
            time.sleep(2)
    startcmd = 'sc start "{0}"'.format(name)
    return not __salt__["cmd.retcode"](startcmd)


# Traceback (AttributeError)
[ERROR   ] Error in function _master_opts:
Traceback (most recent call last):
File "/usr/lib/pymodules/python2.7/salt/master.py", line 1444, in run_func
ret = getattr(self, func)(load)
File "/usr/lib/pymodules/python2.7/salt/master.py", line 891, in _master_opts
envs = self._file_envs()
File "/usr/lib/pymodules/python2.7/salt/fileserver/__init__.py", line 153, in envs
ret.update(self.servers[fstr]())
File "/usr/lib/pymodules/python2.7/salt/fileserver/hgfs.py", line 176, in envs
tags = repo.get_tags()
AttributeError: 'hgclient' object has no attribute 'get_tags'

# Fixed code
def restart(name):
    """
    Restart the named service

    CLI Example:

    .. code-block:: bash

        salt '*' service.restart <service name>
    """
    stop(name)
    for idx in xrange(5):
        if status(name):
            time.sleep(2)
            continue
        return start(name)
    return False
# Buggy code
def status(name, sig=None):
    """
    Return the status for a service, returns the PID or an empty string if the
    service is running or not, pass a signature to use to find the service via
    ps

    CLI Example:

    .. code-block:: bash

        salt '*' service.status <service name> [service signature]
    """
    cmd = 'sc query "{0}"'.format(name)
    statuses = __salt__["cmd.run"](cmd).splitlines()
    for line in statuses:
        if "RUNNING" in line:
            return True
        elif "PENDING" in line:
            return True
    return False


# Traceback (AttributeError)
[ERROR   ] Error in function _master_opts:
Traceback (most recent call last):
File "/usr/lib/pymodules/python2.7/salt/master.py", line 1444, in run_func
ret = getattr(self, func)(load)
File "/usr/lib/pymodules/python2.7/salt/master.py", line 891, in _master_opts
envs = self._file_envs()
File "/usr/lib/pymodules/python2.7/salt/fileserver/__init__.py", line 153, in envs
ret.update(self.servers[fstr]())
File "/usr/lib/pymodules/python2.7/salt/fileserver/hgfs.py", line 176, in envs
tags = repo.get_tags()
AttributeError: 'hgclient' object has no attribute 'get_tags'

# Fixed code
def status(name, sig=None):
    """
    Return the status for a service, returns the PID or an empty string if the
    service is running or not, pass a signature to use to find the service via
    ps

    CLI Example:

    .. code-block:: bash

        salt '*' service.status <service name> [service signature]
    """
    cmd = 'sc query "{0}"'.format(name)
    statuses = __salt__["cmd.run"](cmd).splitlines()
    for line in statuses:
        if "RUNNING" in line:
            return True
        elif "STOP_PENDING" in line:
            return True
    return False
# Buggy code
def set_computer_name(name):
    """
    Set the Windows computer name

    CLI Example:

    .. code-block:: bash

        salt 'minion-id' system.set_computer_name 'DavesComputer'
    """
    cmd = 'wmic computersystem where name="%COMPUTERNAME%" call rename name="{0}"'
    log.debug("Attempting to change computer name. Cmd is: ".format(cmd))
    ret = __salt__["cmd.run"](cmd.format(name))
    if "ReturnValue = 0;" in ret:
        return {"Computer name": name}
    return False


# Traceback (AttributeError)
[ERROR   ] Error in function _master_opts:
Traceback (most recent call last):
File "/usr/lib/pymodules/python2.7/salt/master.py", line 1444, in run_func
ret = getattr(self, func)(load)
File "/usr/lib/pymodules/python2.7/salt/master.py", line 891, in _master_opts
envs = self._file_envs()
File "/usr/lib/pymodules/python2.7/salt/fileserver/__init__.py", line 153, in envs
ret.update(self.servers[fstr]())
File "/usr/lib/pymodules/python2.7/salt/fileserver/hgfs.py", line 176, in envs
tags = repo.get_tags()
AttributeError: 'hgclient' object has no attribute 'get_tags'

# Fixed code
def set_computer_name(name):
    """
    Set the Windows computer name

    CLI Example:

    .. code-block:: bash

        salt 'minion-id' system.set_computer_name 'DavesComputer'
    """
    cmd = 'wmic computersystem where name="%COMPUTERNAME%" call rename name="{0}"'
    log.debug("Attempting to change computer name. Cmd is: ".format(cmd))
    ret = __salt__["cmd.run"](cmd.format(name))
    if "ReturnValue = 0;" in ret:
        ret = {"Computer Name": {"Current": get_computer_name()}}
        pending = get_pending_computer_name()
        if pending not in (None, False):
            ret["Computer Name"]["Pending"] = pending
        return ret
    return False
# Buggy code
def set_computer_desc(desc):
    """
    Set the Windows computer description

    CLI Example:

    .. code-block:: bash

        salt 'minion-id' system.set_computer_desc 'This computer belongs to Dave!'
    """
    cmd = 'net config server /srvcomment:"{0}"'.format(desc)
    __salt__["cmd.run"](cmd)
    return {"Computer Description": desc}


# Traceback (AttributeError)
[ERROR   ] Error in function _master_opts:
Traceback (most recent call last):
File "/usr/lib/pymodules/python2.7/salt/master.py", line 1444, in run_func
ret = getattr(self, func)(load)
File "/usr/lib/pymodules/python2.7/salt/master.py", line 891, in _master_opts
envs = self._file_envs()
File "/usr/lib/pymodules/python2.7/salt/fileserver/__init__.py", line 153, in envs
ret.update(self.servers[fstr]())
File "/usr/lib/pymodules/python2.7/salt/fileserver/hgfs.py", line 176, in envs
tags = repo.get_tags()
AttributeError: 'hgclient' object has no attribute 'get_tags'

# Fixed code
def set_computer_desc(desc):
    """
    Set the Windows computer description

    CLI Example:

    .. code-block:: bash

        salt 'minion-id' system.set_computer_desc 'This computer belongs to Dave!'
    """
    cmd = 'net config server /srvcomment:"{0}"'.format(desc)
    __salt__["cmd.run"](cmd)
    return {"Computer Description": get_computer_desc()}
# Buggy code
def list_pkgs(versions_as_list=False, **kwargs):
    """
    List the packages currently installed as a dict::

        {'<package_name>': '<version>'}

    CLI Example:

    .. code-block:: bash

        salt '*' pkg.list_pkgs
    """
    versions_as_list = salt.utils.is_true(versions_as_list)
    # 'removed' not yet implemented or not applicable
    if salt.utils.is_true(kwargs.get("removed")):
        return {}

    if "pkg.list_pkgs" in __context__:
        if versions_as_list:
            return __context__["pkg.list_pkgs"]
        else:
            ret = copy.deepcopy(__context__["pkg.list_pkgs"])
            __salt__["pkg_resource.stringify"](ret)
            return ret

    cmd = 'rpm -qa --queryformat "%{NAME}_|-%{VERSION}_|-%{RELEASE}\n"'
    ret = {}
    for line in __salt__["cmd.run"](cmd).splitlines():
        name, pkgver, rel = line.split("_|-")
        if rel:
            pkgver += "-{0}".format(rel)
        __salt__["pkg_resource.add_pkg"](ret, name, pkgver)

    __salt__["pkg_resource.sort_pkglist"](ret)
    __context__["pkg.list_pkgs"] = copy.deepcopy(ret)
    if not versions_as_list:
        __salt__["pkg_resource.stringify"](ret)
    return ret


# Traceback (AttributeError)
[ERROR   ] Error in function _master_opts:
Traceback (most recent call last):
File "/usr/lib/pymodules/python2.7/salt/master.py", line 1444, in run_func
ret = getattr(self, func)(load)
File "/usr/lib/pymodules/python2.7/salt/master.py", line 891, in _master_opts
envs = self._file_envs()
File "/usr/lib/pymodules/python2.7/salt/fileserver/__init__.py", line 153, in envs
ret.update(self.servers[fstr]())
File "/usr/lib/pymodules/python2.7/salt/fileserver/hgfs.py", line 176, in envs
tags = repo.get_tags()
AttributeError: 'hgclient' object has no attribute 'get_tags'

# Fixed code
def list_pkgs(versions_as_list=False, **kwargs):
    """
    List the packages currently installed as a dict::

        {'<package_name>': '<version>'}

    CLI Example:

    .. code-block:: bash

        salt '*' pkg.list_pkgs
    """
    versions_as_list = salt.utils.is_true(versions_as_list)
    # 'removed' not yet implemented or not applicable
    if salt.utils.is_true(kwargs.get("removed")):
        return {}

    if "pkg.list_pkgs" in __context__:
        if versions_as_list:
            return __context__["pkg.list_pkgs"]
        else:
            ret = copy.deepcopy(__context__["pkg.list_pkgs"])
            __salt__["pkg_resource.stringify"](ret)
            return ret

    cmd = 'rpm -qa --queryformat "%{NAME}_|-%{VERSION}_|-%{RELEASE}\\n"'
    ret = {}
    for line in __salt__["cmd.run"](cmd).splitlines():
        name, pkgver, rel = line.split("_|-")
        if rel:
            pkgver += "-{0}".format(rel)
        __salt__["pkg_resource.add_pkg"](ret, name, pkgver)

    __salt__["pkg_resource.sort_pkglist"](ret)
    __context__["pkg.list_pkgs"] = copy.deepcopy(ret)
    if not versions_as_list:
        __salt__["pkg_resource.stringify"](ret)
    return ret
# Buggy code
def __init__(self, opts, grains, id_, env, ext=None):
    # use the local file client
    self.opts = self.__gen_opts(opts, grains, id_, env, ext)
    self.client = salt.fileclient.get_file_client(self.opts)
    if opts.get("file_client", "") == "local":
        opts["grains"] = grains
        self.functions = salt.loader.minion_mods(opts)
    else:
        self.functions = salt.loader.minion_mods(self.opts)
    self.matcher = salt.minion.Matcher(self.opts, self.functions)
    self.rend = salt.loader.render(self.opts, self.functions)
    self.ext_pillars = salt.loader.pillars(self.opts, self.functions)


# Traceback (AttributeError)
[ERROR   ] Error in function _master_opts:
Traceback (most recent call last):
File "/usr/lib/pymodules/python2.7/salt/master.py", line 1444, in run_func
ret = getattr(self, func)(load)
File "/usr/lib/pymodules/python2.7/salt/master.py", line 891, in _master_opts
envs = self._file_envs()
File "/usr/lib/pymodules/python2.7/salt/fileserver/__init__.py", line 153, in envs
ret.update(self.servers[fstr]())
File "/usr/lib/pymodules/python2.7/salt/fileserver/hgfs.py", line 176, in envs
tags = repo.get_tags()
AttributeError: 'hgclient' object has no attribute 'get_tags'

# Fixed code
def __init__(self, opts, grains, id_, env, ext=None):
    # Store the file_roots path so we can restore later. Issue 5449
    self.actual_file_roots = opts["file_roots"]
    # use the local file client
    self.opts = self.__gen_opts(opts, grains, id_, env, ext)
    self.client = salt.fileclient.get_file_client(self.opts)
    if opts.get("file_client", "") == "local":
        opts["grains"] = grains
        self.functions = salt.loader.minion_mods(opts)
    else:
        self.functions = salt.loader.minion_mods(self.opts)
    self.matcher = salt.minion.Matcher(self.opts, self.functions)
    self.rend = salt.loader.render(self.opts, self.functions)
    # Fix self.opts['file_roots'] so that ext_pillars know the real
    # location of file_roots. Issue 5951
    ext_pillar_opts = dict(self.opts)
    ext_pillar_opts["file_roots"] = self.actual_file_roots
    self.ext_pillars = salt.loader.pillars(ext_pillar_opts, self.functions)
# Buggy code
def compile_pillar(self):
    """
    Render the pillar data and return
    """
    top, terrors = self.get_top()
    matches = self.top_matches(top)
    pillar, errors = self.render_pillar(matches)
    self.ext_pillar(pillar)
    errors.extend(terrors)
    if self.opts.get("pillar_opts", True):
        mopts = dict(self.opts)
        if "grains" in mopts:
            mopts.pop("grains")
        if "aes" in mopts:
            mopts.pop("aes")
        mopts["saltversion"] = __version__
        pillar["master"] = mopts
    if errors:
        for error in errors:
            log.critical("Pillar render error: {0}".format(error))
        pillar["_errors"] = errors
    return pillar


# Traceback (AttributeError)
[ERROR   ] Error in function _master_opts:
Traceback (most recent call last):
File "/usr/lib/pymodules/python2.7/salt/master.py", line 1444, in run_func
ret = getattr(self, func)(load)
File "/usr/lib/pymodules/python2.7/salt/master.py", line 891, in _master_opts
envs = self._file_envs()
File "/usr/lib/pymodules/python2.7/salt/fileserver/__init__.py", line 153, in envs
ret.update(self.servers[fstr]())
File "/usr/lib/pymodules/python2.7/salt/fileserver/hgfs.py", line 176, in envs
tags = repo.get_tags()
AttributeError: 'hgclient' object has no attribute 'get_tags'

# Fixed code
def compile_pillar(self):
    """
    Render the pillar data and return
    """
    top, terrors = self.get_top()
    matches = self.top_matches(top)
    pillar, errors = self.render_pillar(matches)
    self.ext_pillar(pillar)
    errors.extend(terrors)
    if self.opts.get("pillar_opts", True):
        mopts = dict(self.opts)
        if "grains" in mopts:
            mopts.pop("grains")
        if "aes" in mopts:
            mopts.pop("aes")
        # Restore the actual file_roots path. Issue 5449
        mopts["file_roots"] = self.actual_file_roots
        mopts["saltversion"] = __version__
        pillar["master"] = mopts
    if errors:
        for error in errors:
            log.critical("Pillar render error: {0}".format(error))
        pillar["_errors"] = errors
    return pillar
# Buggy code
def returner(ret):
    """
    Insert minion return data into the sqlite3 database
    """
    log.debug("sqlite3 returner <returner> called with data: {0}".format(ret))
    conn = _get_conn()
    cur = conn.cursor()
    sql = """INSERT INTO salt_returns
             (fun, jid, id, date, full_ret, success)
             VALUES (:fun, :jid, :id, :date, :full_ret, :success)"""
    cur.execute(
        sql,
        {
            "fun": ret["fun"],
            "jid": ret["jid"],
            "id": ret["id"],
            "date": str(datetime.datetime.now()),
            "full_ret": json.dumps(ret["return"]),
            "success": ret["success"],
        },
    )
    _close_conn(conn)


# Traceback (AttributeError)
[ERROR   ] Error in function _master_opts:
Traceback (most recent call last):
File "/usr/lib/pymodules/python2.7/salt/master.py", line 1444, in run_func
ret = getattr(self, func)(load)
File "/usr/lib/pymodules/python2.7/salt/master.py", line 891, in _master_opts
envs = self._file_envs()
File "/usr/lib/pymodules/python2.7/salt/fileserver/__init__.py", line 153, in envs
ret.update(self.servers[fstr]())
File "/usr/lib/pymodules/python2.7/salt/fileserver/hgfs.py", line 176, in envs
tags = repo.get_tags()
AttributeError: 'hgclient' object has no attribute 'get_tags'

# Fixed code
def returner(ret):
    """
    Insert minion return data into the sqlite3 database
    """
    log.debug("sqlite3 returner <returner> called with data: {0}".format(ret))
    conn = _get_conn()
    cur = conn.cursor()
    sql = """INSERT INTO salt_returns
             (fun, jid, id, fun_args, date, full_ret, success)
             VALUES (:fun, :jid, :id, :fun_args, :date, :full_ret, :success)"""
    cur.execute(
        sql,
        {
            "fun": ret["fun"],
            "jid": ret["jid"],
            "id": ret["id"],
            "fun_args": str(ret["fun_args"]) if ret["fun_args"] else None,
            "date": str(datetime.datetime.now()),
            "full_ret": json.dumps(ret["return"]),
            "success": ret["success"],
        },
    )
    _close_conn(conn)
# Buggy code
def over(env="base", os_fn=None):
    """
    Execute an overstate sequence to orchestrate the executing of states
    over a group of systems

    CLI Examples:

    .. code-block:: bash

        salt-run state.over
        salt-run state.over env=dev /root/overstate.sls
    """
    stage_num = 0
    overstate = salt.overstate.OverState(__opts__, env, os_fn)
    for stage in overstate.stages_iter():
        if isinstance(stage, dict):
            # This is highstate data
            print("Stage execution results:")
            for key, val in stage.items():
                if "_|-" in key:
                    salt.output.display_output(
                        {"error": {key: val}}, "highstate", opts=__opts__
                    )
                else:
                    salt.output.display_output({key: val}, "highstate", opts=__opts__)
        elif isinstance(stage, list):
            # This is a stage
            if stage_num == 0:
                print("Executing the following Over State:")
            else:
                print("Executed Stage:")
            salt.output.display_output(stage, "overstatestage", opts=__opts__)
            stage_num += 1
    return overstate.over_run


# Traceback (AttributeError)
[ERROR   ] Error in function _master_opts:
Traceback (most recent call last):
File "/usr/lib/pymodules/python2.7/salt/master.py", line 1444, in run_func
ret = getattr(self, func)(load)
File "/usr/lib/pymodules/python2.7/salt/master.py", line 891, in _master_opts
envs = self._file_envs()
File "/usr/lib/pymodules/python2.7/salt/fileserver/__init__.py", line 153, in envs
ret.update(self.servers[fstr]())
File "/usr/lib/pymodules/python2.7/salt/fileserver/hgfs.py", line 176, in envs
tags = repo.get_tags()
AttributeError: 'hgclient' object has no attribute 'get_tags'

# Fixed code
def over(env="base", os_fn=None):
    """
    Execute an overstate sequence to orchestrate the executing of states
    over a group of systems

    CLI Examples:

    .. code-block:: bash

        salt-run state.over base /path/to/myoverstate.sls
    """
    stage_num = 0
    overstate = salt.overstate.OverState(__opts__, env, os_fn)
    for stage in overstate.stages_iter():
        if isinstance(stage, dict):
            # This is highstate data
            print("Stage execution results:")
            for key, val in stage.items():
                if "_|-" in key:
                    salt.output.display_output(
                        {"error": {key: val}}, "highstate", opts=__opts__
                    )
                else:
                    salt.output.display_output({key: val}, "highstate", opts=__opts__)
        elif isinstance(stage, list):
            # This is a stage
            if stage_num == 0:
                print("Executing the following Over State:")
            else:
                print("Executed Stage:")
            salt.output.display_output(stage, "overstatestage", opts=__opts__)
            stage_num += 1
    return overstate.over_run