gurudesh/pytracebugs huggingface dataset:
# Buggy code
def __init__(self, opts, pillar=None, jid=None):
    if "grains" not in opts:
        opts["grains"] = salt.loader.grains(opts)
    self.opts = opts
    self.opts["pillar"] = self.__gather_pillar()
    if pillar and isinstance(pillar, dict):
        self.opts["pillar"].update(pillar)
    self.state_con = {}
    self.load_modules()
    self.active = set()
    self.mod_init = set()
    self.pre = {}
    self.__run_num = 0
    self.jid = jid


# 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, pillar=None, jid=None):
    if "grains" not in opts:
        opts["grains"] = salt.loader.grains(opts)
    self.opts = opts
    self._pillar_override = pillar
    self.opts["pillar"] = self._gather_pillar()
    self.state_con = {}
    self.load_modules()
    self.active = set()
    self.mod_init = set()
    self.pre = {}
    self.__run_num = 0
    self.jid = jid
# Buggy code
def event(self, chunk_ret):
    """
    Fire an event on the master bus
    """
    if not self.opts.get("local") and self.opts.get("state_events", True):
        tag = salt.utils.event.tagify([self.jid, str(chunk_ret["__run_num__"])])
        self.functions["event.fire_master"](chunk_ret, tag)


# 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 event(self, chunk_ret):
    """
    Fire an event on the master bus
    """
    if not self.opts.get("local") and self.opts.get("state_events", True):
        tag = salt.utils.event.tagify(
            [self.jid, "prog", self.opts["id"], str(chunk_ret["__run_num__"])], "job"
        )
        preload = {"jid": self.jid}
        self.functions["event.fire_master"](chunk_ret, tag, preload=preload)
# Buggy code
def load_dynamic(self, matches):
    """
    If autoload_dynamic_modules is True then automatically load the
    dynamic modules
    """
    if not self.opts["autoload_dynamic_modules"]:
        return
    syncd = self.state.functions["saltutil.sync_all"](list(matches))
    if syncd["grains"]:
        self.opts["grains"] = salt.loader.grains(self.opts)
    self.state.module_refresh()


# 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 load_dynamic(self, matches):
    """
    If autoload_dynamic_modules is True then automatically load the
    dynamic modules
    """
    if not self.opts["autoload_dynamic_modules"]:
        return
    syncd = self.state.functions["saltutil.sync_all"](list(matches))
    if syncd["grains"]:
        self.opts["grains"] = salt.loader.grains(self.opts)
        self.state.opts["pillar"] = self.state._gather_pillar()
    self.state.module_refresh()
# Buggy code
def replace(
    name, pattern, repl, count=0, flags=0, bufsize=1, backup=".bak", show_changes=True
):
    """
    Maintain an edit in a file

    .. versionadded:: 0.17

    Params are identical to :py:func:`~salt.modules.file.replace`.

    """
    ret = {"name": name, "changes": {}, "result": False, "comment": ""}

    check_res, check_msg = _check_file(name)
    if not check_res:
        return _error(ret, check_msg)

    changes = __salt__["file.replace"](
        name,
        pattern,
        repl,
        count=count,
        flags=flags,
        bufsize=bufsize,
        backup=backup,
        dry_run=__opts__["test"],
        show_changes=show_changes,
    )

    if changes:
        ret["changes"] = changes
        ret["comment"] = "Changes were made"
    else:
        ret["comment"] = "No changes were made"

    ret["result"] = True
    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 replace(
    name, pattern, repl, count=0, flags=0, bufsize=1, backup=".bak", show_changes=True
):
    """
    Maintain an edit in a file

    .. versionadded:: 0.17.0

    Params are identical to :py:func:`~salt.modules.file.replace`.

    """
    ret = {"name": name, "changes": {}, "result": False, "comment": ""}

    check_res, check_msg = _check_file(name)
    if not check_res:
        return _error(ret, check_msg)

    changes = __salt__["file.replace"](
        name,
        pattern,
        repl,
        count=count,
        flags=flags,
        bufsize=bufsize,
        backup=backup,
        dry_run=__opts__["test"],
        show_changes=show_changes,
    )

    if changes:
        ret["changes"] = changes
        ret["comment"] = "Changes were made"
    else:
        ret["comment"] = "No changes were made"

    ret["result"] = True
    return ret
# Buggy code
def __ls_remote__(name, branch):
    """
    Returns the upstream hash for any given URL and branch.
    """
    cmd = "git ls-remote -h " + name + " " + branch + " | cut -f 1"
    return __salt__["cmd.run_stdout"](cmd)


# 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 __ls_remote__(name, branch, user, cwd):
    """
    Returns the upstream hash for any given URL and branch.
    """
    cmd = "git ls-remote -h " + name + " " + branch + " | cut -f 1"
    return __salt__["cmd.run_stdout"](cmd, cwd, runas=user)
# Buggy code
def __virtual__():
    """
    Only load if hg is available
    """
    return "hg" if __salt__["cmd.has_exec"](hg_binary) else 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 load if hg is available
    """
    return __salt__["cmd.has_exec"](HG_BINARY)
# Buggy code
def _update_repo(ret, target, user, rev, opts):
    log.debug(
        'target {0} is found, "hg pull && hg up is probably required"'.format(target)
    )

    current_rev = __salt__["hg.revision"](target, user=user)
    if not current_rev:
        return _fail(ret, "Seems that {0} is not a valid hg repo".format(target))

    if __opts__["test"]:
        test_result = (
            "Repository {0} update is probably required (current revision is {1})"
        ).format(target, current_rev)
        return _neutral_test(ret, test_result)

    pull_out = __salt__["hg.pull"](target, user=user, opts=opts)

    if rev:
        __salt__["hg.update"](target, rev, user=user)
    else:
        __salt__["hg.update"](target, "tip", user=user)

    new_rev = __salt__["hg.revision"](cwd=target, user=user)

    if current_rev != new_rev:
        revision_text = "{0} => {1}".format(current_rev, new_rev)
        log.info("Repository {0} updated: {1}".format(target, revision_text))
        ret["comment"] = "Repository {0} updated.".format(target)
        ret["changes"]["revision"] = revision_text
    elif "error:" in pull_out:
        return _fail(ret, "An error was thrown by hg:\n{0}".format(pull_out))
    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 _update_repo(ret, target, clean, user, rev, opts):
    """
    Update the repo to a given revision. Using clean passes -C to the hg up
    """
    log.debug(
        'target {0} is found, "hg pull && hg up is probably required"'.format(target)
    )

    current_rev = __salt__["hg.revision"](target, user=user)
    if not current_rev:
        return _fail(ret, "Seems that {0} is not a valid hg repo".format(target))

    if __opts__["test"]:
        test_result = (
            "Repository {0} update is probably required (current revision is {1})"
        ).format(target, current_rev)
        return _neutral_test(ret, test_result)

    pull_out = __salt__["hg.pull"](target, user=user, opts=opts)

    if rev:
        __salt__["hg.update"](target, rev, force=clean, user=user)
    else:
        __salt__["hg.update"](target, "tip", force=clean, user=user)

    new_rev = __salt__["hg.revision"](cwd=target, user=user)

    if current_rev != new_rev:
        revision_text = "{0} => {1}".format(current_rev, new_rev)
        log.info("Repository {0} updated: {1}".format(target, revision_text))
        ret["comment"] = "Repository {0} updated.".format(target)
        ret["changes"]["revision"] = revision_text
    elif "error:" in pull_out:
        return _fail(ret, "An error was thrown by hg:\n{0}".format(pull_out))
    return ret
# Buggy code
def _enabled_used_error(ret):
    ret["result"] = False
    ret["comment"] = (
        'Service {0} uses non-existant option "enabled".  '
        + 'Perhaps "enable" option was intended?'
    ).format(ret["name"])
    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 _enabled_used_error(ret):
    ret["result"] = False
    ret["comment"] = (
        'Service {0} uses non-existent option "enabled".  '
        + 'Perhaps "enable" option was intended?'
    ).format(ret["name"])
    return ret
# Buggy code
def run(self, low):
    """
    Execute the specified function in the specified state by passing the
    LowData
    """
    l_fun = getattr(self, low["state"])
    f_call = salt.utils.format_call(l_fun, low)
    try:
        ret = l_fun(*f_call.get("args", ()), **f_call.get("kwargs", {}))
    except Exception:
        log.error(
            "Failed to execute {0}: {1}\n".format(low["state"], l_fun), exc_info=True
        )
        return 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 run(self, low):
    """
    Execute the specified function in the specified state by passing the
    LowData
    """
    l_fun = getattr(self, low["state"])
    f_call = salt.utils.format_call(l_fun, low)
    try:
        ret = l_fun(*f_call.get("args", ()), **f_call.get("kwargs", {}))
    except Exception:
        log.error(
            "Failed to execute {0}: {1}\n".format(low["state"], l_fun), exc_info=True
        )
        return False
    return ret
# Buggy code
def fire_master(self, data, tag):
    """
    Fire an event off on the master server

    CLI Example::

        salt '*' event.fire_master 'stuff to be in the event' 'tag'
    """
    load = {"id": self.opts["id"], "tag": tag, "data": data, "cmd": "_minion_event"}
    sreq = salt.payload.SREQ(self.opts["master_uri"])
    try:
        sreq.send("aes", self.auth.crypticle.dumps(load))
    except Exception:
        pass
    return True


# 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 fire_master(self, data, tag, preload=None):
    """
    Fire an event off on the master server

    CLI Example::

        salt '*' event.fire_master 'stuff to be in the event' 'tag'
    """
    load = {}
    if preload:
        load.update(preload)

    load.update(
        {"id": self.opts["id"], "tag": tag, "data": data, "cmd": "_minion_event"}
    )

    sreq = salt.payload.SREQ(self.opts["master_uri"])
    try:
        sreq.send("aes", self.auth.crypticle.dumps(load))
    except Exception:
        pass
    return True
# Buggy code
def __init__(self, environment):
    super(SerializerExtension, self).__init__(environment)
    self.environment.filters.update(
        {
            "yaml": self.format_yaml,
            "json": self.format_json,
            "load_yaml": self.load_yaml,
            "load_json": self.load_json,
        }
    )


# 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, environment):
    super(SerializerExtension, self).__init__(environment)
    self.environment.filters.update(
        {
            "yaml": self.format_yaml,
            "json": self.format_json,
            "load_yaml": self.load_yaml,
            "load_json": self.load_json,
        }
    )

    if self.environment.finalize is None:
        self.environment.finalize = self.finalizer
    else:
        finalizer = self.environment.finalize

        @wraps(finalizer)
        def wrapper(self, data):
            return finalizer(self.finalizer(data))

        self.environment.finalize = wrapper
# Buggy code
def format_yaml(self, value):
    return Markup(yaml.dump(value, default_flow_style=True).strip())


# 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_yaml(self, value):
    return Markup(
        yaml.dump(value, default_flow_style=True, Dumper=OrderedDictDumper).strip()
    )
# Buggy code
def __new__(cls, *args, **kwargs):
    instance = super(OutputOptionsWithTextMixIn, cls).__new__(cls, *args, **kwargs)
    utils.warn_until(
        (0, 19),
        "'OutputOptionsWithTextMixIn' has been deprecated. Please "
        "start using 'OutputOptionsMixIn'; your code should not need "
        "any further changes.",
    )
    return instance


# 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 __new__(cls, *args, **kwargs):
    instance = super(OutputOptionsWithTextMixIn, cls).__new__(cls, *args, **kwargs)
    utils.warn_until(
        "Helium",
        "'OutputOptionsWithTextMixIn' has been deprecated. Please "
        "start using 'OutputOptionsMixIn'; your code should not need "
        "any further changes.",
    )
    return instance
# Buggy code
def setup_config(self):
    return config.minion_config(self.get_config_file_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 setup_config(self):
    return config.minion_config(self.get_config_file_path(), minion_id=True)
# Buggy code
def process_key_logfile(self):
    if self.options.key_logfile:
        # XXX: Remove '--key-logfile' support in 0.18.0
        # In < 0.18.0 error out
        utils.warn_until((0, 18), "", _dont_call_warnings=True)
        self.error(
            "The '--key-logfile' option has been deprecated in favour of '--log-file'"
        )


# 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 process_key_logfile(self):
    if self.options.key_logfile:
        # XXX: Remove '--key-logfile' support in 0.18.0
        # In < 0.18.0 error out
        utils.warn_until(
            "Hydrogen", "Remove '--key-logfile' support", _dont_call_warnings=True
        )
        self.error(
            "The '--key-logfile' option has been deprecated in favour of '--log-file'"
        )
# Buggy code
def _mixin_after_parsed(self):
    if self.options.list:
        if "," in self.args[0]:
            self.config["tgt"] = self.args[0].split(",")
        else:
            self.config["tgt"] = self.args[0].split()
    else:
        self.config["tgt"] = self.args[0]
    if len(self.args) > 0:
        self.config["arg_str"] = " ".join(self.args[1:])


# 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 _mixin_after_parsed(self):
    if not self.args:
        self.print_help()
        self.exit(1)

    if self.options.list:
        if "," in self.args[0]:
            self.config["tgt"] = self.args[0].split(",")
        else:
            self.config["tgt"] = self.args[0].split()
    else:
        self.config["tgt"] = self.args[0]
    if len(self.args) > 0:
        self.config["arg_str"] = " ".join(self.args[1:])
# Buggy code
def __init__(
    self,  # pylint: disable=C0103
    major,
    minor,
    bugfix=0,
    rc=0,  # pylint: disable=C0103
    noc=0,
    sha=None,
):
    if isinstance(major, string_types):
        major = int(major)

    if isinstance(minor, string_types):
        minor = int(minor)

    if bugfix is None:
        bugfix = 0
    elif isinstance(bugfix, string_types):
        bugfix = int(bugfix)

    if rc is None:
        rc = 0
    elif isinstance(rc, string_types):
        rc = int(rc)

    if noc is None:
        noc = 0
    elif isinstance(noc, string_types):
        noc = int(noc)

    self.major = major
    self.minor = minor
    self.bugfix = bugfix
    self.rc = rc  # pylint: disable=C0103
    self.noc = noc
    self.sha = sha


# 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,  # pylint: disable=C0103
    major,
    minor,
    bugfix=0,
    rc=0,  # pylint: disable=C0103
    noc=0,
    sha=None,
):
    if isinstance(major, string_types):
        major = int(major)

    if isinstance(minor, string_types):
        minor = int(minor)

    if bugfix is None:
        bugfix = 0
    elif isinstance(bugfix, string_types):
        bugfix = int(bugfix)

    if rc is None:
        rc = 0
    elif isinstance(rc, string_types):
        rc = int(rc)

    if noc is None:
        noc = 0
    elif isinstance(noc, string_types):
        noc = int(noc)

    self.major = major
    self.minor = minor
    self.bugfix = bugfix
    self.rc = rc  # pylint: disable=C0103
    self.name = self.VNAMES.get((major, minor, bugfix, rc), None)
    self.noc = noc
    self.sha = sha
# Buggy code
def parse(cls, version_string):
    match = cls.git_describe_regex.match(version_string)
    if not match:
        raise ValueError("Unable to parse version string: {0!r}".format(version_string))
    return cls(*match.groups())


# 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 parse(cls, version_string):
    if version_string.lower() in cls.LNAMES:
        return cls.from_name(version_string)
    match = cls.git_describe_regex.match(version_string)
    if not match:
        raise ValueError("Unable to parse version string: {0!r}".format(version_string))
    return cls(*match.groups())
# Buggy code
def event(self, chunk_ret):
    """
    Fire an event on the master bus
    """
    if not self.opts.get("local") and self.opts.get("state_events", True):
        tag = salt.utils.event.tagify([self.jid, chunk_ret["__run_num__"]])
        self.functions["event.fire_master"](chunk_ret, tag)


# Traceback (TypeError)
Traceback (most recent call last):
File "/bin/salt-call", line 28, in <module>
sys.exit(salt.scripts.salt_call())
File "/src/salt/salt/scripts.py", line 77, in salt_call
client.run()
File "/src/salt/salt/cli/__init__.py", line 303, in run
caller.run()
File "/src/salt/salt/cli/caller.py", line 135, in run
ret = self.call()
File "/src/salt/salt/cli/caller.py", line 78, in call
ret['return'] = func(*args, **kwargs)
File "/src/salt/salt/modules/state.py", line 350, in sls
ret = st_.state.call_high(high_)
File "/src/salt/salt/state.py", line 1551, in call_high
ret = self.call_chunks(chunks)
File "/src/salt/salt/state.py", line 1283, in call_chunks
running = self.call_chunk(low, running, chunks)
File "/src/salt/salt/state.py", line 1525, in call_chunk
self.event(running[tag])
File "/src/salt/salt/state.py", line 1388, in event
tag = salt.utils.event.tagify([self.jid, chunk_ret['__run_num__']])
File "/src/salt/salt/utils/event.py", line 119, in tagify
return (TAGPARTER.join([part for part in parts if part]))
TypeError: sequence item 1: expected string, int found

# Fixed code
def event(self, chunk_ret):
    """
    Fire an event on the master bus
    """
    if not self.opts.get("local") and self.opts.get("state_events", True):
        tag = salt.utils.event.tagify([self.jid, str(chunk_ret["__run_num__"])])
        self.functions["event.fire_master"](chunk_ret, tag)
# Buggy code
def finalize_options(self):
    install.finalize_options(self)
    for optname in (
        "root_dir",
        "config_dir",
        "cache_dir",
        "sock_dir",
        "base_file_roots_dir",
        "base_pillar_roots_dir",
        "base_master_roots_dir",
        "logs_dir",
        "pidfile_dir",
    ):
        if not getattr(self, "salt_{0}".format(optname)):
            raise RuntimeError(
                "The value of --salt-{0} needs a proper path value".format(
                    optname.replace("_", "-")
                )
            )


# Traceback (AttributeError)
root@sgtpepper:/usr/local/src/salt# python setup.py install
0.16.0-2614-g45f816c
running install
running build
running build_py
running build_scripts
Traceback (most recent call last):
File "setup.py", line 408, in <module>
setup(**SETUP_KWARGS)
File "/usr/lib/python2.7/distutils/core.py", line 152, in setup
dist.run_commands()
File "/usr/lib/python2.7/distutils/dist.py", line 953, in run_commands
self.run_command(cmd)
File "/usr/lib/python2.7/distutils/dist.py", line 972, in run_command
cmd_obj.run()
File "setup.py", line 248, in run
install.run(self)
File "/usr/lib/python2.7/distutils/command/install.py", line 601, in run
self.run_command('build')
File "/usr/lib/python2.7/distutils/cmd.py", line 326, in run_command
self.distribution.run_command(command)
File "/usr/lib/python2.7/distutils/dist.py", line 972, in run_command
cmd_obj.run()
File "setup.py", line 180, in run
root_dir=self.salt_root_dir,
File "/usr/lib/python2.7/distutils/cmd.py", line 105, in __getattr__
raise AttributeError, attr
AttributeError: salt_root_dir

# Fixed code
def finalize_options(self):
    install.finalize_options(self)
    for optname in (
        "root_dir",
        "config_dir",
        "cache_dir",
        "sock_dir",
        "srv_root_dir",
        "base_file_roots_dir",
        "base_pillar_roots_dir",
        "base_master_roots_dir",
        "logs_dir",
        "pidfile_dir",
    ):
        optvalue = getattr(self, "salt_{0}".format(optname))
        if not optvalue:
            raise RuntimeError(
                "The value of --salt-{0} needs a proper path value".format(
                    optname.replace("_", "-")
                )
            )
        setattr(self.distribution, "salt_{0}".format(optname), optvalue)
# Buggy code
def _handle_aes(self, load):
    """
    Takes the AES encrypted load, decrypts it, and runs the encapsulated
    instructions
    """
    try:
        data = self.crypticle.loads(load)
    except AuthenticationError:
        self.authenticate()
        data = self.crypticle.loads(load)
    # Verify that the publication is valid
    if "tgt" not in data or "jid" not in data or "fun" not in data or "arg" not in data:
        return
    # Verify that the publication applies to this minion
    if "tgt_type" in data:
        if not getattr(self.matcher, "{0}_match".format(data["tgt_type"]))(data["tgt"]):
            return
    else:
        if not self.matcher.glob_match(data["tgt"]):
            return
    # If the minion does not have the function, don't execute,
    # this prevents minions that could not load a minion module
    # from returning a predictable exception
    # if data['fun'] not in self.functions:
    #    return
    if "user" in data:
        log.info(
            "User {0[user]} Executing command {0[fun]} with jid {0[jid]}".format(data)
        )
    else:
        log.info("Executing command {0[fun]} with jid {0[jid]}".format(data))
    log.debug("Command details {0}".format(data))
    self._handle_decoded_payload(data)


# Traceback (AttributeError)
2013-07-05 14:08:17,857 [salt.minion      ][CRITICAL] An exception occurred while polling the minion
Traceback (most recent call last):
File "/usr/lib/pymodules/python2.7/salt/minion.py", line 1013, in tune_in
self._handle_payload(payload)
File "/usr/lib/pymodules/python2.7/salt/minion.py", line 514, in _handle_payload
'clear': self._handle_clear}[payload['enc']](payload['load'])
File "/usr/lib/pymodules/python2.7/salt/minion.py", line 533, in _handle_aes
'{0}_match'.format(data['tgt_type']))(data['tgt']):
AttributeError: 'Matcher' object has no attribute 'user=www_match'

# Fixed code
def _handle_aes(self, load):
    """
    Takes the AES encrypted load, decrypts it, and runs the encapsulated
    instructions
    """
    try:
        data = self.crypticle.loads(load)
    except AuthenticationError:
        self.authenticate()
        data = self.crypticle.loads(load)
    # Verify that the publication is valid
    if "tgt" not in data or "jid" not in data or "fun" not in data or "arg" not in data:
        return
    # Verify that the publication applies to this minion
    if "tgt_type" in data:
        if not getattr(self.matcher, "{0}_match".format(data["tgt_type"]))(
            data["tgt"], False
        ):
            return
    else:
        if not self.matcher.glob_match(data["tgt"]):
            return
    # If the minion does not have the function, don't execute,
    # this prevents minions that could not load a minion module
    # from returning a predictable exception
    # if data['fun'] not in self.functions:
    #    return
    if "user" in data:
        log.info(
            "User {0[user]} Executing command {0[fun]} with jid {0[jid]}".format(data)
        )
    else:
        log.info("Executing command {0[fun]} with jid {0[jid]}".format(data))
    log.debug("Command details {0}".format(data))
    self._handle_decoded_payload(data)
# Buggy code
def doc(module=""):
    """
    Return the docstrings for all modules. Optionally, specify a module or a
    function to narrow the selection.

    The strings are aggregated into a single document on the master for easy
    reading.

    CLI Example::

        salt '*' sys.doc
        salt '*' sys.doc sys
        salt '*' sys.doc sys.doc
    """
    docs = {}
    if module:
        # allow both "sys" and "sys." to match sys, without also matching
        # sysctl
        target_mod = module + "." if not module.endswith(".") else module
    else:
        target_mod = ""
    for fun in __salt__:
        if fun == module or fun.startswith(target_mod):
            docs[fun] = __salt__[fun].__doc__
    return docs


# Traceback (TypeError)
$ sudo salt \* sys.doc test.ping  random_junk othercrap=morecrap
BDB2053 Freeing read locks for locker 0x30a6: 28087/139717077964736
BDB2053 Freeing read locks for locker 0x30a7: 28087/139717077964736
BDB2053 Freeing read locks for locker 0x30a8: 28087/139717077964736
BDB2053 Freeing read locks for locker 0x30a9: 28087/139717077964736
Traceback (most recent call last):
File "/bin/salt", line 10, in <module>
salt_main()
File "/usr/lib/python2.7/site-packages/salt/scripts.py", line 103, in salt_main
client.run()
File "/usr/lib/python2.7/site-packages/salt/cli/__init__.py", line 107, in run
self._output_ret(ret, out)
File "/usr/lib/python2.7/site-packages/salt/cli/__init__.py", line 125, in _output_ret
self._print_docs(ret)
File "/usr/lib/python2.7/site-packages/salt/cli/__init__.py", line 155, in _print_docs
if ret[host][fun]:
TypeError: string indices must be integers, not str
$

# Fixed code
def doc(*args, **kwargs):
    """
    Return the docstrings for all modules. Optionally, specify a module or a
    function to narrow the selection.

    The strings are aggregated into a single document on the master for easy
    reading.

    Multiple modules/functions can be specified.

    CLI Example::

        salt '*' sys.doc
        salt '*' sys.doc sys
        salt '*' sys.doc sys.doc
        salt '*' sys.doc network.traceroute user.info
    """
    ### NOTE: **kwargs is used here to prevent a traceback when garbage
    ###       arguments are tacked on to the end.
    docs = {}
    for module in args:
        if module:
            # allow both "sys" and "sys." to match sys, without also matching
            # sysctl
            target_mod = module + "." if not module.endswith(".") else module
        else:
            target_mod = ""
        for fun in __salt__:
            if fun == module or fun.startswith(target_mod):
                docs[fun] = __salt__[fun].__doc__
    return docs
# Buggy code
def list_functions(module=""):
    """
    List the functions for all modules. Optionally, specify a module to list
    from.

    CLI Example::

        salt '*' sys.list_functions
        salt '*' sys.list_functions sys
    """
    names = set()
    if module:
        # allow both "sys" and "sys." to match sys, without also matching
        # sysctl
        module = module + "." if not module.endswith(".") else module
    for func in __salt__:
        if func.startswith(module):
            names.add(func)
    return sorted(names)


# Traceback (TypeError)
$ sudo salt \* sys.doc test.ping  random_junk othercrap=morecrap
BDB2053 Freeing read locks for locker 0x30a6: 28087/139717077964736
BDB2053 Freeing read locks for locker 0x30a7: 28087/139717077964736
BDB2053 Freeing read locks for locker 0x30a8: 28087/139717077964736
BDB2053 Freeing read locks for locker 0x30a9: 28087/139717077964736
Traceback (most recent call last):
File "/bin/salt", line 10, in <module>
salt_main()
File "/usr/lib/python2.7/site-packages/salt/scripts.py", line 103, in salt_main
client.run()
File "/usr/lib/python2.7/site-packages/salt/cli/__init__.py", line 107, in run
self._output_ret(ret, out)
File "/usr/lib/python2.7/site-packages/salt/cli/__init__.py", line 125, in _output_ret
self._print_docs(ret)
File "/usr/lib/python2.7/site-packages/salt/cli/__init__.py", line 155, in _print_docs
if ret[host][fun]:
TypeError: string indices must be integers, not str
$

# Fixed code
def list_functions(*args, **kwargs):
    """
    List the functions for all modules. Optionally, specify a module or modules
    from which to list.

    CLI Example::

        salt '*' sys.list_functions
        salt '*' sys.list_functions sys
        salt '*' sys.list_functions sys user
    """
    ### NOTE: **kwargs is used here to prevent a traceback when garbage
    ###       arguments are tacked on to the end.
    names = set()
    for module in args:
        if module:
            # allow both "sys" and "sys." to match sys, without also matching
            # sysctl
            module = module + "." if not module.endswith(".") else module
        for func in __salt__:
            if func.startswith(module):
                names.add(func)
    return sorted(names)
# Buggy code
def list_functions(*args, **kwargs):
    """
    List the functions for all modules. Optionally, specify a module or modules
    from which to list.

    CLI Example::

        salt '*' sys.list_functions
        salt '*' sys.list_functions sys
        salt '*' sys.list_functions sys user
    """
    ### NOTE: **kwargs is used here to prevent a traceback when garbage
    ###       arguments are tacked on to the end.
    names = set()
    for module in args:
        if module:
            # allow both "sys" and "sys." to match sys, without also matching
            # sysctl
            module = module + "." if not module.endswith(".") else module
        for func in __salt__:
            if func.startswith(module):
                names.add(func)
    return sorted(names)


# Traceback (TypeError)
$ sudo salt \* sys.doc test.ping  random_junk othercrap=morecrap
BDB2053 Freeing read locks for locker 0x30a6: 28087/139717077964736
BDB2053 Freeing read locks for locker 0x30a7: 28087/139717077964736
BDB2053 Freeing read locks for locker 0x30a8: 28087/139717077964736
BDB2053 Freeing read locks for locker 0x30a9: 28087/139717077964736
Traceback (most recent call last):
File "/bin/salt", line 10, in <module>
salt_main()
File "/usr/lib/python2.7/site-packages/salt/scripts.py", line 103, in salt_main
client.run()
File "/usr/lib/python2.7/site-packages/salt/cli/__init__.py", line 107, in run
self._output_ret(ret, out)
File "/usr/lib/python2.7/site-packages/salt/cli/__init__.py", line 125, in _output_ret
self._print_docs(ret)
File "/usr/lib/python2.7/site-packages/salt/cli/__init__.py", line 155, in _print_docs
if ret[host][fun]:
TypeError: string indices must be integers, not str
$

# Fixed code
def list_functions(*args, **kwargs):
    """
    List the functions for all modules. Optionally, specify a module or modules
    from which to list.

    CLI Example::

        salt '*' sys.list_functions
        salt '*' sys.list_functions sys
        salt '*' sys.list_functions sys user
    """
    ### NOTE: **kwargs is used here to prevent a traceback when garbage
    ###       arguments are tacked on to the end.

    if not args:
        # We're being asked for all functions
        return sorted(__salt__)

    names = set()
    for module in args:
        if module:
            # allow both "sys" and "sys." to match sys, without also matching
            # sysctl
            module = module + "." if not module.endswith(".") else module
        for func in __salt__:
            if func.startswith(module):
                names.add(func)
    return sorted(names)
# Buggy code
def _pecl(command):
    """
    Execute the command passed with pecl
    """
    cmdline = "pecl {0}".format(command)

    ret = __salt__["cmd.run_all"](cmdline)

    if ret["retcode"] == 0:
        return ret["stdout"]
    else:
        return False


# Traceback (AttributeError)
local:
----------
State: - pecl
Name:      memcached
Function:  installed
Result:    False
Comment:   An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib/pymodules/python2.6/salt/state.py", line 1203, in call
ret = self.states[cdata['full']](*cdata['args'])
File "/usr/lib/pymodules/python2.6/salt/states/pecl.py", line 33, in installed
installed_pecls = __salt__['pecl.list']()
File "/usr/lib/pymodules/python2.6/salt/modules/pecl.py", line 78, in list
lines = _pecl('list').splitlines()
AttributeError: 'bool' object has no attribute 'splitlines'

Changes:


State file:
memcached:
pecl.installed

# Fixed code
def _pecl(command):
    """
    Execute the command passed with pecl
    """
    cmdline = "pecl {0}".format(command)

    ret = __salt__["cmd.run_all"](cmdline)

    if ret["retcode"] == 0:
        return ret["stdout"]
    else:
        return ""
# Buggy code
def master_config(path, env_var="SALT_MASTER_CONFIG", defaults=None):
    """
    Reads in the master configuration file and sets up default options
    """
    if defaults is None:
        defaults = DEFAULT_MASTER_OPTS

    overrides = load_config(path, env_var)
    default_include = overrides.get("default_include", defaults["default_include"])
    include = overrides.get("include", [])

    overrides.update(include_config(default_include, path, verbose=False))
    overrides.update(include_config(include, path, verbose=True))
    opts = apply_master_config(overrides, defaults)
    _validate_opts(opts)
    return opts


# Traceback (TypeError)
(saltdev)[root@virtucentos saltdev]# salt -c etc/salt -N www test.ping
Traceback (most recent call last):
File "/home/erik/saltdev/bin/salt", line 8, in <module>
load_entry_point('salt==0.15.0-1262-g16bcbee', 'console_scripts', 'salt')()
File "/home/erik/salt/salt/scripts.py", line 103, in salt_main
client.run()
File "/home/erik/salt/salt/cli/__init__.py", line 117, in run
for full_ret in cmd_func(**kwargs):
File "/home/erik/salt/salt/client.py", line 357, in cmd_cli
**kwargs)
File "/home/erik/salt/salt/client.py", line 213, in run_job
**kwargs)
File "/home/erik/salt/salt/client.py", line 1005, in pub
if tgt not in self.opts['nodegroups']:
TypeError: argument of type 'NoneType' is not iterable

# Fixed code
def master_config(path, env_var="SALT_MASTER_CONFIG", defaults=None):
    """
    Reads in the master configuration file and sets up default options
    """
    if defaults is None:
        defaults = DEFAULT_MASTER_OPTS

    overrides = load_config(path, env_var)
    default_include = overrides.get("default_include", defaults["default_include"])
    include = overrides.get("include", [])

    overrides.update(include_config(default_include, path, verbose=False))
    overrides.update(include_config(include, path, verbose=True))
    opts = apply_master_config(overrides, defaults)
    _validate_opts(opts)
    # If 'nodegroups:' is uncommented in the master config file, and there are
    # no nodegroups defined, opts['nodegroups'] will be None. Fix this by
    # reverting this value to the default, as if 'nodegroups:' was commented
    # out or not present.
    if opts.get("nodegroups") is None:
        opts["nodegroups"] = DEFAULT_MASTER_OPTS.get("nodegroups", {})
    return opts
# Buggy code
def _get_msi_software():
    """
    This searches the msi product databases and returns a dict keyed
    on the product name and all the product properties in another dict
    """
    win32_products = {}
    this_computer = "."
    wmi_service = win32com.client.Dispatch("WbemScripting.SWbemLocator")
    swbem_services = wmi_service.ConnectServer(this_computer, "root\\cimv2")
    products = swbem_services.ExecQuery("Select * from Win32_Product")
    for product in products:
        prd_name = product.Name.encode("ascii", "ignore")
        prd_ver = product.Version.encode("ascii", "ignore")
        win32_products[prd_name] = prd_ver
    return win32_products


# Traceback (com_error)
djs-admin@master:~$ sudo salt 'windows.*' pkg.list_pkgs
windows:
Traceback (most recent call last):
File "salt/minion.py", line 443, in _thread_return
File "salt/modules/win_pkg.py", line 214, in list_pkgs
File "salt/modules/win_pkg.py", line 251, in _get_msi_software
File "win32com/client/util.py", line 84, in next
com_error: (-2147217392, 'OLE error 0x80041010', None, None)

# Fixed code
def _get_msi_software():
    """
    This searches the msi product databases and returns a dict keyed
    on the product name and all the product properties in another dict
    """
    win32_products = {}
    this_computer = "."
    wmi_service = win32com.client.Dispatch("WbemScripting.SWbemLocator")
    swbem_services = wmi_service.ConnectServer(this_computer, "root\\cimv2")
    products = swbem_services.ExecQuery("Select * from Win32_Product")
    for product in products:
        try:
            prd_name = product.Name.encode("ascii", "ignore")
            prd_ver = product.Version.encode("ascii", "ignore")
            win32_products[prd_name] = prd_ver
        except Exception:
            pass
    return win32_products