gurudesh/pytracebugs huggingface dataset:
# Buggy code
def get_all(runas=None):
    """
    Return a list of services that are enabled or available. Can be used to
    find the name of a service.

    :param str runas: User to run launchctl commands

    :return: A list of all the services available or enabled
    :rtype: list

    CLI Example:

    .. code-block:: bash

        salt '*' service.get_all
    """
    # Get list of enabled services
    enabled = get_enabled(runas=runas)

    # Get list of all services
    available = list(salt.utils.mac_utils.available_services().keys())

    # Return composite list
    return sorted(set(enabled + available))


# Traceback (NameError)
Traceback (most recent call last):
File "/testing/scripts/salt-call", line 11, in <module>
salt_call()
File "/testing/salt/scripts.py", line 400, in salt_call
client.run()
File "/testing/salt/cli/call.py", line 57, in run
caller.run()
File "/testing/salt/cli/caller.py", line 134, in run
ret = self.call()
File "/testing/salt/cli/caller.py", line 212, in call
ret['return'] = func(*args, **kwargs)
File "/testing/salt/modules/mac_service.py", line 130, in launchctl
return salt.utils.mac_utils.launchctl(sub_cmd, *args, **kwargs)
File "/testing/salt/utils/mac_utils.py", line 270, in launchctl
ret = salt.modules.cmdmod.run_all(cmd, **kwargs)
File "/testing/salt/modules/cmdmod.py", line 1834, in run_all
**kwargs)
File "/testing/salt/modules/cmdmod.py", line 357, in _run
if not _check_avail(cmd):
File "/testing/salt/modules/cmdmod.py", line 230, in _check_avail
if __salt__['config.get']('cmd_blacklist_glob'):
NameError: global name '__salt__' is not defined

# Fixed code
def get_all(runas=None):
    """
    Return a list of services that are enabled or available. Can be used to
    find the name of a service.

    :param str runas: User to run launchctl commands

    :return: A list of all the services available or enabled
    :rtype: list

    CLI Example:

    .. code-block:: bash

        salt '*' service.get_all
    """
    # Get list of enabled services
    enabled = get_enabled(runas=runas)

    # Get list of all services
    available = list(__utils__["mac_utils.available_services"]().keys())

    # Return composite list
    return sorted(set(enabled + available))
# Buggy code
def _get_sk(**kwargs):
    """
    Return sk
    """
    config = _get_config(**kwargs)
    key = salt.utils.stringutils.to_str(config["sk"])
    sk_file = config["sk_file"]
    if not key and sk_file:
        with salt.utils.files.fopen(sk_file, "rb") as keyf:
            key = salt.utils.stringutils.to_unicode(keyf.read()).rstrip("\n")
    if key is None:
        raise Exception("no key or sk_file found")
    return base64.b64decode(key)


# Traceback (SaltRenderError)
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/utils/templates.py", line 392, in render_jinja_tmpl
[...]
---
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/pillar/__init__.py", line 736, in render_pstate
**defaults)
File "/usr/lib/python2.7/dist-packages/salt/template.py", line 101, in compile_template
ret = render(input_data, saltenv, sls, **render_kwargs)
File "/usr/lib/python2.7/dist-packages/salt/renderers/jinja.py", line 70, in render
**kws)
File "/usr/lib/python2.7/dist-packages/salt/utils/templates.py", line 169, in render_tmpl
output = render_str(tmplstr, context, tmplpath)
File "/usr/lib/python2.7/dist-packages/salt/utils/templates.py", line 441, in render_jinja_tmpl
trace=tracestr)
SaltRenderError: Jinja error: expected str, bytearray, or unicode
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/utils/templates.py", line 392, in render_jinja_tmpl
output = template.render(**decoded_context)
File "/usr/lib/python2.7/dist-packages/jinja2/environment.py", line 989, in render
return self.environment.handle_exception(exc_info, True)
File "/usr/lib/python2.7/dist-packages/jinja2/environment.py", line 754, in handle_exception
reraise(exc_type, exc_value, tb)
File "<template>", line 5, in top-level template code
File "/usr/lib/python2.7/dist-packages/salt/modules/nacl.py", line 228, in dec
return salt.utils.nacl.dec(data, **kwargs)
File "/usr/lib/python2.7/dist-packages/salt/utils/nacl.py", line 272, in dec
return sealedbox_decrypt(data, **kwargs)
File "/usr/lib/python2.7/dist-packages/salt/utils/nacl.py", line 347, in sealedbox_decrypt
sk = _get_sk(**kwargs)
File "/usr/lib/python2.7/dist-packages/salt/utils/nacl.py", line 72, in _get_sk
key = salt.utils.stringutils.to_str(config['sk'])
File "/usr/lib/python2.7/dist-packages/salt/utils/stringutils.py", line 118, in to_str
raise TypeError('expected str, bytearray, or unicode')
TypeError: expected str, bytearray, or unicode

; line 5

# Fixed code
def _get_sk(**kwargs):
    """
    Return sk
    """
    config = _get_config(**kwargs)
    key = None
    if config["sk"]:
        key = salt.utils.stringutils.to_str(config["sk"])
    sk_file = config["sk_file"]
    if not key and sk_file:
        try:
            with salt.utils.files.fopen(sk_file, "rb") as keyf:
                key = salt.utils.stringutils.to_unicode(keyf.read()).rstrip("\n")
        except (IOError, OSError):
            raise Exception("no key or sk_file found")
    return base64.b64decode(key)
# Buggy code
def _get_pk(**kwargs):
    """
    Return pk
    """
    config = _get_config(**kwargs)
    pubkey = salt.utils.stringutils.to_str(config["pk"])
    pk_file = config["pk_file"]
    if not pubkey and pk_file:
        with salt.utils.files.fopen(pk_file, "rb") as keyf:
            pubkey = salt.utils.stringutils.to_unicode(keyf.read()).rstrip("\n")
    if pubkey is None:
        raise Exception("no pubkey or pk_file found")
    pubkey = six.text_type(pubkey)
    return base64.b64decode(pubkey)


# Traceback (SaltRenderError)
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/utils/templates.py", line 392, in render_jinja_tmpl
[...]
---
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/pillar/__init__.py", line 736, in render_pstate
**defaults)
File "/usr/lib/python2.7/dist-packages/salt/template.py", line 101, in compile_template
ret = render(input_data, saltenv, sls, **render_kwargs)
File "/usr/lib/python2.7/dist-packages/salt/renderers/jinja.py", line 70, in render
**kws)
File "/usr/lib/python2.7/dist-packages/salt/utils/templates.py", line 169, in render_tmpl
output = render_str(tmplstr, context, tmplpath)
File "/usr/lib/python2.7/dist-packages/salt/utils/templates.py", line 441, in render_jinja_tmpl
trace=tracestr)
SaltRenderError: Jinja error: expected str, bytearray, or unicode
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/utils/templates.py", line 392, in render_jinja_tmpl
output = template.render(**decoded_context)
File "/usr/lib/python2.7/dist-packages/jinja2/environment.py", line 989, in render
return self.environment.handle_exception(exc_info, True)
File "/usr/lib/python2.7/dist-packages/jinja2/environment.py", line 754, in handle_exception
reraise(exc_type, exc_value, tb)
File "<template>", line 5, in top-level template code
File "/usr/lib/python2.7/dist-packages/salt/modules/nacl.py", line 228, in dec
return salt.utils.nacl.dec(data, **kwargs)
File "/usr/lib/python2.7/dist-packages/salt/utils/nacl.py", line 272, in dec
return sealedbox_decrypt(data, **kwargs)
File "/usr/lib/python2.7/dist-packages/salt/utils/nacl.py", line 347, in sealedbox_decrypt
sk = _get_sk(**kwargs)
File "/usr/lib/python2.7/dist-packages/salt/utils/nacl.py", line 72, in _get_sk
key = salt.utils.stringutils.to_str(config['sk'])
File "/usr/lib/python2.7/dist-packages/salt/utils/stringutils.py", line 118, in to_str
raise TypeError('expected str, bytearray, or unicode')
TypeError: expected str, bytearray, or unicode

; line 5

# Fixed code
def _get_pk(**kwargs):
    """
    Return pk
    """
    config = _get_config(**kwargs)
    pubkey = None
    if config["pk"]:
        pubkey = salt.utils.stringutils.to_str(config["pk"])
    pk_file = config["pk_file"]
    if not pubkey and pk_file:
        try:
            with salt.utils.files.fopen(pk_file, "rb") as keyf:
                pubkey = salt.utils.stringutils.to_unicode(keyf.read()).rstrip("\n")
        except (IOError, OSError):
            raise Exception("no pubkey or pk_file found")
    pubkey = six.text_type(pubkey)
    return base64.b64decode(pubkey)
# Buggy code
def prep_jid(nocache=False, passed_jid=None):  # pylint: disable=unused-argument
    """
    Do any work necessary to prepare a JID, including sending a custom id
    """
    return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)


# Traceback (AttributeError)
test: [ERROR   ] An un-handled exception was caught by salt's global exception handler:
test: AttributeError: 'unicode' object has no attribute 'name'
test: Traceback (most recent call last):
test:   File "/bin/spm", line 12, in <module>
test:     salt_spm()
test:   File "/usr/lib/python2.7/site-packages/salt/scripts.py", line 527, in salt_spm
test:     spm.run()
test:   File "/usr/lib/python2.7/site-packages/salt/cli/spm.py", line 41, in run
test:     client.run(self.args)
test:   File "/usr/lib/python2.7/site-packages/salt/spm/__init__.py", line 125, in run
test:     self._install(args)
test:   File "/usr/lib/python2.7/site-packages/salt/spm/__init__.py", line 379, in _install
test:     self._install_indv_pkg(package, out_file)
test:   File "/usr/lib/python2.7/site-packages/salt/spm/__init__.py", line 532, in _install_indv_pkg
test:     self.files_conn)
test:   File "/usr/lib/python2.7/site-packages/salt/spm/__init__.py", line 161, in _pkgfiles_fun
test:     return self.pkgfiles['{0}.{1}'.format(self.files_prov, func)](*args, **kwargs)
test:   File "/usr/lib/python2.7/site-packages/salt/spm/pkgfiles/local.py", line 147, in install_file
test:     member.name = new_name.name.replace('{0}/'.format(package), '')
test: AttributeError: 'unicode' object has no attribute 'name'
test: Traceback (most recent call last):
test:   File "/bin/spm", line 12, in <module>
test:     salt_spm()
test:   File "/usr/lib/python2.7/site-packages/salt/scripts.py", line 527, in salt_spm
test:     spm.run()
test:   File "/usr/lib/python2.7/site-packages/salt/cli/spm.py", line 41, in run
test:     client.run(self.args)
test:   File "/usr/lib/python2.7/site-packages/salt/spm/__init__.py", line 125, in run
test:     self._install(args)
test:   File "/usr/lib/python2.7/site-packages/salt/spm/__init__.py", line 379, in _install
test:     self._install_indv_pkg(package, out_file)
test:   File "/usr/lib/python2.7/site-packages/salt/spm/__init__.py", line 532, in _install_indv_pkg
test:     self.files_conn)
test:   File "/usr/lib/python2.7/site-packages/salt/spm/__init__.py", line 161, in _pkgfiles_fun
test:     return self.pkgfiles['{0}.{1}'.format(self.files_prov, func)](*args, **kwargs)
test:   File "/usr/lib/python2.7/site-packages/salt/spm/pkgfiles/local.py", line 147, in install_file
test:     member.name = new_name.name.replace('{0}/'.format(package), '')
test: AttributeError: 'unicode' object has no attribute 'name'

# Fixed code
def prep_jid(nocache=False, passed_jid=None):  # pylint: disable=unused-argument
    """
    Do any work necessary to prepare a JID, including sending a custom id.
    """
    return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
# Buggy code
def win_interfaces():
    """
    Obtain interface information for Windows systems
    """
    if WIN_NETWORK_LOADED is False:
        # Let's throw the ImportException again
        import salt.utils.win_network
    return salt.utils.win_network.get_interface_info()


# Traceback (AttributeError)
test: [ERROR   ] An un-handled exception was caught by salt's global exception handler:
test: AttributeError: 'unicode' object has no attribute 'name'
test: Traceback (most recent call last):
test:   File "/bin/spm", line 12, in <module>
test:     salt_spm()
test:   File "/usr/lib/python2.7/site-packages/salt/scripts.py", line 527, in salt_spm
test:     spm.run()
test:   File "/usr/lib/python2.7/site-packages/salt/cli/spm.py", line 41, in run
test:     client.run(self.args)
test:   File "/usr/lib/python2.7/site-packages/salt/spm/__init__.py", line 125, in run
test:     self._install(args)
test:   File "/usr/lib/python2.7/site-packages/salt/spm/__init__.py", line 379, in _install
test:     self._install_indv_pkg(package, out_file)
test:   File "/usr/lib/python2.7/site-packages/salt/spm/__init__.py", line 532, in _install_indv_pkg
test:     self.files_conn)
test:   File "/usr/lib/python2.7/site-packages/salt/spm/__init__.py", line 161, in _pkgfiles_fun
test:     return self.pkgfiles['{0}.{1}'.format(self.files_prov, func)](*args, **kwargs)
test:   File "/usr/lib/python2.7/site-packages/salt/spm/pkgfiles/local.py", line 147, in install_file
test:     member.name = new_name.name.replace('{0}/'.format(package), '')
test: AttributeError: 'unicode' object has no attribute 'name'
test: Traceback (most recent call last):
test:   File "/bin/spm", line 12, in <module>
test:     salt_spm()
test:   File "/usr/lib/python2.7/site-packages/salt/scripts.py", line 527, in salt_spm
test:     spm.run()
test:   File "/usr/lib/python2.7/site-packages/salt/cli/spm.py", line 41, in run
test:     client.run(self.args)
test:   File "/usr/lib/python2.7/site-packages/salt/spm/__init__.py", line 125, in run
test:     self._install(args)
test:   File "/usr/lib/python2.7/site-packages/salt/spm/__init__.py", line 379, in _install
test:     self._install_indv_pkg(package, out_file)
test:   File "/usr/lib/python2.7/site-packages/salt/spm/__init__.py", line 532, in _install_indv_pkg
test:     self.files_conn)
test:   File "/usr/lib/python2.7/site-packages/salt/spm/__init__.py", line 161, in _pkgfiles_fun
test:     return self.pkgfiles['{0}.{1}'.format(self.files_prov, func)](*args, **kwargs)
test:   File "/usr/lib/python2.7/site-packages/salt/spm/pkgfiles/local.py", line 147, in install_file
test:     member.name = new_name.name.replace('{0}/'.format(package), '')
test: AttributeError: 'unicode' object has no attribute 'name'

# Fixed code
def win_interfaces():
    """
    Obtain interface information for Windows systems
    """
    return salt.utils.win_network.get_interface_info()
# Buggy code
def _get_network_interfaces():
    clr.AddReference("System.Net")
    return NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()


# Traceback (AttributeError)
test: [ERROR   ] An un-handled exception was caught by salt's global exception handler:
test: AttributeError: 'unicode' object has no attribute 'name'
test: Traceback (most recent call last):
test:   File "/bin/spm", line 12, in <module>
test:     salt_spm()
test:   File "/usr/lib/python2.7/site-packages/salt/scripts.py", line 527, in salt_spm
test:     spm.run()
test:   File "/usr/lib/python2.7/site-packages/salt/cli/spm.py", line 41, in run
test:     client.run(self.args)
test:   File "/usr/lib/python2.7/site-packages/salt/spm/__init__.py", line 125, in run
test:     self._install(args)
test:   File "/usr/lib/python2.7/site-packages/salt/spm/__init__.py", line 379, in _install
test:     self._install_indv_pkg(package, out_file)
test:   File "/usr/lib/python2.7/site-packages/salt/spm/__init__.py", line 532, in _install_indv_pkg
test:     self.files_conn)
test:   File "/usr/lib/python2.7/site-packages/salt/spm/__init__.py", line 161, in _pkgfiles_fun
test:     return self.pkgfiles['{0}.{1}'.format(self.files_prov, func)](*args, **kwargs)
test:   File "/usr/lib/python2.7/site-packages/salt/spm/pkgfiles/local.py", line 147, in install_file
test:     member.name = new_name.name.replace('{0}/'.format(package), '')
test: AttributeError: 'unicode' object has no attribute 'name'
test: Traceback (most recent call last):
test:   File "/bin/spm", line 12, in <module>
test:     salt_spm()
test:   File "/usr/lib/python2.7/site-packages/salt/scripts.py", line 527, in salt_spm
test:     spm.run()
test:   File "/usr/lib/python2.7/site-packages/salt/cli/spm.py", line 41, in run
test:     client.run(self.args)
test:   File "/usr/lib/python2.7/site-packages/salt/spm/__init__.py", line 125, in run
test:     self._install(args)
test:   File "/usr/lib/python2.7/site-packages/salt/spm/__init__.py", line 379, in _install
test:     self._install_indv_pkg(package, out_file)
test:   File "/usr/lib/python2.7/site-packages/salt/spm/__init__.py", line 532, in _install_indv_pkg
test:     self.files_conn)
test:   File "/usr/lib/python2.7/site-packages/salt/spm/__init__.py", line 161, in _pkgfiles_fun
test:     return self.pkgfiles['{0}.{1}'.format(self.files_prov, func)](*args, **kwargs)
test:   File "/usr/lib/python2.7/site-packages/salt/spm/pkgfiles/local.py", line 147, in install_file
test:     member.name = new_name.name.replace('{0}/'.format(package), '')
test: AttributeError: 'unicode' object has no attribute 'name'

# Fixed code
def _get_network_interfaces():
    return NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()
# Buggy code
def ignores_kwargs(*kwarg_names):
    """
    Decorator to filter out unexpected keyword arguments from the call

    kwarg_names:
        List of argument names to ignore
    """

    def _ignores_kwargs(fn):
        def __ignores_kwargs(*args, **kwargs):
            kwargs_filtered = kwargs.copy()
            for name in kwarg_names:
                if name in kwargs_filtered:
                    del kwargs_filtered[name]
            return fn(*args, **kwargs_filtered)

        return __ignores_kwargs

    return _ignores_kwargs


# Traceback (AttributeError)
[ERROR   ] An un-handled exception was caught by salt's global exception handler:
AttributeError: 'module' object has no attribute '__opts__'
Traceback (most recent call last):
File "/usr/bin/salt-call", line 11, in <module>
salt_call()
File "/usr/lib/python2.7/site-packages/salt/scripts.py", line 391, in salt_call
client.run()
File "/usr/lib/python2.7/site-packages/salt/cli/call.py", line 58, in run
caller.run()
File "/usr/lib/python2.7/site-packages/salt/cli/caller.py", line 134, in run
ret = self.call()
File "/usr/lib/python2.7/site-packages/salt/cli/caller.py", line 204, in call
ret['return'] = func(*args, **kwargs)
File "/usr/lib/python2.7/site-packages/salt/modules/state.py", line 593, in apply_
return highstate(**kwargs)
File "/usr/lib/python2.7/site-packages/salt/modules/state.py", line 892, in highstate
orchestration_jid=orchestration_jid)
File "/usr/lib/python2.7/site-packages/salt/state.py", line 3695, in call_highstate
return self.state.call_high(high, orchestration_jid)
File "/usr/lib/python2.7/site-packages/salt/state.py", line 2531, in call_high
ret = self.call_chunks(chunks)
File "/usr/lib/python2.7/site-packages/salt/state.py", line 2017, in call_chunks
running = self.call_chunk(low, running, chunks)
File "/usr/lib/python2.7/site-packages/salt/state.py", line 2345, in call_chunk
running = self.call_chunk(chunk, running, chunks)
File "/usr/lib/python2.7/site-packages/salt/state.py", line 2362, in call_chunk
self.pre[tag] = self.call(low, chunks, running)
File "/usr/lib/python2.7/site-packages/salt/state.py", line 1796, in call
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
AttributeError: 'module' object has no attribute '__opts__'

# Fixed code
def ignores_kwargs(*kwarg_names):
    """
    Decorator to filter out unexpected keyword arguments from the call

    kwarg_names:
        List of argument names to ignore
    """

    def _ignores_kwargs(fn):
        @wraps(fn)
        def __ignores_kwargs(*args, **kwargs):
            kwargs_filtered = kwargs.copy()
            for name in kwarg_names:
                if name in kwargs_filtered:
                    del kwargs_filtered[name]
            return fn(*args, **kwargs_filtered)

        return __ignores_kwargs

    return _ignores_kwargs
# Buggy code
def _ignores_kwargs(fn):
    def __ignores_kwargs(*args, **kwargs):
        kwargs_filtered = kwargs.copy()
        for name in kwarg_names:
            if name in kwargs_filtered:
                del kwargs_filtered[name]
        return fn(*args, **kwargs_filtered)

    return __ignores_kwargs


# Traceback (AttributeError)
[ERROR   ] An un-handled exception was caught by salt's global exception handler:
AttributeError: 'module' object has no attribute '__opts__'
Traceback (most recent call last):
File "/usr/bin/salt-call", line 11, in <module>
salt_call()
File "/usr/lib/python2.7/site-packages/salt/scripts.py", line 391, in salt_call
client.run()
File "/usr/lib/python2.7/site-packages/salt/cli/call.py", line 58, in run
caller.run()
File "/usr/lib/python2.7/site-packages/salt/cli/caller.py", line 134, in run
ret = self.call()
File "/usr/lib/python2.7/site-packages/salt/cli/caller.py", line 204, in call
ret['return'] = func(*args, **kwargs)
File "/usr/lib/python2.7/site-packages/salt/modules/state.py", line 593, in apply_
return highstate(**kwargs)
File "/usr/lib/python2.7/site-packages/salt/modules/state.py", line 892, in highstate
orchestration_jid=orchestration_jid)
File "/usr/lib/python2.7/site-packages/salt/state.py", line 3695, in call_highstate
return self.state.call_high(high, orchestration_jid)
File "/usr/lib/python2.7/site-packages/salt/state.py", line 2531, in call_high
ret = self.call_chunks(chunks)
File "/usr/lib/python2.7/site-packages/salt/state.py", line 2017, in call_chunks
running = self.call_chunk(low, running, chunks)
File "/usr/lib/python2.7/site-packages/salt/state.py", line 2345, in call_chunk
running = self.call_chunk(chunk, running, chunks)
File "/usr/lib/python2.7/site-packages/salt/state.py", line 2362, in call_chunk
self.pre[tag] = self.call(low, chunks, running)
File "/usr/lib/python2.7/site-packages/salt/state.py", line 1796, in call
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
AttributeError: 'module' object has no attribute '__opts__'

# Fixed code
def _ignores_kwargs(fn):
    @wraps(fn)
    def __ignores_kwargs(*args, **kwargs):
        kwargs_filtered = kwargs.copy()
        for name in kwarg_names:
            if name in kwargs_filtered:
                del kwargs_filtered[name]
        return fn(*args, **kwargs_filtered)

    return __ignores_kwargs
# Buggy code
def top_matches(self, top):
    """
    Search through the top high data for matches and return the states
    that this minion needs to execute.

    Returns:
    {'saltenv': ['state1', 'state2', ...]}
    """
    matches = {}
    for saltenv, body in six.iteritems(top):
        if self.opts["pillarenv"]:
            if saltenv != self.opts["pillarenv"]:
                continue
        for match, data in six.iteritems(body):
            if self.matchers["confirm_top.confirm_top"](
                match,
                data,
                self.opts.get("nodegroups", {}),
            ):
                if saltenv not in matches:
                    matches[saltenv] = env_matches = []
                else:
                    env_matches = matches[saltenv]
                for item in data:
                    if isinstance(item, six.string_types) and item not in env_matches:
                        env_matches.append(item)
    return matches


# Traceback (KeyError)
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/salt/master.py", line 1838, in run_func
ret = getattr(self, func)(load)
File "/usr/lib/python2.7/site-packages/salt/master.py", line 1543, in _pillar
data = pillar.compile_pillar()
File "/usr/lib/python2.7/site-packages/salt/pillar/__init__.py", line 1005, in compile_pillar
matches = self.top_matches(top)
File "/usr/lib/python2.7/site-packages/salt/pillar/__init__.py", line 675, in top_matches
self.opts.get('nodegroups', {}),
File "/usr/lib/python2.7/site-packages/salt/matchers/confirm_top.py", line 36, in confirm_top
return m(match)
File "/usr/lib/python2.7/site-packages/salt/matchers/pillar_match.py", line 24, in match
__opts__['pillar'], tgt, delimiter=delimiter
KeyError: u'pillar'

# Fixed code
def top_matches(self, top, reload=False):
    """
    Search through the top high data for matches and return the states
    that this minion needs to execute.

    Returns:
    {'saltenv': ['state1', 'state2', ...]}

    reload
        Reload the matcher loader
    """
    matches = {}
    if reload:
        self.matchers = salt.loader.matchers(self.opts)
    for saltenv, body in six.iteritems(top):
        if self.opts["pillarenv"]:
            if saltenv != self.opts["pillarenv"]:
                continue
        for match, data in six.iteritems(body):
            if self.matchers["confirm_top.confirm_top"](
                match,
                data,
                self.opts.get("nodegroups", {}),
            ):
                if saltenv not in matches:
                    matches[saltenv] = env_matches = []
                else:
                    env_matches = matches[saltenv]
                for item in data:
                    if isinstance(item, six.string_types) and item not in env_matches:
                        env_matches.append(item)
    return matches
# Buggy code
def _clear_context(context):
    """
    Clear variables stored in __context__. Run this function when a new version
    of chocolatey is installed.
    """
    for var in (x for x in __context__ if x.startswith("chocolatey.")):
        context.pop(var)


# Traceback (KeyError)
Traceback (most recent call last):
File "C:\salt\bin\Scripts\salt-call", line 11, in <module>
salt_call()
File "C:\salt\bin\lib\site-packages\salt\scripts.py", line 391, in salt_call
client.run()
File "C:\salt\bin\lib\site-packages\salt\cli\call.py", line 58, in run
caller.run()
File "C:\salt\bin\lib\site-packages\salt\cli\caller.py", line 134, in run
ret = self.call()
File "C:\salt\bin\lib\site-packages\salt\cli\caller.py", line 204, in call
ret['return'] = func(*args, **kwargs)
File "C:\salt\bin\lib\site-packages\salt\modules\chocolatey.py", line 889, in version
'available': available[pkg]}
KeyError: 'freesshd'

# Fixed code
def _clear_context():
    """
    Clear variables stored in __context__. Run this function when a new version
    of chocolatey is installed.
    """
    for var in (x for x in __context__ if x.startswith("chocolatey.")):
        __context__.pop(var)
# Buggy code
def _yes(context):
    """
    Returns ['--yes'] if on v0.9.9.0 or later, otherwise returns an empty list
    """
    if "chocolatey._yes" in __context__:
        return context["chocolatey._yes"]
    if _LooseVersion(chocolatey_version()) >= _LooseVersion("0.9.9"):
        answer = ["--yes"]
    else:
        answer = []
    context["chocolatey._yes"] = answer
    return answer


# Traceback (KeyError)
Traceback (most recent call last):
File "C:\salt\bin\Scripts\salt-call", line 11, in <module>
salt_call()
File "C:\salt\bin\lib\site-packages\salt\scripts.py", line 391, in salt_call
client.run()
File "C:\salt\bin\lib\site-packages\salt\cli\call.py", line 58, in run
caller.run()
File "C:\salt\bin\lib\site-packages\salt\cli\caller.py", line 134, in run
ret = self.call()
File "C:\salt\bin\lib\site-packages\salt\cli\caller.py", line 204, in call
ret['return'] = func(*args, **kwargs)
File "C:\salt\bin\lib\site-packages\salt\modules\chocolatey.py", line 889, in version
'available': available[pkg]}
KeyError: 'freesshd'

# Fixed code
def _yes():
    """
    Returns ['--yes'] if on v0.9.9.0 or later, otherwise returns an empty list
    Confirm all prompts (--yes_ is available on v0.9.9.0 or later
    """
    if "chocolatey._yes" in __context__:
        return __context__["chocolatey._yes"]
    if _LooseVersion(chocolatey_version()) >= _LooseVersion("0.9.9"):
        answer = ["--yes"]
    else:
        answer = []
    __context__["chocolatey._yes"] = answer
    return __context__["chocolatey._yes"]
# Buggy code
def _find_chocolatey(context, salt):
    """
    Returns the full path to chocolatey.bat on the host.
    """
    if "chocolatey._path" in context:
        return context["chocolatey._path"]
    choc_defaults = [
        "C:\\Chocolatey\\bin\\chocolatey.bat",
        "C:\\ProgramData\\Chocolatey\\bin\\chocolatey.exe",
    ]

    choc_path = salt["cmd.which"]("chocolatey.exe")
    if not choc_path:
        for choc_dir in choc_defaults:
            if salt["cmd.has_exec"](choc_dir):
                choc_path = choc_dir
    if not choc_path:
        err = (
            "Chocolatey not installed. Use chocolatey.bootstrap to "
            "install the Chocolatey package manager."
        )
        raise CommandExecutionError(err)
    context["chocolatey._path"] = choc_path
    return choc_path


# Traceback (KeyError)
Traceback (most recent call last):
File "C:\salt\bin\Scripts\salt-call", line 11, in <module>
salt_call()
File "C:\salt\bin\lib\site-packages\salt\scripts.py", line 391, in salt_call
client.run()
File "C:\salt\bin\lib\site-packages\salt\cli\call.py", line 58, in run
caller.run()
File "C:\salt\bin\lib\site-packages\salt\cli\caller.py", line 134, in run
ret = self.call()
File "C:\salt\bin\lib\site-packages\salt\cli\caller.py", line 204, in call
ret['return'] = func(*args, **kwargs)
File "C:\salt\bin\lib\site-packages\salt\modules\chocolatey.py", line 889, in version
'available': available[pkg]}
KeyError: 'freesshd'

# Fixed code
def _find_chocolatey():
    """
    Returns the full path to chocolatey.bat on the host.
    """
    # Check context
    if "chocolatey._path" in __context__:
        return __context__["chocolatey._path"]

    # Check the path
    choc_path = __salt__["cmd.which"]("chocolatey.exe")
    if choc_path:
        __context__["chocolatey._path"] = choc_path
        return __context__["chocolatey._path"]

    # Check in common locations
    choc_defaults = [
        os.path.join(
            os.environ.get("ProgramData"), "Chocolatey", "bin", "chocolatey.exe"
        ),
        os.path.join(
            os.environ.get("SystemDrive"), "Chocolatey", "bin", "chocolatey.bat"
        ),
    ]
    for choc_exe in choc_defaults:
        if os.path.isfile(choc_exe):
            __context__["chocolatey._path"] = choc_exe
            return __context__["chocolatey._path"]

    # Not installed, raise an error
    err = (
        "Chocolatey not installed. Use chocolatey.bootstrap to "
        "install the Chocolatey package manager."
    )
    raise CommandExecutionError(err)
# Buggy code
def chocolatey_version():
    """
    Returns the version of Chocolatey installed on the minion.

    CLI Example:

    .. code-block:: bash

        salt '*' chocolatey.chocolatey_version
    """
    if "chocolatey._version" in __context__:
        return __context__["chocolatey._version"]

    cmd = [_find_chocolatey(__context__, __salt__)]
    cmd.append("-v")
    out = __salt__["cmd.run"](cmd, python_shell=False)
    __context__["chocolatey._version"] = out

    return __context__["chocolatey._version"]


# Traceback (KeyError)
Traceback (most recent call last):
File "C:\salt\bin\Scripts\salt-call", line 11, in <module>
salt_call()
File "C:\salt\bin\lib\site-packages\salt\scripts.py", line 391, in salt_call
client.run()
File "C:\salt\bin\lib\site-packages\salt\cli\call.py", line 58, in run
caller.run()
File "C:\salt\bin\lib\site-packages\salt\cli\caller.py", line 134, in run
ret = self.call()
File "C:\salt\bin\lib\site-packages\salt\cli\caller.py", line 204, in call
ret['return'] = func(*args, **kwargs)
File "C:\salt\bin\lib\site-packages\salt\modules\chocolatey.py", line 889, in version
'available': available[pkg]}
KeyError: 'freesshd'

# Fixed code
def chocolatey_version():
    """
    Returns the version of Chocolatey installed on the minion.

    CLI Example:

    .. code-block:: bash

        salt '*' chocolatey.chocolatey_version
    """
    if "chocolatey._version" in __context__:
        return __context__["chocolatey._version"]

    cmd = [_find_chocolatey()]
    cmd.append("-v")
    out = __salt__["cmd.run"](cmd, python_shell=False)
    __context__["chocolatey._version"] = out

    return __context__["chocolatey._version"]
# Buggy code
def list_webpi():
    """
    Instructs Chocolatey to pull a full package list from the Microsoft Web PI
    repository.

    Returns:
        str: List of webpi packages

    CLI Example:

    .. code-block:: bash

        salt '*' chocolatey.list_webpi
    """
    choc_path = _find_chocolatey(__context__, __salt__)
    cmd = [choc_path, "list", "--source", "webpi"]
    result = __salt__["cmd.run_all"](cmd, python_shell=False)

    if result["retcode"] != 0:
        err = "Running chocolatey failed: {0}".format(result["stdout"])
        raise CommandExecutionError(err)

    return result["stdout"]


# Traceback (KeyError)
Traceback (most recent call last):
File "C:\salt\bin\Scripts\salt-call", line 11, in <module>
salt_call()
File "C:\salt\bin\lib\site-packages\salt\scripts.py", line 391, in salt_call
client.run()
File "C:\salt\bin\lib\site-packages\salt\cli\call.py", line 58, in run
caller.run()
File "C:\salt\bin\lib\site-packages\salt\cli\caller.py", line 134, in run
ret = self.call()
File "C:\salt\bin\lib\site-packages\salt\cli\caller.py", line 204, in call
ret['return'] = func(*args, **kwargs)
File "C:\salt\bin\lib\site-packages\salt\modules\chocolatey.py", line 889, in version
'available': available[pkg]}
KeyError: 'freesshd'

# Fixed code
def list_webpi():
    """
    Instructs Chocolatey to pull a full package list from the Microsoft Web PI
    repository.

    Returns:
        str: List of webpi packages

    CLI Example:

    .. code-block:: bash

        salt '*' chocolatey.list_webpi
    """
    choc_path = _find_chocolatey()
    cmd = [choc_path, "list", "--source", "webpi"]
    result = __salt__["cmd.run_all"](cmd, python_shell=False)

    if result["retcode"] != 0:
        err = "Running chocolatey failed: {0}".format(result["stdout"])
        raise CommandExecutionError(err)

    return result["stdout"]
# Buggy code
def list_windowsfeatures():
    """
    Instructs Chocolatey to pull a full package list from the Windows Features
    list, via the Deployment Image Servicing and Management tool.

    Returns:
        str: List of Windows Features

    CLI Example:

    .. code-block:: bash

        salt '*' chocolatey.list_windowsfeatures
    """
    choc_path = _find_chocolatey(__context__, __salt__)
    cmd = [choc_path, "list", "--source", "windowsfeatures"]
    result = __salt__["cmd.run_all"](cmd, python_shell=False)

    if result["retcode"] != 0:
        err = "Running chocolatey failed: {0}".format(result["stdout"])
        raise CommandExecutionError(err)

    return result["stdout"]


# Traceback (KeyError)
Traceback (most recent call last):
File "C:\salt\bin\Scripts\salt-call", line 11, in <module>
salt_call()
File "C:\salt\bin\lib\site-packages\salt\scripts.py", line 391, in salt_call
client.run()
File "C:\salt\bin\lib\site-packages\salt\cli\call.py", line 58, in run
caller.run()
File "C:\salt\bin\lib\site-packages\salt\cli\caller.py", line 134, in run
ret = self.call()
File "C:\salt\bin\lib\site-packages\salt\cli\caller.py", line 204, in call
ret['return'] = func(*args, **kwargs)
File "C:\salt\bin\lib\site-packages\salt\modules\chocolatey.py", line 889, in version
'available': available[pkg]}
KeyError: 'freesshd'

# Fixed code
def list_windowsfeatures():
    """
    Instructs Chocolatey to pull a full package list from the Windows Features
    list, via the Deployment Image Servicing and Management tool.

    Returns:
        str: List of Windows Features

    CLI Example:

    .. code-block:: bash

        salt '*' chocolatey.list_windowsfeatures
    """
    choc_path = _find_chocolatey()
    cmd = [choc_path, "list", "--source", "windowsfeatures"]
    result = __salt__["cmd.run_all"](cmd, python_shell=False)

    if result["retcode"] != 0:
        err = "Running chocolatey failed: {0}".format(result["stdout"])
        raise CommandExecutionError(err)

    return result["stdout"]
# Buggy code
def add_source(name, source_location, username=None, password=None):
    """
    Instructs Chocolatey to add a source.

    name
        The name of the source to be added as a chocolatey repository.

    source
        Location of the source you want to work with.

    username
        Provide username for chocolatey sources that need authentication
        credentials.

    password
        Provide password for chocolatey sources that need authentication
        credentials.

    CLI Example:

    .. code-block:: bash

        salt '*' chocolatey.add_source <source name> <source_location>
        salt '*' chocolatey.add_source <source name> <source_location> user=<user> password=<password>

    """
    choc_path = _find_chocolatey(__context__, __salt__)
    cmd = [choc_path, "sources", "add", "--name", name, "--source", source_location]
    if username:
        cmd.extend(["--user", username])
    if password:
        cmd.extend(["--password", password])
    result = __salt__["cmd.run_all"](cmd, python_shell=False)

    if result["retcode"] != 0:
        err = "Running chocolatey failed: {0}".format(result["stdout"])
        raise CommandExecutionError(err)

    return result["stdout"]


# Traceback (KeyError)
Traceback (most recent call last):
File "C:\salt\bin\Scripts\salt-call", line 11, in <module>
salt_call()
File "C:\salt\bin\lib\site-packages\salt\scripts.py", line 391, in salt_call
client.run()
File "C:\salt\bin\lib\site-packages\salt\cli\call.py", line 58, in run
caller.run()
File "C:\salt\bin\lib\site-packages\salt\cli\caller.py", line 134, in run
ret = self.call()
File "C:\salt\bin\lib\site-packages\salt\cli\caller.py", line 204, in call
ret['return'] = func(*args, **kwargs)
File "C:\salt\bin\lib\site-packages\salt\modules\chocolatey.py", line 889, in version
'available': available[pkg]}
KeyError: 'freesshd'

# Fixed code
def add_source(name, source_location, username=None, password=None):
    """
    Instructs Chocolatey to add a source.

    name
        The name of the source to be added as a chocolatey repository.

    source
        Location of the source you want to work with.

    username
        Provide username for chocolatey sources that need authentication
        credentials.

    password
        Provide password for chocolatey sources that need authentication
        credentials.

    CLI Example:

    .. code-block:: bash

        salt '*' chocolatey.add_source <source name> <source_location>
        salt '*' chocolatey.add_source <source name> <source_location> user=<user> password=<password>

    """
    cmd = [
        _find_chocolatey(),
        "sources",
        "add",
        "--name",
        name,
        "--source",
        source_location,
    ]
    if username:
        cmd.extend(["--user", username])
    if password:
        cmd.extend(["--password", password])
    result = __salt__["cmd.run_all"](cmd, python_shell=False)

    if result["retcode"] != 0:
        err = "Running chocolatey failed: {0}".format(result["stdout"])
        raise CommandExecutionError(err)

    return result["stdout"]
# Buggy code
def _change_source_state(name, state):
    """
    Instructs Chocolatey to change the state of a source.

    name
        Name of the repository to affect.

    state
        State in which you want the chocolatey repository.

    """
    choc_path = _find_chocolatey(__context__, __salt__)
    cmd = [choc_path, "source", state, "--name", name]
    result = __salt__["cmd.run_all"](cmd, python_shell=False)

    if result["retcode"] != 0:
        err = "Running chocolatey failed: {0}".format(result["stdout"])
        raise CommandExecutionError(err)

    return result["stdout"]


# Traceback (KeyError)
Traceback (most recent call last):
File "C:\salt\bin\Scripts\salt-call", line 11, in <module>
salt_call()
File "C:\salt\bin\lib\site-packages\salt\scripts.py", line 391, in salt_call
client.run()
File "C:\salt\bin\lib\site-packages\salt\cli\call.py", line 58, in run
caller.run()
File "C:\salt\bin\lib\site-packages\salt\cli\caller.py", line 134, in run
ret = self.call()
File "C:\salt\bin\lib\site-packages\salt\cli\caller.py", line 204, in call
ret['return'] = func(*args, **kwargs)
File "C:\salt\bin\lib\site-packages\salt\modules\chocolatey.py", line 889, in version
'available': available[pkg]}
KeyError: 'freesshd'

# Fixed code
def _change_source_state(name, state):
    """
    Instructs Chocolatey to change the state of a source.

    name
        Name of the repository to affect.

    state
        State in which you want the chocolatey repository.

    """
    cmd = [_find_chocolatey(), "source", state, "--name", name]
    result = __salt__["cmd.run_all"](cmd, python_shell=False)

    if result["retcode"] != 0:
        err = "Running chocolatey failed: {0}".format(result["stdout"])
        raise CommandExecutionError(err)

    return result["stdout"]
# Buggy code
def output(ret, bar, **kwargs):  # pylint: disable=unused-argument
    """
    Update the progress bar
    """
    if "return_count" in ret:
        bar.update(ret["return_count"])
    return ""


# Traceback (ValueError)
# salt --progress -L server1,server2 test.ping
[ERROR   ] An un-handled exception was caught by salt's global exception handler:######################################| Elapsed Time: 0:00:00 Returns: [1/1]
ValueError: Value out of range
Traceback (most recent call last):
File "/usr/bin/salt", line 10, in <module>
salt_main()
File "/usr/lib/python2.7/dist-packages/salt/scripts.py", line 476, in salt_main
client.run()
File "/usr/lib/python2.7/dist-packages/salt/cli/salt.py", line 155, in run
self._progress_ret(progress, out)
File "/usr/lib/python2.7/dist-packages/salt/cli/salt.py", line 345, in _progress_ret
salt.output.update_progress(self.config, progress, self.progress_bar, out)
File "/usr/lib/python2.7/dist-packages/salt/output/__init__.py", line 75, in update_progress
progress_outputter(progress, progress_iter)
File "/usr/lib/python2.7/dist-packages/salt/output/progress.py", line 26, in output
bar.update(ret['return_count'])
File "/usr/lib/pymodules/python2.7/progressbar/__init__.py", line 271, in update
raise ValueError('Value out of range')
ValueError: Value out of range
Traceback (most recent call last):
File "/usr/bin/salt", line 10, in <module>
salt_main()
File "/usr/lib/python2.7/dist-packages/salt/scripts.py", line 476, in salt_main
client.run()
File "/usr/lib/python2.7/dist-packages/salt/cli/salt.py", line 155, in run
self._progress_ret(progress, out)
File "/usr/lib/python2.7/dist-packages/salt/cli/salt.py", line 345, in _progress_ret
salt.output.update_progress(self.config, progress, self.progress_bar, out)
File "/usr/lib/python2.7/dist-packages/salt/output/__init__.py", line 75, in update_progress
progress_outputter(progress, progress_iter)
File "/usr/lib/python2.7/dist-packages/salt/output/progress.py", line 26, in output
bar.update(ret['return_count'])
File "/usr/lib/pymodules/python2.7/progressbar/__init__.py", line 271, in update
raise ValueError('Value out of range')
ValueError: Value out of range
#

# Fixed code
def output(ret, bar, **kwargs):  # pylint: disable=unused-argument
    """
    Update the progress bar
    """
    if "return_count" in ret:
        val = ret["return_count"]
        # Avoid to fail if targets are behind a syndic. In this case actual return count will be
        # higher than targeted by MoM itself.
        # TODO: implement a way to get the proper target minions count and remove this workaround.
        # Details are in #44239.
        if val > bar.maxval:
            bar.maxval = val
        bar.update(val)
    return ""
# Buggy code
def docker_to_uuid(uuid):
    """
    Get the image uuid from an imported docker image

    .. versionadded:: 2019.2.0
    """
    if _is_uuid(uuid):
        return uuid
    if _is_docker_uuid(uuid):
        images = list_installed(verbose=True)
        for image_uuid in images:
            if images[image_uuid]["name"] == uuid:
                return image_uuid
    return None


# Traceback (KeyError)
sudo salt global_deneb state.apply smartos_docker_container.plex3
global_deneb:
----------
ID: https://docker.io
Function: smartos.source_present
Result: True
Comment: image source https://docker.io is present
Started: 16:08:29.276973
Duration: 493.941 ms
Changes:
----------
ID: plex3.agdon.net
Function: smartos.vm_present
Result: False
Comment: An exception occurred in this state: Traceback (most recent call last):
File "/opt/tools/lib/python2.7/site-packages/salt/state.py", line 1951, in call
ret = self.states[cdata['full']](*cdata['args'], **cdata['kwargs'])
File "/opt/tools/lib/python2.7/site-packages/salt/loader.py", line 2033, in wrapper
return f(*args, **kwargs)
File "/opt/tools/lib/python2.7/site-packages/salt/states/smartos.py", line 801, in vm_present
if vmconfig['image_uuid'] not in __salt__['imgadm.list']():
File "/opt/tools/lib/python2.7/site-packages/salt/modules/smartos_imgadm.py", line 257, in list_installed
data = _parse_image_meta(image, verbose)
File "/opt/tools/lib/python2.7/site-packages/salt/modules/smartos_imgadm.py", line 60, in _parse_image_meta
name = image['manifest']['name']
KeyError: u'name'
Started: 16:08:29.772658
Duration: 1384.224 ms
Changes:

Summary for global_deneb
------------
Succeeded: 1
Failed:    1
------------
Total states run:     2
Total run time:   1.878 s

# Fixed code
def docker_to_uuid(uuid):
    """
    Get the image uuid from an imported docker image

    .. versionadded:: 2019.2.0
    """
    if _is_uuid(uuid):
        return uuid
    if _is_docker_uuid(uuid):
        images = list_installed(verbose=True)
        for image_uuid in images:
            if "name" not in images[image_uuid]:
                continue
            if images[image_uuid]["name"] == uuid:
                return image_uuid
    return None
# Buggy code
def handle_key_cache(self):
    """
    Evaluate accepted keys and create a msgpack file
    which contains a list
    """
    if self.opts["key_cache"] == "sched":
        keys = []
        # TODO DRY from CKMinions
        if self.opts["transport"] in ("zeromq", "tcp"):
            acc = "minions"
        else:
            acc = "accepted"

        for fn_ in os.listdir(os.path.join(self.opts["pki_dir"], acc)):
            if not fn_.startswith(".") and os.path.isfile(
                os.path.join(self.opts["pki_dir"], acc, fn_)
            ):
                keys.append(fn_)
        log.debug("Writing master key cache")
        # Write a temporary file securely
        with salt.utils.atomicfile.atomic_open(
            os.path.join(self.opts["pki_dir"], acc, ".key_cache")
        ) as cache_file:
            self.serial.dump(keys, cache_file)


# Traceback (TypeError)
2018-12-13 07:53:11,853 [salt.utils.process:754 ][ERROR   ][5051] An un-handled exception from the multiprocessing process 'Maintenance-94' was caught:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/salt/utils/process.py", line 747, in _run
return self._original_run()
File "/usr/lib/python3/dist-packages/salt/master.py", line 228, in run
self.handle_key_cache()
File "/usr/lib/python3/dist-packages/salt/master.py", line 254, in handle_key_cache
self.serial.dump(keys, cache_file)
File "/usr/lib/python3/dist-packages/salt/payload.py", line 256, in dump
fn_.write(self.dumps(msg, use_bin_type=True))
File "/usr/lib/python3.6/tempfile.py", line 624, in func_wrapper
return func(*args, **kwargs)
TypeError: write() argument must be str, not bytes

# Fixed code
def handle_key_cache(self):
    """
    Evaluate accepted keys and create a msgpack file
    which contains a list
    """
    if self.opts["key_cache"] == "sched":
        keys = []
        # TODO DRY from CKMinions
        if self.opts["transport"] in ("zeromq", "tcp"):
            acc = "minions"
        else:
            acc = "accepted"

        for fn_ in os.listdir(os.path.join(self.opts["pki_dir"], acc)):
            if not fn_.startswith(".") and os.path.isfile(
                os.path.join(self.opts["pki_dir"], acc, fn_)
            ):
                keys.append(fn_)
        log.debug("Writing master key cache")
        # Write a temporary file securely
        if six.PY2:
            with salt.utils.atomicfile.atomic_open(
                os.path.join(self.opts["pki_dir"], acc, ".key_cache")
            ) as cache_file:
                self.serial.dump(keys, cache_file)
        else:
            with salt.utils.atomicfile.atomic_open(
                os.path.join(self.opts["pki_dir"], acc, ".key_cache"), mode="wb"
            ) as cache_file:
                self.serial.dump(keys, cache_file)