gurudesh/pytracebugs huggingface dataset:
# Buggy code
def _pki_minions(self):
    """
    Retreive complete minion list from PKI dir.
    Respects cache if configured
    """
    minions = []
    pki_cache_fn = os.path.join(self.opts["pki_dir"], self.acc, ".key_cache")
    try:
        os.makedirs(os.path.dirname(pki_cache_fn))
    except OSError:
        pass
    try:
        if self.opts["key_cache"] and os.path.exists(pki_cache_fn):
            log.debug("Returning cached minion list")
            with salt.utils.files.fopen(pki_cache_fn) as fn_:
                return self.serial.load(fn_)
        else:
            for fn_ in salt.utils.data.sorted_ignorecase(
                os.listdir(os.path.join(self.opts["pki_dir"], self.acc))
            ):
                if not fn_.startswith(".") and os.path.isfile(
                    os.path.join(self.opts["pki_dir"], self.acc, fn_)
                ):
                    minions.append(fn_)
        return minions
    except OSError as exc:
        log.error("Encountered OSError while evaluating minions in PKI dir: %s", exc)
        return minions


# 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 _pki_minions(self):
    """
    Retreive complete minion list from PKI dir.
    Respects cache if configured
    """
    minions = []
    pki_cache_fn = os.path.join(self.opts["pki_dir"], self.acc, ".key_cache")
    try:
        os.makedirs(os.path.dirname(pki_cache_fn))
    except OSError:
        pass
    try:
        if self.opts["key_cache"] and os.path.exists(pki_cache_fn):
            log.debug("Returning cached minion list")
            if six.PY2:
                with salt.utils.files.fopen(pki_cache_fn) as fn_:
                    return self.serial.load(fn_)
            else:
                with salt.utils.files.fopen(pki_cache_fn, mode="rb") as fn_:
                    return self.serial.load(fn_)
        else:
            for fn_ in salt.utils.data.sorted_ignorecase(
                os.listdir(os.path.join(self.opts["pki_dir"], self.acc))
            ):
                if not fn_.startswith(".") and os.path.isfile(
                    os.path.join(self.opts["pki_dir"], self.acc, fn_)
                ):
                    minions.append(fn_)
        return minions
    except OSError as exc:
        log.error("Encountered OSError while evaluating minions in PKI dir: %s", exc)
        return minions
# Buggy code
def cli(name, format="text", **kwargs):
    """
    Executes the CLI commands and reuturns the text output.

    .. code-block:: yaml

            show version:
              junos:
                - cli
                - format: xml

    Parameters:
      Required
        * command:
          The command that need to be executed on Junos CLI. (default = None)
      Optional
        * format:
          Format in which to get the CLI output. (text or xml, \
            default = 'text')
        * kwargs: Keyworded arguments which can be provided like-
            * timeout:
              Set NETCONF RPC timeout. Can be used for commands which
              take a while to execute. (default = 30 seconds)
            * dest:
              The destination file where the CLI output can be stored.\
               (default = None)
    """
    ret = {"name": name, "changes": {}, "result": True, "comment": ""}
    ret["changes"] = __salt__["junos.cli"](name, format, **kwargs)
    return ret


# Traceback (TypeError)
ID: show_system_uptime
Function: junos.cli
Name: show system uptime
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 1913, in call
**cdata['kwargs'])
File "/usr/lib/python2.7/site-packages/salt/loader.py", line 1898, in wrapper
return f(*args, **kwargs)
File "/usr/lib/python2.7/site-packages/salt/states/junos.py", line 233, in cli
ret['changes'] = __salt__['junos.cli'](name, format, **kwargs)
TypeError: cli() takes at most 1 argument (2 given)
Started: 09:05:32.481469
Duration: 2.482 ms
Changes:

# Fixed code
def cli(name, **kwargs):
    """
    Executes the CLI commands and reuturns the text output.

    .. code-block:: yaml

            show version:
              junos:
                - cli
                - format: xml

    Parameters:
      Required
        * command:
          The command that need to be executed on Junos CLI. (default = None)
      Optional
        * kwargs: Keyworded arguments which can be provided like-
            * format:
              Format in which to get the CLI output. (text or xml, \
                default = 'text')
            * timeout:
              Set NETCONF RPC timeout. Can be used for commands which
              take a while to execute. (default = 30 seconds)
            * dest:
              The destination file where the CLI output can be stored.\
               (default = None)
    """
    ret = {"name": name, "changes": {}, "result": True, "comment": ""}
    ret["changes"] = __salt__["junos.cli"](name, **kwargs)
    return ret
# Buggy code
def _safe_output(line):
    """
    Looks for rabbitmqctl warning, or general formatting, strings that aren't
    intended to be parsed as output.
    Returns a boolean whether the line can be parsed as rabbitmqctl output.
    """
    return not any(
        [
            line.startswith("Listing") and line.endswith("..."),
            "...done" in line,
            line.startswith("WARNING:"),
        ]
    )


# Traceback (ValueError)
Comment: An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/state.py", line 1564, in call
**cdata['kwargs'])
File "/usr/lib/python2.7/dist-packages/salt/states/rabbitmq_user.py", line 158, in present
if _check_perms_changes(name, perms, runas=runas):
File "/usr/lib/python2.7/dist-packages/salt/states/rabbitmq_user.py", line 49, in _check_perms_changes
existing_perms = __salt__['rabbitmq.list_user_permissions'](name, runas=runas)
File "/usr/lib/python2.7/dist-packages/salt/modules/rabbitmq.py", line 369, in list_user_permissions
return _output_to_dict(res)
File "/usr/lib/python2.7/dist-packages/salt/modules/rabbitmq.py", line 94, in _output_to_dict
key, values = row.split('\t', 1)
ValueError: need more than 1 value to unpack

# Fixed code
def _safe_output(line):
    """
    Looks for rabbitmqctl warning, or general formatting, strings that aren't
    intended to be parsed as output.
    Returns a boolean whether the line can be parsed as rabbitmqctl output.
    """
    return not any(
        [
            line.startswith("Listing") and line.endswith("..."),
            line.startswith("Listing") and "\t" not in line,
            "...done" in line,
            line.startswith("WARNING:"),
        ]
    )
# Buggy code
def __init__(self, path=None, opts=None, config_dir=None, pillars=None):
    if opts:
        self.opts = opts
    else:
        self.opts = salt.config.cloud_config(path)

    if pillars:
        for name, provider in six.iteritems(pillars.pop("providers", {})):
            driver = provider["driver"]
            provider["profiles"] = {}
            self.opts["providers"].update({name: {driver: provider}})
        for name, profile in six.iteritems(pillars.pop("profiles", {})):
            provider = profile["provider"].split(":")[0]
            driver = next(six.iterkeys(self.opts["providers"][provider]))
            profile["provider"] = "{0}:{1}".format(provider, driver)
            profile["profile"] = name
            self.opts["profiles"].update({name: profile})
            self.opts["providers"][provider][driver]["profiles"].update({name: profile})
        self.opts.update(pillars)


# Traceback (ImportError)
130 client@rabbit:/usr/local/lib/python2.7/dist-packages/salt/cloud/clouds⟫ sudo python
Python 2.7.6 (default, Oct 26 2016, 20:30:19)
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
import libcloud
from libcloud.compute.types import Provider
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/libcloud/compute/types.py", line 19, in <module>
from libcloud.common.types import LibcloudError, MalformedResponseError
File "/usr/local/lib/python2.7/dist-packages/libcloud/common/types.py", line 16, in <module>
from libcloud.utils.py3 import httplib
File "/usr/local/lib/python2.7/dist-packages/libcloud/utils/py3.py", line 67, in <module>
from backports.ssl_match_hostname import match_hostname, CertificateError  # NOQA
ImportError: No module named backports.ssl_match_hostname


# Fixed code
def __init__(self, path=None, opts=None, config_dir=None, pillars=None):
    if opts:
        self.opts = opts
    else:
        self.opts = salt.config.cloud_config(path)

    # Check the cache-dir exists. If not, create it.
    v_dirs = [self.opts["cachedir"]]
    salt.utils.verify.verify_env(v_dirs, salt.utils.get_user())

    if pillars:
        for name, provider in six.iteritems(pillars.pop("providers", {})):
            driver = provider["driver"]
            provider["profiles"] = {}
            self.opts["providers"].update({name: {driver: provider}})
        for name, profile in six.iteritems(pillars.pop("profiles", {})):
            provider = profile["provider"].split(":")[0]
            driver = next(six.iterkeys(self.opts["providers"][provider]))
            profile["provider"] = "{0}:{1}".format(provider, driver)
            profile["profile"] = name
            self.opts["profiles"].update({name: profile})
            self.opts["providers"][provider][driver]["profiles"].update({name: profile})
        self.opts.update(pillars)
# Buggy code
def get_dependencies():
    """
    Warn if dependencies aren't met.
    """
    return config.check_driver_dependencies(__virtualname__, {"libcloud": HAS_LIBCLOUD})


# Traceback (ImportError)
130 client@rabbit:/usr/local/lib/python2.7/dist-packages/salt/cloud/clouds⟫ sudo python
Python 2.7.6 (default, Oct 26 2016, 20:30:19)
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
import libcloud
from libcloud.compute.types import Provider
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/libcloud/compute/types.py", line 19, in <module>
from libcloud.common.types import LibcloudError, MalformedResponseError
File "/usr/local/lib/python2.7/dist-packages/libcloud/common/types.py", line 16, in <module>
from libcloud.utils.py3 import httplib
File "/usr/local/lib/python2.7/dist-packages/libcloud/utils/py3.py", line 67, in <module>
from backports.ssl_match_hostname import match_hostname, CertificateError  # NOQA
ImportError: No module named backports.ssl_match_hostname


# Fixed code
def get_dependencies():
    """
    Warn if dependencies aren't met.
    """
    if LIBCLOUD_IMPORT_ERROR:
        log.error("Failure when importing LibCloud: ", exc_info=LIBCLOUD_IMPORT_ERROR)
        log.error(
            "Note: The libcloud dependency is called 'apache-libcloud' on PyPi/pip."
        )
    return config.check_driver_dependencies(__virtualname__, {"libcloud": HAS_LIBCLOUD})
# Buggy code
def traverse_dict(data, key, default=None, delimiter=DEFAULT_TARGET_DELIM):
    """
    Traverse a dict using a colon-delimited (or otherwise delimited, using the
    'delimiter' param) target string. The target 'foo:bar:baz' will return
    data['foo']['bar']['baz'] if this value exists, and will otherwise return
    the dict in the default argument.
    """
    try:
        for each in key.split(delimiter):
            data = data[each]
    except (KeyError, IndexError, TypeError):
        # Encountered a non-indexable value in the middle of traversing
        return default
    return data


# Traceback (UnicodeDecodeError)
2018-09-12 14:09:01,744 [salt.utils.minions                                    :696 ][ERROR   ][5648] Failed matching available minions with compound pattern: G@ip_interfaces:*:10.0.1.*
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/salt/utils/minions.py", line 683, in check_minions
_res = check_func(expr, delimiter, greedy)
File "/usr/lib/python2.7/site-packages/salt/utils/minions.py", line 578, in _check_compound_minions
_results = engine(*engine_args)
File "/usr/lib/python2.7/site-packages/salt/utils/minions.py", line 325, in _check_grain_minions
return self._check_cache_minions(expr, delimiter, greedy, 'grains')
File "/usr/lib/python2.7/site-packages/salt/utils/minions.py", line 315, in _check_cache_minions
exact_match=exact_match):
File "/usr/lib/python2.7/site-packages/salt/utils/data.py", line 579, in subdict_match
exact_match=exact_match):
File "/usr/lib/python2.7/site-packages/salt/utils/data.py", line 549, in _dict_match
exact_match=exact_match):
File "/usr/lib/python2.7/site-packages/salt/utils/data.py", line 526, in _match
return fnmatch.fnmatch(six.text_type(target).lower(), pattern.lower())
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 6: ordinal not in range(128)

# Fixed code
def traverse_dict(data, key, default=None, delimiter=DEFAULT_TARGET_DELIM):
    """
    Traverse a dict using a colon-delimited (or otherwise delimited, using the
    'delimiter' param) target string. The target 'foo:bar:baz' will return
    data['foo']['bar']['baz'] if this value exists, and will otherwise return
    the dict in the default argument.
    """
    ptr = data
    try:
        for each in key.split(delimiter):
            ptr = ptr[each]
    except (KeyError, IndexError, TypeError):
        # Encountered a non-indexable value in the middle of traversing
        return default
    return ptr
# Buggy code
def _match(target, pattern, regex_match=False, exact_match=False):
    if regex_match:
        try:
            return re.match(pattern.lower(), six.text_type(target).lower())
        except Exception:
            log.error("Invalid regex '%s' in match", pattern)
            return False
    elif exact_match:
        return six.text_type(target).lower() == pattern.lower()
    else:
        return fnmatch.fnmatch(six.text_type(target).lower(), pattern.lower())


# Traceback (UnicodeDecodeError)
2018-09-12 14:09:01,744 [salt.utils.minions                                    :696 ][ERROR   ][5648] Failed matching available minions with compound pattern: G@ip_interfaces:*:10.0.1.*
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/salt/utils/minions.py", line 683, in check_minions
_res = check_func(expr, delimiter, greedy)
File "/usr/lib/python2.7/site-packages/salt/utils/minions.py", line 578, in _check_compound_minions
_results = engine(*engine_args)
File "/usr/lib/python2.7/site-packages/salt/utils/minions.py", line 325, in _check_grain_minions
return self._check_cache_minions(expr, delimiter, greedy, 'grains')
File "/usr/lib/python2.7/site-packages/salt/utils/minions.py", line 315, in _check_cache_minions
exact_match=exact_match):
File "/usr/lib/python2.7/site-packages/salt/utils/data.py", line 579, in subdict_match
exact_match=exact_match):
File "/usr/lib/python2.7/site-packages/salt/utils/data.py", line 549, in _dict_match
exact_match=exact_match):
File "/usr/lib/python2.7/site-packages/salt/utils/data.py", line 526, in _match
return fnmatch.fnmatch(six.text_type(target).lower(), pattern.lower())
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 6: ordinal not in range(128)

# Fixed code
def _match(target, pattern, regex_match=False, exact_match=False):
    # The reason for using six.text_type first and _then_ using
    # to_unicode as a fallback is because we want to eventually have
    # unicode types for comparison below. If either value is numeric then
    # six.text_type will turn it into a unicode string. However, if the
    # value is a PY2 str type with non-ascii chars, then the result will be
    # a UnicodeDecodeError. In those cases, we simply use to_unicode to
    # decode it to unicode. The reason we can't simply use to_unicode to
    # begin with is that (by design) to_unicode will raise a TypeError if a
    # non-string/bytestring/bytearray value is passed.
    try:
        target = six.text_type(target).lower()
    except UnicodeDecodeError:
        target = salt.utils.stringutils.to_unicode(target).lower()
    try:
        pattern = six.text_type(pattern).lower()
    except UnicodeDecodeError:
        pattern = salt.utils.stringutils.to_unicode(pattern).lower()

    if regex_match:
        try:
            return re.match(pattern, target)
        except Exception:
            log.error("Invalid regex '%s' in match", pattern)
            return False
    else:
        return target == pattern if exact_match else fnmatch.fnmatch(target, pattern)
# Buggy code
def _get_private_key_obj(private_key, passphrase=None):
    """
    Returns a private key object based on PEM text.
    """
    private_key = _text_or_file(private_key)
    private_key = get_pem_entry(private_key, pem_type="RSA PRIVATE KEY")
    rsaprivkey = M2Crypto.RSA.load_key_string(
        private_key, callback=_passphrase_callback(passphrase)
    )
    evpprivkey = M2Crypto.EVP.PKey()
    evpprivkey.assign_rsa(rsaprivkey)
    return evpprivkey


# Traceback (SaltInvocationError)
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/salt/cli/caller.py", line 197, in call
ret['return'] = func(*args, **kwargs)
File "/usr/lib/python2.7/site-packages/salt/modules/x509.py", line 1509, in create_certificate
passphrase=kwargs['signing_private_key_passphrase']),
File "/usr/lib/python2.7/site-packages/salt/modules/x509.py", line 358, in _get_private_key_obj
private_key = get_pem_entry(private_key, pem_type='RSA PRIVATE KEY')
File "/usr/lib/python2.7/site-packages/salt/modules/x509.py", line 472, in get_pem_entry
raise salt.exceptions.SaltInvocationError(errmsg)
SaltInvocationError: PEM does not contain a single entry of type RSA PRIVATE KEY:
-----BEGIN PRIVATE KEY-----
[PRIVATE KEY GOES HERE]
-----END PRIVATE KEY-----

# Fixed code
def _get_private_key_obj(private_key, passphrase=None):
    """
    Returns a private key object based on PEM text.
    """
    private_key = _text_or_file(private_key)
    private_key = get_pem_entry(private_key, pem_type="(?:RSA )?PRIVATE KEY")
    rsaprivkey = M2Crypto.RSA.load_key_string(
        private_key, callback=_passphrase_callback(passphrase)
    )
    evpprivkey = M2Crypto.EVP.PKey()
    evpprivkey.assign_rsa(rsaprivkey)
    return evpprivkey
# Buggy code
def _maybe_set_tags(tags, obj):
    if tags:
        obj.add_tags(tags)

        log.debug(
            "The following tags: {0} were added to {1}".format(", ".join(tags), obj)
        )


# Traceback (AttributeError)
[ERROR   ] An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/salt/state.py", line 1745, in call
**cdata['kwargs'])
File "/usr/lib/python2.7/site-packages/salt/loader.py", line 1702, in wrapper
return f(*args, **kwargs)
File "/usr/lib/python2.7/site-packages/salt/states/boto_vpc.py", line 604, in subnet_present
profile=profile)
File "/usr/lib/python2.7/site-packages/salt/modules/boto_vpc.py", line 869, in create_subnet
keyid=keyid, profile=profile)
File "/usr/lib/python2.7/site-packages/salt/modules/boto_vpc.py", line 268, in _create_resource
_maybe_set_tags(tags, r)
File "/usr/lib/python2.7/site-packages/salt/modules/boto_vpc.py", line 2602, in _maybe_set_tags
obj.add_tags(tags)
AttributeError: 'Subnet' object has no attribute 'add_tags'

# Fixed code
def _maybe_set_tags(tags, obj):
    if tags:
        # Not all objects in Boto have an 'add_tags()' method.
        try:
            obj.add_tags(tags)

        except AttributeError:
            for tag, value in tags.items():
                obj.add_tag(tag, value)

        log.debug(
            "The following tags: {0} were added to {1}".format(", ".join(tags), obj)
        )
# Buggy code
def _handle_sigusr1(sig, stack):
    """
    Signal handler for SIGUSR1, only available on Unix-like systems
    """
    # When running in the foreground, do the right  thing
    # and spit out the debug info straight to the console
    if sys.stderr.isatty():
        output = sys.stderr
        _makepretty(output, stack)
    else:
        filename = "salt-debug-{0}.log".format(int(time.time()))
        destfile = os.path.join(tempfile.gettempdir(), filename)
        with salt.utils.files.fopen(destfile, "w") as output:
            _makepretty(output, salt.utils.stringutils.to_str(stack))


# Traceback (TypeError)
8月 31 11:13:25 t-shhq-infratest-01 salt-master[28444]: [ERROR   ] Future exception was never retrieved: Traceback (most recent call last):
8月 31 11:13:25 t-shhq-infratest-01 salt-master[28444]: File "/usr/lib64/python2.7/site-packages/tornado/gen.py", line 230, in wrapper
8月 31 11:13:25 t-shhq-infratest-01 salt-master[28444]: yielded = next(result)
8月 31 11:13:25 t-shhq-infratest-01 salt-master[28444]: File "/usr/lib/python2.7/site-packages/salt/utils/process.py", line 501, in run
8月 31 11:13:25 t-shhq-infratest-01 salt-master[28444]: time.sleep(10)
8月 31 11:13:25 t-shhq-infratest-01 salt-master[28444]: File "/usr/lib/python2.7/site-packages/salt/utils/debug.py", line 44, in _h...igusr1
8月 31 11:13:25 t-shhq-infratest-01 salt-master[28444]: _makepretty(output, salt.utils.stringutils.to_str(stack))
8月 31 11:13:25 t-shhq-infratest-01 salt-master[28444]: File "/usr/lib/python2.7/site-packages/salt/utils/stringutils.py", line 93,...to_str
8月 31 11:13:25 t-shhq-infratest-01 salt-master[28444]: raise TypeError('expected str, bytearray, or unicode')
8月 31 11:13:25 t-shhq-infratest-01 salt-master[28444]: TypeError: expected str, bytearray, or unicode

# Fixed code
def _handle_sigusr1(sig, stack):
    """
    Signal handler for SIGUSR1, only available on Unix-like systems
    """
    # When running in the foreground, do the right  thing
    # and spit out the debug info straight to the console
    if sys.stderr.isatty():
        output = sys.stderr
        _makepretty(output, stack)
    else:
        filename = "salt-debug-{0}.log".format(int(time.time()))
        destfile = os.path.join(tempfile.gettempdir(), filename)
        with salt.utils.files.fopen(destfile, "w") as output:
            _makepretty(output, stack)
# Buggy code
def store(bank, key, data):
    """
    Store a key value.
    """
    _init_client()
    etcd_key = "{0}/{1}/{2}".format(path_prefix, bank, key)
    try:
        value = __context__["serial"].dumps(data)
        client.set(etcd_key, value)
    except Exception as exc:
        raise SaltCacheError(
            "There was an error writing the key, {0}: {1}".format(etcd_key, exc)
        )


# Traceback (SaltCacheError)
salt-master[3903]: [ERROR   ] Error in function _mine:
salt-master[3903]: Traceback (most recent call last):
salt-master[3903]:   File "/usr/lib/python2.7/dist-packages/salt/master.py", line 1776, in run_func
salt-master[3903]:     ret = getattr(self, func)(load)
salt-master[3903]:   File "/usr/lib/python2.7/dist-packages/salt/master.py", line 1345, in _mine
salt-master[3903]:     return self.masterapi._mine(load, skip_verify=True)
salt-master[3903]:   File "/usr/lib/python2.7/dist-packages/salt/daemons/masterapi.py", line 607, in _mine
salt-master[3903]:     data = self.cache.fetch(cbank, ckey)
salt-master[3903]:   File "/usr/lib/python2.7/dist-packages/salt/cache/__init__.py", line 180, in fetch
salt-master[3903]:     return self.modules[fun](bank, key, **self._kwargs)
salt-master[3903]:   File "/usr/lib/python2.7/dist-packages/salt/cache/etcd_cache.py", line 150, in fetch
salt-master[3903]:     etcd_key, exc
salt-master[3903]: SaltCacheError: There was an error reading the key, /salt_cache/minions/ca.aws-cc1.dev.xxx.yyy.com/mine: Key not found : /salt_cache/minions/ca.aws-cc1.dev.xxx.yyy.com/mine
salt-master[3903]: [ERROR   ] Error in function _mine_get:
salt-master[3903]: Traceback (most recent call last):
salt-master[3903]:   File "/usr/lib/python2.7/dist-packages/salt/master.py", line 1776, in run_func
salt-master[3903]:     ret = getattr(self, func)(load)
salt-master[3903]:   File "/usr/lib/python2.7/dist-packages/salt/master.py", line 1331, in _mine_get
salt-master[3903]:     return self.masterapi._mine_get(load, skip_verify=True)
salt-master[3903]:   File "/usr/lib/python2.7/dist-packages/salt/daemons/masterapi.py", line 589, in _mine_get
salt-master[3903]:     fdata = self.cache.fetch('minions/{0}'.format(minion), 'mine')
salt-master[3903]:   File "/usr/lib/python2.7/dist-packages/salt/cache/__init__.py", line 180, in fetch
salt-master[3903]:     return self.modules[fun](bank, key, **self._kwargs)
salt-master[3903]:   File "/usr/lib/python2.7/dist-packages/salt/cache/etcd_cache.py", line 150, in fetch
salt-master[3903]:     etcd_key, exc
salt-master[3903]: SaltCacheError: There was an error reading the key, /salt_cache/minions/ca.aws-cc1.dev.xxx.yyy.com/mine: Key not found : /salt_cache/minions/ca.aws-cc1.dev.xxx.yyy.com/mine

# Fixed code
def store(bank, key, data):
    """
    Store a key value.
    """
    _init_client()
    etcd_key = "{0}/{1}/{2}".format(path_prefix, bank, key)
    try:
        value = __context__["serial"].dumps(data)
        client.write(etcd_key, base64.b64encode(value))
    except Exception as exc:
        raise SaltCacheError(
            "There was an error writing the key, {0}: {1}".format(etcd_key, exc)
        )
# Buggy code
def _walk(r):
    """
    Recursively walk dirs. Return flattened list of keys.
    r: etcd.EtcdResult
    """
    if not r.dir:
        return [r.key.split("/", 3)[3]]

    keys = []
    for c in client.get(r.key).children:
        keys.extend(_walk(c))
    return keys


# Traceback (SaltCacheError)
salt-master[3903]: [ERROR   ] Error in function _mine:
salt-master[3903]: Traceback (most recent call last):
salt-master[3903]:   File "/usr/lib/python2.7/dist-packages/salt/master.py", line 1776, in run_func
salt-master[3903]:     ret = getattr(self, func)(load)
salt-master[3903]:   File "/usr/lib/python2.7/dist-packages/salt/master.py", line 1345, in _mine
salt-master[3903]:     return self.masterapi._mine(load, skip_verify=True)
salt-master[3903]:   File "/usr/lib/python2.7/dist-packages/salt/daemons/masterapi.py", line 607, in _mine
salt-master[3903]:     data = self.cache.fetch(cbank, ckey)
salt-master[3903]:   File "/usr/lib/python2.7/dist-packages/salt/cache/__init__.py", line 180, in fetch
salt-master[3903]:     return self.modules[fun](bank, key, **self._kwargs)
salt-master[3903]:   File "/usr/lib/python2.7/dist-packages/salt/cache/etcd_cache.py", line 150, in fetch
salt-master[3903]:     etcd_key, exc
salt-master[3903]: SaltCacheError: There was an error reading the key, /salt_cache/minions/ca.aws-cc1.dev.xxx.yyy.com/mine: Key not found : /salt_cache/minions/ca.aws-cc1.dev.xxx.yyy.com/mine
salt-master[3903]: [ERROR   ] Error in function _mine_get:
salt-master[3903]: Traceback (most recent call last):
salt-master[3903]:   File "/usr/lib/python2.7/dist-packages/salt/master.py", line 1776, in run_func
salt-master[3903]:     ret = getattr(self, func)(load)
salt-master[3903]:   File "/usr/lib/python2.7/dist-packages/salt/master.py", line 1331, in _mine_get
salt-master[3903]:     return self.masterapi._mine_get(load, skip_verify=True)
salt-master[3903]:   File "/usr/lib/python2.7/dist-packages/salt/daemons/masterapi.py", line 589, in _mine_get
salt-master[3903]:     fdata = self.cache.fetch('minions/{0}'.format(minion), 'mine')
salt-master[3903]:   File "/usr/lib/python2.7/dist-packages/salt/cache/__init__.py", line 180, in fetch
salt-master[3903]:     return self.modules[fun](bank, key, **self._kwargs)
salt-master[3903]:   File "/usr/lib/python2.7/dist-packages/salt/cache/etcd_cache.py", line 150, in fetch
salt-master[3903]:     etcd_key, exc
salt-master[3903]: SaltCacheError: There was an error reading the key, /salt_cache/minions/ca.aws-cc1.dev.xxx.yyy.com/mine: Key not found : /salt_cache/minions/ca.aws-cc1.dev.xxx.yyy.com/mine

# Fixed code
def _walk(r):
    """
    Recursively walk dirs. Return flattened list of keys.
    r: etcd.EtcdResult
    """
    if not r.dir:
        return [r.key.split("/", 3)[3]]

    keys = []
    for c in client.read(r.key).children:
        keys.extend(_walk(c))
    return keys
# Buggy code
def ls(bank):
    """
    Return an iterable object containing all entries stored in the specified
    bank.
    """
    _init_client()
    path = "{0}/{1}".format(path_prefix, bank)
    try:
        return _walk(client.get(path))
    except Exception as exc:
        raise SaltCacheError(
            'There was an error getting the key "{0}": {1}'.format(bank, exc)
        )


# Traceback (SaltCacheError)
salt-master[3903]: [ERROR   ] Error in function _mine:
salt-master[3903]: Traceback (most recent call last):
salt-master[3903]:   File "/usr/lib/python2.7/dist-packages/salt/master.py", line 1776, in run_func
salt-master[3903]:     ret = getattr(self, func)(load)
salt-master[3903]:   File "/usr/lib/python2.7/dist-packages/salt/master.py", line 1345, in _mine
salt-master[3903]:     return self.masterapi._mine(load, skip_verify=True)
salt-master[3903]:   File "/usr/lib/python2.7/dist-packages/salt/daemons/masterapi.py", line 607, in _mine
salt-master[3903]:     data = self.cache.fetch(cbank, ckey)
salt-master[3903]:   File "/usr/lib/python2.7/dist-packages/salt/cache/__init__.py", line 180, in fetch
salt-master[3903]:     return self.modules[fun](bank, key, **self._kwargs)
salt-master[3903]:   File "/usr/lib/python2.7/dist-packages/salt/cache/etcd_cache.py", line 150, in fetch
salt-master[3903]:     etcd_key, exc
salt-master[3903]: SaltCacheError: There was an error reading the key, /salt_cache/minions/ca.aws-cc1.dev.xxx.yyy.com/mine: Key not found : /salt_cache/minions/ca.aws-cc1.dev.xxx.yyy.com/mine
salt-master[3903]: [ERROR   ] Error in function _mine_get:
salt-master[3903]: Traceback (most recent call last):
salt-master[3903]:   File "/usr/lib/python2.7/dist-packages/salt/master.py", line 1776, in run_func
salt-master[3903]:     ret = getattr(self, func)(load)
salt-master[3903]:   File "/usr/lib/python2.7/dist-packages/salt/master.py", line 1331, in _mine_get
salt-master[3903]:     return self.masterapi._mine_get(load, skip_verify=True)
salt-master[3903]:   File "/usr/lib/python2.7/dist-packages/salt/daemons/masterapi.py", line 589, in _mine_get
salt-master[3903]:     fdata = self.cache.fetch('minions/{0}'.format(minion), 'mine')
salt-master[3903]:   File "/usr/lib/python2.7/dist-packages/salt/cache/__init__.py", line 180, in fetch
salt-master[3903]:     return self.modules[fun](bank, key, **self._kwargs)
salt-master[3903]:   File "/usr/lib/python2.7/dist-packages/salt/cache/etcd_cache.py", line 150, in fetch
salt-master[3903]:     etcd_key, exc
salt-master[3903]: SaltCacheError: There was an error reading the key, /salt_cache/minions/ca.aws-cc1.dev.xxx.yyy.com/mine: Key not found : /salt_cache/minions/ca.aws-cc1.dev.xxx.yyy.com/mine

# Fixed code
def ls(bank):
    """
    Return an iterable object containing all entries stored in the specified
    bank.
    """
    _init_client()
    path = "{0}/{1}".format(path_prefix, bank)
    try:
        return _walk(client.read(path))
    except Exception as exc:
        raise SaltCacheError(
            'There was an error getting the key "{0}": {1}'.format(bank, exc)
        )
# Buggy code
def format_json(self, value, sort_keys=True, indent=None):
    return Markup(
        salt.utils.json.dumps(value, sort_keys=sort_keys, indent=indent).strip()
    )


# Traceback (UnicodeDecodeError)
# salt-call  -l debug state.template /tmp/k2.sls
[...]
local:
Data failed to compile:
----------
Rendering SLS ':/tmp/k2.sls' failed: Jinja error: 'ascii' codec can't decode byte 0xc3 in position 398: ordinal not in range(128)
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/salt/utils/templates.py", line 390, in render_jinja_tmpl
output = template.render(**decoded_context)
File "/usr/lib/python2.7/site-packages/jinja2/environment.py", line 989, in render
return self.environment.handle_exception(exc_info, True)
File "/usr/lib/python2.7/site-packages/jinja2/environment.py", line 754, in handle_exception
reraise(exc_type, exc_value, tb)
File "<template>", line 10, in top-level template code
File "/usr/lib/python2.7/site-packages/salt/utils/jinja.py", line 805, in format_yaml
if yaml_txt.endswith('\n...'):
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 398: ordinal not in range(128)

; line 10

---
[...]
/tmp/k.settings:
file.managed:
- template: jinja
- encoding: UTF-8
- contents: |
{{ settings|yaml }}    <======================

Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/salt/utils/templates.py", line 390, in render_jinja_tmpl
output = template.render(**decoded_context)
File "/usr/lib/python2.7/site-packages/jinja2/environment.py", line 989, in render
[...]
---

# Fixed code
def format_json(self, value, sort_keys=True, indent=None):
    json_txt = salt.utils.json.dumps(value, sort_keys=sort_keys, indent=indent).strip()
    try:
        return Markup(json_txt)
    except UnicodeDecodeError:
        return Markup(salt.utils.stringutils.to_unicode(json_txt))
# Buggy code
def format_yaml(self, value, flow_style=True):
    yaml_txt = salt.utils.yaml.safe_dump(value, default_flow_style=flow_style).strip()
    if yaml_txt.endswith("\n..."):
        yaml_txt = yaml_txt[: len(yaml_txt) - 4]
    return Markup(yaml_txt)


# Traceback (UnicodeDecodeError)
# salt-call  -l debug state.template /tmp/k2.sls
[...]
local:
Data failed to compile:
----------
Rendering SLS ':/tmp/k2.sls' failed: Jinja error: 'ascii' codec can't decode byte 0xc3 in position 398: ordinal not in range(128)
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/salt/utils/templates.py", line 390, in render_jinja_tmpl
output = template.render(**decoded_context)
File "/usr/lib/python2.7/site-packages/jinja2/environment.py", line 989, in render
return self.environment.handle_exception(exc_info, True)
File "/usr/lib/python2.7/site-packages/jinja2/environment.py", line 754, in handle_exception
reraise(exc_type, exc_value, tb)
File "<template>", line 10, in top-level template code
File "/usr/lib/python2.7/site-packages/salt/utils/jinja.py", line 805, in format_yaml
if yaml_txt.endswith('\n...'):
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 398: ordinal not in range(128)

; line 10

---
[...]
/tmp/k.settings:
file.managed:
- template: jinja
- encoding: UTF-8
- contents: |
{{ settings|yaml }}    <======================

Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/salt/utils/templates.py", line 390, in render_jinja_tmpl
output = template.render(**decoded_context)
File "/usr/lib/python2.7/site-packages/jinja2/environment.py", line 989, in render
[...]
---

# Fixed code
def format_yaml(self, value, flow_style=True):
    yaml_txt = salt.utils.yaml.safe_dump(value, default_flow_style=flow_style).strip()
    if yaml_txt.endswith(str("\n...")):  # future lint: disable=blacklisted-function
        yaml_txt = yaml_txt[: len(yaml_txt) - 4]
    try:
        return Markup(yaml_txt)
    except UnicodeDecodeError:
        return Markup(salt.utils.stringutils.to_unicode(yaml_txt))
# Buggy code
def __init__(self, opts):
    super(MinionManager, self).__init__(opts)
    self.auth_wait = self.opts["acceptance_wait_time"]
    self.max_auth_wait = self.opts["acceptance_wait_time_max"]
    self.minions = []
    self.jid_queue = []

    install_zmq()
    self.io_loop = ZMQDefaultLoop.current()
    self.process_manager = ProcessManager(name="MultiMinionProcessManager")
    self.io_loop.spawn_callback(
        self.process_manager.run, **{"async": True}
    )  # Tornado backward compat


# Traceback (TypeError)
[ERROR   ] Exception in callback <functools.partial object at 0x23e97e0>
Traceback (most recent call last):
File "/usr/lib64/python2.7/site-packages/tornado/ioloop.py", line 591, in _run_callback
ret = callback()
File "/usr/lib64/python2.7/site-packages/tornado/stack_context.py", line 274, in null_wrapper
return fn(*args, **kwargs)
File "/usr/lib64/python2.7/site-packages/tornado/ioloop.py", line 597, in <lambda>
self.add_future(ret, lambda f: f.result())
File "/usr/lib64/python2.7/site-packages/tornado/concurrent.py", line 214, in result
raise_exc_info(self._exc_info)
File "/usr/lib64/python2.7/site-packages/tornado/gen.py", line 215, in wrapper
result = func(*args, **kwargs)
TypeError: run() got an unexpected keyword argument 'async'
[ERROR   ] Exception in callback <functools.partial object at 0x23e9890>
Traceback (most recent call last):
File "/usr/lib64/python2.7/site-packages/tornado/ioloop.py", line 591, in _run_callback
ret = callback()
File "/usr/lib64/python2.7/site-packages/tornado/stack_context.py", line 274, in null_wrapper
return fn(*args, **kwargs)
File "/usr/lib64/python2.7/site-packages/tornado/ioloop.py", line 597, in <lambda>
self.add_future(ret, lambda f: f.result())
File "/usr/lib64/python2.7/site-packages/tornado/concurrent.py", line 214, in result
raise_exc_info(self._exc_info)
File "/usr/lib64/python2.7/site-packages/tornado/gen.py", line 215, in wrapper
result = func(*args, **kwargs)
TypeError: run() got an unexpected keyword argument 'async'

# Fixed code
def __init__(self, opts):
    super(MinionManager, self).__init__(opts)
    self.auth_wait = self.opts["acceptance_wait_time"]
    self.max_auth_wait = self.opts["acceptance_wait_time_max"]
    self.minions = []
    self.jid_queue = []

    install_zmq()
    self.io_loop = ZMQDefaultLoop.current()
    self.process_manager = ProcessManager(name="MultiMinionProcessManager")
    self.io_loop.spawn_callback(
        self.process_manager.run, **{"asynchronous": True}
    )  # Tornado backward compat
# Buggy code
def show_instance(name, conn=None, call=None):
    """
    Get VM on this OpenStack account

    name

        name of the instance

    CLI Example

    .. code-block:: bash

        salt-cloud -a show_instance myserver

    """
    if call != "action":
        raise SaltCloudSystemExit(
            "The show_instance action must be called with -a or --action."
        )
    if conn is None:
        conn = get_conn()

    node = conn.get_server(name, bare=True)
    ret = dict(node)
    ret["id"] = node.id
    ret["name"] = node.name
    ret["size"] = conn.get_flavor(node.flavor.id).name
    ret["state"] = node.status
    ret["private_ips"] = _get_ips(node, "private")
    ret["public_ips"] = _get_ips(node, "public")
    ret["floating_ips"] = _get_ips(node, "floating")
    ret["fixed_ips"] = _get_ips(node, "fixed")
    ret["image"] = conn.get_image(node.image.id).name
    return ret


# Traceback (AttributeError)
[DEBUG   ] Manager myopenstack:RegionOne ran task compute.GET.flavors.os-extra_specs in 0.0983929634094s
[ERROR   ] There was a profile error: 'unicode' object has no attribute 'id'
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/cloud/cli.py", line 281, in run
self.config.get('names')
File "/usr/lib/python2.7/dist-packages/salt/cloud/__init__.py", line 1454, in run_profile
ret[name] = self.create(vm_)
File "/usr/lib/python2.7/dist-packages/salt/cloud/__init__.py", line 1284, in create
output = self.clouds[func](vm_)
File "/usr/lib/python2.7/dist-packages/salt/cloud/clouds/openstack.py", line 697, in create
data = request_instance(conn=conn, call='action', vm_=vm_)
File "/usr/lib/python2.7/dist-packages/salt/cloud/clouds/openstack.py", line 651, in request_instance
return show_instance(vm_['name'], conn=conn, call='action')
File "/usr/lib/python2.7/dist-packages/salt/cloud/clouds/openstack.py", line 469, in show_instance
ret['image'] = conn.get_image(node.image.id).name
AttributeError: 'unicode' object has no attribute 'id'

# Fixed code
def show_instance(name, conn=None, call=None):
    """
    Get VM on this OpenStack account

    name

        name of the instance

    CLI Example

    .. code-block:: bash

        salt-cloud -a show_instance myserver

    """
    if call != "action":
        raise SaltCloudSystemExit(
            "The show_instance action must be called with -a or --action."
        )
    if conn is None:
        conn = get_conn()

    node = conn.get_server(name, bare=True)
    ret = dict(node)
    ret["id"] = node.id
    ret["name"] = node.name
    ret["size"] = conn.get_flavor(node.flavor.id).name
    ret["state"] = node.status
    ret["private_ips"] = _get_ips(node, "private")
    ret["public_ips"] = _get_ips(node, "public")
    ret["floating_ips"] = _get_ips(node, "floating")
    ret["fixed_ips"] = _get_ips(node, "fixed")
    if isinstance(node.image, six.string_types):
        ret["image"] = node.image
    else:
        ret["image"] = conn.get_image(node.image.id).name
    return ret
# Buggy code
def _checksum_file_path(path):
    try:
        relpath = ".".join((os.path.relpath(path, __opts__["cachedir"]), "hash"))
        if re.match(r"..[/\\]", relpath):
            # path is a local file
            relpath = salt.utils.path_join(
                "local",
                os.path.splitdrive(path)[-1].lstrip("/\\"),
            )
    except ValueError as exc:
        # The path is on a different drive (Windows)
        if str(exc).startswith("path is on"):
            drive, path = os.path.splitdrive(path)
            relpath = salt.utils.path_join(
                "local",
                drive.rstrip(":"),
                path.lstrip("/\\"),
            )
        else:
            raise
    ret = salt.utils.path_join(__opts__["cachedir"], "archive_hash", relpath)
    log.debug("Using checksum file %s for cached archive file %s", ret, path)
    return ret


# Traceback (ValueError)
local:
----------
ID: extract
Function: archive.extracted
Name: C:\Test
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\archive.py", line 977, in extracted
existing_cached_source_sum = _read_cached_checksum(cached)
File "c:\salt\bin\lib\site-packages\salt\states\archive.py", line 118, in _read_cached_checksum
checksum_file = _checksum_file_path(path)
File "c:\salt\bin\lib\site-packages\salt\states\archive.py", line 69, in _checksum_file_path
relpath = '.'.join((os.path.relpath(path, __opts__['cachedir']), 'hash'))
File "c:\salt\bin\lib\ntpath.py", line 574, in relpath
path_drive, start_drive))
ValueError: path is on mount '\\\\localhost\\c$', start on mount 'c:'
Started: 21:46:53.583293
Duration: 31.369 ms
Changes:

# Fixed code
def _checksum_file_path(path):
    try:
        relpath = ".".join((os.path.relpath(path, __opts__["cachedir"]), "hash"))
        if re.match(r"..[/\\]", relpath):
            # path is a local file
            relpath = salt.utils.path_join(
                "local",
                os.path.splitdrive(path)[-1].lstrip("/\\"),
            )
    except ValueError as exc:
        # The path is on a different drive (Windows)
        if str(exc).startswith("path is on"):
            drive, path = os.path.splitdrive(path)
            relpath = salt.utils.path_join(
                "local",
                drive.rstrip(":"),
                path.lstrip("/\\"),
            )
        elif str(exc).startswith("Cannot mix UNC"):
            relpath = salt.utils.path_join("unc", path)
        else:
            raise
    ret = salt.utils.path_join(__opts__["cachedir"], "archive_hash", relpath)
    log.debug("Using checksum file %s for cached archive file %s", ret, path)
    return ret
# Buggy code
def returner(ret):
    """
    Return data to the local syslog
    """

    _options = _get_options(ret)

    if not _verify_options(_options):
        return

    # Get values from syslog module
    level = getattr(syslog, _options["level"])
    facility = getattr(syslog, _options["facility"])

    # parse for syslog options
    logoption = 0
    for opt in _options["options"]:
        logoption = logoption | getattr(syslog, opt)

    # Open syslog correctly based on options and tag
    try:
        if "tag" in _options:
            syslog.openlog(ident=_options["tag"], logoption=logoption)
        else:
            syslog.openlog(logoption=logoption)
    except TypeError:
        # Python 2.6 syslog.openlog does not accept keyword args
        syslog.openlog(_options.get("tag", "salt-minion"), logoption)

    # Send log of given level and facility
    syslog.syslog(facility | level, salt.utils.json.dumps(ret))

    # Close up to reset syslog to defaults
    syslog.closelog()


# Traceback (TypeError)
2018-07-12 14:15:13,372 [salt.minion      :1729][ERROR   ][4039] The return failed for job 20180712141512530947: openlog() argument 1 must be string, not unicode
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/salt/minion.py", line 1720, in _thread_return
minion_instance.returners[returner_str](ret)
File "/usr/lib/python2.7/site-packages/salt/returners/syslog_return.py", line 202, in returner
syslog.openlog(_options.get('tag', 'salt-minion'), logoption)
TypeError: openlog() argument 1 must be string, not unicode

# Fixed code
def returner(ret):
    """
    Return data to the local syslog
    """

    _options = _get_options(ret)

    if not _verify_options(_options):
        return

    # Get values from syslog module
    level = getattr(syslog, _options["level"])
    facility = getattr(syslog, _options["facility"])

    # parse for syslog options
    logoption = 0
    for opt in _options["options"]:
        logoption = logoption | getattr(syslog, opt)

    # Open syslog correctly based on options and tag
    if "tag" in _options:
        syslog.openlog(
            ident=salt.utils.stringutils.to_str(_options["tag"]), logoption=logoption
        )
    else:
        syslog.openlog(logoption=logoption)

    # Send log of given level and facility
    syslog.syslog(facility | level, salt.utils.json.dumps(ret))

    # Close up to reset syslog to defaults
    syslog.closelog()
# Buggy code
def _p_to_cp(p):
    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):
    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