gurudesh/pytracebugs huggingface dataset:
# Buggy code
def load_provider(self):
    provider = self._task.args.get("provider", {})
    for key, value in iteritems(ios_argument_spec):
        if key in self._task.args:
            provider[key] = self._task.args[key]
        elif "fallback" in value:
            provider[key] = self._fallback(value["fallback"])
        elif key not in provider:
            provider[key] = None
    self._task.args["provider"] = provider


# Traceback (012IOError)
Feb 14 11:24:01 x260 ansible-connection: <ios01> setup connection network_cli
Feb 14 11:24:01 x260 ansible-connection: <ios01> Traceback (most recent call last):#012  File "/home/johnb/git/ansible-inc/ansible/bin/ansible-connection", line 280, in main#012    server = Server(sf_path, pc)#012  File "/home/johnb/git/ansible-inc/ansible/bin/ansible-connection", line 123, in __init__#012    self.conn = connection_loader.get(play_context.connection, play_context, sys.stdin)#012  File "/home/johnb/git/ansible-inc/ansible/lib/ansible/plugins/__init__.py", line 372, in get#012    found_in_cache=found_in_cache, class_only=class_only)#012  File "/home/johnb/git/ansible-inc/ansible/lib/ansible/plugins/__init__.py", line 387, in _display_plugin_load#012    display.debug(msg)#012  File "/home/johnb/git/ansible-inc/ansible/lib/ansible/utils/display.py", line 175, in debug#012    self.display("%6d %0.5f: %s" % (os.getpid(), time.time(), msg), color=C.COLOR_DEBUG)#012  File "/home/johnb/git/ansible-inc/ansible/lib/ansible/utils/display.py", line 133, in display#012    fileobj.flush()#012IOError: [Errno 9] Bad file descriptor

# Fixed code
def load_provider(self):
    provider = self._task.args.get("provider", {})
    for key, value in iteritems(ios_argument_spec):
        if key != "provider" and key not in provider:
            if key in self._task.args:
                provider[key] = self._task.args[key]
            elif "fallback" in value:
                provider[key] = self._fallback(value["fallback"])
            elif key not in provider:
                provider[key] = None
    return provider
# Buggy code
def format_allowed_section(allowed):
    """Format each section of the allowed list"""
    if allowed.count(":") == 0:
        protocol = allowed
        ports = []
    elif allowed.count(":") == 1:
        protocol, ports = allowed.split(":")
    else:
        return []
    if ports.count(","):
        ports = ports.split(",")
    else:
        ports = [ports]
    return_val = {"IPProtocol": protocol}
    if ports:
        return_val["ports"] = ports
    return return_val


# Traceback (nKeyError)
"msg": "Unexpected response: ('ports'). Detail: Traceback (most recent call last):\n  File \"/tmp/ansible_5Dh1sH/ansible_module_gce_net.py\", line 356, in main\n    if allowed_list and (sorted_allowed_list(allowed_list) != sorted_allowed_list(fw.allowed)):\n  File \"/tmp/ansible_5Dh1sH/ansible_module_gce_net.py\", line 234, in sorted_allowed_list\n    return sorted(allowed_by_protocol, key=lambda y: y['ports'].sort())\n  File \"/tmp/ansible_5Dh1sH/ansible_module_gce_net.py\", line 234, in <lambda>\n    return sorted(allowed_by_protocol, key=lambda y: y['ports'].sort())\nKeyError: 'ports'\n"

# Fixed code
def format_allowed_section(allowed):
    """Format each section of the allowed list"""
    if allowed.count(":") == 0:
        protocol = allowed
        ports = []
    elif allowed.count(":") == 1:
        protocol, ports = allowed.split(":")
    else:
        return []
    if ports.count(","):
        ports = ports.split(",")
    elif ports:
        ports = [ports]
    return_val = {"IPProtocol": protocol}
    if ports:
        return_val["ports"] = ports
    return return_val
# Buggy code
def sorted_allowed_list(allowed_list):
    """Sort allowed_list (output of format_allowed) by protocol and port."""
    # sort by protocol
    allowed_by_protocol = sorted(allowed_list, key=lambda x: x["IPProtocol"])
    # sort the ports list
    return sorted(allowed_by_protocol, key=lambda y: y["ports"].sort())


# Traceback (nKeyError)
"msg": "Unexpected response: ('ports'). Detail: Traceback (most recent call last):\n  File \"/tmp/ansible_5Dh1sH/ansible_module_gce_net.py\", line 356, in main\n    if allowed_list and (sorted_allowed_list(allowed_list) != sorted_allowed_list(fw.allowed)):\n  File \"/tmp/ansible_5Dh1sH/ansible_module_gce_net.py\", line 234, in sorted_allowed_list\n    return sorted(allowed_by_protocol, key=lambda y: y['ports'].sort())\n  File \"/tmp/ansible_5Dh1sH/ansible_module_gce_net.py\", line 234, in <lambda>\n    return sorted(allowed_by_protocol, key=lambda y: y['ports'].sort())\nKeyError: 'ports'\n"

# Fixed code
def sorted_allowed_list(allowed_list):
    """Sort allowed_list (output of format_allowed) by protocol and port."""
    # sort by protocol
    allowed_by_protocol = sorted(allowed_list, key=lambda x: x["IPProtocol"])
    # sort the ports list
    return sorted(allowed_by_protocol, key=lambda y: y.get("ports", []).sort())
# Buggy code
def write(self, backup_file=None):
    """
    Write the crontab to the system. Saves all information.
    """
    if backup_file:
        fileh = open(backup_file, "w")
    elif self.cron_file:
        fileh = open(self.cron_file, "w")
    else:
        filed, path = tempfile.mkstemp(prefix="crontab")
        os.chmod(path, int("0644", 8))
        fileh = os.fdopen(filed, "w")

    fileh.write(self.render())
    fileh.close()

    # return if making a backup
    if backup_file:
        return

    # Add the entire crontab back to the user crontab
    if not self.cron_file:
        # quoting shell args for now but really this should be two non-shell calls.  FIXME
        (rc, out, err) = self.module.run_command(
            self._write_execute(path), use_unsafe_shell=True
        )
        os.unlink(path)

        if rc != 0:
            self.module.fail_json(msg=err)

    # set SELinux permissions
    if HAS_SELINUX:
        selinux.selinux_lsetfilecon_default(self.cron_file)


# Traceback (nOSError)
FAILED! => {"changed": false, "failed": true, "module_stderr": "", "module_stdout": "Traceback (most recent call last):\r\n  File \"/tmp/ansible_vHdMFc/ansible_module_cron.py\", line 773, in <module>\r\n    main()\r\n  File \"/tmp/ansible_vHdMFc/ansible_module_cron.py\", line 741, in main\r\n    crontab.write()\r\n  File \"/tmp/ansible_vHdMFc/ansible_module_cron.py\", line 345, in write\r\n    selinux.selinux_lsetfilecon_default(self.cron_file)\r\nOSError: [Errno 14] Bad address\r\n", "msg": "MODULE FAILURE"

# Fixed code
def write(self, backup_file=None):
    """
    Write the crontab to the system. Saves all information.
    """
    if backup_file:
        fileh = open(backup_file, "w")
    elif self.cron_file:
        fileh = open(self.cron_file, "w")
    else:
        filed, path = tempfile.mkstemp(prefix="crontab")
        os.chmod(path, int("0644", 8))
        fileh = os.fdopen(filed, "w")

    fileh.write(self.render())
    fileh.close()

    # return if making a backup
    if backup_file:
        return

    # Add the entire crontab back to the user crontab
    if not self.cron_file:
        # quoting shell args for now but really this should be two non-shell calls.  FIXME
        (rc, out, err) = self.module.run_command(
            self._write_execute(path), use_unsafe_shell=True
        )
        os.unlink(path)

        if rc != 0:
            self.module.fail_json(msg=err)

    # set SELinux permissions
    if self.module.selinux_enabled() and self.cron_file:
        self.module.set_default_selinux_context(self.cron_file, False)
# Buggy code
def _verify_timezone(self):
    tz = self.value["name"]["planned"]
    tzfile = "/usr/share/zoneinfo/%s" % tz
    if not os.path.isfile(tzfile):
        self.abort('given timezone "%s" is not available' % tz)


# Traceback (nNameError)
TASK [base : Set timezone to Europe/Moscow] ************************************
fatal: [192.168.111.222]: FAILED! => {"changed": false, "failed": true, "module_stderr": "BECOME-SUCCESS-bwdmdhqcljigltaovfhqflvkvyfvdzgl", "module_stdout": "Traceback (most recent call last):\r\n  File \"/tmp/ansible_MZQdNh/ansible_module_timezone.py\", line 462, in <module>\r\n    main()\r\n  File \"/tmp/ansible_MZQdNh/ansible_module_timezone.py\", line 435, in main\r\n    tz = Timezone(module)\r\n  File \"/tmp/ansible_MZQdNh/ansible_module_timezone.py\", line 306, in __init__\r\n    self.update_timezone += ' %s /etc/localtime' % tzfile\r\nNameError: global name 'tzfile' is not defined\r\n", "msg": "MODULE FAILURE"}

# Fixed code
def _verify_timezone(self):
    tz = self.value["name"]["planned"]
    tzfile = "/usr/share/zoneinfo/%s" % tz
    if not os.path.isfile(tzfile):
        self.abort('given timezone "%s" is not available' % tz)
    return tzfile
# Buggy code
def encrypt_file(self, filename, output_file=None):
    check_prereqs()

    # A file to be encrypted into a vaultfile could be any encoding
    # so treat the contents as a byte string.
    plaintext = self.read_data(filename)
    ciphertext = self.vault.encrypt(plaintext)
    self.write_data(ciphertext, output_file or filename)


# Traceback (UnicodeDecodeError)
[fedora-23:ansible (devel % u=)]$ cat example_fail.yml

---
- name: 'A play with unicode: ¢ £ ¤ ¥'
hosts: localhost
connection: local
vars:
test_var: 'Ī ī Ĭ ĭ Į į İ ı Ĳ ĳ Ĵ ĵ Ķ ķ ĸ Ĺ ĺ Ļ ļ Ľ ľ Ŀ ŀ Ł ł Ń ń Ņ ņ Ň ň ŉ Ŋ ŋ Ō ō Ŏ ŏ Ő ő Œ'
hostnames:
- 'host-ϬϭϮϯϰ'
- 'host-fóöbär'
- 'host-ΙΚΛΜΝΞ'
- 'host-στυφχψ'
- 'host-ϬϭϮϯϰϱ'

[fedora-23:ansible (devel % u=)]$ ansible-vault encrypt example_fail.yml
Vault password:
Encryption successful
[fedora-23:ansible (devel % u=)]$ ansible-vault -vvv edit example_fail.yml
Using /home/adrian/.ansible.cfg as config file
Vault password:

#  NOTE: when in the interactive editor, edit the file in some way so that it is different so it will be reencrypted

ERROR! Unexpected Exception: 'ascii' codec can't decode byte 0xc2 in position 34: ordinal not in range(128)
the full traceback was:

Traceback (most recent call last):
File "/home/adrian/src/ansible/bin/ansible-vault", line 103, in <module>
exit_code = cli.run()
File "/home/adrian/src/ansible/lib/ansible/cli/vault.py", line 123, in run
self.execute()
File "/home/adrian/src/ansible/lib/ansible/cli/__init__.py", line 147, in execute
fn()
File "/home/adrian/src/ansible/lib/ansible/cli/vault.py", line 159, in execute_edit
self.editor.edit_file(f)
File "/home/adrian/src/ansible/lib/ansible/parsing/vault/__init__.py", line 464, in edit_file
self._edit_file_helper(filename, existing_data=plaintext, force_save=False)
File "/home/adrian/src/ansible/lib/ansible/parsing/vault/__init__.py", line 411, in _edit_file_helper
enc_data = self.vault.encrypt(tmpdata.decode())
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 34: ordinal not in range(128)

# Fixed code
def encrypt_file(self, filename, output_file=None):
    check_prereqs()

    # A file to be encrypted into a vaultfile could be any encoding
    # so treat the contents as a byte string.
    b_plaintext = self.read_data(filename)
    b_ciphertext = self.vault.encrypt(b_plaintext)
    self.write_data(b_ciphertext, output_file or filename)
# Buggy code
def list_items(module, base, command):
    """List package info based on the command."""
    # Rename updates to upgrades
    if command == "updates":
        command = "upgrades"

    # Return the corresponding packages
    if command in ["installed", "upgrades", "available"]:
        results = [
            _package_dict(package) for package in getattr(base.sack.query(), command)()
        ]
    # Return the enabled repository ids
    elif command in ["repos", "repositories"]:
        results = [
            {"repoid": repo.id, "state": "enabled"}
            for repo in base.repos.iter_enabled()
        ]
    # Return any matching packages
    else:
        packages = subject.Subject(command).get_best_query(base.sack)
        results = [_package_dict(package) for package in packages]

    module.exit_json(results=results)


# Traceback (nNameError)
TASK [install essential software] *********************************************
failed: [54.213.90.47] => (item=[u'python-dnf', u'java-1.8.0-openjdk']) => {"failed": true, "item": ["python-dnf", "java-1.8.0-openjdk"], "module_stderr": "", "module_stdout": "Traceback (most recent call last):\r\n  File \"/home/fedora/.ansible/tmp/ansible-tmp-1455147718.94-110285313538093/dnf\", line 2284, in <module>\r\n    main()\r\n  File \"/home/fedora/.ansible/tmp/ansible-tmp-1455147718.94-110285313538093/dnf\", line 339, in main\r\n    if not util.am_i_root():\r\nNameError: global name 'util' is not defined\r\n", "msg": "MODULE FAILURE", "parsed": false}

# Fixed code
def list_items(module, base, command):
    """List package info based on the command."""
    # Rename updates to upgrades
    if command == "updates":
        command = "upgrades"

    # Return the corresponding packages
    if command in ["installed", "upgrades", "available"]:
        results = [
            _package_dict(package) for package in getattr(base.sack.query(), command)()
        ]
    # Return the enabled repository ids
    elif command in ["repos", "repositories"]:
        results = [
            {"repoid": repo.id, "state": "enabled"}
            for repo in base.repos.iter_enabled()
        ]
    # Return any matching packages
    else:
        packages = dnf.subject.Subject(command).get_best_query(base.sack)
        results = [_package_dict(package) for package in packages]

    module.exit_json(results=results)
# Buggy code
def _mark_package_install(module, base, pkg_spec):
    """Mark the package for install."""
    try:
        base.install(pkg_spec)
    except exceptions.MarkingError:
        module.fail_json(msg="No package {} available.".format(pkg_spec))


# Traceback (nNameError)
TASK [install essential software] *********************************************
failed: [54.213.90.47] => (item=[u'python-dnf', u'java-1.8.0-openjdk']) => {"failed": true, "item": ["python-dnf", "java-1.8.0-openjdk"], "module_stderr": "", "module_stdout": "Traceback (most recent call last):\r\n  File \"/home/fedora/.ansible/tmp/ansible-tmp-1455147718.94-110285313538093/dnf\", line 2284, in <module>\r\n    main()\r\n  File \"/home/fedora/.ansible/tmp/ansible-tmp-1455147718.94-110285313538093/dnf\", line 339, in main\r\n    if not util.am_i_root():\r\nNameError: global name 'util' is not defined\r\n", "msg": "MODULE FAILURE", "parsed": false}

# Fixed code
def _mark_package_install(module, base, pkg_spec):
    """Mark the package for install."""
    try:
        base.install(pkg_spec)
    except dnf.exceptions.MarkingError:
        module.fail_json(msg="No package {} available.".format(pkg_spec))
# Buggy code
def detect_su_prompt(data):
    SU_PROMPT_LOCALIZATIONS_RE = re.compile(
        "|".join(["(\w+'s )?" + x + " ?: ?" for x in SU_PROMPT_LOCALIZATIONS]),
        flags=re.IGNORECASE,
    )
    return bool(SU_PROMPT_LOCALIZATIONS_RE.match(data))


# Traceback (UnicodeEncodeError)
An exception occurred during task execution. The full traceback is:
Traceback (most recent call last):
File "/home/jon/Development/Personal/server-build/ansible/lib/ansible/executor/task_executor.py", line 96, in run
item_results = self._run_loop(items)
File "/home/jon/Development/Personal/server-build/ansible/lib/ansible/executor/task_executor.py", line 252, in _run_loop
res = self._execute(variables=task_vars)
File "/home/jon/Development/Personal/server-build/ansible/lib/ansible/executor/task_executor.py", line 447, in _execute
result = self._handler.run(task_vars=variables)
File "/home/jon/Development/Personal/server-build/ansible/lib/ansible/plugins/action/normal.py", line 33, in run
results = merge_hash(results, self._execute_module(tmp=tmp, task_vars=task_vars))
File "/home/jon/Development/Personal/server-build/ansible/lib/ansible/plugins/action/__init__.py", line 647, in _execute_module
res = self._low_level_execute_command(cmd, sudoable=sudoable, in_data=in_data)
File "/home/jon/Development/Personal/server-build/ansible/lib/ansible/plugins/action/__init__.py", line 721, in _low_level_execute_command
rc, stdout, stderr = self._connection.exec_command(cmd, in_data=in_data, sudoable=sudoable)
File "/home/jon/Development/Personal/server-build/ansible/lib/ansible/plugins/connection/paramiko_ssh.py", line 311, in exec_command
chan.sendall(self._play_context.become_pass + '\n')
File "/usr/lib/python2.7/dist-packages/paramiko/channel.py", line 797, in sendall
sent = self.send(s)
File "/usr/lib/python2.7/dist-packages/paramiko/channel.py", line 729, in send
m.add_string(s[:size])
File "/usr/lib/python2.7/dist-packages/paramiko/message.py", line 259, in add_string
self.packet.write(s)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa3' in position 1: ordinal not in range(128)

fatal: [server.example.com]: FAILED! => {"failed": true, "msg": "Unexpected failure during module execution.", "stdout": ""}

# Fixed code
def detect_su_prompt(b_data):
    b_SU_PROMPT_LOCALIZATIONS_RE = re.compile(
        b"|".join([b"(\w+'s )?" + x + b" ?: ?" for x in b_SU_PROMPT_LOCALIZATIONS]),
        flags=re.IGNORECASE,
    )
    return bool(b_SU_PROMPT_LOCALIZATIONS_RE.match(b_data))
# Buggy code
def detect_ksu_prompt(data):
    return re.match("Kerberos password for .*@.*:", data)


# Traceback (UnicodeEncodeError)
An exception occurred during task execution. The full traceback is:
Traceback (most recent call last):
File "/home/jon/Development/Personal/server-build/ansible/lib/ansible/executor/task_executor.py", line 96, in run
item_results = self._run_loop(items)
File "/home/jon/Development/Personal/server-build/ansible/lib/ansible/executor/task_executor.py", line 252, in _run_loop
res = self._execute(variables=task_vars)
File "/home/jon/Development/Personal/server-build/ansible/lib/ansible/executor/task_executor.py", line 447, in _execute
result = self._handler.run(task_vars=variables)
File "/home/jon/Development/Personal/server-build/ansible/lib/ansible/plugins/action/normal.py", line 33, in run
results = merge_hash(results, self._execute_module(tmp=tmp, task_vars=task_vars))
File "/home/jon/Development/Personal/server-build/ansible/lib/ansible/plugins/action/__init__.py", line 647, in _execute_module
res = self._low_level_execute_command(cmd, sudoable=sudoable, in_data=in_data)
File "/home/jon/Development/Personal/server-build/ansible/lib/ansible/plugins/action/__init__.py", line 721, in _low_level_execute_command
rc, stdout, stderr = self._connection.exec_command(cmd, in_data=in_data, sudoable=sudoable)
File "/home/jon/Development/Personal/server-build/ansible/lib/ansible/plugins/connection/paramiko_ssh.py", line 311, in exec_command
chan.sendall(self._play_context.become_pass + '\n')
File "/usr/lib/python2.7/dist-packages/paramiko/channel.py", line 797, in sendall
sent = self.send(s)
File "/usr/lib/python2.7/dist-packages/paramiko/channel.py", line 729, in send
m.add_string(s[:size])
File "/usr/lib/python2.7/dist-packages/paramiko/message.py", line 259, in add_string
self.packet.write(s)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa3' in position 1: ordinal not in range(128)

fatal: [server.example.com]: FAILED! => {"failed": true, "msg": "Unexpected failure during module execution.", "stdout": ""}

# Fixed code
def detect_ksu_prompt(b_data):
    return re.match(b"Kerberos password for .*@.*:", b_data)
# Buggy code
def __init__(self, *args, **kwargs):
    self._timeout = float(C.CACHE_PLUGIN_TIMEOUT)
    self._cache = {}
    self._cache_dir = os.path.expanduser(os.path.expandvars(C.CACHE_PLUGIN_CONNECTION))

    if not self._cache_dir:
        raise AnsibleError(
            "error, 'jsonfile' cache plugin requires the 'fact_caching_connection' config option to be set (to a writeable directory path)"
        )

    if not os.path.exists(self._cache_dir):
        try:
            os.makedirs(self._cache_dir)
        except (OSError, IOError) as e:
            display.warning(
                "error in 'jsonfile' cache plugin while trying to create cache dir %s : %s"
                % (self._cache_dir, to_bytes(e))
            )
            return None


# Traceback (TypeError)
[fedora-23:ansible (cache_timeout_0 %)]$ ANSIBLE_CONFIG=~/ansible/ansible-fact-jsonfile.cfg ansible-playbook -vvv repro/archive_single_file/archive.yml
Using /home/adrian/ansible/ansible-fact-jsonfile.cfg as config file
ERROR! Unexpected Exception: argument of type 'NoneType' is not iterable
the full traceback was:

Traceback (most recent call last):
File "/home/adrian/src/ansible/bin/ansible-playbook", line 103, in <module>
exit_code = cli.run()
File "/home/adrian/src/ansible/lib/ansible/cli/playbook.py", line 126, in run
variable_manager = VariableManager()
File "/home/adrian/src/ansible/lib/ansible/vars/__init__.py", line 97, in __init__
self._fact_cache = FactCache()
File "/home/adrian/src/ansible/lib/ansible/plugins/cache/__init__.py", line 35, in __init__
self._plugin = cache_loader.get(C.CACHE_PLUGIN)
File "/home/adrian/src/ansible/lib/ansible/plugins/__init__.py", line 358, in get
obj = obj(*args, **kwargs)
File "/home/adrian/src/ansible/lib/ansible/plugins/cache/jsonfile.py", line 53, in __init__
self._cache_dir = os.path.expanduser(os.path.expandvars(C.CACHE_PLUGIN_CONNECTION)) # expects a dir path
File "/usr/lib64/python2.7/posixpath.py", line 287, in expandvars
if '$' not in path:
TypeError: argument of type 'NoneType' is not iterable

# Fixed code
def __init__(self, *args, **kwargs):
    self._timeout = float(C.CACHE_PLUGIN_TIMEOUT)
    self._cache = {}
    self._cache_dir = None

    if C.CACHE_PLUGIN_CONNECTION:
        # expects a dir path
        self._cache_dir = os.path.expanduser(
            os.path.expandvars(C.CACHE_PLUGIN_CONNECTION)
        )

    if not self._cache_dir:
        raise AnsibleError(
            "error, 'jsonfile' cache plugin requires the 'fact_caching_connection' config option to be set (to a writeable directory path)"
        )

    if not os.path.exists(self._cache_dir):
        try:
            os.makedirs(self._cache_dir)
        except (OSError, IOError) as e:
            display.warning(
                "error in 'jsonfile' cache plugin while trying to create cache dir %s : %s"
                % (self._cache_dir, to_bytes(e))
            )
            return None
# Buggy code
def load_config_file():
    """Load Config File order(first found is used): ENV, CWD, HOME, /etc/ansible"""

    p = configparser.ConfigParser()

    path0 = os.getenv("ANSIBLE_CONFIG", None)
    if path0 is not None:
        path0 = os.path.expanduser(path0)
        if os.path.isdir(path0):
            path0 += "/ansible.cfg"
    path1 = os.getcwd() + "/ansible.cfg"
    path2 = os.path.expanduser("~/.ansible.cfg")
    path3 = "/etc/ansible/ansible.cfg"

    for path in [path0, path1, path2, path3]:
        if path is not None and os.path.exists(path):
            try:
                p.read(path)
            except configparser.Error as e:
                raise AnsibleOptionsError("Error reading config file: \n{0}".format(e))
            return p, path
    return None, ""


# Traceback (OSError)
Traceback (most recent call last):
File "../venv/bin/ansible", line 44, in <module>
import ansible.constants as C
File "/Users/dpowers/Code/ansible/venv/lib/python2.7/site-packages/ansible/constants.py", line 128, in <module>
p, CONFIG_FILE = load_config_file()
File "/Users/dpowers/Code/ansible/venv/lib/python2.7/site-packages/ansible/constants.py", line 115, in load_config_file
path1 = os.getcwd() + "/ansible.cfg"
OSError: [Errno 2] No such file or directory

# Fixed code
def load_config_file():
    """Load Config File order(first found is used): ENV, CWD, HOME, /etc/ansible"""

    p = configparser.ConfigParser()

    path0 = os.getenv("ANSIBLE_CONFIG", None)
    if path0 is not None:
        path0 = os.path.expanduser(path0)
        if os.path.isdir(path0):
            path0 += "/ansible.cfg"
    try:
        path1 = os.getcwd() + "/ansible.cfg"
    except OSError:
        path1 = None
    path2 = os.path.expanduser("~/.ansible.cfg")
    path3 = "/etc/ansible/ansible.cfg"

    for path in [path0, path1, path2, path3]:
        if path is not None and os.path.exists(path):
            try:
                p.read(path)
            except configparser.Error as e:
                raise AnsibleOptionsError("Error reading config file: \n{0}".format(e))
            return p, path
    return None, ""
# Buggy code
def timeout(seconds=10, error_message="Timer expired"):
    def decorator(func):
        def _handle_timeout(signum, frame):
            raise TimeoutError(error_message)

        def wrapper(*args, **kwargs):
            signal.signal(signal.SIGALRM, _handle_timeout)
            signal.alarm(seconds)
            try:
                result = func(*args, **kwargs)
            finally:
                signal.alarm(0)
            return result

        return wrapper

    return decorator


# Traceback (TimeoutError)
failed: [SOME_HOST] => {"cmd": "/bin/lsblk -ln --output UUID /dev/sdi2", "failed": true, "rc": 257}
msg: Traceback (most recent call last):
File "<stdin>", line 1650, in run_command
File "/usr/lib64/python2.4/subprocess.py", line 550, in __init__
errread, errwrite)
File "/usr/lib64/python2.4/subprocess.py", line 988, in _execute_child
data = os.read(errpipe_read, 1048576) # Exceptions limited to 1 MB
File "<stdin>", line 1796, in _handle_timeout
TimeoutError: Timer expired

# Fixed code
def timeout(seconds=10, error_message="Timer expired"):
    def decorator(func):
        def _handle_timeout(signum, frame):
            raise TimeoutError(error_message)

        def wrapper(*args, **kwargs):
            if "GATHER_TIMEOUT" in globals():
                if GATHER_TIMEOUT:
                    seconds = GATHER_TIMEOUT
            signal.signal(signal.SIGALRM, _handle_timeout)
            signal.alarm(seconds)
            try:
                result = func(*args, **kwargs)
            finally:
                signal.alarm(0)
            return result

        return wrapper

    return decorator
# Buggy code
def decorator(func):
    def _handle_timeout(signum, frame):
        raise TimeoutError(error_message)

    def wrapper(*args, **kwargs):
        signal.signal(signal.SIGALRM, _handle_timeout)
        signal.alarm(seconds)
        try:
            result = func(*args, **kwargs)
        finally:
            signal.alarm(0)
        return result

    return wrapper


# Traceback (TimeoutError)
failed: [SOME_HOST] => {"cmd": "/bin/lsblk -ln --output UUID /dev/sdi2", "failed": true, "rc": 257}
msg: Traceback (most recent call last):
File "<stdin>", line 1650, in run_command
File "/usr/lib64/python2.4/subprocess.py", line 550, in __init__
errread, errwrite)
File "/usr/lib64/python2.4/subprocess.py", line 988, in _execute_child
data = os.read(errpipe_read, 1048576) # Exceptions limited to 1 MB
File "<stdin>", line 1796, in _handle_timeout
TimeoutError: Timer expired

# Fixed code
def decorator(func):
    def _handle_timeout(signum, frame):
        raise TimeoutError(error_message)

    def wrapper(*args, **kwargs):
        if "GATHER_TIMEOUT" in globals():
            if GATHER_TIMEOUT:
                seconds = GATHER_TIMEOUT
        signal.signal(signal.SIGALRM, _handle_timeout)
        signal.alarm(seconds)
        try:
            result = func(*args, **kwargs)
        finally:
            signal.alarm(0)
        return result

    return wrapper
# Buggy code
def wrapper(*args, **kwargs):
    signal.signal(signal.SIGALRM, _handle_timeout)
    signal.alarm(seconds)
    try:
        result = func(*args, **kwargs)
    finally:
        signal.alarm(0)
    return result


# Traceback (TimeoutError)
failed: [SOME_HOST] => {"cmd": "/bin/lsblk -ln --output UUID /dev/sdi2", "failed": true, "rc": 257}
msg: Traceback (most recent call last):
File "<stdin>", line 1650, in run_command
File "/usr/lib64/python2.4/subprocess.py", line 550, in __init__
errread, errwrite)
File "/usr/lib64/python2.4/subprocess.py", line 988, in _execute_child
data = os.read(errpipe_read, 1048576) # Exceptions limited to 1 MB
File "<stdin>", line 1796, in _handle_timeout
TimeoutError: Timer expired

# Fixed code
def wrapper(*args, **kwargs):
    if "GATHER_TIMEOUT" in globals():
        if GATHER_TIMEOUT:
            seconds = GATHER_TIMEOUT
    signal.signal(signal.SIGALRM, _handle_timeout)
    signal.alarm(seconds)
    try:
        result = func(*args, **kwargs)
    finally:
        signal.alarm(0)
    return result
# Buggy code
def __new__(cls, *arguments, **keyword):
    # When Hardware is created, it chooses a subclass to create instead.
    # This check prevents the subclass from then trying to find a subclass
    # and create that.
    if cls is not Hardware:
        return super(Hardware, cls).__new__(cls)

    subclass = cls
    for sc in get_all_subclasses(Hardware):
        if sc.platform == platform.system():
            subclass = sc
    return super(cls, subclass).__new__(subclass, *arguments, **keyword)


# Traceback (TimeoutError)
failed: [SOME_HOST] => {"cmd": "/bin/lsblk -ln --output UUID /dev/sdi2", "failed": true, "rc": 257}
msg: Traceback (most recent call last):
File "<stdin>", line 1650, in run_command
File "/usr/lib64/python2.4/subprocess.py", line 550, in __init__
errread, errwrite)
File "/usr/lib64/python2.4/subprocess.py", line 988, in _execute_child
data = os.read(errpipe_read, 1048576) # Exceptions limited to 1 MB
File "<stdin>", line 1796, in _handle_timeout
TimeoutError: Timer expired

# Fixed code
def __new__(cls, *arguments, **keyword):
    # When Hardware is created, it chooses a subclass to create instead.
    # This check prevents the subclass from then trying to find a subclass
    # and create that.
    if cls is not Hardware:
        return super(Hardware, cls).__new__(cls)

    subclass = cls
    for sc in get_all_subclasses(Hardware):
        if sc.platform == platform.system():
            subclass = sc
    if PY3:
        return super(cls, subclass).__new__(subclass)
    else:
        return super(cls, subclass).__new__(subclass, *arguments, **keyword)
# Buggy code
def __new__(cls, *arguments, **keyword):
    # When Network is created, it chooses a subclass to create instead.
    # This check prevents the subclass from then trying to find a subclass
    # and create that.
    if cls is not Network:
        return super(Network, cls).__new__(cls)

    subclass = cls
    for sc in get_all_subclasses(Network):
        if sc.platform == platform.system():
            subclass = sc
    return super(cls, subclass).__new__(subclass, *arguments, **keyword)


# Traceback (TimeoutError)
failed: [SOME_HOST] => {"cmd": "/bin/lsblk -ln --output UUID /dev/sdi2", "failed": true, "rc": 257}
msg: Traceback (most recent call last):
File "<stdin>", line 1650, in run_command
File "/usr/lib64/python2.4/subprocess.py", line 550, in __init__
errread, errwrite)
File "/usr/lib64/python2.4/subprocess.py", line 988, in _execute_child
data = os.read(errpipe_read, 1048576) # Exceptions limited to 1 MB
File "<stdin>", line 1796, in _handle_timeout
TimeoutError: Timer expired

# Fixed code
def __new__(cls, *arguments, **keyword):
    # When Network is created, it chooses a subclass to create instead.
    # This check prevents the subclass from then trying to find a subclass
    # and create that.
    if cls is not Network:
        return super(Network, cls).__new__(cls)

    subclass = cls
    for sc in get_all_subclasses(Network):
        if sc.platform == platform.system():
            subclass = sc
    if PY3:
        return super(cls, subclass).__new__(subclass)
    else:
        return super(cls, subclass).__new__(subclass, *arguments, **keyword)
# Buggy code
def __new__(cls, *arguments, **keyword):
    # When Virtual is created, it chooses a subclass to create instead.
    # This check prevents the subclass from then trying to find a subclass
    # and create that.
    if cls is not Virtual:
        return super(Virtual, cls).__new__(cls)

    subclass = cls
    for sc in get_all_subclasses(Virtual):
        if sc.platform == platform.system():
            subclass = sc
    return super(cls, subclass).__new__(subclass, *arguments, **keyword)


# Traceback (TimeoutError)
failed: [SOME_HOST] => {"cmd": "/bin/lsblk -ln --output UUID /dev/sdi2", "failed": true, "rc": 257}
msg: Traceback (most recent call last):
File "<stdin>", line 1650, in run_command
File "/usr/lib64/python2.4/subprocess.py", line 550, in __init__
errread, errwrite)
File "/usr/lib64/python2.4/subprocess.py", line 988, in _execute_child
data = os.read(errpipe_read, 1048576) # Exceptions limited to 1 MB
File "<stdin>", line 1796, in _handle_timeout
TimeoutError: Timer expired

# Fixed code
def __new__(cls, *arguments, **keyword):
    # When Virtual is created, it chooses a subclass to create instead.
    # This check prevents the subclass from then trying to find a subclass
    # and create that.
    if cls is not Virtual:
        return super(Virtual, cls).__new__(cls)

    subclass = cls
    for sc in get_all_subclasses(Virtual):
        if sc.platform == platform.system():
            subclass = sc

    if PY3:
        return super(cls, subclass).__new__(subclass)
    else:
        return super(cls, subclass).__new__(subclass, *arguments, **keyword)
# Buggy code
def debugl(self, text):
    if self.args.debug:
        print(text)


# Traceback (UnicodeEncodeError)
./vmware_inventory.py --list
Traceback (most recent call last):
File "./vmware_inventory.py", line 568, in <module>
print(VMWareInventory().show())
File "./vmware_inventory.py", line 109, in __init__
self.do_api_calls_update_cache()
File "./vmware_inventory.py", line 147, in do_api_calls_update_cache
instances = self.get_instances()
File "./vmware_inventory.py", line 282, in get_instances
instances = self._get_instances(kwargs)
File "./vmware_inventory.py", line 307, in _get_instances
ifacts = self.facts_from_vobj(instance)
File "./vmware_inventory.py", line 514, in facts_from_vobj
rdata[method] = self._process_object_types(methodToCall, level=level)
File "./vmware_inventory.py", line 545, in _process_object_types
md = self.facts_from_vobj(vobj, level=(level+1))
File "./vmware_inventory.py", line 487, in facts_from_vobj
rdata[k] = self._process_object_types(v, level=level)
File "./vmware_inventory.py", line 523, in _process_object_types
self.debugl("PROCESSING: %s" % str(vobj))
UnicodeEncodeError: 'ascii' codec can't encode character u'\u0159' in position 205: ordinal not in range(128)

# Fixed code
def debugl(self, text):
    if self.args.debug:
        try:
            text = str(text)
        except UnicodeEncodeError:
            text = text.encode("ascii", "ignore")
        print(text)
# Buggy code
def create_template_mapping(self, inventory, pattern, dtype="string"):
    """Return a hash of uuid to templated string from pattern"""

    mapping = {}
    for k, v in inventory["_meta"]["hostvars"].iteritems():
        t = jinja2.Template(pattern)
        newkey = None
        try:
            newkey = t.render(v)
            newkey = newkey.strip()
        except Exception as e:
            self.debugl(str(e))
            # import epdb; epdb.st()
        if not newkey:
            continue
        elif dtype == "integer":
            newkey = int(newkey)
        elif dtype == "boolean":
            if newkey.lower() == "false":
                newkey = False
            elif newkey.lower() == "true":
                newkey = True
        elif dtype == "string":
            pass
        mapping[k] = newkey
    return mapping


# Traceback (UnicodeEncodeError)
./vmware_inventory.py --list
Traceback (most recent call last):
File "./vmware_inventory.py", line 568, in <module>
print(VMWareInventory().show())
File "./vmware_inventory.py", line 109, in __init__
self.do_api_calls_update_cache()
File "./vmware_inventory.py", line 147, in do_api_calls_update_cache
instances = self.get_instances()
File "./vmware_inventory.py", line 282, in get_instances
instances = self._get_instances(kwargs)
File "./vmware_inventory.py", line 307, in _get_instances
ifacts = self.facts_from_vobj(instance)
File "./vmware_inventory.py", line 514, in facts_from_vobj
rdata[method] = self._process_object_types(methodToCall, level=level)
File "./vmware_inventory.py", line 545, in _process_object_types
md = self.facts_from_vobj(vobj, level=(level+1))
File "./vmware_inventory.py", line 487, in facts_from_vobj
rdata[k] = self._process_object_types(v, level=level)
File "./vmware_inventory.py", line 523, in _process_object_types
self.debugl("PROCESSING: %s" % str(vobj))
UnicodeEncodeError: 'ascii' codec can't encode character u'\u0159' in position 205: ordinal not in range(128)

# Fixed code
def create_template_mapping(self, inventory, pattern, dtype="string"):
    """Return a hash of uuid to templated string from pattern"""

    mapping = {}
    for k, v in inventory["_meta"]["hostvars"].iteritems():
        t = jinja2.Template(pattern)
        newkey = None
        try:
            newkey = t.render(v)
            newkey = newkey.strip()
        except Exception as e:
            self.debugl(e)
            # import epdb; epdb.st()
        if not newkey:
            continue
        elif dtype == "integer":
            newkey = int(newkey)
        elif dtype == "boolean":
            if newkey.lower() == "false":
                newkey = False
            elif newkey.lower() == "true":
                newkey = True
        elif dtype == "string":
            pass
        mapping[k] = newkey
    return mapping
# Buggy code
def set(self, key, value):
    self._cache[key] = value

    cachefile = "%s/%s" % (self._cache_dir, key)
    try:
        f = codecs.open(cachefile, "w", encoding="utf-8")
    except (OSError, IOError) as e:
        display.warning(
            "error while trying to write to %s : %s" % (cachefile, to_bytes(e))
        )
        pass
    else:
        f.write(jsonify(value))
    finally:
        f.close()


# Traceback (UnboundLocalError)
Traceback (most recent call last):
File "/usr/bin/ansible-playbook", line 86, in <module>
sys.exit(cli.run())
File "/usr/lib/python2.6/site-packages/ansible/cli/playbook.py", line 150, in run
results = pbex.run()
File "/usr/lib/python2.6/site-packages/ansible/executor/playbook_executor.py", line 140, in run
result = self._tqm.run(play=play)
File "/usr/lib/python2.6/site-packages/ansible/executor/task_queue_manager.py", line 238, in run
play_return = strategy.run(iterator, play_context)
File "/usr/lib/python2.6/site-packages/ansible/plugins/strategy/linear.py", line 268, in run
results += self._wait_on_pending_results(iterator)
File "/usr/lib/python2.6/site-packages/ansible/plugins/strategy/__init__.py", line 354, in _wait_on_pending_results
results = self._process_pending_results(iterator)
File "/usr/lib/python2.6/site-packages/ansible/plugins/strategy/__init__.py", line 331, in _process_pending_results
self._variable_manager.set_host_facts(target_host, facts)
File "/usr/lib/python2.6/site-packages/ansible/vars/__init__.py", line 580, in set_host_facts
self._fact_cache.update(host.name, facts)
File "/usr/lib/python2.6/site-packages/ansible/plugins/cache/__init__.py", line 77, in update
self._plugin.set(key, host_cache)
File "/usr/lib/python2.6/site-packages/ansible/plugins/cache/jsonfile.py", line 101, in set
f.close()
UnboundLocalError: local variable 'f' referenced before assignment

# Fixed code
def set(self, key, value):
    self._cache[key] = value

    cachefile = "%s/%s" % (self._cache_dir, key)
    try:
        f = codecs.open(cachefile, "w", encoding="utf-8")
    except (OSError, IOError) as e:
        display.warning(
            "error while trying to write to %s : %s" % (cachefile, to_bytes(e))
        )
        pass
    else:
        f.write(jsonify(value))
    finally:
        try:
            f.close()
        except UnboundLocalError:
            pass
# Buggy code
def _editor_shell_command(self, filename):
    EDITOR = os.environ.get("EDITOR", "vim")
    editor = shlex.split(EDITOR)
    editor.append(filename)

    return editor


# Traceback (OSError)
No config file found; using defaults
New Vault password:
Confirm New Vault password:
ERROR! Unexpected Exception: [Errno 2] No such file or directory
the full traceback was:

Traceback (most recent call last):
File "/usr/local/bin/ansible-vault", line 86, in <module>
sys.exit(cli.run())
File "/usr/local/lib/python2.7/dist-packages/ansible/cli/vault.py", line 120, in run
self.execute()
File "/usr/local/lib/python2.7/dist-packages/ansible/cli/__init__.py", line 114, in execute
fn()
File "/usr/local/lib/python2.7/dist-packages/ansible/cli/vault.py", line 152, in execute_create
self.editor.create_file(self.args[0])
File "/usr/local/lib/python2.7/dist-packages/ansible/parsing/vault/__init__.py", line 351, in create_file
self._edit_file_helper(filename)
File "/usr/local/lib/python2.7/dist-packages/ansible/parsing/vault/__init__.py", line 302, in _edit_file_helper
call(self._editor_shell_command(tmp_path))
File "/usr/lib/python2.7/subprocess.py", line 493, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.7/subprocess.py", line 679, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1259, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory

# Fixed code
def _editor_shell_command(self, filename):
    EDITOR = os.environ.get("EDITOR", "vi")
    editor = shlex.split(EDITOR)
    editor.append(filename)

    return editor
# Buggy code
def get_opt(self, k, defval=""):
    """
    Returns an option from an Optparse values instance.
    """
    try:
        data = getattr(self.options, k)
    except:
        return defval
    if k == "roles_path":
        if os.pathsep in data:
            data = data.split(os.pathsep)[0]
    return data


# Traceback (AttributeError)
20:29 $ ansible-galaxy -v -v -v -v -v install bcoca.tidy
Using /Users/adrian/ansible/ansible.cfg as config file
Opened /Users/adrian/.ansible_galaxy
Validate TLS certificates: True
Connecting to galaxy_server: https://galaxy.ansible.com
Base API: https://galaxy.ansible.com/api/v1
ERROR! Unexpected Exception: 'Galaxy' object has no attribute 'roles_paths'
the full traceback was:

Traceback (most recent call last):
File "/Users/adrian/src/ansible/bin/ansible-galaxy", line 86, in <module>
sys.exit(cli.run())
File "/Users/adrian/src/ansible/lib/ansible/cli/galaxy.py", line 153, in run
self.execute()
File "/Users/adrian/src/ansible/lib/ansible/cli/__init__.py", line 114, in execute
fn()
File "/Users/adrian/src/ansible/lib/ansible/cli/galaxy.py", line 394, in execute_install
roles_left.append(GalaxyRole(self.galaxy, **role))
File "/Users/adrian/src/ansible/lib/ansible/galaxy/role.py", line 70, in __init__
for path in galaxy.roles_paths:
AttributeError: 'Galaxy' object has no attribute 'roles_paths'

# Fixed code
def get_opt(self, k, defval=""):
    """
    Returns an option from an Optparse values instance.
    """
    try:
        data = getattr(self.options, k)
    except:
        return defval
    # FIXME: Can this be removed if cli and/or constants ensures it's a
    # list?
    if k == "roles_path":
        if os.pathsep in data:
            data = data.split(os.pathsep)[0]
    return data
# Buggy code
def __init__(self, options):
    self.options = options
    roles_paths = getattr(self.options, "roles_path", [])
    if isinstance(roles_paths, string_types):
        self.roles_paths = [
            os.path.expanduser(roles_path)
            for roles_path in roles_paths.split(os.pathsep)
        ]

    self.roles = {}

    # load data path for resource usage
    this_dir, this_filename = os.path.split(__file__)
    self.DATA_PATH = os.path.join(this_dir, "data")

    self._default_readme = None
    self._default_meta = None
    self._default_test = None
    self._default_travis = None


# Traceback (AttributeError)
20:29 $ ansible-galaxy -v -v -v -v -v install bcoca.tidy
Using /Users/adrian/ansible/ansible.cfg as config file
Opened /Users/adrian/.ansible_galaxy
Validate TLS certificates: True
Connecting to galaxy_server: https://galaxy.ansible.com
Base API: https://galaxy.ansible.com/api/v1
ERROR! Unexpected Exception: 'Galaxy' object has no attribute 'roles_paths'
the full traceback was:

Traceback (most recent call last):
File "/Users/adrian/src/ansible/bin/ansible-galaxy", line 86, in <module>
sys.exit(cli.run())
File "/Users/adrian/src/ansible/lib/ansible/cli/galaxy.py", line 153, in run
self.execute()
File "/Users/adrian/src/ansible/lib/ansible/cli/__init__.py", line 114, in execute
fn()
File "/Users/adrian/src/ansible/lib/ansible/cli/galaxy.py", line 394, in execute_install
roles_left.append(GalaxyRole(self.galaxy, **role))
File "/Users/adrian/src/ansible/lib/ansible/galaxy/role.py", line 70, in __init__
for path in galaxy.roles_paths:
AttributeError: 'Galaxy' object has no attribute 'roles_paths'

# Fixed code
def __init__(self, options):
    self.options = options
    # self.options.roles_path needs to be a list and will be by default
    roles_path = getattr(self.options, "roles_path", [])
    # cli option handling is responsible for making roles_path a list
    self.roles_paths = roles_path

    self.roles = {}

    # load data path for resource usage
    this_dir, this_filename = os.path.split(__file__)
    self.DATA_PATH = os.path.join(this_dir, "data")

    self._default_readme = None
    self._default_meta = None
    self._default_test = None
    self._default_travis = None
# Buggy code
def __init__(self, galaxy, name, src=None, version=None, scm=None, path=None):
    self._metadata = None
    self._install_info = None

    self.options = galaxy.options
    self.galaxy = galaxy

    self.name = name
    self.version = version
    self.src = src or name
    self.scm = scm

    if path is not None:
        if self.name not in path:
            path = os.path.join(path, self.name)
        self.path = path
    else:
        for path in galaxy.roles_paths:
            role_path = os.path.join(path, self.name)
            if os.path.exists(role_path):
                self.path = role_path
                break
        else:
            # use the first path by default
            self.path = os.path.join(galaxy.roles_paths[0], self.name)


# Traceback (AttributeError)
20:29 $ ansible-galaxy -v -v -v -v -v install bcoca.tidy
Using /Users/adrian/ansible/ansible.cfg as config file
Opened /Users/adrian/.ansible_galaxy
Validate TLS certificates: True
Connecting to galaxy_server: https://galaxy.ansible.com
Base API: https://galaxy.ansible.com/api/v1
ERROR! Unexpected Exception: 'Galaxy' object has no attribute 'roles_paths'
the full traceback was:

Traceback (most recent call last):
File "/Users/adrian/src/ansible/bin/ansible-galaxy", line 86, in <module>
sys.exit(cli.run())
File "/Users/adrian/src/ansible/lib/ansible/cli/galaxy.py", line 153, in run
self.execute()
File "/Users/adrian/src/ansible/lib/ansible/cli/__init__.py", line 114, in execute
fn()
File "/Users/adrian/src/ansible/lib/ansible/cli/galaxy.py", line 394, in execute_install
roles_left.append(GalaxyRole(self.galaxy, **role))
File "/Users/adrian/src/ansible/lib/ansible/galaxy/role.py", line 70, in __init__
for path in galaxy.roles_paths:
AttributeError: 'Galaxy' object has no attribute 'roles_paths'

# Fixed code
def __init__(self, galaxy, name, src=None, version=None, scm=None, path=None):
    self._metadata = None
    self._install_info = None

    self.options = galaxy.options
    self.galaxy = galaxy

    self.name = name
    self.version = version
    self.src = src or name
    self.scm = scm

    if path is not None:
        if self.name not in path:
            path = os.path.join(path, self.name)
        self.path = path
    else:
        for role_path_dir in galaxy.roles_paths:
            role_path = os.path.join(role_path_dir, self.name)
            if os.path.exists(role_path):
                self.path = role_path
                break
        else:
            # use the first path by default
            self.path = os.path.join(galaxy.roles_paths[0], self.name)