We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Parallel execution ran into "patch does not apply"
I modified a bunch of repos using `pre-commit` in parallel and ran `git commit` at the same time, with unstaged changes. The pre-commit processes did `[WARNING] Unstaged files detected.`, stashed the changes in a pach, ran, and then tried to reapply the patches.

Some repos failed with:


```
[WARNING] Stashed changes conflicted with hook auto-fixes... Rolling back fixes...
An unexpected error has occurred: CalledProcessError: command: ('/usr/local/Cellar/git/2.31.1/libexec/git-core/git', '-c', 'core.autocrlf=false', 'apply', '--whitespace=nowarn', '/Users/chainz/.cache/pre-commit/patch1618586253')
return code: 1
expected return code: 0
stdout: (none)
stderr:
    error: patch failed: .github/workflows/main.yml:21
    error: .github/workflows/main.yml: patch does not apply

Check the log at /Users/chainz/.cache/pre-commit/pre-commit.log
```

It looks like this is due to use of the unix timestamp as the only differentiator in patch file paths, causing the parallely-created patches to clobber each other.

`pre-commit.log` says:

### version information

```
pre-commit version: 2.12.0
sys.version:
    3.9.4 (default, Apr  5 2021, 01:49:30) 
    [Clang 12.0.0 (clang-1200.0.32.29)]
sys.executable: /usr/local/Cellar/pre-commit/2.12.0/libexec/bin/python3
os.name: posix
sys.platform: darwin
```

### error information

```
An unexpected error has occurred: CalledProcessError: command: ('/usr/local/Cellar/git/2.31.1/libexec/git-core/git', '-c', 'core.autocrlf=false', 'apply', '--whitespace=nowarn', '/Users/chainz/.cache/pre-commit/patch1618586253')
return code: 1
expected return code: 0
stdout: (none)
stderr:
    error: patch failed: .github/workflows/main.yml:21
    error: .github/workflows/main.yml: patch does not apply
    
```

```
Traceback (most recent call last):
  File "/usr/local/Cellar/pre-commit/2.12.0/libexec/lib/python3.9/site-packages/pre_commit/staged_files_only.py", line 20, in _git_apply
    cmd_output_b('git', *args)
  File "/usr/local/Cellar/pre-commit/2.12.0/libexec/lib/python3.9/site-packages/pre_commit/util.py", line 154, in cmd_output_b
    raise CalledProcessError(returncode, cmd, retcode, stdout_b, stderr_b)
pre_commit.util.CalledProcessError: command: ('/usr/local/Cellar/git/2.31.1/libexec/git-core/git', 'apply', '--whitespace=nowarn', '/Users/chainz/.cache/pre-commit/patch1618586253')
return code: 1
expected return code: 0
stdout: (none)
stderr:
    error: patch failed: .github/workflows/main.yml:21
    error: .github/workflows/main.yml: patch does not apply
    

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/Cellar/pre-commit/2.12.0/libexec/lib/python3.9/site-packages/pre_commit/staged_files_only.py", line 68, in _unstaged_changes_cleared
    _git_apply(patch_filename)
  File "/usr/local/Cellar/pre-commit/2.12.0/libexec/lib/python3.9/site-packages/pre_commit/staged_files_only.py", line 23, in _git_apply
    cmd_output_b('git', '-c', 'core.autocrlf=false', *args)
  File "/usr/local/Cellar/pre-commit/2.12.0/libexec/lib/python3.9/site-packages/pre_commit/util.py", line 154, in cmd_output_b
    raise CalledProcessError(returncode, cmd, retcode, stdout_b, stderr_b)
pre_commit.util.CalledProcessError: command: ('/usr/local/Cellar/git/2.31.1/libexec/git-core/git', '-c', 'core.autocrlf=false', 'apply', '--whitespace=nowarn', '/Users/chainz/.cache/pre-commit/patch1618586253')
return code: 1
expected return code: 0
stdout: (none)
stderr:
    error: patch failed: .github/workflows/main.yml:21
    error: .github/workflows/main.yml: patch does not apply
    

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/Cellar/pre-commit/2.12.0/libexec/lib/python3.9/site-packages/pre_commit/staged_files_only.py", line 20, in _git_apply
    cmd_output_b('git', *args)
  File "/usr/local/Cellar/pre-commit/2.12.0/libexec/lib/python3.9/site-packages/pre_commit/util.py", line 154, in cmd_output_b
    raise CalledProcessError(returncode, cmd, retcode, stdout_b, stderr_b)
pre_commit.util.CalledProcessError: command: ('/usr/local/Cellar/git/2.31.1/libexec/git-core/git', 'apply', '--whitespace=nowarn', '/Users/chainz/.cache/pre-commit/patch1618586253')
return code: 1
expected return code: 0
stdout: (none)
stderr:
    error: patch failed: .github/workflows/main.yml:21
    error: .github/workflows/main.yml: patch does not apply
    

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/Cellar/pre-commit/2.12.0/libexec/lib/python3.9/site-packages/pre_commit/error_handler.py", line 65, in error_handler
    yield
  File "/usr/local/Cellar/pre-commit/2.12.0/libexec/lib/python3.9/site-packages/pre_commit/main.py", line 357, in main
    return hook_impl(
  File "/usr/local/Cellar/pre-commit/2.12.0/libexec/lib/python3.9/site-packages/pre_commit/commands/hook_impl.py", line 227, in hook_impl
    return retv | run(config, store, ns)
  File "/usr/local/Cellar/pre-commit/2.12.0/libexec/lib/python3.9/site-packages/pre_commit/commands/run.py", line 408, in run
    return _run_hooks(config, hooks, args, environ)
  File "/usr/local/Cellar/python@3.9/3.9.4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/contextlib.py", line 513, in __exit__
    raise exc_details[1]
  File "/usr/local/Cellar/python@3.9/3.9.4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/contextlib.py", line 498, in __exit__
    if cb(*exc_details):
  File "/usr/local/Cellar/python@3.9/3.9.4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/contextlib.py", line 124, in __exit__
    next(self.gen)
  File "/usr/local/Cellar/pre-commit/2.12.0/libexec/lib/python3.9/site-packages/pre_commit/staged_files_only.py", line 93, in staged_files_only
    yield
  File "/usr/local/Cellar/python@3.9/3.9.4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/contextlib.py", line 124, in __exit__
    next(self.gen)
  File "/usr/local/Cellar/pre-commit/2.12.0/libexec/lib/python3.9/site-packages/pre_commit/staged_files_only.py", line 78, in _unstaged_changes_cleared
    _git_apply(patch_filename)
  File "/usr/local/Cellar/pre-commit/2.12.0/libexec/lib/python3.9/site-packages/pre_commit/staged_files_only.py", line 23, in _git_apply
    cmd_output_b('git', '-c', 'core.autocrlf=false', *args)
  File "/usr/local/Cellar/pre-commit/2.12.0/libexec/lib/python3.9/site-packages/pre_commit/util.py", line 154, in cmd_output_b
    raise CalledProcessError(returncode, cmd, retcode, stdout_b, stderr_b)
pre_commit.util.CalledProcessError: command: ('/usr/local/Cellar/git/2.31.1/libexec/git-core/git', '-c', 'core.autocrlf=false', 'apply', '--whitespace=nowarn', '/Users/chainz/.cache/pre-commit/patch1618586253')
return code: 1
expected return code: 0
stdout: (none)
stderr:
    error: patch failed: .github/workflows/main.yml:21
    error: .github/workflows/main.yml: patch does not apply
```

--- 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 import contextlib
2 import logging
3 import os.path
4 import time
5 from typing import Generator
6 
7 from pre_commit import git
8 from pre_commit.util import CalledProcessError
9 from pre_commit.util import cmd_output
10 from pre_commit.util import cmd_output_b
11 from pre_commit.xargs import xargs
12 
13 
14 logger = logging.getLogger('pre_commit')
15 
16 
17 def _git_apply(patch: str) -> None:
18     args = ('apply', '--whitespace=nowarn', patch)
19     try:
20         cmd_output_b('git', *args)
21     except CalledProcessError:
22         # Retry with autocrlf=false -- see #570
23         cmd_output_b('git', '-c', 'core.autocrlf=false', *args)
24 
25 
26 @contextlib.contextmanager
27 def _intent_to_add_cleared() -> Generator[None, None, None]:
28     intent_to_add = git.intent_to_add_files()
29     if intent_to_add:
30         logger.warning('Unstaged intent-to-add files detected.')
31 
32         xargs(('git', 'rm', '--cached', '--'), intent_to_add)
33         try:
34             yield
35         finally:
36             xargs(('git', 'add', '--intent-to-add', '--'), intent_to_add)
37     else:
38         yield
39 
40 
41 @contextlib.contextmanager
42 def _unstaged_changes_cleared(patch_dir: str) -> Generator[None, None, None]:
43     tree = cmd_output('git', 'write-tree')[1].strip()
44     retcode, diff_stdout_binary, _ = cmd_output_b(
45         'git', 'diff-index', '--ignore-submodules', '--binary',
46         '--exit-code', '--no-color', '--no-ext-diff', tree, '--',
47         retcode=None,
48     )
49     if retcode and diff_stdout_binary.strip():
50         patch_filename = f'patch{int(time.time())}'
51         patch_filename = os.path.join(patch_dir, patch_filename)
52         logger.warning('Unstaged files detected.')
53         logger.info(f'Stashing unstaged files to {patch_filename}.')
54         # Save the current unstaged changes as a patch
55         os.makedirs(patch_dir, exist_ok=True)
56         with open(patch_filename, 'wb') as patch_file:
57             patch_file.write(diff_stdout_binary)
58 
59         # prevent recursive post-checkout hooks (#1418)
60         no_checkout_env = dict(os.environ, _PRE_COMMIT_SKIP_POST_CHECKOUT='1')
61         cmd_output_b('git', 'checkout', '--', '.', env=no_checkout_env)
62 
63         try:
64             yield
65         finally:
66             # Try to apply the patch we saved
67             try:
68                 _git_apply(patch_filename)
69             except CalledProcessError:
70                 logger.warning(
71                     'Stashed changes conflicted with hook auto-fixes... '
72                     'Rolling back fixes...',
73                 )
74                 # We failed to apply the patch, presumably due to fixes made
75                 # by hooks.
76                 # Roll back the changes made by hooks.
77                 cmd_output_b('git', 'checkout', '--', '.', env=no_checkout_env)
78                 _git_apply(patch_filename)
79 
80             logger.info(f'Restored changes from {patch_filename}.')
81     else:
82         # There weren't any staged files so we don't need to do anything
83         # special
84         yield
85 
86 
87 @contextlib.contextmanager
88 def staged_files_only(patch_dir: str) -> Generator[None, None, None]:
89     """Clear any unstaged changes from the git working directory inside this
90     context.
91     """
92     with _intent_to_add_cleared(), _unstaged_changes_cleared(patch_dir):
93         yield
94
```
--- 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()

```

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
@@ -47,7 +47,7 @@
         retcode=None,
     )
     if retcode and diff_stdout_binary.strip():
-        patch_filename = f'patch{int(time.time())}'
+        patch_filename = f'patch{int(time.time())}-{os.getpid()}'
         patch_filename = os.path.join(patch_dir, patch_filename)
         logger.warning('Unstaged files detected.')
         logger.info(f'Stashing unstaged files to {patch_filename}.')

{"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@@ -47,7 +47,7 @@\n         retcode=None,\n     )\n     if retcode and diff_stdout_binary.strip():\n-        patch_filename = f'patch{int(time.time())}'\n+        patch_filename = f'patch{int(time.time())}-{os.getpid()}'\n         patch_filename = os.path.join(patch_dir, patch_filename)\n         logger.warning('Unstaged files detected.')\n         logger.info(f'Stashing unstaged files to {patch_filename}.')\n", "issue": "Parallel execution ran into \"patch does not apply\"\nI modified a bunch of repos using `pre-commit` in parallel and ran `git commit` at the same time, with unstaged changes. The pre-commit processes did `[WARNING] Unstaged files detected.`, stashed the changes in a pach, ran, and then tried to reapply the patches.\r\n\r\nSome repos failed with:\r\n\r\n\r\n```\r\n[WARNING] Stashed changes conflicted with hook auto-fixes... Rolling back fixes...\r\nAn unexpected error has occurred: CalledProcessError: command: ('/usr/local/Cellar/git/2.31.1/libexec/git-core/git', '-c', 'core.autocrlf=false', 'apply', '--whitespace=nowarn', '/Users/chainz/.cache/pre-commit/patch1618586253')\r\nreturn code: 1\r\nexpected return code: 0\r\nstdout: (none)\r\nstderr:\r\n    error: patch failed: .github/workflows/main.yml:21\r\n    error: .github/workflows/main.yml: patch does not apply\r\n\r\nCheck the log at /Users/chainz/.cache/pre-commit/pre-commit.log\r\n```\r\n\r\nIt looks like this is due to use of the unix timestamp as the only differentiator in patch file paths, causing the parallely-created patches to clobber each other.\r\n\r\n`pre-commit.log` says:\r\n\r\n### version information\r\n\r\n```\r\npre-commit version: 2.12.0\r\nsys.version:\r\n    3.9.4 (default, Apr  5 2021, 01:49:30) \r\n    [Clang 12.0.0 (clang-1200.0.32.29)]\r\nsys.executable: /usr/local/Cellar/pre-commit/2.12.0/libexec/bin/python3\r\nos.name: posix\r\nsys.platform: darwin\r\n```\r\n\r\n### error information\r\n\r\n```\r\nAn unexpected error has occurred: CalledProcessError: command: ('/usr/local/Cellar/git/2.31.1/libexec/git-core/git', '-c', 'core.autocrlf=false', 'apply', '--whitespace=nowarn', '/Users/chainz/.cache/pre-commit/patch1618586253')\r\nreturn code: 1\r\nexpected return code: 0\r\nstdout: (none)\r\nstderr:\r\n    error: patch failed: .github/workflows/main.yml:21\r\n    error: .github/workflows/main.yml: patch does not apply\r\n    \r\n```\r\n\r\n```\r\nTraceback (most recent call last):\r\n  File \"/usr/local/Cellar/pre-commit/2.12.0/libexec/lib/python3.9/site-packages/pre_commit/staged_files_only.py\", line 20, in _git_apply\r\n    cmd_output_b('git', *args)\r\n  File \"/usr/local/Cellar/pre-commit/2.12.0/libexec/lib/python3.9/site-packages/pre_commit/util.py\", line 154, in cmd_output_b\r\n    raise CalledProcessError(returncode, cmd, retcode, stdout_b, stderr_b)\r\npre_commit.util.CalledProcessError: command: ('/usr/local/Cellar/git/2.31.1/libexec/git-core/git', 'apply', '--whitespace=nowarn', '/Users/chainz/.cache/pre-commit/patch1618586253')\r\nreturn code: 1\r\nexpected return code: 0\r\nstdout: (none)\r\nstderr:\r\n    error: patch failed: .github/workflows/main.yml:21\r\n    error: .github/workflows/main.yml: patch does not apply\r\n    \r\n\r\nDuring handling of the above exception, another exception occurred:\r\n\r\nTraceback (most recent call last):\r\n  File \"/usr/local/Cellar/pre-commit/2.12.0/libexec/lib/python3.9/site-packages/pre_commit/staged_files_only.py\", line 68, in _unstaged_changes_cleared\r\n    _git_apply(patch_filename)\r\n  File \"/usr/local/Cellar/pre-commit/2.12.0/libexec/lib/python3.9/site-packages/pre_commit/staged_files_only.py\", line 23, in _git_apply\r\n    cmd_output_b('git', '-c', 'core.autocrlf=false', *args)\r\n  File \"/usr/local/Cellar/pre-commit/2.12.0/libexec/lib/python3.9/site-packages/pre_commit/util.py\", line 154, in cmd_output_b\r\n    raise CalledProcessError(returncode, cmd, retcode, stdout_b, stderr_b)\r\npre_commit.util.CalledProcessError: command: ('/usr/local/Cellar/git/2.31.1/libexec/git-core/git', '-c', 'core.autocrlf=false', 'apply', '--whitespace=nowarn', '/Users/chainz/.cache/pre-commit/patch1618586253')\r\nreturn code: 1\r\nexpected return code: 0\r\nstdout: (none)\r\nstderr:\r\n    error: patch failed: .github/workflows/main.yml:21\r\n    error: .github/workflows/main.yml: patch does not apply\r\n    \r\n\r\nDuring handling of the above exception, another exception occurred:\r\n\r\nTraceback (most recent call last):\r\n  File \"/usr/local/Cellar/pre-commit/2.12.0/libexec/lib/python3.9/site-packages/pre_commit/staged_files_only.py\", line 20, in _git_apply\r\n    cmd_output_b('git', *args)\r\n  File \"/usr/local/Cellar/pre-commit/2.12.0/libexec/lib/python3.9/site-packages/pre_commit/util.py\", line 154, in cmd_output_b\r\n    raise CalledProcessError(returncode, cmd, retcode, stdout_b, stderr_b)\r\npre_commit.util.CalledProcessError: command: ('/usr/local/Cellar/git/2.31.1/libexec/git-core/git', 'apply', '--whitespace=nowarn', '/Users/chainz/.cache/pre-commit/patch1618586253')\r\nreturn code: 1\r\nexpected return code: 0\r\nstdout: (none)\r\nstderr:\r\n    error: patch failed: .github/workflows/main.yml:21\r\n    error: .github/workflows/main.yml: patch does not apply\r\n    \r\n\r\nDuring handling of the above exception, another exception occurred:\r\n\r\nTraceback (most recent call last):\r\n  File \"/usr/local/Cellar/pre-commit/2.12.0/libexec/lib/python3.9/site-packages/pre_commit/error_handler.py\", line 65, in error_handler\r\n    yield\r\n  File \"/usr/local/Cellar/pre-commit/2.12.0/libexec/lib/python3.9/site-packages/pre_commit/main.py\", line 357, in main\r\n    return hook_impl(\r\n  File \"/usr/local/Cellar/pre-commit/2.12.0/libexec/lib/python3.9/site-packages/pre_commit/commands/hook_impl.py\", line 227, in hook_impl\r\n    return retv | run(config, store, ns)\r\n  File \"/usr/local/Cellar/pre-commit/2.12.0/libexec/lib/python3.9/site-packages/pre_commit/commands/run.py\", line 408, in run\r\n    return _run_hooks(config, hooks, args, environ)\r\n  File \"/usr/local/Cellar/python@3.9/3.9.4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/contextlib.py\", line 513, in __exit__\r\n    raise exc_details[1]\r\n  File \"/usr/local/Cellar/python@3.9/3.9.4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/contextlib.py\", line 498, in __exit__\r\n    if cb(*exc_details):\r\n  File \"/usr/local/Cellar/python@3.9/3.9.4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/contextlib.py\", line 124, in __exit__\r\n    next(self.gen)\r\n  File \"/usr/local/Cellar/pre-commit/2.12.0/libexec/lib/python3.9/site-packages/pre_commit/staged_files_only.py\", line 93, in staged_files_only\r\n    yield\r\n  File \"/usr/local/Cellar/python@3.9/3.9.4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/contextlib.py\", line 124, in __exit__\r\n    next(self.gen)\r\n  File \"/usr/local/Cellar/pre-commit/2.12.0/libexec/lib/python3.9/site-packages/pre_commit/staged_files_only.py\", line 78, in _unstaged_changes_cleared\r\n    _git_apply(patch_filename)\r\n  File \"/usr/local/Cellar/pre-commit/2.12.0/libexec/lib/python3.9/site-packages/pre_commit/staged_files_only.py\", line 23, in _git_apply\r\n    cmd_output_b('git', '-c', 'core.autocrlf=false', *args)\r\n  File \"/usr/local/Cellar/pre-commit/2.12.0/libexec/lib/python3.9/site-packages/pre_commit/util.py\", line 154, in cmd_output_b\r\n    raise CalledProcessError(returncode, cmd, retcode, stdout_b, stderr_b)\r\npre_commit.util.CalledProcessError: command: ('/usr/local/Cellar/git/2.31.1/libexec/git-core/git', '-c', 'core.autocrlf=false', 'apply', '--whitespace=nowarn', '/Users/chainz/.cache/pre-commit/patch1618586253')\r\nreturn code: 1\r\nexpected return code: 0\r\nstdout: (none)\r\nstderr:\r\n    error: patch failed: .github/workflows/main.yml:21\r\n    error: .github/workflows/main.yml: patch does not apply\r\n```\n", "before_files": [{"content": "import contextlib\nimport logging\nimport os.path\nimport time\nfrom typing import Generator\n\nfrom pre_commit import git\nfrom pre_commit.util import CalledProcessError\nfrom pre_commit.util import cmd_output\nfrom pre_commit.util import cmd_output_b\nfrom pre_commit.xargs import xargs\n\n\nlogger = logging.getLogger('pre_commit')\n\n\ndef _git_apply(patch: str) -> None:\n    args = ('apply', '--whitespace=nowarn', patch)\n    try:\n        cmd_output_b('git', *args)\n    except CalledProcessError:\n        # Retry with autocrlf=false -- see #570\n        cmd_output_b('git', '-c', 'core.autocrlf=false', *args)\n\n\n@contextlib.contextmanager\ndef _intent_to_add_cleared() -> Generator[None, None, None]:\n    intent_to_add = git.intent_to_add_files()\n    if intent_to_add:\n        logger.warning('Unstaged intent-to-add files detected.')\n\n        xargs(('git', 'rm', '--cached', '--'), intent_to_add)\n        try:\n            yield\n        finally:\n            xargs(('git', 'add', '--intent-to-add', '--'), intent_to_add)\n    else:\n        yield\n\n\n@contextlib.contextmanager\ndef _unstaged_changes_cleared(patch_dir: str) -> Generator[None, None, None]:\n    tree = cmd_output('git', 'write-tree')[1].strip()\n    retcode, diff_stdout_binary, _ = cmd_output_b(\n        'git', 'diff-index', '--ignore-submodules', '--binary',\n        '--exit-code', '--no-color', '--no-ext-diff', tree, '--',\n        retcode=None,\n    )\n    if retcode and diff_stdout_binary.strip():\n        patch_filename = f'patch{int(time.time())}'\n        patch_filename = os.path.join(patch_dir, patch_filename)\n        logger.warning('Unstaged files detected.')\n        logger.info(f'Stashing unstaged files to {patch_filename}.')\n        # Save the current unstaged changes as a patch\n        os.makedirs(patch_dir, exist_ok=True)\n        with open(patch_filename, 'wb') as patch_file:\n            patch_file.write(diff_stdout_binary)\n\n        # prevent recursive post-checkout hooks (#1418)\n        no_checkout_env = dict(os.environ, _PRE_COMMIT_SKIP_POST_CHECKOUT='1')\n        cmd_output_b('git', 'checkout', '--', '.', env=no_checkout_env)\n\n        try:\n            yield\n        finally:\n            # Try to apply the patch we saved\n            try:\n                _git_apply(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_output_b('git', 'checkout', '--', '.', env=no_checkout_env)\n                _git_apply(patch_filename)\n\n            logger.info(f'Restored changes from {patch_filename}.')\n    else:\n        # There weren't any staged files so we don't need to do anything\n        # special\n        yield\n\n\n@contextlib.contextmanager\ndef staged_files_only(patch_dir: str) -> Generator[None, None, None]:\n    \"\"\"Clear any unstaged changes from the git working directory inside this\n    context.\n    \"\"\"\n    with _intent_to_add_cleared(), _unstaged_changes_cleared(patch_dir):\n        yield\n", "path": "pre_commit/staged_files_only.py"}], "after_files": [{"content": "import contextlib\nimport logging\nimport os.path\nimport time\nfrom typing import Generator\n\nfrom pre_commit import git\nfrom pre_commit.util import CalledProcessError\nfrom pre_commit.util import cmd_output\nfrom pre_commit.util import cmd_output_b\nfrom pre_commit.xargs import xargs\n\n\nlogger = logging.getLogger('pre_commit')\n\n\ndef _git_apply(patch: str) -> None:\n    args = ('apply', '--whitespace=nowarn', patch)\n    try:\n        cmd_output_b('git', *args)\n    except CalledProcessError:\n        # Retry with autocrlf=false -- see #570\n        cmd_output_b('git', '-c', 'core.autocrlf=false', *args)\n\n\n@contextlib.contextmanager\ndef _intent_to_add_cleared() -> Generator[None, None, None]:\n    intent_to_add = git.intent_to_add_files()\n    if intent_to_add:\n        logger.warning('Unstaged intent-to-add files detected.')\n\n        xargs(('git', 'rm', '--cached', '--'), intent_to_add)\n        try:\n            yield\n        finally:\n            xargs(('git', 'add', '--intent-to-add', '--'), intent_to_add)\n    else:\n        yield\n\n\n@contextlib.contextmanager\ndef _unstaged_changes_cleared(patch_dir: str) -> Generator[None, None, None]:\n    tree = cmd_output('git', 'write-tree')[1].strip()\n    retcode, diff_stdout_binary, _ = cmd_output_b(\n        'git', 'diff-index', '--ignore-submodules', '--binary',\n        '--exit-code', '--no-color', '--no-ext-diff', tree, '--',\n        retcode=None,\n    )\n    if retcode and diff_stdout_binary.strip():\n        patch_filename = f'patch{int(time.time())}-{os.getpid()}'\n        patch_filename = os.path.join(patch_dir, patch_filename)\n        logger.warning('Unstaged files detected.')\n        logger.info(f'Stashing unstaged files to {patch_filename}.')\n        # Save the current unstaged changes as a patch\n        os.makedirs(patch_dir, exist_ok=True)\n        with open(patch_filename, 'wb') as patch_file:\n            patch_file.write(diff_stdout_binary)\n\n        # prevent recursive post-checkout hooks (#1418)\n        no_checkout_env = dict(os.environ, _PRE_COMMIT_SKIP_POST_CHECKOUT='1')\n        cmd_output_b('git', 'checkout', '--', '.', env=no_checkout_env)\n\n        try:\n            yield\n        finally:\n            # Try to apply the patch we saved\n            try:\n                _git_apply(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_output_b('git', 'checkout', '--', '.', env=no_checkout_env)\n                _git_apply(patch_filename)\n\n            logger.info(f'Restored changes from {patch_filename}.')\n    else:\n        # There weren't any staged files so we don't need to do anything\n        # special\n        yield\n\n\n@contextlib.contextmanager\ndef staged_files_only(patch_dir: str) -> Generator[None, None, None]:\n    \"\"\"Clear any unstaged changes from the git working directory inside this\n    context.\n    \"\"\"\n    with _intent_to_add_cleared(), _unstaged_changes_cleared(patch_dir):\n        yield\n", "path": "pre_commit/staged_files_only.py"}]}