gurudesh/pytracebugs huggingface dataset:
# Buggy code
def envs(self, back=None, sources=False):
    """
    Return the environments for the named backend or all backends
    """
    back = self._gen_back(back)
    ret = set()
    if sources:
        ret = {}
    for fsb in back:
        fstr = "{0}.envs".format(fsb)
        if sources:
            ret[fsb] = self.servers[fstr]()
        else:
            ret.update(self.servers[fstr]())
    if sources:
        return ret
    return list(ret)


# Traceback (012ValueError)
[ERROR   ] Error in function _file_hash:
#012Traceback (most recent call last):
#012  File "/usr/lib/python2.6/site-packages/salt/master.py", line 1444, in run_func
#012    ret = getattr(self, func)(load)
#012  File "/usr/lib/python2.6/site-packages/salt/fileserver/__init__.py", line 233, in file_hash
#012    return self.servers[fstr](load, fnd)
#012  File "/usr/lib/python2.6/site-packages/salt/fileserver/roots.py", line 153, in file_hash
#012    hsum, mtime = fp_.read().split(':')
#012ValueError: need more than 1 value to unpack

# Fixed code
def envs(self, back=None, sources=False):
    """
    Return the environments for the named backend or all back-ends
    """
    back = self._gen_back(back)
    ret = set()
    if sources:
        ret = {}
    for fsb in back:
        fstr = "{0}.envs".format(fsb)
        if sources:
            ret[fsb] = self.servers[fstr]()
        else:
            ret.update(self.servers[fstr]())
    if sources:
        return ret
    return list(ret)
# Buggy code
def enable(name, **kwargs):
    """
    Enable the named service to start at boot

    CLI Example:

    .. code-block:: bash

        salt '*' service.enable <service name>
    """
    osmajor = _osrel()[0]
    if osmajor < "6":
        cmd = "update-rc.d -f {0} defaults 99".format(_cmd_quote(name))
    else:
        cmd = "update-rc.d {0} enable".format(_cmd_quote(name))
    try:
        if int(osmajor) >= 6:
            cmd = "insserv {0} && ".format(_cmd_quote(name)) + cmd
    except ValueError:
        if osmajor == "testing/unstable" or osmajor == "unstable":
            cmd = "insserv {0} && ".format(_cmd_quote(name)) + cmd
    return not __salt__["cmd.retcode"](cmd, python_shell=True)


# Traceback (ValueError)
State: - service
Name:      cdn-supervisor
Function:  running
Result:    False
Comment:   An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/state.py", line 1316, in call
*cdata['args'], **cdata['kwargs'])
File "/usr/lib/python2.7/dist-packages/salt/states/service.py", line 306, in running
return _enable(name, True, **kwargs)
File "/usr/lib/python2.7/dist-packages/salt/states/service.py", line 108, in _enable
if __salt__['service.enable'](name, **kwargs):
File "/usr/lib/python2.7/dist-packages/salt/modules/debian_service.py", line 207, in enable
if int(osmajor) >= 6:
ValueError: invalid literal for int() with base 10: 'testing/unstable'

# Fixed code
def enable(name, **kwargs):
    """
    Enable the named service to start at boot

    CLI Example:

    .. code-block:: bash

        salt '*' service.enable <service name>
    """
    osmajor = _osrel()[0]
    if osmajor < "6":
        cmd = "update-rc.d -f {0} defaults 99".format(_cmd_quote(name))
    else:
        cmd = "update-rc.d {0} enable".format(_cmd_quote(name))
    try:
        if int(osmajor) >= 6:
            cmd = "insserv {0} && ".format(_cmd_quote(name)) + cmd
    except ValueError:
        osrel = _osrel()
        if osrel == "testing/unstable" or osrel == "unstable" or osrel.endswith("/sid"):
            cmd = "insserv {0} && ".format(_cmd_quote(name)) + cmd
    return not __salt__["cmd.retcode"](cmd, python_shell=True)
# Buggy code
def salt_cloud():
    """
    The main function for salt-cloud
    """
    if "" in sys.path:
        sys.path.remove("")
    try:
        cloud = salt.cloud.cli.SaltCloud()
        cloud.run()
    except KeyboardInterrupt:
        raise SystemExit("\nExiting gracefully on Ctrl-c")


# Traceback (AttributeError)
curl -L http://bootstrap.saltstack.org | sudo sh -s -- git develop
...
the stuff...
...
salt-cloud
Traceback (most recent call last):
File "/usr/bin/salt-cloud", line 10, in <module>
salt_cloud()
File "/usr/lib/python2.7/dist-packages/salt/scripts.py", line 120, in salt_cloud
cloud = salt.cloud.cli.SaltCloud()
AttributeError: 'module' object has no attribute 'cli'

# Fixed code
def salt_cloud():
    """
    The main function for salt-cloud
    """
    if "" in sys.path:
        sys.path.remove("")

    if not HAS_SALTCLOUD:
        print("salt-cloud is not available in this system")
        sys.exit(1)

    try:
        salt.cloud.libcloudfuncs.check_libcloud_version()
    except ImportError as exc:
        print(exc)
        sys.exit(1)

    try:
        cloud = salt.cloud.cli.SaltCloud()
        cloud.run()
    except KeyboardInterrupt:
        raise SystemExit("\nExiting gracefully on Ctrl-c")
# Buggy code
def _format_job_instance(job):
    return {
        "Function": job["fun"],
        "Arguments": list(job["arg"]),
        "Target": job["tgt"],
        "Target-type": job["tgt_type"],
        "User": job.get("user", "root"),
    }


# Traceback (KeyError)
root@master:/home/tomas# salt-run jobs.lookup_jid 20140115140610176289
root@master:/home/tomas# salt-run jobs.active
[ERROR   ] An un-handled exception was caught by salt's global exception handler:
KeyError: 'arg'
Traceback (most recent call last):
File "/usr/bin/salt-run", line 10, in <module>
salt_run()
File "/usr/lib/python2.7/dist-packages/salt/scripts.py", line 90, in salt_run
client.run()
File "/usr/lib/python2.7/dist-packages/salt/cli/__init__.py", line 346, in run
runner.run()
File "/usr/lib/python2.7/dist-packages/salt/runner.py", line 153, in run
self.opts['fun'], self.opts['arg'], self.opts)
File "/usr/lib/python2.7/dist-packages/salt/runner.py", line 85, in cmd
return self.functions[fun](*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/salt/runners/jobs.py", line 39, in active
'Arguments': list(job['arg']),
KeyError: 'arg'
Traceback (most recent call last):
File "/usr/bin/salt-run", line 10, in <module>
salt_run()
File "/usr/lib/python2.7/dist-packages/salt/scripts.py", line 90, in salt_run
client.run()
File "/usr/lib/python2.7/dist-packages/salt/cli/__init__.py", line 346, in run
runner.run()
File "/usr/lib/python2.7/dist-packages/salt/runner.py", line 153, in run
self.opts['fun'], self.opts['arg'], self.opts)
File "/usr/lib/python2.7/dist-packages/salt/runner.py", line 85, in cmd
return self.functions[fun](*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/salt/runners/jobs.py", line 39, in active
'Arguments': list(job['arg']),
KeyError: 'arg'

# Fixed code
def _format_job_instance(job):
    return {
        "Function": job["fun"],
        "Arguments": list(job.get("arg", [])),
        "Target": job["tgt"],
        "Target-type": job.get("tgt_type", []),
        "User": job.get("user", "root"),
    }
# Buggy code
def __virtual__():
    """
    Only works on Windows systems
    """
    if salt.utils.is_windows():
        if HAS_WINDOWS_MODULES:
            global check_perms, get_managed, makedirs_perms, manage_file
            global source_list, mkdir, __clean_tmp, makedirs, file_exists
            global check_managed, check_file_meta

            check_perms = _namespaced_function(check_perms, globals())
            get_managed = _namespaced_function(get_managed, globals())
            check_managed = _namespaced_function(check_managed, globals())
            check_file_meta = _namespaced_function(check_file_meta, globals())
            makedirs_perms = _namespaced_function(makedirs_perms, globals())
            makedirs = _namespaced_function(makedirs, globals())
            manage_file = _namespaced_function(manage_file, globals())
            source_list = _namespaced_function(source_list, globals())
            mkdir = _namespaced_function(mkdir, globals())
            file_exists = _namespaced_function(file_exists, globals())
            __clean_tmp = _namespaced_function(__clean_tmp, globals())

            return __virtualname__
        log.warn(salt.utils.required_modules_error(__file__, __doc__))
    return False


# Traceback (AttributeError)
# salt WX0230  file.touch  c:/salt/conf/t
WX0230:
Traceback (most recent call last):
File "salt/minion.py", line 721, in _thread_return
AttributeError: 'module' object has no attribute '__context__'

# Fixed code
def __virtual__():
    """
    Only works on Windows systems
    """
    if salt.utils.is_windows():
        if HAS_WINDOWS_MODULES:
            global check_perms, get_managed, makedirs_perms, manage_file
            global source_list, mkdir, __clean_tmp, makedirs, file_exists
            global check_managed, check_file_meta, remove

            remove = _namespaced_function(remove, globals())
            check_perms = _namespaced_function(check_perms, globals())
            get_managed = _namespaced_function(get_managed, globals())
            check_managed = _namespaced_function(check_managed, globals())
            check_file_meta = _namespaced_function(check_file_meta, globals())
            makedirs_perms = _namespaced_function(makedirs_perms, globals())
            makedirs = _namespaced_function(makedirs, globals())
            manage_file = _namespaced_function(manage_file, globals())
            source_list = _namespaced_function(source_list, globals())
            mkdir = _namespaced_function(mkdir, globals())
            file_exists = _namespaced_function(file_exists, globals())
            __clean_tmp = _namespaced_function(__clean_tmp, globals())

            return __virtualname__
        log.warn(salt.utils.required_modules_error(__file__, __doc__))
    return False
# Buggy code
def __virtual__():
    """
    Only works on Windows systems
    """
    if salt.utils.is_windows():
        if HAS_WINDOWS_MODULES:
            global check_perms, get_managed, makedirs_perms, manage_file
            global source_list, mkdir, __clean_tmp, makedirs, file_exists
            global check_managed, check_file_meta, remove

            remove = _namespaced_function(remove, globals())
            check_perms = _namespaced_function(check_perms, globals())
            get_managed = _namespaced_function(get_managed, globals())
            check_managed = _namespaced_function(check_managed, globals())
            check_file_meta = _namespaced_function(check_file_meta, globals())
            makedirs_perms = _namespaced_function(makedirs_perms, globals())
            makedirs = _namespaced_function(makedirs, globals())
            manage_file = _namespaced_function(manage_file, globals())
            source_list = _namespaced_function(source_list, globals())
            mkdir = _namespaced_function(mkdir, globals())
            file_exists = _namespaced_function(file_exists, globals())
            __clean_tmp = _namespaced_function(__clean_tmp, globals())

            return __virtualname__
        log.warn(salt.utils.required_modules_error(__file__, __doc__))
    return False


# Traceback (AttributeError)
# salt WX0230  file.touch  c:/salt/conf/t
WX0230:
Traceback (most recent call last):
File "salt/minion.py", line 721, in _thread_return
AttributeError: 'module' object has no attribute '__context__'

# Fixed code
def __virtual__():
    """
    Only works on Windows systems
    """
    if salt.utils.is_windows():
        if HAS_WINDOWS_MODULES:
            global check_perms, get_managed, makedirs_perms, manage_file
            global source_list, mkdir, __clean_tmp, makedirs, file_exists
            global check_managed, check_file_meta, remove, append

            remove = _namespaced_function(remove, globals())
            append = _namespaced_function(append, globals())
            check_perms = _namespaced_function(check_perms, globals())
            get_managed = _namespaced_function(get_managed, globals())
            check_managed = _namespaced_function(check_managed, globals())
            check_file_meta = _namespaced_function(check_file_meta, globals())
            makedirs_perms = _namespaced_function(makedirs_perms, globals())
            makedirs = _namespaced_function(makedirs, globals())
            manage_file = _namespaced_function(manage_file, globals())
            source_list = _namespaced_function(source_list, globals())
            mkdir = _namespaced_function(mkdir, globals())
            file_exists = _namespaced_function(file_exists, globals())
            __clean_tmp = _namespaced_function(__clean_tmp, globals())

            return __virtualname__
        log.warn(salt.utils.required_modules_error(__file__, __doc__))
    return False
# Buggy code
def __virtual__():
    """
    Only works on Windows systems
    """
    if salt.utils.is_windows():
        if HAS_WINDOWS_MODULES:
            global check_perms, get_managed, makedirs_perms, manage_file
            global source_list, mkdir, __clean_tmp, makedirs, file_exists
            global check_managed, check_file_meta

            check_perms = _namespaced_function(check_perms, globals())
            get_managed = _namespaced_function(get_managed, globals())
            check_managed = _namespaced_function(check_managed, globals())
            check_file_meta = _namespaced_function(check_file_meta, globals())
            makedirs_perms = _namespaced_function(makedirs_perms, globals())
            makedirs = _namespaced_function(makedirs, globals())
            manage_file = _namespaced_function(manage_file, globals())
            source_list = _namespaced_function(source_list, globals())
            mkdir = _namespaced_function(mkdir, globals())
            file_exists = _namespaced_function(file_exists, globals())
            __clean_tmp = _namespaced_function(__clean_tmp, globals())

            return "file"
        log.warn(salt.utils.required_modules_error(__file__, __doc__))
    return False


# Traceback (AttributeError)
# salt WX0230  file.touch  c:/salt/conf/t
WX0230:
Traceback (most recent call last):
File "salt/minion.py", line 721, in _thread_return
AttributeError: 'module' object has no attribute '__context__'

# Fixed code
def __virtual__():
    """
    Only works on Windows systems
    """
    if salt.utils.is_windows():
        if HAS_WINDOWS_MODULES:
            global check_perms, get_managed, makedirs_perms, manage_file
            global source_list, mkdir, __clean_tmp, makedirs, file_exists
            global check_managed, check_file_meta, remove

            remove = _namespaced_function(remove, globals())
            check_perms = _namespaced_function(check_perms, globals())
            get_managed = _namespaced_function(get_managed, globals())
            check_managed = _namespaced_function(check_managed, globals())
            check_file_meta = _namespaced_function(check_file_meta, globals())
            makedirs_perms = _namespaced_function(makedirs_perms, globals())
            makedirs = _namespaced_function(makedirs, globals())
            manage_file = _namespaced_function(manage_file, globals())
            source_list = _namespaced_function(source_list, globals())
            mkdir = _namespaced_function(mkdir, globals())
            file_exists = _namespaced_function(file_exists, globals())
            __clean_tmp = _namespaced_function(__clean_tmp, globals())

            return "file"
        log.warn(salt.utils.required_modules_error(__file__, __doc__))
    return False
# Buggy code
def __virtual__():
    """
    Only works on Windows systems
    """
    if salt.utils.is_windows():
        if HAS_WINDOWS_MODULES:
            global check_perms, get_managed, makedirs_perms, manage_file
            global source_list, mkdir, __clean_tmp, makedirs, file_exists
            global check_managed, check_file_meta, remove

            remove = _namespaced_function(remove, globals())
            check_perms = _namespaced_function(check_perms, globals())
            get_managed = _namespaced_function(get_managed, globals())
            check_managed = _namespaced_function(check_managed, globals())
            check_file_meta = _namespaced_function(check_file_meta, globals())
            makedirs_perms = _namespaced_function(makedirs_perms, globals())
            makedirs = _namespaced_function(makedirs, globals())
            manage_file = _namespaced_function(manage_file, globals())
            source_list = _namespaced_function(source_list, globals())
            mkdir = _namespaced_function(mkdir, globals())
            file_exists = _namespaced_function(file_exists, globals())
            __clean_tmp = _namespaced_function(__clean_tmp, globals())

            return "file"
        log.warn(salt.utils.required_modules_error(__file__, __doc__))
    return False


# Traceback (AttributeError)
# salt WX0230  file.touch  c:/salt/conf/t
WX0230:
Traceback (most recent call last):
File "salt/minion.py", line 721, in _thread_return
AttributeError: 'module' object has no attribute '__context__'

# Fixed code
def __virtual__():
    """
    Only works on Windows systems
    """
    if salt.utils.is_windows():
        if HAS_WINDOWS_MODULES:
            global check_perms, get_managed, makedirs_perms, manage_file
            global source_list, mkdir, __clean_tmp, makedirs, file_exists
            global check_managed, check_file_meta, remove, append

            remove = _namespaced_function(remove, globals())
            append = _namespaced_function(append, globals())
            check_perms = _namespaced_function(check_perms, globals())
            get_managed = _namespaced_function(get_managed, globals())
            check_managed = _namespaced_function(check_managed, globals())
            check_file_meta = _namespaced_function(check_file_meta, globals())
            makedirs_perms = _namespaced_function(makedirs_perms, globals())
            makedirs = _namespaced_function(makedirs, globals())
            manage_file = _namespaced_function(manage_file, globals())
            source_list = _namespaced_function(source_list, globals())
            mkdir = _namespaced_function(mkdir, globals())
            file_exists = _namespaced_function(file_exists, globals())
            __clean_tmp = _namespaced_function(__clean_tmp, globals())

            return "file"
        log.warn(salt.utils.required_modules_error(__file__, __doc__))
    return False
# Buggy code
def __virtual__():
    """
    Only works on Windows systems
    """
    if salt.utils.is_windows():
        if HAS_WINDOWS_MODULES:
            global check_perms, get_managed, makedirs_perms, manage_file
            global source_list, mkdir, __clean_tmp, makedirs, file_exists

            check_perms = _namespaced_function(check_perms, globals())
            get_managed = _namespaced_function(get_managed, globals())
            makedirs_perms = _namespaced_function(makedirs_perms, globals())
            makedirs = _namespaced_function(makedirs, globals())
            manage_file = _namespaced_function(manage_file, globals())
            source_list = _namespaced_function(source_list, globals())
            mkdir = _namespaced_function(mkdir, globals())
            file_exists = _namespaced_function(file_exists, globals())
            __clean_tmp = _namespaced_function(__clean_tmp, globals())

            return __virtualname__
        log.warn(salt.utils.required_modules_error(__file__, __doc__))
    return False


# Traceback (NameError)
render20:
----------
file_|-jboss-log4j_|-d:\Apps\jboss\server\default\conf\jboss-log4j.xml_|-managed:
----------
__run_num__:
0
changes:
----------
comment:
An exception occurred in this state: Traceback (most recent call last):
File "salt/state.py", line 1305, in call
File "salt/states/file.py", line 1116, in managed
File "salt/modules/file.py", line 1797, in check_managed
File "salt/modules/file.py", line 1620, in get_managed
NameError: global name '__salt__' is not defined

name:
d:\Apps\jboss\server\default\conf\jboss-log4j.xml
result:
False

# Fixed code
def __virtual__():
    """
    Only works on Windows systems
    """
    if salt.utils.is_windows():
        if HAS_WINDOWS_MODULES:
            global check_perms, get_managed, makedirs_perms, manage_file
            global source_list, mkdir, __clean_tmp, makedirs, file_exists
            global check_managed, check_file_meta, remove, append

            remove = _namespaced_function(remove, globals())
            append = _namespaced_function(append, globals())
            check_perms = _namespaced_function(check_perms, globals())
            get_managed = _namespaced_function(get_managed, globals())
            check_managed = _namespaced_function(check_managed, globals())
            check_file_meta = _namespaced_function(check_file_meta, globals())
            makedirs_perms = _namespaced_function(makedirs_perms, globals())
            makedirs = _namespaced_function(makedirs, globals())
            manage_file = _namespaced_function(manage_file, globals())
            source_list = _namespaced_function(source_list, globals())
            mkdir = _namespaced_function(mkdir, globals())
            file_exists = _namespaced_function(file_exists, globals())
            __clean_tmp = _namespaced_function(__clean_tmp, globals())

            return __virtualname__
        log.warn(salt.utils.required_modules_error(__file__, __doc__))
    return False
# Buggy code
def close(self):
    # One second to send any queued messages
    self._context.destroy(1 * 1000)


# Traceback (AttributeError)
@arch-dev-vbox ~/projects/jules/halite:G:v0.17.2 > salt '*' test.ping
localdev:
True
Error in atexit._run_exitfuncs:
Traceback (most recent call last):
File "/usr/lib64/python2.7/atexit.py", line 24, in _run_exitfuncs
func(*targs, **kargs)
File "/usr/lib64/python2.7/logging/__init__.py", line 1651, in shutdown
h.close()
File "/media/sf_shared/jules/salt/salt/log/handlers/logstash_mod.py", line 323, in close
self._context.destroy(1 * 1000)
AttributeError: 'NoneType' object has no attribute 'destroy'
Error in sys.exitfunc:
[ERROR   ] An un-handled exception was caught by salt's global exception handler:
AttributeError: 'NoneType' object has no attribute 'destroy'
Traceback (most recent call last):
File "/usr/lib64/python2.7/atexit.py", line 24, in _run_exitfuncs
func(*targs, **kargs)
File "/usr/lib64/python2.7/logging/__init__.py", line 1651, in shutdown
h.close()
File "/media/sf_shared/jules/salt/salt/log/handlers/logstash_mod.py", line 323, in close
self._context.destroy(1 * 1000)
AttributeError: 'NoneType' object has no attribute 'destroy'

# Fixed code
def close(self):
    if self._context is not None:
        # One second to send any queued messages
        self._context.destroy(1 * 1000)
# Buggy code
def get_event(self, wait=0.25, tag="", full=False):
    """
    Returns next available event with tag tag from event bus
    If any within wait seconds
    Otherwise return None

    If tag is empty then return events for all tags
    If full then add tag field to returned data

    If wait is 0 then block forever or until next event becomes available.
    """
    return self.event.get_event(wait=wait, tag=tag, full=full)


# Traceback (EauthAuthenticationError)
In [25]: api.verify_token(token)
Out[25]:
{'eauth': 'pam',
'expire': 1384485615.857448,
'name': 'wari',
'start': 1384442415.857448,
'token': '2d18887a11cb55c3b99971a120b8925a'}

In [26]: cmd=dict(token=token, fun='runner.manage.status')

In [27]: api.run(cmd)
---------------------------------------------------------------------------
EauthAuthenticationError                  Traceback (most recent call last)
/root/<ipython-input-27-d138619efa48> in <module>()
----> 1 api.run(cmd)

/usr/lib/python2.7/dist-packages/salt/client/api.pyc in run(self, cmd)
120
121         executor = getattr(self, '{0}_{1}'.format(client, mode))
--> 122         result = executor(**cmd)
123         return result
124

/usr/lib/python2.7/dist-packages/salt/client/api.pyc in runner_async(self, **kwargs)
147         of the function to call
148         ''''''
--> 149         return self.runnerClient.master_call(**kwargs)
150
151     runner_sync = runner_async  # always runner async, so works in either mode

/usr/lib/python2.7/dist-packages/salt/runner.pyc in master_call(self, **kwargs)
125         ret = sreq.send('clear', load)
126         if ret == '':
--> 127             raise salt.exceptions.EauthAuthenticationError
128         return ret
129

EauthAuthenticationError:

# Fixed code
def get_event(self, wait=0.25, tag="", full=False):
    """
    Get a single salt event.
    If no events are available, then block for up to ``wait`` seconds.
    Return the event if it matches the tag (or ``tag`` is empty)
    Otherwise return None

    If wait is 0 then block forever or until next event becomes available.
    """
    return self.event.get_event(wait=wait, tag=tag, full=full)
# Buggy code
def valid_id(opts, id_):
    """
    Returns if the passed id is valid
    """
    return bool(clean_path(opts["pki_dir"], id_))


# Traceback (AttributeError)
[INFO    ] Clear payload received with command _auth
[DEBUG   ] This salt-master instance has accepted 16 minion keys.
Process MWorker-5:
Traceback (most recent call last):
File "/usr/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap
self.run()
File "/usr/local/lib/python2.7/dist-packages/salt/master.py", line 706, in run
self.__bind()
File "/usr/local/lib/python2.7/dist-packages/salt/master.py", line 611, in __bind
ret = self.serial.dumps(self._handle_payload(payload))
File "/usr/local/lib/python2.7/dist-packages/salt/master.py", line 635, in _handle_payload
'clear': self._handle_clear}[key](load)
File "/usr/local/lib/python2.7/dist-packages/salt/master.py", line 644, in _handle_clear
return getattr(self.clear_funcs, load['cmd'])(load)
File "/usr/local/lib/python2.7/dist-packages/salt/master.py", line 1715, in _auth
if not salt.utils.verify.valid_id(self.opts, load['id']):
File "/usr/local/lib/python2.7/dist-packages/salt/utils/verify.py", line 453, in valid_id
return bool(clean_path(opts['pki_dir'], id_))
File "/usr/local/lib/python2.7/dist-packages/salt/utils/verify.py", line 437, in clean_path
if not os.path.isabs(path):
File "/usr/lib/python2.7/posixpath.py", line 53, in isabs
return s.startswith('/')
AttributeError: 'NoneType' object has no attribute 'startswith'

# Fixed code
def valid_id(opts, id_):
    """
    Returns if the passed id is valid
    """
    try:
        return bool(clean_path(opts["pki_dir"], id_))
    except (AttributeError, KeyError) as e:
        return False
# Buggy code
def file_list(self, env="base", prefix=""):
    """
    List the files on the master
    """
    load = {"env": env, "prefix": prefix, "cmd": "_file_list"}
    try:
        return self.auth.crypticle.loads(
            self.sreq.send("aes", self.auth.crypticle.dumps(load), 3, 60)
        )
    except SaltReqTimeoutError:
        return ""


# Traceback (AuthenticationError)
----------
State: - file
Name:      /tmp/test-restart-salt1
Function:  managed
Result:    False
Comment:   An exception occurred in this state: Traceback (most recent call last):
File "/srv/salt/makina-states/src/salt/salt/state.py", line 1260, in call
*cdata['args'], **cdata['kwargs'])
File "/srv/salt/makina-states/src/salt/salt/states/file.py", line 1115, in managed
**kwargs
File "/srv/salt/makina-states/src/salt/salt/modules/file.py", line 1605, in get_managed
source_sum = __salt__['cp.hash_file'](source, env)
File "/srv/salt/makina-states/src/salt/salt/modules/cp.py", line 424, in hash_file
return __context__['cp.fileclient'].hash_file(path, env)
File "/srv/salt/makina-states/src/salt/salt/fileclient.py", line 796, in hash_file
60)
File "/srv/salt/makina-states/src/salt/salt/crypt.py", line 424, in loads
data = self.decrypt(data)
File "/srv/salt/makina-states/src/salt/salt/crypt.py", line 401, in decrypt
raise AuthenticationError('message authentication failed')
AuthenticationError: message authentication failed

Changes:
----------

# Fixed code
def file_list(self, env="base", prefix=""):
    """
    List the files on the master
    """
    load = {"env": env, "prefix": prefix, "cmd": "_file_list"}
    try:
        return self._crypted_transfer(load)
    except SaltReqTimeoutError:
        return ""
# Buggy code
def file_list_emptydirs(self, env="base", prefix=""):
    """
    List the empty dirs on the master
    """
    load = {"env": env, "prefix": prefix, "cmd": "_file_list_emptydirs"}
    try:
        return self.auth.crypticle.loads(
            self.sreq.send("aes", self.auth.crypticle.dumps(load), 3, 60)
        )
    except SaltReqTimeoutError:
        return ""


# Traceback (AuthenticationError)
----------
State: - file
Name:      /tmp/test-restart-salt1
Function:  managed
Result:    False
Comment:   An exception occurred in this state: Traceback (most recent call last):
File "/srv/salt/makina-states/src/salt/salt/state.py", line 1260, in call
*cdata['args'], **cdata['kwargs'])
File "/srv/salt/makina-states/src/salt/salt/states/file.py", line 1115, in managed
**kwargs
File "/srv/salt/makina-states/src/salt/salt/modules/file.py", line 1605, in get_managed
source_sum = __salt__['cp.hash_file'](source, env)
File "/srv/salt/makina-states/src/salt/salt/modules/cp.py", line 424, in hash_file
return __context__['cp.fileclient'].hash_file(path, env)
File "/srv/salt/makina-states/src/salt/salt/fileclient.py", line 796, in hash_file
60)
File "/srv/salt/makina-states/src/salt/salt/crypt.py", line 424, in loads
data = self.decrypt(data)
File "/srv/salt/makina-states/src/salt/salt/crypt.py", line 401, in decrypt
raise AuthenticationError('message authentication failed')
AuthenticationError: message authentication failed

Changes:
----------

# Fixed code
def file_list_emptydirs(self, env="base", prefix=""):
    """
    List the empty dirs on the master
    """
    load = {"env": env, "prefix": prefix, "cmd": "_file_list_emptydirs"}
    try:
        self._crypted_transfer(load)
    except SaltReqTimeoutError:
        return ""
# Buggy code
def dir_list(self, env="base", prefix=""):
    """
    List the dirs on the master
    """
    load = {"env": env, "prefix": prefix, "cmd": "_dir_list"}
    try:
        return self.auth.crypticle.loads(
            self.sreq.send("aes", self.auth.crypticle.dumps(load), 3, 60)
        )
    except SaltReqTimeoutError:
        return ""


# Traceback (AuthenticationError)
----------
State: - file
Name:      /tmp/test-restart-salt1
Function:  managed
Result:    False
Comment:   An exception occurred in this state: Traceback (most recent call last):
File "/srv/salt/makina-states/src/salt/salt/state.py", line 1260, in call
*cdata['args'], **cdata['kwargs'])
File "/srv/salt/makina-states/src/salt/salt/states/file.py", line 1115, in managed
**kwargs
File "/srv/salt/makina-states/src/salt/salt/modules/file.py", line 1605, in get_managed
source_sum = __salt__['cp.hash_file'](source, env)
File "/srv/salt/makina-states/src/salt/salt/modules/cp.py", line 424, in hash_file
return __context__['cp.fileclient'].hash_file(path, env)
File "/srv/salt/makina-states/src/salt/salt/fileclient.py", line 796, in hash_file
60)
File "/srv/salt/makina-states/src/salt/salt/crypt.py", line 424, in loads
data = self.decrypt(data)
File "/srv/salt/makina-states/src/salt/salt/crypt.py", line 401, in decrypt
raise AuthenticationError('message authentication failed')
AuthenticationError: message authentication failed

Changes:
----------

# Fixed code
def dir_list(self, env="base", prefix=""):
    """
    List the dirs on the master
    """
    load = {"env": env, "prefix": prefix, "cmd": "_dir_list"}
    try:
        return self._crypted_transfer(load)
    except SaltReqTimeoutError:
        return ""
# Buggy code
def symlink_list(self, env="base", prefix=""):
    """
    List symlinked files and dirs on the master
    """
    load = {"env": env, "prefix": prefix, "cmd": "_symlink_list"}
    try:
        return self.auth.crypticle.loads(
            self.sreq.send("aes", self.auth.crypticle.dumps(load), 3, 60)
        )
    except SaltReqTimeoutError:
        return ""


# Traceback (AuthenticationError)
----------
State: - file
Name:      /tmp/test-restart-salt1
Function:  managed
Result:    False
Comment:   An exception occurred in this state: Traceback (most recent call last):
File "/srv/salt/makina-states/src/salt/salt/state.py", line 1260, in call
*cdata['args'], **cdata['kwargs'])
File "/srv/salt/makina-states/src/salt/salt/states/file.py", line 1115, in managed
**kwargs
File "/srv/salt/makina-states/src/salt/salt/modules/file.py", line 1605, in get_managed
source_sum = __salt__['cp.hash_file'](source, env)
File "/srv/salt/makina-states/src/salt/salt/modules/cp.py", line 424, in hash_file
return __context__['cp.fileclient'].hash_file(path, env)
File "/srv/salt/makina-states/src/salt/salt/fileclient.py", line 796, in hash_file
60)
File "/srv/salt/makina-states/src/salt/salt/crypt.py", line 424, in loads
data = self.decrypt(data)
File "/srv/salt/makina-states/src/salt/salt/crypt.py", line 401, in decrypt
raise AuthenticationError('message authentication failed')
AuthenticationError: message authentication failed

Changes:
----------

# Fixed code
def symlink_list(self, env="base", prefix=""):
    """
    List symlinked files and dirs on the master
    """
    load = {"env": env, "prefix": prefix, "cmd": "_symlink_list"}
    try:
        return self._crypted_transfer(load)
    except SaltReqTimeoutError:
        return ""
# Buggy code
def hash_file(self, path, env="base"):
    """
    Return the hash of a file, to get the hash of a file on the salt
    master file server prepend the path with salt://<file on server>
    otherwise, prepend the file with / for a local file.
    """
    try:
        path = self._check_proto(path)
    except MinionError:
        if not os.path.isfile(path):
            err = "Specified file {0} is not present to generate hash"
            log.warning(err.format(path))
            return {}
        else:
            ret = {}
            ret["hsum"] = salt.utils.get_hash(path, form="md5", chunk_size=4096)
            ret["hash_type"] = "md5"
            return ret
    load = {"path": path, "env": env, "cmd": "_file_hash"}
    try:
        return self.auth.crypticle.loads(
            self.sreq.send("aes", self.auth.crypticle.dumps(load), 3, 60)
        )
    except SaltReqTimeoutError:
        return ""


# Traceback (AuthenticationError)
----------
State: - file
Name:      /tmp/test-restart-salt1
Function:  managed
Result:    False
Comment:   An exception occurred in this state: Traceback (most recent call last):
File "/srv/salt/makina-states/src/salt/salt/state.py", line 1260, in call
*cdata['args'], **cdata['kwargs'])
File "/srv/salt/makina-states/src/salt/salt/states/file.py", line 1115, in managed
**kwargs
File "/srv/salt/makina-states/src/salt/salt/modules/file.py", line 1605, in get_managed
source_sum = __salt__['cp.hash_file'](source, env)
File "/srv/salt/makina-states/src/salt/salt/modules/cp.py", line 424, in hash_file
return __context__['cp.fileclient'].hash_file(path, env)
File "/srv/salt/makina-states/src/salt/salt/fileclient.py", line 796, in hash_file
60)
File "/srv/salt/makina-states/src/salt/salt/crypt.py", line 424, in loads
data = self.decrypt(data)
File "/srv/salt/makina-states/src/salt/salt/crypt.py", line 401, in decrypt
raise AuthenticationError('message authentication failed')
AuthenticationError: message authentication failed

Changes:
----------

# Fixed code
def hash_file(self, path, env="base"):
    """
    Return the hash of a file, to get the hash of a file on the salt
    master file server prepend the path with salt://<file on server>
    otherwise, prepend the file with / for a local file.
    """
    try:
        path = self._check_proto(path)
    except MinionError:
        if not os.path.isfile(path):
            err = "Specified file {0} is not present to generate hash"
            log.warning(err.format(path))
            return {}
        else:
            ret = {}
            ret["hsum"] = salt.utils.get_hash(path, form="md5", chunk_size=4096)
            ret["hash_type"] = "md5"
            return ret
    load = {"path": path, "env": env, "cmd": "_file_hash"}
    try:
        return self._crypted_transfer(load)
    except SaltReqTimeoutError:
        return ""
# Buggy code
def list_env(self, env="base"):
    """
    Return a list of the files in the file server's specified environment
    """
    load = {"env": env, "cmd": "_file_list"}
    try:
        return self.auth.crypticle.loads(
            self.sreq.send("aes", self.auth.crypticle.dumps(load), 3, 60)
        )
    except SaltReqTimeoutError:
        return ""


# Traceback (AuthenticationError)
----------
State: - file
Name:      /tmp/test-restart-salt1
Function:  managed
Result:    False
Comment:   An exception occurred in this state: Traceback (most recent call last):
File "/srv/salt/makina-states/src/salt/salt/state.py", line 1260, in call
*cdata['args'], **cdata['kwargs'])
File "/srv/salt/makina-states/src/salt/salt/states/file.py", line 1115, in managed
**kwargs
File "/srv/salt/makina-states/src/salt/salt/modules/file.py", line 1605, in get_managed
source_sum = __salt__['cp.hash_file'](source, env)
File "/srv/salt/makina-states/src/salt/salt/modules/cp.py", line 424, in hash_file
return __context__['cp.fileclient'].hash_file(path, env)
File "/srv/salt/makina-states/src/salt/salt/fileclient.py", line 796, in hash_file
60)
File "/srv/salt/makina-states/src/salt/salt/crypt.py", line 424, in loads
data = self.decrypt(data)
File "/srv/salt/makina-states/src/salt/salt/crypt.py", line 401, in decrypt
raise AuthenticationError('message authentication failed')
AuthenticationError: message authentication failed

Changes:
----------

# Fixed code
def list_env(self, env="base"):
    """
    Return a list of the files in the file server's specified environment
    """
    load = {"env": env, "cmd": "_file_list"}
    try:
        return self._crypted_transfer(load)
    except SaltReqTimeoutError:
        return ""
# Buggy code
def master_opts(self):
    """
    Return the master opts data
    """
    load = {"cmd": "_master_opts"}
    try:
        return self.auth.crypticle.loads(
            self.sreq.send("aes", self.auth.crypticle.dumps(load), 3, 60)
        )
    except SaltReqTimeoutError:
        return ""


# Traceback (AuthenticationError)
----------
State: - file
Name:      /tmp/test-restart-salt1
Function:  managed
Result:    False
Comment:   An exception occurred in this state: Traceback (most recent call last):
File "/srv/salt/makina-states/src/salt/salt/state.py", line 1260, in call
*cdata['args'], **cdata['kwargs'])
File "/srv/salt/makina-states/src/salt/salt/states/file.py", line 1115, in managed
**kwargs
File "/srv/salt/makina-states/src/salt/salt/modules/file.py", line 1605, in get_managed
source_sum = __salt__['cp.hash_file'](source, env)
File "/srv/salt/makina-states/src/salt/salt/modules/cp.py", line 424, in hash_file
return __context__['cp.fileclient'].hash_file(path, env)
File "/srv/salt/makina-states/src/salt/salt/fileclient.py", line 796, in hash_file
60)
File "/srv/salt/makina-states/src/salt/salt/crypt.py", line 424, in loads
data = self.decrypt(data)
File "/srv/salt/makina-states/src/salt/salt/crypt.py", line 401, in decrypt
raise AuthenticationError('message authentication failed')
AuthenticationError: message authentication failed

Changes:
----------

# Fixed code
def master_opts(self):
    """
    Return the master opts data
    """
    load = {"cmd": "_master_opts"}
    try:
        return self._crypted_transfer(load)
    except SaltReqTimeoutError:
        return ""
# Buggy code
def ext_nodes(self):
    """
    Return the metadata derived from the external nodes system on the
    master.
    """
    load = {
        "cmd": "_ext_nodes",
        "id": self.opts["id"],
        "opts": self.opts,
        "tok": self.auth.gen_token("salt"),
    }
    try:
        return self.auth.crypticle.loads(
            self.sreq.send("aes", self.auth.crypticle.dumps(load), 3, 60)
        )
    except SaltReqTimeoutError:
        return ""


# Traceback (AuthenticationError)
----------
State: - file
Name:      /tmp/test-restart-salt1
Function:  managed
Result:    False
Comment:   An exception occurred in this state: Traceback (most recent call last):
File "/srv/salt/makina-states/src/salt/salt/state.py", line 1260, in call
*cdata['args'], **cdata['kwargs'])
File "/srv/salt/makina-states/src/salt/salt/states/file.py", line 1115, in managed
**kwargs
File "/srv/salt/makina-states/src/salt/salt/modules/file.py", line 1605, in get_managed
source_sum = __salt__['cp.hash_file'](source, env)
File "/srv/salt/makina-states/src/salt/salt/modules/cp.py", line 424, in hash_file
return __context__['cp.fileclient'].hash_file(path, env)
File "/srv/salt/makina-states/src/salt/salt/fileclient.py", line 796, in hash_file
60)
File "/srv/salt/makina-states/src/salt/salt/crypt.py", line 424, in loads
data = self.decrypt(data)
File "/srv/salt/makina-states/src/salt/salt/crypt.py", line 401, in decrypt
raise AuthenticationError('message authentication failed')
AuthenticationError: message authentication failed

Changes:
----------

# Fixed code
def ext_nodes(self):
    """
    Return the metadata derived from the external nodes system on the
    master.
    """
    load = {
        "cmd": "_ext_nodes",
        "id": self.opts["id"],
        "opts": self.opts,
        "tok": self.auth.gen_token("salt"),
    }
    try:
        return self._crypted_transfer(load)
    except SaltReqTimeoutError:
        return ""
# Buggy code
def envs():
    """
    Return a list of refs that can be used as environments
    """
    ret = set()
    repos = init()
    for repo in repos:
        repo.open()
        if __opts__["hgfs_branch_method"] != "bookmarks":
            branches = repo.branches()
            for branch in branches:
                branch_name = branch[0]
                if branch_name == "default":
                    branch = "base"
                ret.add(branch_name)
        if __opts__["hgfs_branch_method"] != "branches":
            bookmarks = repo.bookmarks()
            for bookmark in bookmarks:
                bookmark_name = bookmark[0]
                ret.add(bookmark_name)
        tags = repo.get_tags()
        for tag in tags.keys():
            tag_name = tag[0]
            ret.add(tag_name)
    return list(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 envs():
    """
    Return a list of refs that can be used as environments
    """
    ret = set()
    repos = init()
    for repo in repos:
        repo.open()
        if __opts__["hgfs_branch_method"] != "bookmarks":
            branches = repo.branches()
            for branch in branches:
                branch_name = branch[0]
                if branch_name == "default":
                    branch_name = "base"
                ret.add(branch_name)
        if __opts__["hgfs_branch_method"] != "branches":
            bookmarks = repo.bookmarks()
            for bookmark in bookmarks:
                bookmark_name = bookmark[0]
                ret.add(bookmark_name)
        tags = repo.tags()
        for tag in tags:
            tag_name = tag[0]
            # Avoid adding the special 'tip' tag ad an env.
            if tag_name != "tip":
                ret.add(tag_name)
    return list(ret)
# Buggy code
def __getattr__(self, name):
    if name in ("__file__", "__path__"):
        return "/dev/null"
    elif name[0] == name[0].upper():
        return type(name, (), {})
    else:
        return Mock()


# 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 __getattr__(self, name):
    if name in ("__file__", "__path__"):
        return "/dev/null"
    else:
        return Mock()
# Buggy code
def verify_env(self):
    """
    Verify that salt-ssh is ready to run
    """
    if not salt.utils.which("sshpass"):
        print(
            "Warning:  sshpass is not present, so password-based "
            "authentication is not available."
        )


# 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 verify_env(self):
    """
    Verify that salt-ssh is ready to run
    """
    if not salt.utils.which("sshpass"):
        log.warning(
            "Warning:  sshpass is not present, so password-based "
            "authentication is not available."
        )
# Buggy code
def key_deploy(self, host, ret):
    """
    Deploy the SSH key if the minions don't auth
    """
    if not isinstance(ret[host], basestring):
        if self.opts.get("ssh_key_deploy"):
            target = self.targets[host]
            if "passwd" in target:
                self._key_deploy_run(host, target, False)
        return ret
    if ret[host].startswith("Permission denied"):
        target = self.targets[host]
        # permission denied, attempt to auto deploy ssh key
        print(
            (
                "Permission denied for host {0}, do you want to "
                "deploy the salt-ssh key?"
            ).format(host)
        )
        deploy = raw_input("[Y/n]")
        if deploy.startswith(("n", "N")):
            return ret
        target["passwd"] = getpass.getpass("Password for {0}:".format(host))
        return self._key_deploy_run(host, target, 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 key_deploy(self, host, ret):
    """
    Deploy the SSH key if the minions don't auth
    """
    if not isinstance(ret[host], basestring):
        if self.opts.get("ssh_key_deploy"):
            target = self.targets[host]
            if "passwd" in target:
                self._key_deploy_run(host, target, False)
        return ret
    if ret[host].startswith("Permission denied"):
        target = self.targets[host]
        # permission denied, attempt to auto deploy ssh key
        print(
            (
                "Permission denied for host {0}, do you want to deploy "
                "the salt-ssh key? (password required):"
            ).format(host)
        )
        deploy = raw_input("[Y/n]")
        if deploy.startswith(("n", "N")):
            return ret
        target["passwd"] = getpass.getpass(
            "Password for {0}@{1}:".format(host, target["user"])
        )
        return self._key_deploy_run(host, target, True)
    return ret