gurudesh/pytracebugs huggingface dataset:
# Buggy code
def no_git_env(_env=None):
    # Too many bugs dealing with environment variables and GIT:
    # https://github.com/pre-commit/pre-commit/issues/300
    # In git 2.6.3 (maybe others), git exports GIT_WORK_TREE while running
    # pre-commit hooks
    # In git 1.9.1 (maybe others), git exports GIT_DIR and GIT_INDEX_FILE
    # while running pre-commit hooks in submodules.
    # GIT_DIR: Causes git clone to clone wrong thing
    # GIT_INDEX_FILE: Causes 'error invalid object ...' during commit
    _env = _env if _env is not None else os.environ
    return {
        k: v
        for k, v in _env.items()
        if not k.startswith("GIT_")
        or k in {"GIT_EXEC_PATH", "GIT_SSH", "GIT_SSH_COMMAND"}
    }


# Traceback (pre_commit.util.CalledProcessError)
An unexpected error has occurred: CalledProcessError: Command: ('/home/igankevich/.guix-profile/bin/git', 'fetch', 'origin', '--tags')
Return code: 128
Expected return code: 0
Output: (none)
Errors:
fatal: unable to access 'https://github.com/pre-commit/pre-commit-hooks/': server certificate verification failed. CAfile: none CRLfile: none

Traceback (most recent call last):
File "/gnu/store/35ppc0zpffbzc6zsw9xnks1hxmr7wh19-python-pre-commit-1.20.0/lib/python3.7/site-packages/pre_commit/store.py", line 168, in clone_strategy
self._shallow_clone(ref, _git_cmd)
File "/gnu/store/35ppc0zpffbzc6zsw9xnks1hxmr7wh19-python-pre-commit-1.20.0/lib/python3.7/site-packages/pre_commit/store.py", line 150, in _shallow_clone
git_cmd('-c', git_config, 'fetch', 'origin', ref, '--depth=1')
File "/gnu/store/35ppc0zpffbzc6zsw9xnks1hxmr7wh19-python-pre-commit-1.20.0/lib/python3.7/site-packages/pre_commit/store.py", line 165, in _git_cmd
cmd_output_b('git', *args, cwd=directory, env=env)
File "/gnu/store/35ppc0zpffbzc6zsw9xnks1hxmr7wh19-python-pre-commit-1.20.0/lib/python3.7/site-packages/pre_commit/util.py", line 147, in cmd_output_b
returncode, cmd, retcode, output=(stdout_b, stderr_b),
pre_commit.util.CalledProcessError: Command: ('/home/igankevich/.guix-profile/bin/git', '-c', 'protocol.version=2', 'fetch', 'origin', 'v2.4.0', '--depth=1')
Return code: 128
Expected return code: 0
Output: (none)
Errors:
fatal: unable to access 'https://github.com/pre-commit/pre-commit-hooks/': server certificate verification failed. CAfile: none CRLfile: none

# Fixed code
def no_git_env(_env=None):
    # Too many bugs dealing with environment variables and GIT:
    # https://github.com/pre-commit/pre-commit/issues/300
    # In git 2.6.3 (maybe others), git exports GIT_WORK_TREE while running
    # pre-commit hooks
    # In git 1.9.1 (maybe others), git exports GIT_DIR and GIT_INDEX_FILE
    # while running pre-commit hooks in submodules.
    # GIT_DIR: Causes git clone to clone wrong thing
    # GIT_INDEX_FILE: Causes 'error invalid object ...' during commit
    _env = _env if _env is not None else os.environ
    return {
        k: v
        for k, v in _env.items()
        if not k.startswith("GIT_")
        or k in {"GIT_EXEC_PATH", "GIT_SSH", "GIT_SSH_COMMAND", "GIT_SSL_CAINFO"}
    }
# Buggy code
def handle_remove_readonly(func, path, exc):  # pragma: no cover (windows)
    excvalue = exc[1]
    if func in (os.rmdir, os.remove, os.unlink) and excvalue.errno == errno.EACCES:
        os.chmod(path, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
        func(path)
    else:
        raise


# Traceback (PermissionError)
An unexpected error has occurred: PermissionError: [Errno 13] Permission denied: '/Users/detailyang/.cache/pre-commit/repo2ba1f3b5/golangenv-default/pkg/mod/github.com/!burnt!sushi/toml@v0.3.1/.gitignore'
Traceback (most recent call last):
File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/shutil.py", line 447, in _rmtree_safe_fd
os.unlink(entry.name, dir_fd=topfd)
PermissionError: [Errno 13] Permission denied: '.gitignore'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/pre_commit/error_handler.py", line 46, in error_handler
yield
File "/usr/local/lib/python3.7/site-packages/pre_commit/main.py", line 294, in main
return run(args.config, store, args)
File "/usr/local/lib/python3.7/site-packages/pre_commit/commands/run.py", line 285, in run
install_hook_envs(hooks, store)
File "/usr/local/lib/python3.7/site-packages/pre_commit/repository.py", line 215, in install_hook_envs
hook.install()
File "/usr/local/lib/python3.7/site-packages/pre_commit/repository.py", line 90, in install
rmtree(self.prefix.path(venv))
File "/usr/local/lib/python3.7/site-packages/pre_commit/util.py", line 171, in rmtree
shutil.rmtree(path, ignore_errors=False, onerror=handle_remove_readonly)
File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/shutil.py", line 491, in rmtree
_rmtree_safe_fd(fd, path, onerror)
File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/shutil.py", line 429, in _rmtree_safe_fd
_rmtree_safe_fd(dirfd, fullname, onerror)
File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/shutil.py", line 429, in _rmtree_safe_fd
_rmtree_safe_fd(dirfd, fullname, onerror)
File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/shutil.py", line 429, in _rmtree_safe_fd
_rmtree_safe_fd(dirfd, fullname, onerror)
[Previous line repeated 2 more times]
File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/shutil.py", line 449, in _rmtree_safe_fd
onerror(os.unlink, fullname, sys.exc_info())
File "/usr/local/lib/python3.7/site-packages/pre_commit/util.py", line 168, in handle_remove_readonly
func(path)
PermissionError: [Errno 13] Permission denied: '/Users/detailyang/.cache/pre-commit/repo2ba1f3b5/golangenv-default/pkg/mod/github.com/!burnt!sushi/toml@v0.3.1/.gitignore'

# Fixed code
def handle_remove_readonly(func, path, exc):
    excvalue = exc[1]
    if func in (os.rmdir, os.remove, os.unlink) and excvalue.errno == errno.EACCES:
        for p in (path, os.path.dirname(path)):
            os.chmod(p, os.stat(p).st_mode | stat.S_IWUSR)
        func(path)
    else:
        raise
# Buggy code
def healthy(prefix, language_version):
    with in_env(prefix, language_version):
        retcode, _, _ = cmd_output(
            "python",
            "-c",
            "import ctypes, datetime, io, os, ssl, weakref",
            retcode=None,
        )
    return retcode == 0


# Traceback (UnicodeDecodeError)
An unexpected error has occurred: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe3 in position 282: invalid continuation byte
Traceback (most recent call last):
File "c:\pytest\.tox\linting\lib\site-packages\pre_commit\error_handler.py", line 46, in error_handler
yield
File "c:\pytest\.tox\linting\lib\site-packages\pre_commit\main.py", line 294, in main
return run(args.config, store, args)
File "c:\pytest\.tox\linting\lib\site-packages\pre_commit\commands\run.py", line 285, in run
install_hook_envs(hooks, store)
File "c:\pytest\.tox\linting\lib\site-packages\pre_commit\repository.py", line 210, in install_hook_envs
if not _need_installed():
File "c:\pytest\.tox\linting\lib\site-packages\pre_commit\repository.py", line 205, in _need_installed
if hook.install_key not in seen and not hook.installed():
File "c:\pytest\.tox\linting\lib\site-packages\pre_commit\repository.py", line 75, in installed
lang.healthy(self.prefix, self.language_version)
File "c:\pytest\.tox\linting\lib\site-packages\pre_commit\languages\python.py", line 139, in healthy
retcode, _, _ = cmd_output(
File "c:\pytest\.tox\linting\lib\site-packages\pre_commit\util.py", line 149, in cmd_output
stderr = stderr.decode(encoding)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe3 in position 282: invalid continuation byte

# Fixed code
def healthy(prefix, language_version):
    with in_env(prefix, language_version):
        retcode, _, _ = cmd_output(
            "python",
            "-c",
            "import ctypes, datetime, io, os, ssl, weakref",
            retcode=None,
            encoding=None,
        )
    return retcode == 0
# Buggy code
def get_staged_files():
    return zsplit(
        cmd_output(
            "git",
            "diff",
            "--staged",
            "--name-only",
            "--no-ext-diff",
            "-z",
            # Everything except for D
            "--diff-filter=ACMRTUXB",
        )[1]
    )


# Traceback (pre_commit.util.CalledProcessError)
$ cat /home/asottile/.cache/pre-commit/pre-commit.log
An unexpected error has occurred: CalledProcessError: Command: ('/usr/bin/git', 'commit', '--no-edit', '--no-gpg-sign', '-n', '-minit')
Return code: 1
Expected return code: 0
Output:
On branch _pc_tmp
nothing to commit, working tree clean

Errors: (none)

Traceback (most recent call last):
File "/home/asottile/opt/venv/lib/python3.6/site-packages/pre_commit/error_handler.py", line 46, in error_handler
yield
File "/home/asottile/opt/venv/lib/python3.6/site-packages/pre_commit/main.py", line 295, in main
return try_repo(args)
File "/home/asottile/opt/venv/lib/python3.6/site-packages/pre_commit/commands/try_repo.py", line 48, in try_repo
repo, ref = _repo_ref(tempdir, args.repo, args.ref)
File "/home/asottile/opt/venv/lib/python3.6/site-packages/pre_commit/commands/try_repo.py", line 39, in _repo_ref
git.commit(repo=shadow)
File "/home/asottile/opt/venv/lib/python3.6/site-packages/pre_commit/git.py", line 143, in commit
cmd_output(*cmd, cwd=repo, env=env)
File "/home/asottile/opt/venv/lib/python3.6/site-packages/pre_commit/util.py", line 153, in cmd_output
returncode, cmd, retcode, output=(stdout, stderr),
pre_commit.util.CalledProcessError: Command: ('/usr/bin/git', 'commit', '--no-edit', '--no-gpg-sign', '-n', '-minit')
Return code: 1
Expected return code: 0
Output:
On branch _pc_tmp
nothing to commit, working tree clean

Errors: (none)

# Fixed code
def get_staged_files(cwd=None):
    return zsplit(
        cmd_output(
            "git",
            "diff",
            "--staged",
            "--name-only",
            "--no-ext-diff",
            "-z",
            # Everything except for D
            "--diff-filter=ACMRTUXB",
            cwd=cwd,
        )[1]
    )
# Buggy code
def run_cmd_partition(run_cmd):
    return cmd_output(*run_cmd, encoding=None, retcode=None)


# Traceback (pre_commit.util.CalledProcessError)
$ cat /home/asottile/.cache/pre-commit/pre-commit.log
An unexpected error has occurred: CalledProcessError: Command: ('/usr/bin/git', 'commit', '--no-edit', '--no-gpg-sign', '-n', '-minit')
Return code: 1
Expected return code: 0
Output:
On branch _pc_tmp
nothing to commit, working tree clean

Errors: (none)

Traceback (most recent call last):
File "/home/asottile/opt/venv/lib/python3.6/site-packages/pre_commit/error_handler.py", line 46, in error_handler
yield
File "/home/asottile/opt/venv/lib/python3.6/site-packages/pre_commit/main.py", line 295, in main
return try_repo(args)
File "/home/asottile/opt/venv/lib/python3.6/site-packages/pre_commit/commands/try_repo.py", line 48, in try_repo
repo, ref = _repo_ref(tempdir, args.repo, args.ref)
File "/home/asottile/opt/venv/lib/python3.6/site-packages/pre_commit/commands/try_repo.py", line 39, in _repo_ref
git.commit(repo=shadow)
File "/home/asottile/opt/venv/lib/python3.6/site-packages/pre_commit/git.py", line 143, in commit
cmd_output(*cmd, cwd=repo, env=env)
File "/home/asottile/opt/venv/lib/python3.6/site-packages/pre_commit/util.py", line 153, in cmd_output
returncode, cmd, retcode, output=(stdout, stderr),
pre_commit.util.CalledProcessError: Command: ('/usr/bin/git', 'commit', '--no-edit', '--no-gpg-sign', '-n', '-minit')
Return code: 1
Expected return code: 0
Output:
On branch _pc_tmp
nothing to commit, working tree clean

Errors: (none)

# Fixed code
def run_cmd_partition(run_cmd):
    return cmd_output(*run_cmd, encoding=None, retcode=None, **kwargs)
# Buggy code
def normexe(orig_exe):
    if os.sep not in orig_exe:
        exe = find_executable(orig_exe)
        if exe is None:
            raise ExecutableNotFoundError(
                "Executable `{}` not found".format(orig_exe),
            )
        return exe
    else:
        return orig_exe


# Traceback (OSError)
Bashate..................................................................An unexpected error has occurred: OSError: [Errno 2] No such file or directory
Check the log at /Users/ssbarnea/.cache/pre-commit/pre-commit.log

An unexpected error has occurred: OSError: [Errno 2] No such file or directory
Traceback (most recent call last):
File "/Users/ssbarnea/.pyenv/versions/2.7.14/lib/python2.7/site-packages/pre_commit/error_handler.py", line 47, in error_handler
yield
File "/Users/ssbarnea/.pyenv/versions/2.7.14/lib/python2.7/site-packages/pre_commit/main.py", line 258, in main
return run(runner, args)
File "/Users/ssbarnea/.pyenv/versions/2.7.14/lib/python2.7/site-packages/pre_commit/commands/run.py", line 270, in run
return _run_hooks(runner.config, repo_hooks, args, environ)
File "/Users/ssbarnea/.pyenv/versions/2.7.14/lib/python2.7/site-packages/pre_commit/commands/run.py", line 199, in _run_hooks
retval |= _run_single_hook(filenames, hook, repo, args, skips, cols)
File "/Users/ssbarnea/.pyenv/versions/2.7.14/lib/python2.7/site-packages/pre_commit/commands/run.py", line 110, in _run_single_hook
hook, tuple(filenames) if hook['pass_filenames'] else (),
File "/Users/ssbarnea/.pyenv/versions/2.7.14/lib/python2.7/site-packages/pre_commit/repository.py", line 207, in run_hook
return languages[language_name].run_hook(prefix, hook, file_args)
File "/Users/ssbarnea/.pyenv/versions/2.7.14/lib/python2.7/site-packages/pre_commit/languages/script.py", line 16, in run_hook
return xargs(cmd, file_args)
File "/Users/ssbarnea/.pyenv/versions/2.7.14/lib/python2.7/site-packages/pre_commit/xargs.py", line 63, in xargs
*run_cmd, encoding=None, retcode=None
File "/Users/ssbarnea/.pyenv/versions/2.7.14/lib/python2.7/site-packages/pre_commit/util.py", line 167, in cmd_output
proc = subprocess.Popen(cmd, **popen_kwargs)
File "/Users/ssbarnea/.pyenv/versions/2.7.14/lib/python2.7/subprocess.py", line 390, in __init__
errread, errwrite)
File "/Users/ssbarnea/.pyenv/versions/2.7.14/lib/python2.7/subprocess.py", line 1025, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory

# Fixed code
def normexe(orig):
    def _error(msg):
        raise ExecutableNotFoundError("Executable `{}` {}".format(orig, msg))

    if os.sep not in orig and (not os.altsep or os.altsep not in orig):
        exe = find_executable(orig)
        if exe is None:
            _error("not found")
        return exe
    elif not os.access(orig, os.X_OK):
        _error("not found")
    elif os.path.isdir(orig):
        _error("is a directory")
    else:
        return orig
# Buggy code
def make_local(self, deps):
    def make_local_strategy(directory):
        copy_tree_to_path(resource_filename("empty_template"), directory)

    return self._new_repo(
        "local:{}".format(",".join(sorted(deps))),
        C.LOCAL_REPO_VERSION,
        make_local_strategy,
    )


# Traceback (CalledProcessError)
An unexpected error has occurred: CalledProcessError: Command: ('/usr/bin/git', 'config', 'remote.origin.url')
Return code: 1
Expected return code: 0
Output: (none)
Errors: (none)

Traceback (most recent call last):
File "/tmp/wat/venv/local/lib/python2.7/site-packages/pre_commit/error_handler.py", line 47, in error_handler
yield
File "/tmp/wat/venv/local/lib/python2.7/site-packages/pre_commit/main.py", line 259, in main
return run(runner, args)
File "/tmp/wat/venv/local/lib/python2.7/site-packages/pre_commit/commands/run.py", line 256, in run
repo.require_installed()
File "/tmp/wat/venv/local/lib/python2.7/site-packages/pre_commit/repository.py", line 202, in require_installed
_install_all(self._venvs, self.repo_config['repo'], self.store)
File "/tmp/wat/venv/local/lib/python2.7/site-packages/pre_commit/repository.py", line 102, in _install_all
language.install_environment(cmd_runner, version, deps)
File "/tmp/wat/venv/local/lib/python2.7/site-packages/pre_commit/languages/golang.py", line 60, in install_environment
remote = git.get_remote_url(repo_cmd_runner.path())
File "/tmp/wat/venv/local/lib/python2.7/site-packages/pre_commit/git.py", line 41, in get_remote_url
ret = cmd_output('git', 'config', 'remote.origin.url', cwd=git_root)[1]
File "/tmp/wat/venv/local/lib/python2.7/site-packages/pre_commit/util.py", line 188, in cmd_output
returncode, cmd, retcode, output=(stdout, stderr),
CalledProcessError: Command: ('/usr/bin/git', 'config', 'remote.origin.url')
Return code: 1
Expected return code: 0
Output: (none)
Errors: (none)

# Fixed code
def make_local(self, deps):
    def make_local_strategy(directory):
        copy_tree_to_path(resource_filename("empty_template"), directory)

        env = no_git_env()
        name, email = "pre-commit", "asottile+pre-commit@umich.edu"
        env["GIT_AUTHOR_NAME"] = env["GIT_COMMITTER_NAME"] = name
        env["GIT_AUTHOR_EMAIL"] = env["GIT_COMMITTER_EMAIL"] = email

        # initialize the git repository so it looks more like cloned repos
        def _git_cmd(*args):
            cmd_output("git", "-C", directory, *args, env=env)

        _git_cmd("init", ".")
        _git_cmd("config", "remote.origin.url", "<<unknown>>")
        _git_cmd("add", ".")
        _git_cmd("commit", "--no-edit", "--no-gpg-sign", "-n", "-minit")

    return self._new_repo(
        "local:{}".format(",".join(sorted(deps))),
        C.LOCAL_REPO_VERSION,
        make_local_strategy,
    )
# Buggy code
def make_local_strategy(directory):
    copy_tree_to_path(resource_filename("empty_template"), directory)


# Traceback (CalledProcessError)
An unexpected error has occurred: CalledProcessError: Command: ('/usr/bin/git', 'config', 'remote.origin.url')
Return code: 1
Expected return code: 0
Output: (none)
Errors: (none)

Traceback (most recent call last):
File "/tmp/wat/venv/local/lib/python2.7/site-packages/pre_commit/error_handler.py", line 47, in error_handler
yield
File "/tmp/wat/venv/local/lib/python2.7/site-packages/pre_commit/main.py", line 259, in main
return run(runner, args)
File "/tmp/wat/venv/local/lib/python2.7/site-packages/pre_commit/commands/run.py", line 256, in run
repo.require_installed()
File "/tmp/wat/venv/local/lib/python2.7/site-packages/pre_commit/repository.py", line 202, in require_installed
_install_all(self._venvs, self.repo_config['repo'], self.store)
File "/tmp/wat/venv/local/lib/python2.7/site-packages/pre_commit/repository.py", line 102, in _install_all
language.install_environment(cmd_runner, version, deps)
File "/tmp/wat/venv/local/lib/python2.7/site-packages/pre_commit/languages/golang.py", line 60, in install_environment
remote = git.get_remote_url(repo_cmd_runner.path())
File "/tmp/wat/venv/local/lib/python2.7/site-packages/pre_commit/git.py", line 41, in get_remote_url
ret = cmd_output('git', 'config', 'remote.origin.url', cwd=git_root)[1]
File "/tmp/wat/venv/local/lib/python2.7/site-packages/pre_commit/util.py", line 188, in cmd_output
returncode, cmd, retcode, output=(stdout, stderr),
CalledProcessError: Command: ('/usr/bin/git', 'config', 'remote.origin.url')
Return code: 1
Expected return code: 0
Output: (none)
Errors: (none)

# Fixed code
def make_local_strategy(directory):
    copy_tree_to_path(resource_filename("empty_template"), directory)

    env = no_git_env()
    name, email = "pre-commit", "asottile+pre-commit@umich.edu"
    env["GIT_AUTHOR_NAME"] = env["GIT_COMMITTER_NAME"] = name
    env["GIT_AUTHOR_EMAIL"] = env["GIT_COMMITTER_EMAIL"] = email

    # initialize the git repository so it looks more like cloned repos
    def _git_cmd(*args):
        cmd_output("git", "-C", directory, *args, env=env)

    _git_cmd("init", ".")
    _git_cmd("config", "remote.origin.url", "<<unknown>>")
    _git_cmd("add", ".")
    _git_cmd("commit", "--no-edit", "--no-gpg-sign", "-n", "-minit")
# Buggy code
def run(self, cmd, **kwargs):
    self._create_path_if_not_exists()
    replaced_cmd = _replace_cmd(cmd, prefix=self.prefix_dir)
    return cmd_output(*replaced_cmd, __popen=self.__popen, **kwargs)


# Traceback (IndexError)
An unexpected error has occurred: IndexError: tuple index out of range
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/pre_commit/error_handler.py", line 36, in error_handler
yield
File "/usr/local/lib/python2.7/site-packages/pre_commit/main.py", line 150, in main
return run(runner, args)
File "/usr/local/lib/python2.7/site-packages/pre_commit/commands/run.py", line 212, in run
return _run_hooks(repo_hooks, args, write, environ)
File "/usr/local/lib/python2.7/site-packages/pre_commit/commands/run.py", line 136, in _run_hooks
retval |= _run_single_hook(hook, repo, args, write, skips)
File "/usr/local/lib/python2.7/site-packages/pre_commit/commands/run.py", line 89, in _run_single_hook
retcode, stdout, stderr = repo.run_hook(hook, filenames)
File "/usr/local/lib/python2.7/site-packages/pre_commit/repository.py", line 145, in run_hook
self.cmd_runner, hook, file_args,
File "/usr/local/lib/python2.7/site-packages/pre_commit/languages/script.py", line 23, in run_hook
encoding=None,
File "/usr/local/lib/python2.7/site-packages/pre_commit/prefixed_command_runner.py", line 40, in run
replaced_cmd = _replace_cmd(cmd, prefix=self.prefix_dir)
File "/usr/local/lib/python2.7/site-packages/pre_commit/prefixed_command_runner.py", line 11, in _replace_cmd
return [part.format(**kwargs) for part in cmd]
IndexError: tuple index out of range

# Fixed code
def run(self, cmd, **kwargs):
    self._create_path_if_not_exists()
    replaced_cmd = [part.replace("{prefix}", self.prefix_dir) for part in cmd]
    return cmd_output(*replaced_cmd, __popen=self.__popen, **kwargs)
# Buggy code
def run_hook(env, hook, file_args):
    quoted_args = [pipes.quote(arg) for arg in hook["args"]]
    return env.run(
        # Use -s 4000 (slightly less than posix mandated minimum)
        # This is to prevent "xargs: ... Bad file number" on windows
        " ".join(["xargs", "-0", "-s4000", hook["entry"]] + quoted_args),
        stdin=file_args_to_stdin(file_args),
        retcode=None,
    )


# Traceback (UnicodeDecodeError)
An unexpected error has occurred: UnicodeDecodeError: 'utf8' codec can't decode byte 0xbb in position 23: invalid start byte
Traceback (most recent call last):
File "/home/lucas/.local/lib/python2.7/site-packages/pre_commit/error_handler.py", line 34, in error_handler
yield
File "/home/lucas/.local/lib/python2.7/site-packages/pre_commit/main.py", line 144, in main
return run(runner, args)
File "/home/lucas/.local/lib/python2.7/site-packages/pre_commit/commands/run.py", line 185, in run
return _run_hooks(repo_hooks, args, write, environ)
File "/home/lucas/.local/lib/python2.7/site-packages/pre_commit/commands/run.py", line 117, in _run_hooks
retval |= _run_single_hook(hook, repo, args, write, skips)
File "/home/lucas/.local/lib/python2.7/site-packages/pre_commit/commands/run.py", line 88, in _run_single_hook
retcode, stdout, stderr = repo.run_hook(hook, filenames)
File "/home/lucas/.local/lib/python2.7/site-packages/pre_commit/repository.py", line 123, in run_hook
self.cmd_runner, hook, file_args,
File "/home/lucas/.local/lib/python2.7/site-packages/pre_commit/languages/script.py", line 19, in run_hook
retcode=None,
File "/home/lucas/.local/lib/python2.7/site-packages/pre_commit/prefixed_command_runner.py", line 41, in run
return cmd_output(*replaced_cmd, __popen=self.__popen, **kwargs)
File "/home/lucas/.local/lib/python2.7/site-packages/pre_commit/util.py", line 153, in cmd_output
stdout = stdout.decode(encoding)
File "/usr/lib/python2.7/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xbb in position 23: invalid start byte

# Fixed code
def run_hook(env, hook, file_args):
    quoted_args = [pipes.quote(arg) for arg in hook["args"]]
    return env.run(
        # Use -s 4000 (slightly less than posix mandated minimum)
        # This is to prevent "xargs: ... Bad file number" on windows
        " ".join(["xargs", "-0", "-s4000", hook["entry"]] + quoted_args),
        stdin=file_args_to_stdin(file_args),
        retcode=None,
        encoding=None,
    )
# Buggy code
def run_hook(repo_cmd_runner, hook, file_args):
    # For PCRE the entry is the regular expression to match
    return repo_cmd_runner.run(
        [
            "xargs",
            "-0",
            "sh",
            "-c",
            # Grep usually returns 0 for matches, and nonzero for non-matches
            # so we flip it here.
            "! grep -H -n -P {0} $@".format(shell_escape(hook["entry"])),
            "--",
        ],
        stdin=file_args_to_stdin(file_args),
        retcode=None,
    )


# Traceback (UnicodeDecodeError)
An unexpected error has occurred: UnicodeDecodeError: 'utf8' codec can't decode byte 0xbb in position 23: invalid start byte
Traceback (most recent call last):
File "/home/lucas/.local/lib/python2.7/site-packages/pre_commit/error_handler.py", line 34, in error_handler
yield
File "/home/lucas/.local/lib/python2.7/site-packages/pre_commit/main.py", line 144, in main
return run(runner, args)
File "/home/lucas/.local/lib/python2.7/site-packages/pre_commit/commands/run.py", line 185, in run
return _run_hooks(repo_hooks, args, write, environ)
File "/home/lucas/.local/lib/python2.7/site-packages/pre_commit/commands/run.py", line 117, in _run_hooks
retval |= _run_single_hook(hook, repo, args, write, skips)
File "/home/lucas/.local/lib/python2.7/site-packages/pre_commit/commands/run.py", line 88, in _run_single_hook
retcode, stdout, stderr = repo.run_hook(hook, filenames)
File "/home/lucas/.local/lib/python2.7/site-packages/pre_commit/repository.py", line 123, in run_hook
self.cmd_runner, hook, file_args,
File "/home/lucas/.local/lib/python2.7/site-packages/pre_commit/languages/script.py", line 19, in run_hook
retcode=None,
File "/home/lucas/.local/lib/python2.7/site-packages/pre_commit/prefixed_command_runner.py", line 41, in run
return cmd_output(*replaced_cmd, __popen=self.__popen, **kwargs)
File "/home/lucas/.local/lib/python2.7/site-packages/pre_commit/util.py", line 153, in cmd_output
stdout = stdout.decode(encoding)
File "/usr/lib/python2.7/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xbb in position 23: invalid start byte

# Fixed code
def run_hook(repo_cmd_runner, hook, file_args):
    # For PCRE the entry is the regular expression to match
    return repo_cmd_runner.run(
        [
            "xargs",
            "-0",
            "sh",
            "-c",
            # Grep usually returns 0 for matches, and nonzero for non-matches
            # so we flip it here.
            "! grep -H -n -P {0} $@".format(shell_escape(hook["entry"])),
            "--",
        ],
        stdin=file_args_to_stdin(file_args),
        retcode=None,
        encoding=None,
    )
# Buggy code
def run_hook(repo_cmd_runner, hook, file_args):
    return repo_cmd_runner.run(
        ["xargs", "-0", "{{prefix}}{0}".format(hook["entry"])] + hook["args"],
        # TODO: this is duplicated in pre_commit/languages/helpers.py
        stdin=file_args_to_stdin(file_args),
        retcode=None,
    )


# Traceback (UnicodeDecodeError)
An unexpected error has occurred: UnicodeDecodeError: 'utf8' codec can't decode byte 0xbb in position 23: invalid start byte
Traceback (most recent call last):
File "/home/lucas/.local/lib/python2.7/site-packages/pre_commit/error_handler.py", line 34, in error_handler
yield
File "/home/lucas/.local/lib/python2.7/site-packages/pre_commit/main.py", line 144, in main
return run(runner, args)
File "/home/lucas/.local/lib/python2.7/site-packages/pre_commit/commands/run.py", line 185, in run
return _run_hooks(repo_hooks, args, write, environ)
File "/home/lucas/.local/lib/python2.7/site-packages/pre_commit/commands/run.py", line 117, in _run_hooks
retval |= _run_single_hook(hook, repo, args, write, skips)
File "/home/lucas/.local/lib/python2.7/site-packages/pre_commit/commands/run.py", line 88, in _run_single_hook
retcode, stdout, stderr = repo.run_hook(hook, filenames)
File "/home/lucas/.local/lib/python2.7/site-packages/pre_commit/repository.py", line 123, in run_hook
self.cmd_runner, hook, file_args,
File "/home/lucas/.local/lib/python2.7/site-packages/pre_commit/languages/script.py", line 19, in run_hook
retcode=None,
File "/home/lucas/.local/lib/python2.7/site-packages/pre_commit/prefixed_command_runner.py", line 41, in run
return cmd_output(*replaced_cmd, __popen=self.__popen, **kwargs)
File "/home/lucas/.local/lib/python2.7/site-packages/pre_commit/util.py", line 153, in cmd_output
stdout = stdout.decode(encoding)
File "/usr/lib/python2.7/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xbb in position 23: invalid start byte

# Fixed code
def run_hook(repo_cmd_runner, hook, file_args):
    return repo_cmd_runner.run(
        ["xargs", "-0", "{{prefix}}{0}".format(hook["entry"])] + hook["args"],
        # TODO: this is duplicated in pre_commit/languages/helpers.py
        stdin=file_args_to_stdin(file_args),
        retcode=None,
        encoding=None,
    )
# Buggy code
def run_hook(repo_cmd_runner, hook, file_args):
    return repo_cmd_runner.run(
        ["xargs", "-0"] + shlex.split(hook["entry"]) + hook["args"],
        stdin=file_args_to_stdin(file_args),
        retcode=None,
    )


# Traceback (UnicodeDecodeError)
An unexpected error has occurred: UnicodeDecodeError: 'utf8' codec can't decode byte 0xbb in position 23: invalid start byte
Traceback (most recent call last):
File "/home/lucas/.local/lib/python2.7/site-packages/pre_commit/error_handler.py", line 34, in error_handler
yield
File "/home/lucas/.local/lib/python2.7/site-packages/pre_commit/main.py", line 144, in main
return run(runner, args)
File "/home/lucas/.local/lib/python2.7/site-packages/pre_commit/commands/run.py", line 185, in run
return _run_hooks(repo_hooks, args, write, environ)
File "/home/lucas/.local/lib/python2.7/site-packages/pre_commit/commands/run.py", line 117, in _run_hooks
retval |= _run_single_hook(hook, repo, args, write, skips)
File "/home/lucas/.local/lib/python2.7/site-packages/pre_commit/commands/run.py", line 88, in _run_single_hook
retcode, stdout, stderr = repo.run_hook(hook, filenames)
File "/home/lucas/.local/lib/python2.7/site-packages/pre_commit/repository.py", line 123, in run_hook
self.cmd_runner, hook, file_args,
File "/home/lucas/.local/lib/python2.7/site-packages/pre_commit/languages/script.py", line 19, in run_hook
retcode=None,
File "/home/lucas/.local/lib/python2.7/site-packages/pre_commit/prefixed_command_runner.py", line 41, in run
return cmd_output(*replaced_cmd, __popen=self.__popen, **kwargs)
File "/home/lucas/.local/lib/python2.7/site-packages/pre_commit/util.py", line 153, in cmd_output
stdout = stdout.decode(encoding)
File "/usr/lib/python2.7/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xbb in position 23: invalid start byte

# Fixed code
def run_hook(repo_cmd_runner, hook, file_args):
    return repo_cmd_runner.run(
        ["xargs", "-0"] + shlex.split(hook["entry"]) + hook["args"],
        stdin=file_args_to_stdin(file_args),
        retcode=None,
        encoding=None,
    )
# Buggy code
def __init__(self, repo_config, repo_path_getter=None):
    repo_path_getter = None
    super(LocalRepository, self).__init__(repo_config, repo_path_getter)


# Traceback (AttributeError)
$ pre-commit autoupdate
Updating git@github.com:pre-commit/pre-commit-hooks...updating 9ce45609a92f648c87b42207410386fd69a5d1e5 -> cf550fcab3f12015f8676b8278b30e1a5bc10e70.
Updating git@github.com:pre-commit/pre-commit...updating 4352d45451296934bc17494073b82bcacca3205c -> 1c46446427ab0dfa6293221426b855420533ef8d.
Updating git@github.com:asottile/reorder_python_imports...updating aeda21eb7df6af8c9f6cd990abb086375c71c953 -> 3d86483455ab5bd06cc1069fdd5ac57be5463f10.
Updating local...An unexpected error has occurred: AttributeError: 'NoneType' object has no attribute 'repo_path'
Check the log at ~/.pre-commit/pre-commit.log
(venv-pre_commit)asottile@work:~/workspace/pre-commit$ cat ~/.pre-commit/pre-commit.log
An unexpected error has occurred: AttributeError: 'NoneType' object has no attribute 'repo_path'
Traceback (most recent call last):
File "/home/asottile/workspace/pre-commit/pre_commit/error_handler.py", line 34, in error_handler
yield
File "/home/asottile/workspace/pre-commit/pre_commit/main.py", line 142, in main
return autoupdate(runner)
File "/home/asottile/workspace/pre-commit/pre_commit/commands/autoupdate.py", line 73, in autoupdate
new_repo_config = _update_repository(repo_config, runner)
File "/home/asottile/workspace/pre-commit/pre_commit/commands/autoupdate.py", line 33, in _update_repository
with cwd(repo.repo_path_getter.repo_path):
AttributeError: 'NoneType' object has no attribute 'repo_path'

(venv-pre_commit)asottile@work:~/workspace/pre-commit$ git diff
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 397ee72..20393a7 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -20,3 +20,10 @@
sha: aeda21eb7df6af8c9f6cd990abb086375c71c953
hooks:
-   id: reorder-python-imports
+-   repo: local
+    hooks:
+    -   id: herp
+        name: Herp
+        entry: echo derp
+        language: system
+        files: ^$

# Fixed code
def __init__(self, repo_config):
    super(LocalRepository, self).__init__(repo_config, None)
# Buggy code
def sys_stdout_write_wrapper(s, stream=sys.stdout):
    """Python 2.6 chokes on unicode being passed to sys.stdout.write.

    This is an adapter because PY2 is ok with bytes and PY3 requires text.
    """
    assert type(s) is five.text
    if five.PY2:  # pragma: no cover (PY2)
        s = s.encode("UTF-8")
    stream.write(s)


# Traceback (UnicodeDecodeError)
$ pre-commit run ☃
An unexpected error has occurred: UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 0: ordinal not in range(128)
Check the log at ~/.pre-commit/pre-commit.log
$ cat ~/.pre-commit/pre-commit.log
An unexpected error has occurred: UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 0: ordinal not in range(128)
Traceback (most recent call last):
File "/home/asottile/workspace/pre-commit/pre_commit/error_handler.py", line 34, in error_handler
yield
File "/home/asottile/workspace/pre-commit/pre_commit/main.py", line 129, in main
return run(runner, args)
File "/home/asottile/workspace/pre-commit/pre_commit/commands/run.py", line 163, in run
return _run_hook(runner, args, write=write)
File "/home/asottile/workspace/pre-commit/pre_commit/commands/run.py", line 133, in _run_hook
write('No hook with id `{0}`\n'.format(hook_id))
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 0: ordinal not in range(128)

# Fixed code
def sys_stdout_write_wrapper(s, stream=stdout_byte_stream):
    stream.write(five.to_bytes(s))
# Buggy code
def run(runner, args, write=sys.stdout.write, environ=os.environ):
    # Set up our logging handler
    logger.addHandler(LoggingHandler(args.color, write=write))
    logger.setLevel(logging.INFO)

    # Check if we have unresolved merge conflict files and fail fast.
    if _has_unmerged_paths(runner):
        logger.error("Unmerged files.  Resolve before committing.")
        return 1

    if args.no_stash or args.all_files:
        ctx = noop_context()
    else:
        ctx = staged_files_only(runner.cmd_runner)

    with ctx:
        if args.hook:
            return _run_hook(runner, args, write=write)
        else:
            return _run_hooks(runner, args, write=write, environ=environ)


# Traceback (UnicodeEncodeError)
$ pre-commit run fixmyjs
fixmyjs............................................................................................................................................................................................Failed
hookid: fixmyjs

Traceback (most recent call last):
File "virtualenv_run/bin/pre-commit", line 14, in <module>
sys.exit(main())
File "virtualenv_run/lib/python2.6/site-packages/pre_commit/util.py", line 41, in wrapper
return func(argv)
File "virtualenv_run/lib/python2.6/site-packages/pre_commit/main.py", line 99, in main
return run(runner, args)
File "virtualenv_run/lib/python2.6/site-packages/pre_commit/commands/run.py", line 144, in run
return _run_hook(runner, args, write=write)
File "virtualenv_run/lib/python2.6/site-packages/pre_commit/commands/run.py", line 116, in _run_hook
return _run_single_hook(runner, repo, hook_id, args, write=write)
File "virtualenv_run/lib/python2.6/site-packages/pre_commit/commands/run.py", line 91, in _run_single_hook
write(output.strip() + '\n')
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2713' in position 0: ordinal not in range(128)

# Fixed code
def run(runner, args, write=sys_stdout_write_wrapper, environ=os.environ):
    # Set up our logging handler
    logger.addHandler(LoggingHandler(args.color, write=write))
    logger.setLevel(logging.INFO)

    # Check if we have unresolved merge conflict files and fail fast.
    if _has_unmerged_paths(runner):
        logger.error("Unmerged files.  Resolve before committing.")
        return 1

    if args.no_stash or args.all_files:
        ctx = noop_context()
    else:
        ctx = staged_files_only(runner.cmd_runner)

    with ctx:
        if args.hook:
            return _run_hook(runner, args, write=write)
        else:
            return _run_hooks(runner, args, write=write, environ=environ)
# Buggy code
def __new__(cls, text, lang, tkey):
    """
    :param cls: the class to use when creating the instance
    :param text: value for this key
    :param lang: language code
    :param tkey: UTF-8 version of the key name
    """

    self = str.__new__(cls, text)
    self.lang = lang
    self.tkey = tkey
    return self


# Traceback (TypeError)
Traceback (most recent call last):
File "example.py", line 6, in <module>
new_im = pickle.loads(p)
TypeError: __new__() missing 2 required positional arguments: 'lang' and 'tkey'

# Fixed code
def __new__(cls, text, lang=None, tkey=None):
    """
    :param cls: the class to use when creating the instance
    :param text: value for this key
    :param lang: language code
    :param tkey: UTF-8 version of the key name
    """

    self = str.__new__(cls, text)
    self.lang = lang
    self.tkey = tkey
    return self
# Buggy code
def multiline_text(
    self,
    xy,
    text,
    fill=None,
    font=None,
    anchor=None,
    spacing=4,
    align="left",
    direction=None,
    features=None,
):
    widths = []
    max_width = 0
    lines = self._multiline_split(text)
    line_spacing = self.textsize("A", font=font)[1] + spacing
    for line in lines:
        line_width, line_height = self.textsize(line, font)
        widths.append(line_width)
        max_width = max(max_width, line_width)
    left, top = xy
    for idx, line in enumerate(lines):
        if align == "left":
            pass  # left = x
        elif align == "center":
            left += (max_width - widths[idx]) / 2.0
        elif align == "right":
            left += max_width - widths[idx]
        else:
            assert False, 'align must be "left", "center" or "right"'
        self.text(
            (left, top),
            line,
            fill,
            font,
            anchor,
            direction=direction,
            features=features,
        )
        top += line_spacing
        left = xy[0]


# Traceback (AttributeError)
Traceback (most recent call last):
File "test.py", line 1, in <module>
import PIL
File "/usr/lib/python3.6/site-packages/PIL/__init__.py", line 27, in <module>
__doc__ = __doc__.format(__version__)  # include version in docstring
AttributeError: 'NoneType' object has no attribute 'format'

# Fixed code
def multiline_text(
    self,
    xy,
    text,
    fill=None,
    font=None,
    anchor=None,
    spacing=4,
    align="left",
    direction=None,
    features=None,
):
    widths = []
    max_width = 0
    lines = self._multiline_split(text)
    line_spacing = self.textsize("A", font=font)[1] + spacing
    for line in lines:
        line_width, line_height = self.textsize(line, font)
        widths.append(line_width)
        max_width = max(max_width, line_width)
    left, top = xy
    for idx, line in enumerate(lines):
        if align == "left":
            pass  # left = x
        elif align == "center":
            left += (max_width - widths[idx]) / 2.0
        elif align == "right":
            left += max_width - widths[idx]
        else:
            raise ValueError('align must be "left", "center" or "right"')
        self.text(
            (left, top),
            line,
            fill,
            font,
            anchor,
            direction=direction,
            features=features,
        )
        top += line_spacing
        left = xy[0]
# Buggy code
def load_byte(self, data, legacy_api=True):
    return data if legacy_api else tuple(map(ord, data) if bytes is str else data)


# Traceback (TypeError)
Traceback (most recent call last):
File "pyi_lib_PIL_img_conversion.py", line 17, in <module>
im.save(os.path.join(basedir, "tinysample.png"))
File "c:\Users\Rio\Documents\src\pyinst1328\.env27\lib\site-packages\PIL\Image.py", line 1665, in save
save_handler(self, fp, filename)
File "c:\Users\Rio\Documents\src\pyinst1328\.env27\lib\site-packages\PIL\PngImagePlugin.py", line 757, in _save
data = name + b"\0\0" + zlib.compress(im.info["icc_profile"])
TypeError: must be string or read-only buffer, not tuple

# Fixed code
def load_byte(self, data, legacy_api=True):
    return data
# Buggy code
def __init__(self, match: str, scopes: List[Scope], **kwargs) -> None:
    self.id = kwargs.get("id", str(uuid4()))
    self.match = match
    self.scopes = scopes or list()


# Traceback (ValueError)
{
"code": 500,
"errors": [
"ValueError: 'read:prodalerts' is not a valid Scope\n\nDuring handling of the above exception, another exception occurred:\n\nTraceback (most recent call last):\n  File \"/app/.heroku/python/lib/python3.7/site-packages/flask/app.py\", line 1813, in full_dispatch_request\n    rv = self.dispatch_request()\n  File \"/app/.heroku/python/lib/python3.7/site-packages/flask/app.py\", line 1799, in dispatch_request\n    return self.view_functions[rule.endpoint](**req.view_args)\n  File \"/app/.heroku/python/lib/python3.7/site-packages/flask_cors/decorator.py\", line 128, in wrapped_function\n    resp = make_response(f(*args, **kwargs))\n  File \"/app/.heroku/python/lib/python3.7/site-packages/alerta/auth/decorators.py\", line 112, in wrapped\n    return f(*args, **kwargs)\n  File \"/app/.heroku/python/lib/python3.7/site-packages/alerta/utils/response.py\", line 19, in decorated\n    return func(*args, **kwargs)\n  File \"/app/.heroku/python/lib/python3.7/site-packages/alerta/views/permissions.py\", line 67, in list_perms\n    perms = Permission.find_all(query)\n  File \"/app/.heroku/python/lib/python3.7/site-packages/alerta/models/permission.py\", line 75, in find_all\n    return [Permission.from_db(perm) for perm in db.get_perms(query)]\n  File \"/app/.heroku/python/lib/python3.7/site-packages/alerta/models/permission.py\", line 75, in <listcomp>\n    return [Permission.from_db(perm) for perm in db.get_perms(query)]\n  File \"/app/.heroku/python/lib/python3.7/site-packages/alerta/models/permission.py\", line 62, in from_db\n    return cls.from_document(r)\n  File \"/app/.heroku/python/lib/python3.7/site-packages/alerta/models/permission.py\", line 48, in from_document\n    scopes=[Scope(s) for s in doc.get('scopes', list())]\n  File \"/app/.heroku/python/lib/python3.7/site-packages/alerta/models/permission.py\", line 48, in <listcomp>\n    scopes=[Scope(s) for s in doc.get('scopes', list())]\n  File \"/app/.heroku/python/lib/python3.7/enum.py\", line 310, in __call__\n    return cls.__new__(cls, value)\n  File \"/app/.heroku/python/lib/python3.7/enum.py\", line 564, in __new__\n    raise exc\n  File \"/app/.heroku/python/lib/python3.7/enum.py\", line 548, in __new__\n    result = cls._missing_(value)\n  File \"/app/.heroku/python/lib/python3.7/enum.py\", line 577, in _missing_\n    raise ValueError(\"%r is not a valid %s\" % (value, cls.__name__))\nValueError: 'read:prodalerts' is not a valid Scope\n"
],
"message": "'read:prodalerts' is not a valid Scope",
"requestId": "109e9b17-1626-4816-9390-53021164ab4c",
"status": "error"
}

# Fixed code
def __init__(self, match: str, scopes: List[Scope], **kwargs) -> None:
    for s in scopes:
        if s not in list(Scope):
            raise ValueError("invalid scope: {}".format(s))

    self.id = kwargs.get("id", str(uuid4()))
    self.match = match
    self.scopes = scopes or list()
# Buggy code
def __init__(
    self,
    origin: str = None,
    tags: List[str] = None,
    create_time: datetime = None,
    timeout: int = None,
    customer: str = None,
    **kwargs,
) -> None:
    self.id = kwargs.get("id", str(uuid4()))
    self.origin = origin or "{}/{}".format(
        os.path.basename(sys.argv[0]), platform.uname()[1]
    )
    self.tags = tags or list()
    self.event_type = kwargs.get("event_type", kwargs.get("type", None)) or "Heartbeat"
    self.create_time = create_time or datetime.utcnow()
    self.timeout = (
        timeout if timeout is not None else current_app.config["HEARTBEAT_TIMEOUT"]
    )
    self.receive_time = kwargs.get("receive_time", None) or datetime.utcnow()
    self.customer = customer


# Traceback (ValueError)
result = aclient.get_alert("5645884f-f486-4db3-8058-46e17260fb95")
Traceback (most recent call last):
File "/Users/thomasjongerius/Library/Preferences/PyCharmCE2017.3/scratches/scratch_36.py", line 13, in <module>
result = aclient.get_alert("5645884f-f486-4db3-8058-46e17260fb95")
File "/Users/thomasjongerius/PycharmProjects/videns/venv37/lib/python3.7/site-packages/alertaclient/api.py", line 65, in get_alert
return Alert.parse(self.http.get('/alert/%s' % id)['alert'])
File "/Users/thomasjongerius/PycharmProjects/videns/venv37/lib/python3.7/site-packages/alertaclient/models/alert.py", line 64, in parse
raise ValueError('timeout must be an integer')
ValueError: timeout must be an integer

# Fixed code
def __init__(
    self,
    origin: str = None,
    tags: List[str] = None,
    create_time: datetime = None,
    timeout: int = None,
    customer: str = None,
    **kwargs,
) -> None:
    timeout = (
        timeout if timeout is not None else current_app.config["HEARTBEAT_TIMEOUT"]
    )
    try:
        timeout = int(timeout)
    except ValueError:
        raise ValueError(
            "Could not convert 'timeout' value of '{}' to an integer".format(timeout)
        )
    if timeout < 0:
        raise ValueError("Invalid negative 'timeout' value ({})".format(timeout))

    self.id = kwargs.get("id", str(uuid4()))
    self.origin = origin or "{}/{}".format(
        os.path.basename(sys.argv[0]), platform.uname()[1]
    )
    self.tags = tags or list()
    self.event_type = kwargs.get("event_type", kwargs.get("type", None)) or "Heartbeat"
    self.create_time = create_time or datetime.utcnow()
    self.timeout = timeout
    self.receive_time = kwargs.get("receive_time", None) or datetime.utcnow()
    self.customer = customer