# Buggy code
def staged_files_only(cmd_runner):
    """Clear any unstaged changes from the git working directory inside this
    context.

    Args:
        cmd_runner - PrefixedCommandRunner
    """
    # Determine if there are unstaged files
    tree = cmd_runner.run(("git", "write-tree"))[1].strip()
    retcode, diff_stdout_binary, _ = cmd_runner.run(
        (
            "git",
            "diff-index",
            "--ignore-submodules",
            "--binary",
            "--exit-code",
            "--no-color",
            "--no-ext-diff",
            tree,
            "--",
        ),
        retcode=None,
        encoding=None,
    )
    if retcode and diff_stdout_binary.strip():
        patch_filename = cmd_runner.path("patch{}".format(int(time.time())))
        logger.warning("Unstaged files detected.")
        logger.info(
            "Stashing unstaged files to {}.".format(patch_filename),
        )
        # Save the current unstaged changes as a patch
        with io.open(patch_filename, "wb") as patch_file:
            patch_file.write(diff_stdout_binary)

        # Clear the working directory of unstaged changes
        cmd_runner.run(("git", "checkout", "--", "."))
        try:
            yield
        finally:
            # Try to apply the patch we saved
            try:
                cmd_runner.run(
                    ("git", "apply", "--whitespace=nowarn", patch_filename),
                    encoding=None,
                )
            except CalledProcessError:
                logger.warning(
                    "Stashed changes conflicted with hook auto-fixes... "
                    "Rolling back fixes...",
                )
                # We failed to apply the patch, presumably due to fixes made
                # by hooks.
                # Roll back the changes made by hooks.
                cmd_runner.run(("git", "checkout", "--", "."))
                cmd_runner.run(
                    ("git", "apply", patch_filename, "--whitespace=nowarn"),
                    encoding=None,
                )
            logger.info("Restored changes from {}.".format(patch_filename))
    else:
        # There weren't any staged files so we don't need to do anything
        # special
        yield


# Traceback (CalledProcessError)
An unexpected error has occurred: CalledProcessError: Command: ('C:\\Program Files\\Git\\mingw64\\libexec\\git-core\\git.exe', 'apply', 'C:\\Users\\56929\\.pre-commit\\patch1501483011')
Return code: 1
Expected return code: 0
Output: (none)
Errors:
error: patch failed: svnchecker_stylelint_support/checks/Stylelint.py:20
error: svnchecker_stylelint_support/checks/Stylelint.py: patch does not apply


Traceback (most recent call last):
File "c:\python27\lib\site-packages\pre_commit\error_handler.py", line 48, in error_handler
yield
File "c:\python27\lib\site-packages\pre_commit\main.py", line 231, in main
return run(runner, args)
File "c:\python27\lib\site-packages\pre_commit\commands\run.py", line 273, in run
return _run_hooks(repo_hooks, args, environ)
File "c:\python27\lib\contextlib.py", line 24, in __exit__
self.gen.next()
File "c:\python27\lib\site-packages\pre_commit\staged_files_only.py", line 58, in staged_files_only
cmd_runner.run(('git', 'apply', patch_filename), encoding=None)
File "c:\python27\lib\site-packages\pre_commit\prefixed_command_runner.py", line 38, in run
return cmd_output(*replaced_cmd, __popen=self.__popen, **kwargs)
File "c:\python27\lib\site-packages\pre_commit\util.py", line 189, in cmd_output
returncode, cmd, retcode, output=(stdout, stderr),
CalledProcessError: Command: ('C:\\Program Files\\Git\\mingw64\\libexec\\git-core\\git.exe', 'apply', 'C:\\Users\\56929\\.pre-commit\\patch1501483011')
Return code: 1
Expected return code: 0
Output: (none)
Errors:
error: patch failed: svnchecker_stylelint_support/checks/Stylelint.py:20
error: svnchecker_stylelint_support/checks/Stylelint.py: patch does not apply

# Fixed code
def staged_files_only(cmd_runner):
    """Clear any unstaged changes from the git working directory inside this
    context.

    Args:
        cmd_runner - PrefixedCommandRunner
    """
    # Determine if there are unstaged files
    tree = cmd_runner.run(("git", "write-tree"))[1].strip()
    retcode, diff_stdout_binary, _ = cmd_runner.run(
        (
            "git",
            "diff-index",
            "--ignore-submodules",
            "--binary",
            "--exit-code",
            "--no-color",
            "--no-ext-diff",
            tree,
            "--",
        ),
        retcode=None,
        encoding=None,
    )
    if retcode and diff_stdout_binary.strip():
        patch_filename = cmd_runner.path("patch{}".format(int(time.time())))
        logger.warning("Unstaged files detected.")
        logger.info(
            "Stashing unstaged files to {}.".format(patch_filename),
        )
        # Save the current unstaged changes as a patch
        with io.open(patch_filename, "wb") as patch_file:
            patch_file.write(diff_stdout_binary)

        # Clear the working directory of unstaged changes
        cmd_runner.run(("git", "checkout", "--", "."))
        try:
            yield
        finally:
            # Try to apply the patch we saved
            try:
                _git_apply(cmd_runner, patch_filename)
            except CalledProcessError:
                logger.warning(
                    "Stashed changes conflicted with hook auto-fixes... "
                    "Rolling back fixes...",
                )
                # We failed to apply the patch, presumably due to fixes made
                # by hooks.
                # Roll back the changes made by hooks.
                cmd_runner.run(("git", "checkout", "--", "."))
                _git_apply(cmd_runner, patch_filename)
            logger.info("Restored changes from {}.".format(patch_filename))
    else:
        # There weren't any staged files so we don't need to do anything
        # special
        yield