gurudesh/pytracebugs huggingface dataset:
# Buggy code
def _cpv_to_cp(cpv):
    ret = portage.cpv_getkey(cpv)
    if ret:
        return ret
    else:
        return cpv


# Traceback (AttributeError)
ID: sys-apps/util-linux
Function: pkg.installed
Result: False
Comment: An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib64/python2.7/site-packages/salt/state.py", line 1723, in call
**cdata['kwargs'])
File "/usr/lib64/python2.7/site-packages/salt/loader.py", line 1650, in wrapper
return f(*args, **kwargs)
File "/usr/lib64/python2.7/site-packages/salt/states/pkg.py", line 1208, in installed
**kwargs)
File "/usr/lib64/python2.7/site-packages/salt/modules/ebuild.py", line 643, in install
['~ARCH'])
File "/usr/lib64/python2.7/site-packages/salt/modules/portage_config.py", line 348, in append_to_package_conf
append_to_package_conf(conf, string=atom, overwrite=overwrite)
File "/usr/lib64/python2.7/site-packages/salt/modules/portage_config.py", line 357, in append_to_package_conf
pdir = os.path.dirname(complete_file_path)
File "/usr/lib64/python2.7/posixpath.py", line 122, in dirname
i = p.rfind('/') + 1
AttributeError: 'NoneType' object has no attribute 'rfind'
Started: 21:26:12.025851
Duration: 1081.085 ms
Changes

# Fixed code
def _cpv_to_cp(cpv):
    try:
        ret = portage.dep_getkey(cpv)
        if ret:
            return ret
    except portage.exception.InvalidAtom:
        pass

    return cpv
# Buggy code
def _get_config_file(conf, atom):
    """
    Parse the given atom, allowing access to its parts
    Success does not mean that the atom exists, just that it
    is in the correct format.
    Returns none if the atom is invalid.
    """
    if "*" in atom:
        parts = portage.dep.Atom(atom, allow_wildcard=True)
        if not parts:
            return
        if parts.cp == "*/*":
            # parts.repo will be empty if there is no repo part
            relative_path = parts.repo or "gentoo"
        else:
            relative_path = os.path.join(
                *[x for x in os.path.split(parts.cp) if x != "*"]
            )
    else:
        relative_path = _p_to_cp(atom)
        if not relative_path:
            return

    complete_file_path = BASE_PATH.format(conf) + "/" + relative_path

    return complete_file_path


# Traceback (AttributeError)
ID: sys-apps/util-linux
Function: pkg.installed
Result: False
Comment: An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib64/python2.7/site-packages/salt/state.py", line 1723, in call
**cdata['kwargs'])
File "/usr/lib64/python2.7/site-packages/salt/loader.py", line 1650, in wrapper
return f(*args, **kwargs)
File "/usr/lib64/python2.7/site-packages/salt/states/pkg.py", line 1208, in installed
**kwargs)
File "/usr/lib64/python2.7/site-packages/salt/modules/ebuild.py", line 643, in install
['~ARCH'])
File "/usr/lib64/python2.7/site-packages/salt/modules/portage_config.py", line 348, in append_to_package_conf
append_to_package_conf(conf, string=atom, overwrite=overwrite)
File "/usr/lib64/python2.7/site-packages/salt/modules/portage_config.py", line 357, in append_to_package_conf
pdir = os.path.dirname(complete_file_path)
File "/usr/lib64/python2.7/posixpath.py", line 122, in dirname
i = p.rfind('/') + 1
AttributeError: 'NoneType' object has no attribute 'rfind'
Started: 21:26:12.025851
Duration: 1081.085 ms
Changes

# Fixed code
def _get_config_file(conf, atom):
    """
    Parse the given atom, allowing access to its parts
    Success does not mean that the atom exists, just that it
    is in the correct format.
    Returns none if the atom is invalid.
    """
    if "*" in atom:
        parts = portage.dep.Atom(atom, allow_wildcard=True)
        if not parts:
            return
        if parts.cp == "*/*":
            # parts.repo will be empty if there is no repo part
            relative_path = parts.repo or "gentoo"
        elif str(parts.cp).endswith("/*"):
            relative_path = str(parts.cp).split("/")[0] + "_"
        else:
            relative_path = os.path.join(
                *[x for x in os.path.split(parts.cp) if x != "*"]
            )
    else:
        relative_path = _p_to_cp(atom)
        if not relative_path:
            return

    complete_file_path = BASE_PATH.format(conf) + "/" + relative_path

    return complete_file_path
# Buggy code
def _p_to_cp(p):
    """
    Convert a package name or a DEPEND atom to category/package format.
    Raises an exception if program name is ambiguous.
    """
    ret = _porttree().dbapi.xmatch("match-all", p)
    if ret:
        return portage.cpv_getkey(ret[0])
    return None


# Traceback (AttributeError)
ID: sys-apps/util-linux
Function: pkg.installed
Result: False
Comment: An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib64/python2.7/site-packages/salt/state.py", line 1723, in call
**cdata['kwargs'])
File "/usr/lib64/python2.7/site-packages/salt/loader.py", line 1650, in wrapper
return f(*args, **kwargs)
File "/usr/lib64/python2.7/site-packages/salt/states/pkg.py", line 1208, in installed
**kwargs)
File "/usr/lib64/python2.7/site-packages/salt/modules/ebuild.py", line 643, in install
['~ARCH'])
File "/usr/lib64/python2.7/site-packages/salt/modules/portage_config.py", line 348, in append_to_package_conf
append_to_package_conf(conf, string=atom, overwrite=overwrite)
File "/usr/lib64/python2.7/site-packages/salt/modules/portage_config.py", line 357, in append_to_package_conf
pdir = os.path.dirname(complete_file_path)
File "/usr/lib64/python2.7/posixpath.py", line 122, in dirname
i = p.rfind('/') + 1
AttributeError: 'NoneType' object has no attribute 'rfind'
Started: 21:26:12.025851
Duration: 1081.085 ms
Changes

# Fixed code
def _p_to_cp(p):
    """
    Convert a package name or a DEPEND atom to category/package format.
    Raises an exception if program name is ambiguous.
    """
    try:
        ret = portage.dep_getkey(p)
        if ret:
            return ret
    except portage.exception.InvalidAtom:
        pass

    try:
        ret = _porttree().dbapi.xmatch("bestmatch-visible", p)
        if ret:
            return portage.dep_getkey(ret)
    except portage.exception.InvalidAtom:
        pass

    return None
# Buggy code
def _package_conf_file_to_dir(file_name):
    """
    Convert a config file to a config directory.
    """
    if file_name in SUPPORTED_CONFS:
        path = BASE_PATH.format(file_name)
        if os.path.exists(path):
            if os.path.isdir(path):
                return False
            else:
                os.rename(path, path + ".tmpbak")
                os.mkdir(path, 0o755)
                with salt.utils.files.fopen(path + ".tmpbak") as fh_:
                    for line in fh_:
                        line = line.strip()
                        if line and not line.startswith("#"):
                            append_to_package_conf(file_name, string=line)
                os.remove(path + ".tmpbak")
                return True
        else:
            os.mkdir(path, 0o755)
            return True


# Traceback (AttributeError)
ID: sys-apps/util-linux
Function: pkg.installed
Result: False
Comment: An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib64/python2.7/site-packages/salt/state.py", line 1723, in call
**cdata['kwargs'])
File "/usr/lib64/python2.7/site-packages/salt/loader.py", line 1650, in wrapper
return f(*args, **kwargs)
File "/usr/lib64/python2.7/site-packages/salt/states/pkg.py", line 1208, in installed
**kwargs)
File "/usr/lib64/python2.7/site-packages/salt/modules/ebuild.py", line 643, in install
['~ARCH'])
File "/usr/lib64/python2.7/site-packages/salt/modules/portage_config.py", line 348, in append_to_package_conf
append_to_package_conf(conf, string=atom, overwrite=overwrite)
File "/usr/lib64/python2.7/site-packages/salt/modules/portage_config.py", line 357, in append_to_package_conf
pdir = os.path.dirname(complete_file_path)
File "/usr/lib64/python2.7/posixpath.py", line 122, in dirname
i = p.rfind('/') + 1
AttributeError: 'NoneType' object has no attribute 'rfind'
Started: 21:26:12.025851
Duration: 1081.085 ms
Changes

# Fixed code
def _package_conf_file_to_dir(file_name):
    """
    Convert a config file to a config directory.
    """
    if file_name in SUPPORTED_CONFS:
        path = BASE_PATH.format(file_name)
        if os.path.exists(path):
            if os.path.isdir(path):
                return False
            else:
                os.rename(path, path + ".tmpbak")
                os.mkdir(path, 0o755)
                os.rename(path + ".tmpbak", os.path.join(path, "tmp"))
                return True
        else:
            os.mkdir(path, 0o755)
            return True
# Buggy code
def __gather_minions(self):
    """
    Return a list of minions to use for the batch run
    """
    args = [
        self.opts["tgt"],
        "test.ping",
        [],
        self.opts["timeout"],
    ]

    selected_target_option = self.opts.get("selected_target_option", None)
    if selected_target_option is not None:
        args.append(selected_target_option)
    else:
        args.append(self.opts.get("expr_form", "glob"))

    ping_gen = self.local.cmd_iter(*args, **self.eauth)

    fret = set()
    try:
        for ret in ping_gen:
            m = next(six.iterkeys(ret))
            if m is not None:
                fret.add(m)
        return (list(fret), ping_gen)
    except StopIteration:
        raise salt.exceptions.SaltClientError("No minions matched the target.")


# Traceback (SaltClientError)
----------
ID: test-state
Function: salt.state
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 1723, in call
**cdata['kwargs'])
File "/usr/lib/python2.7/dist-packages/salt/loader.py", line 1650, in wrapper
return f(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/salt/states/saltmod.py", line 230, in state
cmd_ret = __salt__['saltutil.cmd'](tgt, fun, **cmd_kw)
File "/usr/lib/python2.7/dist-packages/salt/modules/saltutil.py", line 959, in cmd
client, tgt, fun, arg, timeout, expr_form, ret, kwarg, **kwargs)
File "/usr/lib/python2.7/dist-packages/salt/modules/saltutil.py", line 927, in _exec
for ret_comp in _cmd(**cmd_kwargs):
File "/usr/lib/python2.7/dist-packages/salt/client/__init__.py", line 439, in cmd_batch
batch = salt.cli.batch.Batch(opts, quiet=True)
File "/usr/lib/python2.7/dist-packages/salt/cli/batch.py", line 35, in __init__
self.minions, self.ping_gen = self.__gather_minions()
File "/usr/lib/python2.7/dist-packages/salt/cli/batch.py", line 64, in __gather_minions
raise salt.exceptions.SaltClientError('No minions matched the target.')
SaltClientError: No minions matched the target.
Started: 07:44:19.694000
Duration: 36.931 ms
Changes:

# Fixed code
def __gather_minions(self):
    """
    Return a list of minions to use for the batch run
    """
    args = [
        self.opts["tgt"],
        "test.ping",
        [],
        self.opts["timeout"],
    ]

    selected_target_option = self.opts.get("selected_target_option", None)
    if selected_target_option is not None:
        args.append(selected_target_option)
    else:
        args.append(self.opts.get("expr_form", "glob"))

    ping_gen = self.local.cmd_iter(*args, **self.eauth)

    # Broadcast to targets
    fret = set()
    try:
        for ret in ping_gen:
            m = next(six.iterkeys(ret))
            if m is not None:
                fret.add(m)
    except StopIteration:
        if not self.quiet:
            print_cli("No minions matched the target.")
    return list(fret), ping_gen
# Buggy code
def _passphrase_callback(passphrase):
    """
    Returns a callback function used to supply a passphrase for private keys
    """

    def f(*args):
        return passphrase

    return f


# Traceback (CommandExecutionError)
salt-call state.apply testcase
[ERROR   ] An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/salt/state.py", line 1878, in call
**cdata['kwargs'])
File "/usr/lib/python2.7/site-packages/salt/loader.py", line 1823, in wrapper
return f(*args, **kwargs)
File "/usr/lib/python2.7/site-packages/salt/states/x509.py", line 303, in private_key_managed
name, bits=bits, passphrase=passphrase, new=new, overwrite=overwrite):
File "/usr/lib/python2.7/site-packages/salt/states/x509.py", line 240, in _check_private_key
'The provided passphrase cannot decrypt the private key.')
CommandExecutionError: The provided passphrase cannot decrypt the private key.

local:
----------
ID: test_key
Function: x509.private_key_managed
Name: /tmp/test.key
Result: False
Comment: An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/salt/state.py", line 1878, in call
**cdata['kwargs'])
File "/usr/lib/python2.7/site-packages/salt/loader.py", line 1823, in wrapper
return f(*args, **kwargs)
File "/usr/lib/python2.7/site-packages/salt/states/x509.py", line 303, in private_key_managed
name, bits=bits, passphrase=passphrase, new=new, overwrite=overwrite):
File "/usr/lib/python2.7/site-packages/salt/states/x509.py", line 240, in _check_private_key
'The provided passphrase cannot decrypt the private key.')
CommandExecutionError: The provided passphrase cannot decrypt the private key.
Started: 09:13:58.553635
Duration: 10.903 ms
Changes:
----------
ID: test_cert
Function: x509.certificate_managed
Name: /tmp/test.crt
Result: False
Comment: One or more requisite failed: testcase.test_key
Changes:

Summary for local
------------
Succeeded: 0
Failed:    2
------------
Total states run:     2
Total run time:  10.903 ms

# Fixed code
def _passphrase_callback(passphrase):
    """
    Returns a callback function used to supply a passphrase for private keys
    """

    def f(*args):
        return salt.utils.stringutils.to_str(passphrase)

    return f
# Buggy code
def f(*args):
    return passphrase


# Traceback (CommandExecutionError)
salt-call state.apply testcase
[ERROR   ] An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/salt/state.py", line 1878, in call
**cdata['kwargs'])
File "/usr/lib/python2.7/site-packages/salt/loader.py", line 1823, in wrapper
return f(*args, **kwargs)
File "/usr/lib/python2.7/site-packages/salt/states/x509.py", line 303, in private_key_managed
name, bits=bits, passphrase=passphrase, new=new, overwrite=overwrite):
File "/usr/lib/python2.7/site-packages/salt/states/x509.py", line 240, in _check_private_key
'The provided passphrase cannot decrypt the private key.')
CommandExecutionError: The provided passphrase cannot decrypt the private key.

local:
----------
ID: test_key
Function: x509.private_key_managed
Name: /tmp/test.key
Result: False
Comment: An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/salt/state.py", line 1878, in call
**cdata['kwargs'])
File "/usr/lib/python2.7/site-packages/salt/loader.py", line 1823, in wrapper
return f(*args, **kwargs)
File "/usr/lib/python2.7/site-packages/salt/states/x509.py", line 303, in private_key_managed
name, bits=bits, passphrase=passphrase, new=new, overwrite=overwrite):
File "/usr/lib/python2.7/site-packages/salt/states/x509.py", line 240, in _check_private_key
'The provided passphrase cannot decrypt the private key.')
CommandExecutionError: The provided passphrase cannot decrypt the private key.
Started: 09:13:58.553635
Duration: 10.903 ms
Changes:
----------
ID: test_cert
Function: x509.certificate_managed
Name: /tmp/test.crt
Result: False
Comment: One or more requisite failed: testcase.test_key
Changes:

Summary for local
------------
Succeeded: 0
Failed:    2
------------
Total states run:     2
Total run time:  10.903 ms

# Fixed code
def f(*args):
    return salt.utils.stringutils.to_str(passphrase)
# Buggy code
def cache_nodes_ip(opts, base=None):
    """
    Retrieve a list of all nodes from Salt Cloud cache, and any associated IP
    addresses. Returns a dict.
    """
    salt.utils.versions.warn_until(
        "Flourine",
        "This function is incomplete and non-functional "
        "and will be removed in Salt Flourine.",
    )
    if base is None:
        base = opts["cachedir"]

    minions = list_cache_nodes_full(opts, base=base)


# Traceback (ValueError)
Function: win_servermanager.installed
Name: Web-Common-HTTP
Result: False
Comment: An exception occurred in this state: Traceback (most recent call last):
File "c:\salt\bin\lib\site-packages\salt\state.py", line 1878, in call
**cdata['kwargs'])
File "c:\salt\bin\lib\site-packages\salt\loader.py", line 1823, in wrapper
return f(*args, **kwargs)
File "c:\salt\bin\lib\site-packages\salt\states\win_servermanager.py", line 119, in installed
'Parameter \'force\' has been detected in the argument list. This'
File "c:\salt\bin\lib\site-packages\salt\utils\versions.py", line 116, in warn_until
version = salt.version.SaltStackVersion.from_name(version)
File "c:\salt\bin\lib\site-packages\salt\version.py", line 278, in from_name
'Named version \'{0}\' is not known'.format(name)
ValueError: Named version 'Flourine' is not known
Started: 12:54:49.158419
Duration: 0.0 ms
Changes:

# Fixed code
def cache_nodes_ip(opts, base=None):
    """
    Retrieve a list of all nodes from Salt Cloud cache, and any associated IP
    addresses. Returns a dict.
    """
    salt.utils.versions.warn_until(
        "Fluorine",
        "This function is incomplete and non-functional "
        "and will be removed in Salt Fluorine.",
    )
    if base is None:
        base = opts["cachedir"]

    minions = list_cache_nodes_full(opts, base=base)
# Buggy code
def server_list_min(self):
    """
    List minimal information about servers
    """
    nt_ks = self.compute_conn
    ret = {}
    for item in nt_ks.servers.list(detailed=False):
        try:
            ret[item.name] = {"id": item.id, "status": "Running"}
        except TypeError:
            pass
    return ret


# Traceback (KeyError)
[INFO    ] Applying map from 'blah'.
[DEBUG   ] Could not LazyLoad nova.optimize_providers: 'nova.optimize_providers' is not available.
[DEBUG   ] The 'nova' cloud driver is unable to be optimized.
[DEBUG   ] LazyLoaded versions.warn_until
[DEBUG   ] Could not LazyLoad parallels.avail_sizes: 'parallels' __virtual__ returned False
[DEBUG   ] LazyLoaded parallels.avail_locations
[DEBUG   ] LazyLoaded proxmox.avail_sizes
[ERROR   ] There was a query error: u'state'
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/salt/cloud/cli.py", line 303, in run
dmap = mapper.map_data()
File "/usr/lib/python2.7/site-packages/salt/cloud/__init__.py", line 2005, in map_data
matching = get_matching_by_name(name)
File "/usr/lib/python2.7/site-packages/salt/cloud/__init__.py", line 1994, in get_matching_by_name
matches[driver] = details['state']
KeyError: u'state'

# Fixed code
def server_list_min(self):
    """
    List minimal information about servers
    """
    nt_ks = self.compute_conn
    ret = {}
    for item in nt_ks.servers.list(detailed=False):
        try:
            ret[item.name] = {"id": item.id, "state": "Running"}
        except TypeError:
            pass
    return ret
# Buggy code
def list_upgrades(refresh=True):
    """
    List all available package upgrades on this system

    CLI Example:

    .. code-block:: bash

        salt '*' pkg.list_upgrades
    """
    if salt.utils.is_true(refresh):
        refresh_db()

    ret = {}
    for name, data in six.iteritems(get_repo_data().get("repo", {})):
        if version(name):
            latest = latest_version(name)
            if latest:
                ret[name] = latest
    return ret


# Traceback (CommandExecutionError)
----------
ID: openvpn
Function: pkg.installed
Result: False
Comment: An exception occurred in this state: Traceback (most recent call last):
File "C:\salt\bin\lib\site-packages\salt\state.py", line 1626, in call
**cdata['kwargs'])
File "C:\salt\bin\lib\site-packages\salt\loader.py", line 1492, in wrapper
return f(*args, **kwargs)
File "c:\salt\var\cache\salt\minion\extmods\states\pkg.py", line 984, in installed
**kwargs)
File "c:\salt\var\cache\salt\minion\extmods\states\pkg.py", line 294, in _find_install_targets
cur_pkgs = __salt__['pkg.list_pkgs'](versions_as_list=True, **kwargs)
File "c:\salt\var\cache\salt\minion\extmods\modules\win_pkg.py", line 244, in list_pkgs
name_map = _get_name_map()
File "c:\salt\var\cache\salt\minion\extmods\modules\win_pkg.py", line 1067, in _get_name_map
name_map = get_repo_data().get('name_map', {})
File "c:\salt\var\cache\salt\minion\extmods\modules\win_pkg.py", line 1050, in get_repo_data
'Windows repo cache doesn\'t exist, pkg.refresh_db likely '
CommandExecutionError: Windows repo cache doesn't exist, pkg.refresh_db likely needed

# Fixed code
def list_upgrades(refresh=True, saltenv="base"):
    """
    List all available package upgrades on this system

    CLI Example:

    .. code-block:: bash

        salt '*' pkg.list_upgrades
    """
    if salt.utils.is_true(refresh):
        refresh_db(saltenv)

    ret = {}
    for name, data in six.iteritems(get_repo_data(saltenv).get("repo", {})):
        if version(name):
            latest = latest_version(name)
            if latest:
                ret[name] = latest
    return ret
# Buggy code
def list_available(*names):
    """
    Return a list of available versions of the specified package.

    CLI Example:

    .. code-block:: bash

        salt '*' pkg.list_available <package name>
        salt '*' pkg.list_available <package name01> <package name02>
    """
    if not names:
        return ""
    if len(names) == 1:
        pkginfo = _get_package_info(names[0])
        if not pkginfo:
            return ""
        versions = list(pkginfo.keys())
    else:
        versions = {}
        for name in names:
            pkginfo = _get_package_info(name)
            if not pkginfo:
                continue
            versions[name] = list(pkginfo.keys()) if pkginfo else []
    versions = sorted(versions, cmp=_reverse_cmp_pkg_versions)
    return versions


# Traceback (CommandExecutionError)
----------
ID: openvpn
Function: pkg.installed
Result: False
Comment: An exception occurred in this state: Traceback (most recent call last):
File "C:\salt\bin\lib\site-packages\salt\state.py", line 1626, in call
**cdata['kwargs'])
File "C:\salt\bin\lib\site-packages\salt\loader.py", line 1492, in wrapper
return f(*args, **kwargs)
File "c:\salt\var\cache\salt\minion\extmods\states\pkg.py", line 984, in installed
**kwargs)
File "c:\salt\var\cache\salt\minion\extmods\states\pkg.py", line 294, in _find_install_targets
cur_pkgs = __salt__['pkg.list_pkgs'](versions_as_list=True, **kwargs)
File "c:\salt\var\cache\salt\minion\extmods\modules\win_pkg.py", line 244, in list_pkgs
name_map = _get_name_map()
File "c:\salt\var\cache\salt\minion\extmods\modules\win_pkg.py", line 1067, in _get_name_map
name_map = get_repo_data().get('name_map', {})
File "c:\salt\var\cache\salt\minion\extmods\modules\win_pkg.py", line 1050, in get_repo_data
'Windows repo cache doesn\'t exist, pkg.refresh_db likely '
CommandExecutionError: Windows repo cache doesn't exist, pkg.refresh_db likely needed

# Fixed code
def list_available(saltenv="base", *names):
    """
    Return a list of available versions of the specified package.

    CLI Example:

    .. code-block:: bash

        salt '*' pkg.list_available <package name>
        salt '*' pkg.list_available <package name01> <package name02>
    """
    if not names:
        return ""
    if len(names) == 1:
        pkginfo = _get_package_info(names[0], saltenv=saltenv)
        if not pkginfo:
            return ""
        versions = list(pkginfo.keys())
    else:
        versions = {}
        for name in names:
            pkginfo = _get_package_info(name, saltenv=saltenv)
            if not pkginfo:
                continue
            versions[name] = list(pkginfo.keys()) if pkginfo else []
    versions = sorted(versions, cmp=_reverse_cmp_pkg_versions)
    return versions
# Buggy code
def purge(name=None, pkgs=None, version=None, **kwargs):
    """
    Package purges are not supported, this function is identical to
    ``remove()``.

    name
        The name of the package to be deleted.

    version
        The version of the package to be deleted. If this option is used in
        combination with the ``pkgs`` option below, then this version will be
        applied to all targeted packages.


    Multiple Package Options:

    pkgs
        A list of packages to delete. Must be passed as a python list. The
        ``name`` parameter will be ignored if this option is passed.

    .. versionadded:: 0.16.0


    Returns a dict containing the changes.

    CLI Example:

    .. code-block:: bash

        salt '*' pkg.purge <package name>
        salt '*' pkg.purge <package1>,<package2>,<package3>
        salt '*' pkg.purge pkgs='["foo", "bar"]'
    """
    return remove(name=name, pkgs=pkgs, version=version, **kwargs)


# Traceback (CommandExecutionError)
----------
ID: openvpn
Function: pkg.installed
Result: False
Comment: An exception occurred in this state: Traceback (most recent call last):
File "C:\salt\bin\lib\site-packages\salt\state.py", line 1626, in call
**cdata['kwargs'])
File "C:\salt\bin\lib\site-packages\salt\loader.py", line 1492, in wrapper
return f(*args, **kwargs)
File "c:\salt\var\cache\salt\minion\extmods\states\pkg.py", line 984, in installed
**kwargs)
File "c:\salt\var\cache\salt\minion\extmods\states\pkg.py", line 294, in _find_install_targets
cur_pkgs = __salt__['pkg.list_pkgs'](versions_as_list=True, **kwargs)
File "c:\salt\var\cache\salt\minion\extmods\modules\win_pkg.py", line 244, in list_pkgs
name_map = _get_name_map()
File "c:\salt\var\cache\salt\minion\extmods\modules\win_pkg.py", line 1067, in _get_name_map
name_map = get_repo_data().get('name_map', {})
File "c:\salt\var\cache\salt\minion\extmods\modules\win_pkg.py", line 1050, in get_repo_data
'Windows repo cache doesn\'t exist, pkg.refresh_db likely '
CommandExecutionError: Windows repo cache doesn't exist, pkg.refresh_db likely needed

# Fixed code
def purge(name=None, pkgs=None, version=None, saltenv="base", **kwargs):
    """
    Package purges are not supported, this function is identical to
    ``remove()``.

    name
        The name of the package to be deleted.

    version
        The version of the package to be deleted. If this option is used in
        combination with the ``pkgs`` option below, then this version will be
        applied to all targeted packages.


    Multiple Package Options:

    pkgs
        A list of packages to delete. Must be passed as a python list. The
        ``name`` parameter will be ignored if this option is passed.

    .. versionadded:: 0.16.0


    Returns a dict containing the changes.

    CLI Example:

    .. code-block:: bash

        salt '*' pkg.purge <package name>
        salt '*' pkg.purge <package1>,<package2>,<package3>
        salt '*' pkg.purge pkgs='["foo", "bar"]'
    """
    return remove(name=name, pkgs=pkgs, version=version, saltenv=saltenv, **kwargs)
# Buggy code
def get_name_map():
    return _get_name_map()


# Traceback (CommandExecutionError)
----------
ID: openvpn
Function: pkg.installed
Result: False
Comment: An exception occurred in this state: Traceback (most recent call last):
File "C:\salt\bin\lib\site-packages\salt\state.py", line 1626, in call
**cdata['kwargs'])
File "C:\salt\bin\lib\site-packages\salt\loader.py", line 1492, in wrapper
return f(*args, **kwargs)
File "c:\salt\var\cache\salt\minion\extmods\states\pkg.py", line 984, in installed
**kwargs)
File "c:\salt\var\cache\salt\minion\extmods\states\pkg.py", line 294, in _find_install_targets
cur_pkgs = __salt__['pkg.list_pkgs'](versions_as_list=True, **kwargs)
File "c:\salt\var\cache\salt\minion\extmods\modules\win_pkg.py", line 244, in list_pkgs
name_map = _get_name_map()
File "c:\salt\var\cache\salt\minion\extmods\modules\win_pkg.py", line 1067, in _get_name_map
name_map = get_repo_data().get('name_map', {})
File "c:\salt\var\cache\salt\minion\extmods\modules\win_pkg.py", line 1050, in get_repo_data
'Windows repo cache doesn\'t exist, pkg.refresh_db likely '
CommandExecutionError: Windows repo cache doesn't exist, pkg.refresh_db likely needed

# Fixed code
def get_name_map(saltenv="base"):
    return _get_name_map(saltenv)
# Buggy code
def _get_name_map():
    """
    Return a reverse map of full pkg names to the names recognized by winrepo.
    """
    u_name_map = {}
    name_map = get_repo_data().get("name_map", {})
    for k in name_map.keys():
        u_name_map[k.decode("utf-8")] = name_map[k]
    return u_name_map


# Traceback (CommandExecutionError)
----------
ID: openvpn
Function: pkg.installed
Result: False
Comment: An exception occurred in this state: Traceback (most recent call last):
File "C:\salt\bin\lib\site-packages\salt\state.py", line 1626, in call
**cdata['kwargs'])
File "C:\salt\bin\lib\site-packages\salt\loader.py", line 1492, in wrapper
return f(*args, **kwargs)
File "c:\salt\var\cache\salt\minion\extmods\states\pkg.py", line 984, in installed
**kwargs)
File "c:\salt\var\cache\salt\minion\extmods\states\pkg.py", line 294, in _find_install_targets
cur_pkgs = __salt__['pkg.list_pkgs'](versions_as_list=True, **kwargs)
File "c:\salt\var\cache\salt\minion\extmods\modules\win_pkg.py", line 244, in list_pkgs
name_map = _get_name_map()
File "c:\salt\var\cache\salt\minion\extmods\modules\win_pkg.py", line 1067, in _get_name_map
name_map = get_repo_data().get('name_map', {})
File "c:\salt\var\cache\salt\minion\extmods\modules\win_pkg.py", line 1050, in get_repo_data
'Windows repo cache doesn\'t exist, pkg.refresh_db likely '
CommandExecutionError: Windows repo cache doesn't exist, pkg.refresh_db likely needed

# Fixed code
def _get_name_map(saltenv="base"):
    """
    Return a reverse map of full pkg names to the names recognized by winrepo.
    """
    u_name_map = {}
    name_map = get_repo_data(saltenv).get("name_map", {})
    for k in name_map.keys():
        u_name_map[k.decode("utf-8")] = name_map[k]
    return u_name_map
# Buggy code
def _get_package_info(name):
    """
    Return package info.
    Returns empty map if package not available
    TODO: Add option for version
    """
    return get_repo_data().get("repo", {}).get(name, {})


# Traceback (CommandExecutionError)
----------
ID: openvpn
Function: pkg.installed
Result: False
Comment: An exception occurred in this state: Traceback (most recent call last):
File "C:\salt\bin\lib\site-packages\salt\state.py", line 1626, in call
**cdata['kwargs'])
File "C:\salt\bin\lib\site-packages\salt\loader.py", line 1492, in wrapper
return f(*args, **kwargs)
File "c:\salt\var\cache\salt\minion\extmods\states\pkg.py", line 984, in installed
**kwargs)
File "c:\salt\var\cache\salt\minion\extmods\states\pkg.py", line 294, in _find_install_targets
cur_pkgs = __salt__['pkg.list_pkgs'](versions_as_list=True, **kwargs)
File "c:\salt\var\cache\salt\minion\extmods\modules\win_pkg.py", line 244, in list_pkgs
name_map = _get_name_map()
File "c:\salt\var\cache\salt\minion\extmods\modules\win_pkg.py", line 1067, in _get_name_map
name_map = get_repo_data().get('name_map', {})
File "c:\salt\var\cache\salt\minion\extmods\modules\win_pkg.py", line 1050, in get_repo_data
'Windows repo cache doesn\'t exist, pkg.refresh_db likely '
CommandExecutionError: Windows repo cache doesn't exist, pkg.refresh_db likely needed

# Fixed code
def _get_package_info(name, saltenv="base"):
    """
    Return package info.
    Returns empty map if package not available
    TODO: Add option for version
    """
    return get_repo_data(saltenv).get("repo", {}).get(name, {})
# Buggy code
def ip_to_host(ip):
    """
    Returns the hostname of a given IP
    """
    try:
        hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip)
    except Exception:
        hostname = None
    return hostname


# Traceback (AssertionError)
salt:/srv # salt-ssh minionname state.sls deploy.system+root......
[ERROR   ] An un-handled exception was caught by salt's global exception handler:
AssertionError:
Traceback (most recent call last):
File "/usr/bin/salt-ssh", line 11, in <module>
sys.exit(salt_ssh())
File "/usr/lib/python2.7/site-packages/salt/scripts.py", line 425, in salt_ssh
client.run()
File "/usr/lib/python2.7/site-packages/salt/cli/ssh.py", line 23, in run
ssh = salt.client.ssh.SSH(self.config)
File "/usr/lib/python2.7/site-packages/salt/client/ssh/__init__.py", line 235, in __init__
self.tgt_type)
File "/usr/lib/python2.7/site-packages/salt/roster/__init__.py", line 105, in targets
targets.update(self.rosters[f_str](tgt, tgt_type))
File "/usr/lib/python2.7/site-packages/salt/roster/flat.py", line 49, in targets
rmatcher = RosterMatcher(conditioned_raw, tgt, tgt_type, 'ipv4')
File "/usr/lib/python2.7/site-packages/salt/roster/flat.py", line 58, in __init__
assert tgt
AssertionError
Traceback (most recent call last):
File "/usr/bin/salt-ssh", line 11, in <module>
sys.exit(salt_ssh())
File "/usr/lib/python2.7/site-packages/salt/scripts.py", line 425, in salt_ssh
client.run()
File "/usr/lib/python2.7/site-packages/salt/cli/ssh.py", line 23, in run
ssh = salt.client.ssh.SSH(self.config)
File "/usr/lib/python2.7/site-packages/salt/client/ssh/__init__.py", line 235, in __init__
self.tgt_type)
File "/usr/lib/python2.7/site-packages/salt/roster/__init__.py", line 105, in targets
targets.update(self.rosters[f_str](tgt, tgt_type))
File "/usr/lib/python2.7/site-packages/salt/roster/flat.py", line 49, in targets
rmatcher = RosterMatcher(conditioned_raw, tgt, tgt_type, 'ipv4')
File "/usr/lib/python2.7/site-packages/salt/roster/flat.py", line 58, in __init__
assert tgt
AssertionError

# Fixed code
def ip_to_host(ip):
    """
    Returns the hostname of a given IP
    """
    try:
        hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip)
    except Exception as exc:
        log.debug("salt.utils.network.ip_to_host(%r) failed: %s", ip, exc)
        hostname = None
    return hostname
# Buggy code
def validate(config):
    """
    Validate the beacon configuration
    """
    # Configuration for adb beacon should be a dictionary with states array
    if not isinstance(config, list):
        log.info("Configuration for salt_proxy beacon must be a list.")
        return False, ("Configuration for salt_proxy beacon must be a list.")

    else:
        _config = {}
        list(map(_config.update, config))

        if "proxies" not in _config:
            return False, ("Configuration for salt_proxy beacon requires proxies.")
        else:
            if not isinstance(_config["proxies"], dict):
                return False, ("Proxies for salt_proxy beacon must be a dictionary.")


# Traceback (TypeError)
[TRACE   ] Beacon processing: salt_proxy
[DEBUG   ] LazyLoaded salt_proxy.beacon
[CRITICAL] The beacon errored:
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/salt/minion.py", line 2484, in handle_beacons
beacons = self.process_beacons(self.functions)
File "/usr/lib/python2.7/site-packages/salt/minion.py", line 444, in process_beacons
return self.beacons.process(b_conf, self.opts['grains'])  # pylint: disable=no-member
File "/usr/lib/python2.7/site-packages/salt/beacons/__init__.py", line 104, in process
valid, vcomment = self.beacons[validate_str](b_config[mod])
TypeError: 'NoneType' object is not iterable
[TRACE   ] ==== evaluating schedule now None =====
[DEBUG   ] LazyLoaded status.master
[TRACE   ] Beacon processing: salt_proxy
[CRITICAL] The beacon errored:
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/salt/minion.py", line 2484, in handle_beacons
beacons = self.process_beacons(self.functions)
File "/usr/lib/python2.7/site-packages/salt/minion.py", line 444, in process_beacons
return self.beacons.process(b_conf, self.opts['grains'])  # pylint: disable=no-member
File "/usr/lib/python2.7/site-packages/salt/beacons/__init__.py", line 104, in process
valid, vcomment = self.beacons[validate_str](b_config[mod])
TypeError: 'NoneType' object is not iterable

# Fixed code
def validate(config):
    """
    Validate the beacon configuration
    """
    # Configuration for adb beacon should be a dictionary with states array
    if not isinstance(config, list):
        log.info("Configuration for salt_proxy beacon must be a list.")
        return False, ("Configuration for salt_proxy beacon must be a list.")

    else:
        _config = {}
        list(map(_config.update, config))

        if "proxies" not in _config:
            return False, ("Configuration for salt_proxy beacon requires proxies.")
        else:
            if not isinstance(_config["proxies"], dict):
                return False, ("Proxies for salt_proxy beacon must be a dictionary.")
    return True, "Valid beacon configuration"
# Buggy code
def _zfs_pool_data():
    """
    Provide grains about zpools
    """
    grains = {}

    # collect zpool data
    zpool_list_cmd = __utils__["zfs.zpool_command"](
        "list",
        flags=["-H", "-p"],
        opts={"-o": "name,size"},
    )
    for zpool in __salt__["cmd.run"](zpool_list_cmd).splitlines():
        if "zpool" not in grains:
            grains["zpool"] = {}
        zpool = zpool.split()
        grains["zpool"][zpool[0]] = __utils__["zfs.to_size"](zpool[1], True)

    # return grain data
    return grains


# Traceback (IndexError)
# salt-call saltutil.sync_all
[ERROR   ] Command '/sbin/zpool list -H -p -o name,size' failed with return code: 2
[ERROR   ] output: invalid option 'p'
usage:
list [-gHLPv] [-o property[,...]] [-T d|u] [pool] ... [interval [count]]
...

[CRITICAL] Failed to load grains defined in grain file zfs.zfs in function <function zfs at 0x7fa3241bf2a8>, error:
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/loader.py", line 756, in grains
ret = funcs[key]()
File "/usr/lib/python2.7/dist-packages/salt/grains/zfs.py", line 116, in zfs
grains = salt.utils.dictupdate.update(grains, _zfs_pool_data(), merge_lists=True)
File "/usr/lib/python2.7/dist-packages/salt/grains/zfs.py", line 102, in _zfs_pool_data
grains['zpool'][zpool[0]] = _conform_value(zpool[1], True)
IndexError: list index out of range
...

# Fixed code
def _zfs_pool_data():
    """
    Provide grains about zpools
    """
    grains = {}

    # collect zpool data
    zpool_list_cmd = __utils__["zfs.zpool_command"](
        "list",
        flags=["-H"],
        opts={"-o": "name,size"},
    )
    for zpool in __salt__["cmd.run"](zpool_list_cmd).splitlines():
        if "zpool" not in grains:
            grains["zpool"] = {}
        zpool = zpool.split()
        grains["zpool"][zpool[0]] = __utils__["zfs.to_size"](zpool[1], False)

    # return grain data
    return grains
# Buggy code
def decode_tuple(
    data,
    encoding=None,
    errors="strict",
    keep=False,
    normalize=False,
    preserve_dict_class=False,
):
    """
    Decode all string values to Unicode
    """
    return tuple(
        decode_list(data, encoding, errors, keep, normalize, preserve_dict_class, True)
    )


# Traceback (TypeError)
2018-04-04 05:37:16,969 [salt.loaded.int.pillar.pillar_ldap:262 ][CRITICAL][5777] Failed to retrieve pillar data from LDAP:
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/salt/pillar/pillar_ldap.py", line 256, in _do_search
**connargs)['results']
File "/usr/lib/python2.7/site-packages/salt/modules/ldapmod.py", line 150, in search
results = _ldap.search_s(dn, int(scope), filter, attrs)
File "/usr/lib64/python2.7/site-packages/ldap/ldapobject.py", line 552, in search_s
return self.search_ext_s(base,scope,filterstr,attrlist,attrsonly,None,None,timeout=self.timeout)
File "/usr/lib64/python2.7/site-packages/ldap/ldapobject.py", line 545, in search_ext_s
msgid = self.search_ext(base,scope,filterstr,attrlist,attrsonly,serverctrls,clientctrls,timeout,sizelimit)
File "/usr/lib64/python2.7/site-packages/ldap/ldapobject.py", line 541, in search_ext
timeout,sizelimit,
File "/usr/lib64/python2.7/site-packages/ldap/ldapobject.py", line 99, in _ldap_call
result = func(*args,**kwargs)
TypeError: ('expected string in list', u'uid')

# Fixed code
def decode_tuple(
    data,
    encoding=None,
    errors="strict",
    keep=False,
    normalize=False,
    preserve_dict_class=False,
    to_str=False,
):
    """
    Decode all string values to Unicode. Optionally use to_str=True to ensure
    strings are str types and not unicode on Python 2.
    """
    return tuple(
        decode_list(
            data, encoding, errors, keep, normalize, preserve_dict_class, True, to_str
        )
    )
# Buggy code
def key_exists(hive, key, use_32bit_registry=False):
    """
    Check that the key is found in the registry

    :param str hive: The hive to connect to.
    :param str key: The key to check
    :param bool use_32bit_registry: Look in the 32bit portion of the registry

    :return: Returns True if found, False if not found
    :rtype: bool
    """
    local_hive = _to_unicode(hive)
    local_key = _to_unicode(key)

    registry = Registry()
    hkey = registry.hkeys[local_hive]
    access_mask = registry.registry_32[use_32bit_registry]

    try:
        handle = win32api.RegOpenKeyEx(hkey, local_key, 0, access_mask)
        win32api.RegCloseKey(handle)
        return True
    except Exception:  # pylint: disable=E0602
        return False


# Traceback (TypeError)
local:
---------
ID: test_reg
Function: reg.present
Name: HKEY_LOCAL_MACHINE\SOFTWARE\salttest\salty\salted
Result: False
Comment: An exception occurred in this state: Traceback (most recent call last):
File "c:\salt\bin\lib\site-packages\salt\state.py", line 1878, in call
**cdata['kwargs'])
File "c:\salt\bin\lib\site-packages\salt\loader.py", line 1823, in wrapper
return f(*args, **kwargs)
File "c:\salt\bin\lib\site-packages\salt\states\reg.py", line 196, in present
vdata_decoded = salt.utils.stringutils.to_unicode(vdata, 'utf-8')
File "c:\salt\bin\lib\site-packages\salt\utils\stringutils.py", line 99, in to_unicode
raise TypeError('expected str, bytes, or bytearray')
TypeError: expected str, bytes, or bytearray

# Fixed code
def key_exists(hive, key, use_32bit_registry=False):
    """
    Check that the key is found in the registry

    :param str hive: The hive to connect to.
    :param str key: The key to check
    :param bool use_32bit_registry: Look in the 32bit portion of the registry

    :return: Returns True if found, False if not found
    :rtype: bool
    """
    local_hive = _to_unicode(hive)
    local_key = _to_unicode(key)

    registry = Registry()
    try:
        hkey = registry.hkeys[local_hive]
    except KeyError:
        raise CommandExecutionError("Invalid Hive: {0}".format(local_hive))
    access_mask = registry.registry_32[use_32bit_registry]

    try:
        handle = win32api.RegOpenKeyEx(hkey, local_key, 0, access_mask)
        win32api.RegCloseKey(handle)
        return True
    except Exception:  # pylint: disable=E0602
        return False
# Buggy code
def is_binary(data):
    """
    Detects if the passed string of data is binary or text
    """
    if not data or not isinstance(data, six.string_types):
        return False
    if "\0" in data:
        return True

    text_characters = "".join([chr(x) for x in range(32, 127)] + list("\n\r\t\b"))
    # Get the non-text characters (map each character to itself then use the
    # 'remove' option to get rid of the text characters.)
    if six.PY3:
        trans = "".maketrans("", "", text_characters)
        nontext = data.translate(trans)
    else:
        if isinstance(data, unicode):  # pylint: disable=incompatible-py3-code
            trans_args = ({ord(x): None for x in text_characters},)
        else:
            trans_args = (
                None,
                str(text_characters),
            )  # future lint: blacklisted-function
        nontext = data.translate(*trans_args)

    # If more than 30% non-text characters, then
    # this is considered binary data
    if float(len(nontext)) / len(data) > 0.30:
        return True
    return False


# Traceback (UnicodeDecodeError)
ID: /srv/server/session-ticket-keys/0.key
Function: file.managed
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 1878, in call
**cdata['kwargs'])
File "/usr/lib/python2.7/dist-packages/salt/loader.py", line 1823, in wrapper
return f(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/salt/states/file.py", line 2267, in managed
isinstance(use_contents, six.string_types) and '\0' in use_contents
UnicodeDecodeError: 'ascii' codec can't decode byte 0xf5 in position 1: ordinal not in range(128)
Started: 17:29:34.221921
Duration: 4.871 ms
Changes:

# Fixed code
def is_binary(data):
    """
    Detects if the passed string of data is binary or text
    """
    if not data or not isinstance(data, (six.string_types, six.binary_type)):
        return False

    if isinstance(data, six.binary_type):
        if b"\0" in data:
            return True
    elif str("\0") in data:
        return True

    text_characters = "".join([chr(x) for x in range(32, 127)] + list("\n\r\t\b"))
    # Get the non-text characters (map each character to itself then use the
    # 'remove' option to get rid of the text characters.)
    if six.PY3:
        if isinstance(data, six.binary_type):
            import salt.utils.data

            nontext = data.translate(None, salt.utils.data.encode(text_characters))
        else:
            trans = "".maketrans("", "", text_characters)
            nontext = data.translate(trans)
    else:
        if isinstance(data, six.text_type):
            trans_args = ({ord(x): None for x in text_characters},)
        else:
            trans_args = (
                None,
                str(text_characters),
            )  # future lint: blacklisted-function
        nontext = data.translate(*trans_args)

    # If more than 30% non-text characters, then
    # this is considered binary data
    if float(len(nontext)) / len(data) > 0.30:
        return True
    return False
# Buggy code
def valid_id(opts, id_):
    """
    Returns if the passed id is valid
    """
    try:
        if any(x in id_ for x in ("/", "\\", "\0")):
            return False
        return bool(clean_path(opts["pki_dir"], id_))
    except (AttributeError, KeyError, TypeError):
        return False


# Traceback (UnicodeDecodeError)
ID: /srv/server/session-ticket-keys/0.key
Function: file.managed
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 1878, in call
**cdata['kwargs'])
File "/usr/lib/python2.7/dist-packages/salt/loader.py", line 1823, in wrapper
return f(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/salt/states/file.py", line 2267, in managed
isinstance(use_contents, six.string_types) and '\0' in use_contents
UnicodeDecodeError: 'ascii' codec can't decode byte 0xf5 in position 1: ordinal not in range(128)
Started: 17:29:34.221921
Duration: 4.871 ms
Changes:

# Fixed code
def valid_id(opts, id_):
    """
    Returns if the passed id is valid
    """
    try:
        if any(x in id_ for x in ("/", "\\", str("\0"))):
            return False
        return bool(clean_path(opts["pki_dir"], id_))
    except (AttributeError, KeyError, TypeError):
        return False