gurudesh/pytracebugs huggingface dataset:
# Buggy code
def _key_deploy_run(self, host, target, re_run=True):
    """
    The ssh-copy-id routine
    """
    arg_str = "ssh.set_auth_key {0} {1}".format(
        target.get("user", "root"), self.get_pubkey()
    )
    single = Single(self.opts, arg_str, host, **target)
    if salt.utils.which("ssh-copy-id"):
        # we have ssh-copy-id, use it!
        single.shell.copy_id()
    else:
        ret = single.cmd_block()
        if ret[0].startswith("deploy"):
            single.deploy()
            ret = single.cmd_block()
    if re_run:
        target.pop("passwd")
        single = Single(self.opts, self.opts["arg_str"], host, **target)
        stdout, stderr = single.cmd_block()
        try:
            data = json.loads(stdout)
            return {host: data.get("local", data)}
        except Exception:
            if stderr:
                return {host: stderr}
            return {host: "Bad Return"}


# 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 _key_deploy_run(self, host, target, re_run=True):
    """
    The ssh-copy-id routine
    """
    arg_str = "ssh.set_auth_key {0} {1}".format(
        target.get("user", "root"), self.get_pubkey()
    )

    single = Single(self.opts, arg_str, host, **target)
    if salt.utils.which("ssh-copy-id"):
        # we have ssh-copy-id, use it!
        single.shell.copy_id()
    else:
        ret = single.run()
    if re_run:
        target.pop("passwd")
        single = Single(self.opts, self.opts["arg_str"], host, **target)
        stdout, stderr = single.cmd_block()
        try:
            data = json.loads(stdout)
            return {host: data.get("local", data)}
        except Exception:
            if stderr:
                return {host: stderr}
            return {host: "Bad Return"}
# Buggy code
def cmd_block(self):
    """
    Prepare the precheck command to send to the subsystem
    """
    # 1. check if python is on the target
    # 2. check is salt-call is on the target
    # 3. deploy salt-thin
    # 4. execute command
    sudo = "sudo" if self.target["sudo"] else ""
    cmd = SSH_SHIM.format(sudo, self.arg_str)
    stdout, stderr = self.shell.exec_cmd(cmd)
    if RSTR in stdout:
        stdout = stdout.split(RSTR)[1].strip()
    if stdout.startswith("deploy"):
        self.deploy()
        stdout, stderr = self.shell.exec_cmd(cmd)
        if RSTR in stdout:
            stdout = stdout.split(RSTR)[1].strip()
    return stdout, stderr


# 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 cmd_block(self, is_retry=False):
    """
    Prepare the precheck command to send to the subsystem
    """
    # 1. check if python is on the target
    # 2. check is salt-call is on the target
    # 3. deploy salt-thin
    # 4. execute command
    sudo = "sudo" if self.target["sudo"] else ""
    cmd = SSH_SHIM.format(sudo, self.arg_str)
    log.debug("Performing shimmed command as follows:\n{0}".format(cmd))
    stdout, stderr = self.shell.exec_cmd(cmd)

    log.debug("STDOUT {1}\n{0}".format(stdout, self.target["host"]))
    log.debug("STDERR {1}\n{0}".format(stderr, self.target["host"]))

    error = self.categorize_shim_errors(stdout, stderr)
    if error:
        return "ERROR: {0}".format(error), stderr

    if RSTR in stdout:
        stdout = stdout.split(RSTR)[1].strip()

    return stdout, stderr
# Buggy code
def _cmd_str(self, cmd, ssh="ssh"):
    """
    Return the cmd string to execute
    """

    # TODO: if tty, then our SSH_SHIM cannot be supplied from STDIN Will
    # need to deliver the SHIM to the remote host and execute it there

    if self.passwd and salt.utils.which("sshpass"):
        opts = self._passwd_opts()
        return 'sshpass -p "{0}" {1} {2} {3} {4} {5}'.format(
            self.passwd,
            ssh,
            "" if ssh == "scp" else self.host,
            "-t -t" if self.tty else "",
            opts,
            cmd,
        )
    if self.priv:
        opts = self._key_opts()
        return "{0} {1} {2} {3} {4}".format(
            ssh,
            "" if ssh == "scp" else self.host,
            "-t -t" if self.tty else "",
            opts,
            cmd,
        )
    return 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 _cmd_str(self, cmd, ssh="ssh"):
    """
    Return the cmd string to execute
    """

    # TODO: if tty, then our SSH_SHIM cannot be supplied from STDIN Will
    # need to deliver the SHIM to the remote host and execute it there

    if self.passwd and salt.utils.which("sshpass"):
        opts = self._passwd_opts()
        return "sshpass -p '{0}' {1} {2} {3} {4} '{5}'".format(
            self.passwd,
            ssh,
            "" if ssh == "scp" else self.host,
            "-t -t" if self.tty else "",
            opts,
            cmd,
        )
    if self.priv:
        opts = self._key_opts()
        return "{0} {1} {2} {3} '{4}'".format(
            ssh,
            "" if ssh == "scp" else self.host,
            "-t -t" if self.tty else "",
            opts,
            cmd,
        )
    return None
# Buggy code
def init():
    """
    Return the git repo object for this session
    """
    bp_ = os.path.join(__opts__["cachedir"], "gitfs")
    repos = []
    for ind, opt in enumerate(__opts__["gitfs_remotes"]):
        rp_ = os.path.join(bp_, str(ind))
        if not os.path.isdir(rp_):
            os.makedirs(rp_)
        repo = git.Repo.init(rp_)
        if not repo.remotes:
            try:
                repo.create_remote("origin", opt)
            except Exception:
                # This exception occurs when two processes are trying to write
                # to the git config at once, go ahead and pass over it since
                # this is the only write
                # This should place a lock down
                pass
        if repo.remotes:
            repos.append(repo)
    return repos


# 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():
    """
    Return the git repo object for this session
    """
    bp_ = os.path.join(__opts__["cachedir"], "gitfs")
    repos = []
    for _, opt in enumerate(__opts__["gitfs_remotes"]):
        repo_hash = hashlib.md5(opt).hexdigest()
        rp_ = os.path.join(bp_, repo_hash)
        if not os.path.isdir(rp_):
            os.makedirs(rp_)
        repo = git.Repo.init(rp_)
        if not repo.remotes:
            try:
                repo.create_remote("origin", opt)
            except Exception:
                # This exception occurs when two processes are trying to write
                # to the git config at once, go ahead and pass over it since
                # this is the only write
                # This should place a lock down
                pass
        if repo.remotes:
            repos.append(repo)
    return repos
# Buggy code
def update():
    """
    Execute a git pull on all of the repos
    """
    # data for the fileserver event
    data = {"changed": False, "backend": "gitfs"}
    pid = os.getpid()
    repos = init()
    for repo in repos:
        origin = repo.remotes[0]
        lk_fn = os.path.join(repo.working_dir, "update.lk")
        with salt.utils.fopen(lk_fn, "w+") as fp_:
            fp_.write(str(pid))
        try:
            for fetch in origin.fetch():
                if fetch.old_commit is not None:
                    data["changed"] = True
        except Exception as exc:
            log.warning("GitPython exception caught while fetching: {0}".format(exc))
        try:
            os.remove(lk_fn)
        except (IOError, OSError):
            pass

    # if there is a change, fire an event
    event = salt.utils.event.MasterEvent(__opts__["sock_dir"])
    event.fire_event(data, tagify(["gitfs", "update"], prefix="fileserver"))
    try:
        salt.fileserver.reap_fileserver_cache_dir(
            os.path.join(__opts__["cachedir"], "gitfs/hash"), find_file
        )
    except (IOError, OSError):
        # Hash file won't exist if no files have yet been served up
        pass


# 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():
    """
    Execute a git pull on all of the repos
    """
    # data for the fileserver event
    data = {"changed": False, "backend": "gitfs"}
    pid = os.getpid()
    data["changed"] = purge_cache()
    repos = init()
    for repo in repos:
        origin = repo.remotes[0]
        lk_fn = os.path.join(repo.working_dir, "update.lk")
        with salt.utils.fopen(lk_fn, "w+") as fp_:
            fp_.write(str(pid))
        try:
            for fetch in origin.fetch():
                if fetch.old_commit is not None:
                    data["changed"] = True
        except Exception as exc:
            log.warning("GitPython exception caught while fetching: {0}".format(exc))
        try:
            os.remove(lk_fn)
        except (IOError, OSError):
            pass

    # if there is a change, fire an event
    event = salt.utils.event.MasterEvent(__opts__["sock_dir"])
    event.fire_event(data, tagify(["gitfs", "update"], prefix="fileserver"))
    try:
        salt.fileserver.reap_fileserver_cache_dir(
            os.path.join(__opts__["cachedir"], "gitfs/hash"), find_file
        )
    except (IOError, OSError):
        # Hash file won't exist if no files have yet been served up
        pass
# Buggy code
def accept_all(self):
    """
    Accept all keys
    """
    self.accept("*", include_rejected=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 accept_all(self, include_rejected=False):
    """
    Accept all keys
    """
    self.accept("*", include_rejected=include_rejected)
# Buggy code
def reject_all(self):
    """
    Reject all keys
    """
    self.reject("*", include_accepted=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 reject_all(self, include_accepted=False):
    """
    Reject all keys
    """
    self.reject("*", include_accepted=include_accepted)
# Buggy code
def run(self):
    """
    Run the logic for saltkey
    """
    if self.opts["gen_keys"]:
        salt.crypt.gen_keys(
            self.opts["gen_keys_dir"], self.opts["gen_keys"], self.opts["keysize"]
        )
        return
    if self.opts["list"]:
        self.list_status(self.opts["list"])
    elif self.opts["list_all"]:
        self.list_all()
    elif self.opts["print"]:
        self.print_key(self.opts["print"])
    elif self.opts["print_all"]:
        self.print_all()
    elif self.opts["accept"]:
        self.accept(self.opts["accept"], include_rejected=self.opts["include_all"])
    elif self.opts["accept_all"]:
        self.accept_all()
    elif self.opts["reject"]:
        self.reject(self.opts["reject"], include_accepted=self.opts["include_all"])
    elif self.opts["reject_all"]:
        self.reject_all()
    elif self.opts["delete"]:
        self.delete(self.opts["delete"])
    elif self.opts["delete_all"]:
        self.delete_all()
    elif self.opts["finger"]:
        self.finger(self.opts["finger"])
    elif self.opts["finger_all"]:
        self.finger_all()
    else:
        self.list_all()


# 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):
    """
    Run the logic for saltkey
    """
    if self.opts["gen_keys"]:
        salt.crypt.gen_keys(
            self.opts["gen_keys_dir"], self.opts["gen_keys"], self.opts["keysize"]
        )
        return
    if self.opts["list"]:
        self.list_status(self.opts["list"])
    elif self.opts["list_all"]:
        self.list_all()
    elif self.opts["print"]:
        self.print_key(self.opts["print"])
    elif self.opts["print_all"]:
        self.print_all()
    elif self.opts["accept"]:
        self.accept(self.opts["accept"], include_rejected=self.opts["include_all"])
    elif self.opts["accept_all"]:
        self.accept_all(include_rejected=self.opts["include_all"])
    elif self.opts["reject"]:
        self.reject(self.opts["reject"], include_accepted=self.opts["include_all"])
    elif self.opts["reject_all"]:
        self.reject_all(include_accepted=self.opts["include_all"])
    elif self.opts["delete"]:
        self.delete(self.opts["delete"])
    elif self.opts["delete_all"]:
        self.delete_all()
    elif self.opts["finger"]:
        self.finger(self.opts["finger"])
    elif self.opts["finger_all"]:
        self.finger_all()
    else:
        self.list_all()
# Buggy code
def accept(self, match, include_rejected=False):
    """
    Accept a specified host's public key based on name or keys based on
    glob
    """
    matches = self.name_match(match)
    keydirs = ["minions_pre"]
    if include_rejected:
        keydirs.append("minions_rejected")
    for keydir in keydirs:
        for key in matches.get(keydir, []):
            try:
                shutil.move(
                    os.path.join(self.opts["pki_dir"], keydir, key),
                    os.path.join(self.opts["pki_dir"], "minions", key),
                )
                eload = {"result": True, "act": "accept", "id": key}
                self.event.fire_event(eload, tagify(prefix="key"))
            except (IOError, OSError):
                pass
    return self.name_match(match)


# 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 accept(self, match=None, match_dict=None, include_rejected=False):
    """
    Accept public keys. If "match" is passed, it is evaluated as a glob.
    Pre-gathered matches can also be passed via "match_dict".
    """
    if match is not None:
        matches = self.name_match(match)
    elif match_dict is not None and isinstance(match_dict, dict):
        matches = match_dict
    else:
        matches = {}
    keydirs = ["minions_pre"]
    if include_rejected:
        keydirs.append("minions_rejected")
    for keydir in keydirs:
        for key in matches.get(keydir, []):
            try:
                shutil.move(
                    os.path.join(self.opts["pki_dir"], keydir, key),
                    os.path.join(self.opts["pki_dir"], "minions", key),
                )
                eload = {"result": True, "act": "accept", "id": key}
                self.event.fire_event(eload, tagify(prefix="key"))
            except (IOError, OSError):
                pass
    return self.name_match(match) if match is not None else self.dict_match(matches)
# Buggy code
def delete_key(self, match):
    """
    Delete a single key or keys by glob
    """
    for status, keys in self.name_match(match).items():
        for key in keys:
            try:
                os.remove(os.path.join(self.opts["pki_dir"], status, key))
                eload = {"result": True, "act": "delete", "id": key}
                self.event.fire_event(eload, tagify(prefix="key"))
            except (OSError, IOError):
                pass
    self.check_minion_cache()
    salt.crypt.dropfile(self.opts["cachedir"], self.opts["user"])
    return self.list_keys()


# 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 delete_key(self, match=None, match_dict=None):
    """
    Delete public keys. If "match" is passed, it is evaluated as a glob.
    Pre-gathered matches can also be passed via "match_dict".
    """
    if match is not None:
        matches = self.name_match(match)
    elif match_dict is not None and isinstance(match_dict, dict):
        matches = match_dict
    else:
        matches = {}
    for status, keys in matches.items():
        for key in keys:
            try:
                os.remove(os.path.join(self.opts["pki_dir"], status, key))
                eload = {"result": True, "act": "delete", "id": key}
                self.event.fire_event(eload, tagify(prefix="key"))
            except (OSError, IOError):
                pass
    self.check_minion_cache()
    salt.crypt.dropfile(self.opts["cachedir"], self.opts["user"])
    return self.name_match(match) if match is not None else self.dict_match(matches)
# Buggy code
def reject(self, match, include_accepted=False):
    """
    Reject a specified host's public key or keys based on a glob
    """
    matches = self.name_match(match)
    keydirs = ["minions_pre"]
    if include_accepted:
        keydirs.append("minions")
    for keydir in keydirs:
        for key in matches.get(keydir, []):
            try:
                shutil.move(
                    os.path.join(self.opts["pki_dir"], keydir, key),
                    os.path.join(self.opts["pki_dir"], "minions_rejected", key),
                )
                eload = {"result": True, "act": "reject", "id": key}
                self.event.fire_event(eload, tagify(prefix="key"))
            except (IOError, OSError):
                pass
    self.check_minion_cache()
    salt.crypt.dropfile(self.opts["cachedir"], self.opts["user"])
    return self.name_match(match)


# 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 reject(self, match=None, match_dict=None, include_accepted=False):
    """
    Reject public keys. If "match" is passed, it is evaluated as a glob.
    Pre-gathered matches can also be passed via "match_dict".
    """
    if match is not None:
        matches = self.name_match(match)
    elif match_dict is not None and isinstance(match_dict, dict):
        matches = match_dict
    else:
        matches = {}
    keydirs = ["minions_pre"]
    if include_accepted:
        keydirs.append("minions")
    for keydir in keydirs:
        for key in matches.get(keydir, []):
            try:
                shutil.move(
                    os.path.join(self.opts["pki_dir"], keydir, key),
                    os.path.join(self.opts["pki_dir"], "minions_rejected", key),
                )
                eload = {"result": True, "act": "reject", "id": key}
                self.event.fire_event(eload, tagify(prefix="key"))
            except (IOError, OSError):
                pass
    self.check_minion_cache()
    salt.crypt.dropfile(self.opts["cachedir"], self.opts["user"])
    return self.name_match(match) if match is not None else self.dict_match(matches)
# Buggy code
def __load_modules(self):
    """
    Return the functions and the returners loaded up from the loader
    module
    """
    self.opts["grains"] = salt.loader.grains(self.opts)
    functions = salt.loader.minion_mods(self.opts)
    returners = salt.loader.returners(self.opts, functions)
    return functions, returners


# 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_modules(self):
    """
    Return the functions and the returners loaded up from the loader
    module
    """
    # if this is a *nix system AND modules_max_memory is set, lets enforce
    # a memory limit on module imports
    # this feature ONLY works on *nix like OSs (resource module doesn't work on windows)
    modules_max_memory = False
    if self.opts.get("modules_max_memory", -1) > 0 and HAS_PSUTIL and HAS_RESOURCE:
        log.debug(
            "modules_max_memory set, enforcing a maximum of {0}".format(
                self.opts["modules_max_memory"]
            )
        )
        modules_max_memory = True
        old_mem_limit = resource.getrlimit(resource.RLIMIT_AS)
        rss, vms = psutil.Process(os.getpid()).get_memory_info()
        mem_limit = rss + vms + self.opts["modules_max_memory"]
        resource.setrlimit(resource.RLIMIT_AS, (mem_limit, mem_limit))
    elif self.opts.get("modules_max_memory", -1) > 0:
        if not HAS_PSUTIL:
            log.error("Unable to enforce modules_max_memory because psutil is missing")
        if not HAS_RESOURCE:
            log.error(
                "Unable to enforce modules_max_memory because resource is missing"
            )

    self.opts["grains"] = salt.loader.grains(self.opts)
    functions = salt.loader.minion_mods(self.opts)
    returners = salt.loader.returners(self.opts, functions)

    # we're done, reset the limits!
    if modules_max_memory is True:
        resource.setrlimit(resource.RLIMIT_AS, old_mem_limit)

    return functions, returners
# Buggy code
def _lstrip_word(string, prefix):
    """
    Return a copy of the string after the specified prefix was removed
    from the beginning of the string
    """

    if string.startswith(prefix):
        return string[len(prefix) :]
    return string


# 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 _lstrip_word(word, prefix):
    """
    Return a copy of the string after the specified prefix was removed
    from the beginning of the string
    """

    if str(word).startswith(prefix):
        return str(word)[len(prefix) :]
    return word
# Buggy code
def _get_django_admin(bin_env):
    """
    Return the django admin
    """
    if not bin_env:
        return "django-admin.py"

    # try to get django-admin.py bin from env
    if os.path.exists(os.path.join(bin_env, "bin", "django-admin.py")):
        return os.path.join(bin_env, "bin", "django-admin.py")
    return bin_env


# 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 _get_django_admin(bin_env):
    """
    Return the django admin
    """
    if not bin_env:
        if salt.utils.which("django-admin.py"):
            return "django-admin.py"
        elif salt.utils.which("django-admin"):
            return "django-admin"
        else:
            raise salt.exceptions.CommandExecutionError(
                "django-admin or django-admin.py not found on PATH"
            )

    # try to get django-admin.py bin from env
    if os.path.exists(os.path.join(bin_env, "bin", "django-admin.py")):
        return os.path.join(bin_env, "bin", "django-admin.py")
    return bin_env
# Buggy code
def fire_master(data, tag):
    """
    Fire an event off up to the master server

    CLI Example:

    .. code-block:: bash

        salt '*' event.fire_master 'stuff to be in the event' 'tag'
    """
    load = {"id": __opts__["id"], "tag": tag, "data": data, "cmd": "_minion_event"}
    auth = salt.crypt.SAuth(__opts__)
    sreq = salt.payload.SREQ(__opts__["master_uri"])
    try:
        sreq.send("aes", 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(data, tag, preload=None):
    """
    Fire an event off up to the master server

    CLI Example:

    .. code-block:: bash

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

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

    auth = salt.crypt.SAuth(__opts__)
    sreq = salt.payload.SREQ(__opts__["master_uri"])
    try:
        sreq.send("aes", auth.crypticle.dumps(load))
    except Exception:
        pass
    return True
# Buggy code
def sed_contains(path, text, limit="", flags="g"):
    """
    .. deprecated:: 0.17
       Use :func:`search` instead.

    Return True if the file at ``path`` contains ``text``. Utilizes sed to
    perform the search (line-wise search).

    Note: the ``p`` flag will be added to any flags you pass in.

    CLI Example:

    .. code-block:: bash

        salt '*' file.contains /etc/crontab 'mymaintenance.sh'
    """
    # Largely inspired by Fabric's contrib.files.contains()

    if not os.path.exists(path):
        return False

    before = _sed_esc(str(text), False)
    limit = _sed_esc(str(limit), False)
    options = "-n -r -e"
    if sys.platform == "darwin":
        options = options.replace("-r", "-E")

    cmd = r"sed {options} '{limit}s/{before}/$/{flags}' {path}".format(
        options=options,
        limit="/{0}/ ".format(limit) if limit else "",
        before=before,
        flags="p{0}".format(flags),
        path=path,
    )

    result = __salt__["cmd.run"](cmd)

    return bool(result)


# 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 sed_contains(path, text, limit="", flags="g"):
    """
    .. deprecated:: 0.17.0
       Use :func:`search` instead.

    Return True if the file at ``path`` contains ``text``. Utilizes sed to
    perform the search (line-wise search).

    Note: the ``p`` flag will be added to any flags you pass in.

    CLI Example:

    .. code-block:: bash

        salt '*' file.contains /etc/crontab 'mymaintenance.sh'
    """
    # Largely inspired by Fabric's contrib.files.contains()

    if not os.path.exists(path):
        return False

    before = _sed_esc(str(text), False)
    limit = _sed_esc(str(limit), False)
    options = "-n -r -e"
    if sys.platform == "darwin":
        options = options.replace("-r", "-E")

    cmd = r"sed {options} '{limit}s/{before}/$/{flags}' {path}".format(
        options=options,
        limit="/{0}/ ".format(limit) if limit else "",
        before=before,
        flags="p{0}".format(flags),
        path=path,
    )

    result = __salt__["cmd.run"](cmd)

    return bool(result)
# Buggy code
def uncomment(path, regex, char="#", backup=".bak"):
    """
    .. deprecated:: 0.17
       Use :py:func:`~salt.modules.file.replace` instead.

    Uncomment specified commented lines in a file

    path
        The full path to the file to be edited
    regex
        A regular expression used to find the lines that are to be uncommented.
        This regex should not include the comment character. A leading ``^``
        character will be stripped for convenience (for easily switching
        between comment() and uncomment()).
    char : ``#``
        The character to remove in order to uncomment a line
    backup : ``.bak``
        The file will be backed up before edit with this file extension;
        **WARNING:** each time ``sed``/``comment``/``uncomment`` is called will
        overwrite this backup

    CLI Example:

    .. code-block:: bash

        salt '*' file.uncomment /etc/hosts.deny 'ALL: PARANOID'
    """
    # Largely inspired by Fabric's contrib.files.uncomment()

    return sed(
        path,
        before=r"^([[:space:]]*){0}".format(char),
        after=r"\1",
        limit=regex.lstrip("^"),
        backup=backup,
    )


# 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 uncomment(path, regex, char="#", backup=".bak"):
    """
    .. deprecated:: 0.17.0
       Use :py:func:`~salt.modules.file.replace` instead.

    Uncomment specified commented lines in a file

    path
        The full path to the file to be edited
    regex
        A regular expression used to find the lines that are to be uncommented.
        This regex should not include the comment character. A leading ``^``
        character will be stripped for convenience (for easily switching
        between comment() and uncomment()).
    char : ``#``
        The character to remove in order to uncomment a line
    backup : ``.bak``
        The file will be backed up before edit with this file extension;
        **WARNING:** each time ``sed``/``comment``/``uncomment`` is called will
        overwrite this backup

    CLI Example:

    .. code-block:: bash

        salt '*' file.uncomment /etc/hosts.deny 'ALL: PARANOID'
    """
    # Largely inspired by Fabric's contrib.files.uncomment()

    return sed(
        path,
        before=r"^([[:space:]]*){0}".format(char),
        after=r"\1",
        limit=regex.lstrip("^"),
        backup=backup,
    )
# Buggy code
def search(
    path,
    pattern,
    flags=0,
    bufsize=1,
):
    """
    Search for occurances of a pattern in a file

    .. versionadded:: 0.17

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

    CLI Example:

    .. code-block:: bash

        salt '*' file.search /etc/crontab 'mymaintenance.sh'
    """
    # This function wraps file.replace on purpose in order to enforce
    # consistent usage, compatible regex's, expected behavior, *and* bugs. :)
    # Any enhancements or fixes to one should affect the other.
    return replace(
        path,
        pattern,
        "",
        flags=flags,
        bufsize=bufsize,
        dry_run=True,
        search_only=True,
        show_changes=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 search(
    path,
    pattern,
    flags=0,
    bufsize=1,
):
    """
    Search for occurances of a pattern in a file

    .. versionadded:: 0.17.0

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

    CLI Example:

    .. code-block:: bash

        salt '*' file.search /etc/crontab 'mymaintenance.sh'
    """
    # This function wraps file.replace on purpose in order to enforce
    # consistent usage, compatible regex's, expected behavior, *and* bugs. :)
    # Any enhancements or fixes to one should affect the other.
    return replace(
        path,
        pattern,
        "",
        flags=flags,
        bufsize=bufsize,
        dry_run=True,
        search_only=True,
        show_changes=False,
    )
# Buggy code
def contains(path, text):
    """
    .. deprecated:: 0.17
       Use :func:`search` instead.

    Return ``True`` if the file at ``path`` contains ``text``

    CLI Example:

    .. code-block:: bash

        salt '*' file.contains /etc/crontab 'mymaintenance.sh'
    """
    if not os.path.exists(path):
        return False

    stripped_text = str(text).strip()
    try:
        with salt.utils.filebuffer.BufferedReader(path) as breader:
            for chunk in breader:
                if stripped_text in chunk:
                    return True
        return False
    except (IOError, OSError):
        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 contains(path, text):
    """
    .. deprecated:: 0.17.0
       Use :func:`search` instead.

    Return ``True`` if the file at ``path`` contains ``text``

    CLI Example:

    .. code-block:: bash

        salt '*' file.contains /etc/crontab 'mymaintenance.sh'
    """
    if not os.path.exists(path):
        return False

    stripped_text = str(text).strip()
    try:
        with salt.utils.filebuffer.BufferedReader(path) as breader:
            for chunk in breader:
                if stripped_text in chunk:
                    return True
        return False
    except (IOError, OSError):
        return False
# Buggy code
def contains_regex(path, regex, lchar=""):
    """
    .. deprecated:: 0.17
       Use :func:`search` instead.

    Return True if the given regular expression matches on any line in the text
    of a given file.

    If the lchar argument (leading char) is specified, it
    will strip `lchar` from the left side of each line before trying to match

    CLI Example:

    .. code-block:: bash

        salt '*' file.contains_regex /etc/crontab
    """
    if not os.path.exists(path):
        return False

    try:
        with salt.utils.fopen(path, "r") as target:
            for line in target:
                if lchar:
                    line = line.lstrip(lchar)
                if re.search(regex, line):
                    return True
            return False
    except (IOError, OSError):
        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 contains_regex(path, regex, lchar=""):
    """
    .. deprecated:: 0.17.0
       Use :func:`search` instead.

    Return True if the given regular expression matches on any line in the text
    of a given file.

    If the lchar argument (leading char) is specified, it
    will strip `lchar` from the left side of each line before trying to match

    CLI Example:

    .. code-block:: bash

        salt '*' file.contains_regex /etc/crontab
    """
    if not os.path.exists(path):
        return False

    try:
        with salt.utils.fopen(path, "r") as target:
            for line in target:
                if lchar:
                    line = line.lstrip(lchar)
                if re.search(regex, line):
                    return True
            return False
    except (IOError, OSError):
        return False
# Buggy code
def contains_regex_multiline(path, regex):
    """
    .. deprecated:: 0.17
       Use :func:`search` instead.

    Return True if the given regular expression matches anything in the text
    of a given file

    Traverses multiple lines at a time, via the salt BufferedReader (reads in
    chunks)

    CLI Example:

    .. code-block:: bash

        salt '*' file.contains_regex_multiline /etc/crontab '^maint'
    """
    if not os.path.exists(path):
        return False

    try:
        with salt.utils.filebuffer.BufferedReader(path) as breader:
            for chunk in breader:
                if re.search(regex, chunk, re.MULTILINE):
                    return True
            return False
    except (IOError, OSError):
        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 contains_regex_multiline(path, regex):
    """
    .. deprecated:: 0.17.0
       Use :func:`search` instead.

    Return True if the given regular expression matches anything in the text
    of a given file

    Traverses multiple lines at a time, via the salt BufferedReader (reads in
    chunks)

    CLI Example:

    .. code-block:: bash

        salt '*' file.contains_regex_multiline /etc/crontab '^maint'
    """
    if not os.path.exists(path):
        return False

    try:
        with salt.utils.filebuffer.BufferedReader(path) as breader:
            for chunk in breader:
                if re.search(regex, chunk, re.MULTILINE):
                    return True
            return False
    except (IOError, OSError):
        return False
# Buggy code
def contains_glob(path, glob):
    """
    .. deprecated:: 0.17
       Use :func:`search` instead.

    Return True if the given glob matches a string in the named file

    CLI Example:

    .. code-block:: bash

        salt '*' file.contains_glob /etc/foobar '*cheese*'
    """
    if not os.path.exists(path):
        return False

    try:
        with salt.utils.filebuffer.BufferedReader(path) as breader:
            for chunk in breader:
                if fnmatch.fnmatch(chunk, glob):
                    return True
            return False
    except (IOError, OSError):
        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 contains_glob(path, glob):
    """
    .. deprecated:: 0.17.0
       Use :func:`search` instead.

    Return True if the given glob matches a string in the named file

    CLI Example:

    .. code-block:: bash

        salt '*' file.contains_glob /etc/foobar '*cheese*'
    """
    if not os.path.exists(path):
        return False

    try:
        with salt.utils.filebuffer.BufferedReader(path) as breader:
            for chunk in breader:
                if fnmatch.fnmatch(chunk, glob):
                    return True
            return False
    except (IOError, OSError):
        return False