prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  git unadd changes lost if hook fails on windows
  ```
  D:\CubeadProjects\devops [test +0 ~2 -0 | +0 ~1 -0 !]> git cm "asd"
  [WARNING] Unstaged files detected.
  [INFO] Stashing unstaged files to C:\Users\56929\.pre-commit\patch1501482991.
  run pylint...............................................................Failed
  hookid: python-pylint
  
  ************* Module install
  C: 10, 0: Exactly one space required around assignment
  a=1
   ^ (bad-whitespace)
  C: 46, 0: Line too long (108/100) (line-too-long)
  W: 39, 4: Unused variable 'stylelint_root' (unused-variable)
  W: 37, 4: Unused variable 'node_root' (unused-variable)
  W: 24, 8: Unused variable 'checks' (unused-variable)
  
  [WARNING] Stashed changes conflicted with hook auto-fixes... Rolling back fixes...
  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
  
  
  Check the log at ~/.pre-commit/pre-commit.log
  ```
  
  ### ~/.pre-commit/pre-commit.log
  ```
  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
  ```
  Then, I open the patch file. (C:\\Users\\56929\\.pre-commit\\patch1501483011),it looks like 
  
  ```diff
  diff --git a/svnchecker_stylelint_support/checks/Stylelint.py b/svnchecker_stylelint_support/checks/Stylelint.py
  index 4422b4d..f85ecb1 100644
  --- a/svnchecker_stylelint_support/checks/Stylelint.py
  +++ b/svnchecker_stylelint_support/checks/Stylelint.py
  @@ -20,3 +20,5 @@ def run(transaction, config):
               return ('{}\n{}'.format(stdoutdata, stderrdata), 1)^M
  ^M
       return ("", 0)^M
  ^M
  ^M
  ^M
  ```
  
  --- END ISSUE ---
  
  Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
  --- BEGIN FILES ---
  Path: `pre_commit/staged_files_only.py`
  Content:
  ```
  1 from __future__ import unicode_literals
  2 
  3 import contextlib
  4 import io
  5 import logging
  6 import time
  7 
  8 from pre_commit.util import CalledProcessError
  9 
  10 
  11 logger = logging.getLogger('pre_commit')
  12 
  13 
  14 @contextlib.contextmanager
  15 def staged_files_only(cmd_runner):
  16     """Clear any unstaged changes from the git working directory inside this
  17     context.
  18 
  19     Args:
  20         cmd_runner - PrefixedCommandRunner
  21     """
  22     # Determine if there are unstaged files
  23     tree = cmd_runner.run(('git', 'write-tree'))[1].strip()
  24     retcode, diff_stdout_binary, _ = cmd_runner.run(
  25         (
  26             'git', 'diff-index', '--ignore-submodules', '--binary',
  27             '--exit-code', '--no-color', '--no-ext-diff', tree, '--',
  28         ),
  29         retcode=None,
  30         encoding=None,
  31     )
  32     if retcode and diff_stdout_binary.strip():
  33         patch_filename = cmd_runner.path('patch{}'.format(int(time.time())))
  34         logger.warning('Unstaged files detected.')
  35         logger.info(
  36             'Stashing unstaged files to {}.'.format(patch_filename),
  37         )
  38         # Save the current unstaged changes as a patch
  39         with io.open(patch_filename, 'wb') as patch_file:
  40             patch_file.write(diff_stdout_binary)
  41 
  42         # Clear the working directory of unstaged changes
  43         cmd_runner.run(('git', 'checkout', '--', '.'))
  44         try:
  45             yield
  46         finally:
  47             # Try to apply the patch we saved
  48             try:
  49                 cmd_runner.run(
  50                     ('git', 'apply', '--whitespace=nowarn', patch_filename),
  51                     encoding=None,
  52                 )
  53             except CalledProcessError:
  54                 logger.warning(
  55                     'Stashed changes conflicted with hook auto-fixes... '
  56                     'Rolling back fixes...',
  57                 )
  58                 # We failed to apply the patch, presumably due to fixes made
  59                 # by hooks.
  60                 # Roll back the changes made by hooks.
  61                 cmd_runner.run(('git', 'checkout', '--', '.'))
  62                 cmd_runner.run(
  63                     ('git', 'apply', patch_filename, '--whitespace=nowarn'),
  64                     encoding=None,
  65                 )
  66             logger.info('Restored changes from {}.'.format(patch_filename))
  67     else:
  68         # There weren't any staged files so we don't need to do anything
  69         # special
  70         yield
  71
  ```
  --- END FILES ---
  
  Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.
  
  Here is an example:
  
  ```diff
  diff --git a/examples/server_async.py b/examples/server_async.py
  --- a/examples/server_async.py
  +++ b/examples/server_async.py
  @@ -313,4 +313,4 @@
   
   
   if __name__ == "__main__":
  -    asyncio.run(run_async_server("."), debug=True)
  +    asyncio.run(run_async_server(), debug=True)
  diff --git a/examples/server_sync.py b/examples/server_sync.py
  --- a/examples/server_sync.py
  +++ b/examples/server_sync.py
  @@ -313,5 +313,5 @@
   
   
   if __name__ == "__main__":
  -    server = run_sync_server(".")
  +    server = run_sync_server()
       server.shutdown()
  
  ```
  
golden_diff: diff --git a/pre_commit/staged_files_only.py b/pre_commit/staged_files_only.py
  --- a/pre_commit/staged_files_only.py
  +++ b/pre_commit/staged_files_only.py
  @@ -11,6 +11,16 @@
   logger = logging.getLogger('pre_commit')
   
   
  +def _git_apply(cmd_runner, patch):
  +    args = ('apply', '--whitespace=nowarn', patch)
  +    try:
  +        cmd_runner.run(('git',) + args, encoding=None)
  +    except CalledProcessError:
  +        # Retry with autocrlf=false -- see #570
  +        cmd = ('git', '-c', 'core.autocrlf=false') + args
  +        cmd_runner.run(cmd, encoding=None)
  +
  +
   @contextlib.contextmanager
   def staged_files_only(cmd_runner):
       """Clear any unstaged changes from the git working directory inside this
  @@ -46,10 +56,7 @@
           finally:
               # Try to apply the patch we saved
               try:
  -                cmd_runner.run(
  -                    ('git', 'apply', '--whitespace=nowarn', patch_filename),
  -                    encoding=None,
  -                )
  +                _git_apply(cmd_runner, patch_filename)
               except CalledProcessError:
                   logger.warning(
                       'Stashed changes conflicted with hook auto-fixes... '
  @@ -59,10 +66,7 @@
                   # 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,
  -                )
  +                _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
  
verification_info: {"golden_diff": "diff --git a/pre_commit/staged_files_only.py b/pre_commit/staged_files_only.py\n--- a/pre_commit/staged_files_only.py\n+++ b/pre_commit/staged_files_only.py\n@@ -11,6 +11,16 @@\n logger = logging.getLogger('pre_commit')\n \n \n+def _git_apply(cmd_runner, patch):\n+    args = ('apply', '--whitespace=nowarn', patch)\n+    try:\n+        cmd_runner.run(('git',) + args, encoding=None)\n+    except CalledProcessError:\n+        # Retry with autocrlf=false -- see #570\n+        cmd = ('git', '-c', 'core.autocrlf=false') + args\n+        cmd_runner.run(cmd, encoding=None)\n+\n+\n @contextlib.contextmanager\n def staged_files_only(cmd_runner):\n     \"\"\"Clear any unstaged changes from the git working directory inside this\n@@ -46,10 +56,7 @@\n         finally:\n             # Try to apply the patch we saved\n             try:\n-                cmd_runner.run(\n-                    ('git', 'apply', '--whitespace=nowarn', patch_filename),\n-                    encoding=None,\n-                )\n+                _git_apply(cmd_runner, patch_filename)\n             except CalledProcessError:\n                 logger.warning(\n                     'Stashed changes conflicted with hook auto-fixes... '\n@@ -59,10 +66,7 @@\n                 # by hooks.\n                 # Roll back the changes made by hooks.\n                 cmd_runner.run(('git', 'checkout', '--', '.'))\n-                cmd_runner.run(\n-                    ('git', 'apply', patch_filename, '--whitespace=nowarn'),\n-                    encoding=None,\n-                )\n+                _git_apply(cmd_runner, patch_filename)\n             logger.info('Restored changes from {}.'.format(patch_filename))\n     else:\n         # There weren't any staged files so we don't need to do anything\n", "issue": "git unadd changes lost if hook fails on windows\n```\r\nD:\\CubeadProjects\\devops [test +0 ~2 -0 | +0 ~1 -0 !]> git cm \"asd\"\r\n[WARNING] Unstaged files detected.\r\n[INFO] Stashing unstaged files to C:\\Users\\56929\\.pre-commit\\patch1501482991.\r\nrun pylint...............................................................Failed\r\nhookid: python-pylint\r\n\r\n************* Module install\r\nC: 10, 0: Exactly one space required around assignment\r\na=1\r\n ^ (bad-whitespace)\r\nC: 46, 0: Line too long (108/100) (line-too-long)\r\nW: 39, 4: Unused variable 'stylelint_root' (unused-variable)\r\nW: 37, 4: Unused variable 'node_root' (unused-variable)\r\nW: 24, 8: Unused variable 'checks' (unused-variable)\r\n\r\n[WARNING] Stashed changes conflicted with hook auto-fixes... Rolling back fixes...\r\nAn unexpected error has occurred: CalledProcessError: Command: ('C:\\\\Program Files\\\\Git\\\\mingw64\\\\libexec\\\\git-core\\\\git.exe', 'apply', 'C:\\\\Users\\\\56929\\\\.pre-commit\\\\patch1501483011')\r\nReturn code: 1\r\nExpected return code: 0\r\nOutput: (none)\r\nErrors:\r\n    error: patch failed: svnchecker_stylelint_support/checks/Stylelint.py:20\r\n    error: svnchecker_stylelint_support/checks/Stylelint.py: patch does not apply\r\n\r\n\r\nCheck the log at ~/.pre-commit/pre-commit.log\r\n```\r\n\r\n### ~/.pre-commit/pre-commit.log\r\n```\r\nAn unexpected error has occurred: CalledProcessError: Command: ('C:\\\\Program Files\\\\Git\\\\mingw64\\\\libexec\\\\git-core\\\\git.exe', 'apply', 'C:\\\\Users\\\\56929\\\\.pre-commit\\\\patch1501483011')\r\nReturn code: 1\r\nExpected return code: 0\r\nOutput: (none)\r\nErrors: \r\n    error: patch failed: svnchecker_stylelint_support/checks/Stylelint.py:20\r\n    error: svnchecker_stylelint_support/checks/Stylelint.py: patch does not apply\r\n    \r\n\r\nTraceback (most recent call last):\r\n  File \"c:\\python27\\lib\\site-packages\\pre_commit\\error_handler.py\", line 48, in error_handler\r\n    yield\r\n  File \"c:\\python27\\lib\\site-packages\\pre_commit\\main.py\", line 231, in main\r\n    return run(runner, args)\r\n  File \"c:\\python27\\lib\\site-packages\\pre_commit\\commands\\run.py\", line 273, in run\r\n    return _run_hooks(repo_hooks, args, environ)\r\n  File \"c:\\python27\\lib\\contextlib.py\", line 24, in __exit__\r\n    self.gen.next()\r\n  File \"c:\\python27\\lib\\site-packages\\pre_commit\\staged_files_only.py\", line 58, in staged_files_only\r\n    cmd_runner.run(('git', 'apply', patch_filename), encoding=None)\r\n  File \"c:\\python27\\lib\\site-packages\\pre_commit\\prefixed_command_runner.py\", line 38, in run\r\n    return cmd_output(*replaced_cmd, __popen=self.__popen, **kwargs)\r\n  File \"c:\\python27\\lib\\site-packages\\pre_commit\\util.py\", line 189, in cmd_output\r\n    returncode, cmd, retcode, output=(stdout, stderr),\r\nCalledProcessError: Command: ('C:\\\\Program Files\\\\Git\\\\mingw64\\\\libexec\\\\git-core\\\\git.exe', 'apply', 'C:\\\\Users\\\\56929\\\\.pre-commit\\\\patch1501483011')\r\nReturn code: 1\r\nExpected return code: 0\r\nOutput: (none)\r\nErrors: \r\n    error: patch failed: svnchecker_stylelint_support/checks/Stylelint.py:20\r\n    error: svnchecker_stylelint_support/checks/Stylelint.py: patch does not apply\r\n```\r\nThen, I open the patch file. (C:\\\\Users\\\\56929\\\\.pre-commit\\\\patch1501483011),it looks like \r\n\r\n```diff\r\ndiff --git a/svnchecker_stylelint_support/checks/Stylelint.py b/svnchecker_stylelint_support/checks/Stylelint.py\r\nindex 4422b4d..f85ecb1 100644\r\n--- a/svnchecker_stylelint_support/checks/Stylelint.py\r\n+++ b/svnchecker_stylelint_support/checks/Stylelint.py\r\n@@ -20,3 +20,5 @@ def run(transaction, config):\r\n             return ('{}\\n{}'.format(stdoutdata, stderrdata), 1)^M\r\n^M\r\n     return (\"\", 0)^M\r\n^M\r\n^M\r\n^M\r\n```\n", "before_files": [{"content": "from __future__ import unicode_literals\n\nimport contextlib\nimport io\nimport logging\nimport time\n\nfrom pre_commit.util import CalledProcessError\n\n\nlogger = logging.getLogger('pre_commit')\n\n\n@contextlib.contextmanager\ndef staged_files_only(cmd_runner):\n    \"\"\"Clear any unstaged changes from the git working directory inside this\n    context.\n\n    Args:\n        cmd_runner - PrefixedCommandRunner\n    \"\"\"\n    # Determine if there are unstaged files\n    tree = cmd_runner.run(('git', 'write-tree'))[1].strip()\n    retcode, diff_stdout_binary, _ = cmd_runner.run(\n        (\n            'git', 'diff-index', '--ignore-submodules', '--binary',\n            '--exit-code', '--no-color', '--no-ext-diff', tree, '--',\n        ),\n        retcode=None,\n        encoding=None,\n    )\n    if retcode and diff_stdout_binary.strip():\n        patch_filename = cmd_runner.path('patch{}'.format(int(time.time())))\n        logger.warning('Unstaged files detected.')\n        logger.info(\n            'Stashing unstaged files to {}.'.format(patch_filename),\n        )\n        # Save the current unstaged changes as a patch\n        with io.open(patch_filename, 'wb') as patch_file:\n            patch_file.write(diff_stdout_binary)\n\n        # Clear the working directory of unstaged changes\n        cmd_runner.run(('git', 'checkout', '--', '.'))\n        try:\n            yield\n        finally:\n            # Try to apply the patch we saved\n            try:\n                cmd_runner.run(\n                    ('git', 'apply', '--whitespace=nowarn', patch_filename),\n                    encoding=None,\n                )\n            except CalledProcessError:\n                logger.warning(\n                    'Stashed changes conflicted with hook auto-fixes... '\n                    'Rolling back fixes...',\n                )\n                # We failed to apply the patch, presumably due to fixes made\n                # by hooks.\n                # Roll back the changes made by hooks.\n                cmd_runner.run(('git', 'checkout', '--', '.'))\n                cmd_runner.run(\n                    ('git', 'apply', patch_filename, '--whitespace=nowarn'),\n                    encoding=None,\n                )\n            logger.info('Restored changes from {}.'.format(patch_filename))\n    else:\n        # There weren't any staged files so we don't need to do anything\n        # special\n        yield\n", "path": "pre_commit/staged_files_only.py"}], "after_files": [{"content": "from __future__ import unicode_literals\n\nimport contextlib\nimport io\nimport logging\nimport time\n\nfrom pre_commit.util import CalledProcessError\n\n\nlogger = logging.getLogger('pre_commit')\n\n\ndef _git_apply(cmd_runner, patch):\n    args = ('apply', '--whitespace=nowarn', patch)\n    try:\n        cmd_runner.run(('git',) + args, encoding=None)\n    except CalledProcessError:\n        # Retry with autocrlf=false -- see #570\n        cmd = ('git', '-c', 'core.autocrlf=false') + args\n        cmd_runner.run(cmd, encoding=None)\n\n\n@contextlib.contextmanager\ndef staged_files_only(cmd_runner):\n    \"\"\"Clear any unstaged changes from the git working directory inside this\n    context.\n\n    Args:\n        cmd_runner - PrefixedCommandRunner\n    \"\"\"\n    # Determine if there are unstaged files\n    tree = cmd_runner.run(('git', 'write-tree'))[1].strip()\n    retcode, diff_stdout_binary, _ = cmd_runner.run(\n        (\n            'git', 'diff-index', '--ignore-submodules', '--binary',\n            '--exit-code', '--no-color', '--no-ext-diff', tree, '--',\n        ),\n        retcode=None,\n        encoding=None,\n    )\n    if retcode and diff_stdout_binary.strip():\n        patch_filename = cmd_runner.path('patch{}'.format(int(time.time())))\n        logger.warning('Unstaged files detected.')\n        logger.info(\n            'Stashing unstaged files to {}.'.format(patch_filename),\n        )\n        # Save the current unstaged changes as a patch\n        with io.open(patch_filename, 'wb') as patch_file:\n            patch_file.write(diff_stdout_binary)\n\n        # Clear the working directory of unstaged changes\n        cmd_runner.run(('git', 'checkout', '--', '.'))\n        try:\n            yield\n        finally:\n            # Try to apply the patch we saved\n            try:\n                _git_apply(cmd_runner, patch_filename)\n            except CalledProcessError:\n                logger.warning(\n                    'Stashed changes conflicted with hook auto-fixes... '\n                    'Rolling back fixes...',\n                )\n                # We failed to apply the patch, presumably due to fixes made\n                # by hooks.\n                # Roll back the changes made by hooks.\n                cmd_runner.run(('git', 'checkout', '--', '.'))\n                _git_apply(cmd_runner, patch_filename)\n            logger.info('Restored changes from {}.'.format(patch_filename))\n    else:\n        # There weren't any staged files so we don't need to do anything\n        # special\n        yield\n", "path": "pre_commit/staged_files_only.py"}]}