prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  UnicodeDecodeError in staged_files_only
  ```
  $ pre-commit
  [WARNING] Unstaged files detected.
  [INFO] Stashing unstaged files to .../.pre-commit-files/patch1397853050.
  Traceback (most recent call last):
    File ".../bin/pre-commit", line 9, in <module>
      load_entry_point('pre-commit==0.0.0', 'console_scripts', 'pre-commit')()
    File ".../lib/python2.6/site-packages/pre_commit/util.py", line 52, in wrapper
      return func(argv)
    File ".../lib/python2.6/site-packages/pre_commit/run.py", line 59, in run
      return commands.run(runner, args)
    File ".../lib/python2.6/site-packages/pre_commit/commands.py", line 254, in run
      with ctx:
    File "/usr/lib64/python2.6/contextlib.py", line 16, in __enter__
      return self.gen.next()
    File ".../lib/python2.6/site-packages/pre_commit/staged_files_only.py", line 32, in staged_files_only
      patch_file.write(diff_stdout)
  UnicodeEncodeError: 'ascii' codec can't encode character u'\xfc' in position 3795: ordinal not in range(128)
  ```
  
  
  --- 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 time
  4 
  5 from pre_commit.prefixed_command_runner import CalledProcessError
  6 
  7 
  8 logger = logging.getLogger('pre_commit')
  9 
  10 
  11 @contextlib.contextmanager
  12 def staged_files_only(cmd_runner):
  13     """Clear any unstaged changes from the git working directory inside this
  14     context.
  15 
  16     Args:
  17         cmd_runner - PrefixedCommandRunner
  18     """
  19     # Determine if there are unstaged files
  20     retcode, diff_stdout, _ = cmd_runner.run(
  21         ['git', 'diff', '--ignore-submodules', '--binary', '--exit-code'],
  22         retcode=None,
  23     )
  24     if retcode and diff_stdout.strip():
  25         patch_filename = cmd_runner.path('patch{0}'.format(int(time.time())))
  26         logger.warning('Unstaged files detected.')
  27         logger.info(
  28             'Stashing unstaged files to {0}.'.format(patch_filename),
  29         )
  30         # Save the current unstaged changes as a patch
  31         with open(patch_filename, 'w') as patch_file:
  32             patch_file.write(diff_stdout)
  33 
  34         # Clear the working directory of unstaged changes
  35         cmd_runner.run(['git', 'checkout', '--', '.'])
  36         try:
  37             yield
  38         finally:
  39             # Try to apply the patch we saved
  40             try:
  41                 cmd_runner.run(['git', 'apply', patch_filename])
  42             except CalledProcessError:
  43                 logger.warning(
  44                     'Stashed changes conflicted with hook auto-fixes... '
  45                     'Rolling back fixes...'
  46                 )
  47                 # We failed to apply the patch, presumably due to fixes made
  48                 # by hooks.
  49                 # Roll back the changes made by hooks.
  50                 cmd_runner.run(['git', 'checkout', '--', '.'])
  51                 cmd_runner.run(['git', 'apply', patch_filename])
  52             logger.info('Restored changes from {0}.'.format(patch_filename))
  53     else:
  54         # There weren't any staged files so we don't need to do anything
  55         # special
  56         yield
  57
  ```
  --- 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
  @@ -1,4 +1,5 @@
   import contextlib
  +import io
   import logging
   import time
   
  @@ -28,7 +29,7 @@
               'Stashing unstaged files to {0}.'.format(patch_filename),
           )
           # Save the current unstaged changes as a patch
  -        with open(patch_filename, 'w') as patch_file:
  +        with io.open(patch_filename, 'w', encoding='utf-8') as patch_file:
               patch_file.write(diff_stdout)
   
           # Clear the working directory of unstaged changes
  
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@@ -1,4 +1,5 @@\n import contextlib\n+import io\n import logging\n import time\n \n@@ -28,7 +29,7 @@\n             'Stashing unstaged files to {0}.'.format(patch_filename),\n         )\n         # Save the current unstaged changes as a patch\n-        with open(patch_filename, 'w') as patch_file:\n+        with io.open(patch_filename, 'w', encoding='utf-8') as patch_file:\n             patch_file.write(diff_stdout)\n \n         # Clear the working directory of unstaged changes\n", "issue": "UnicodeDecodeError in staged_files_only\n```\n$ pre-commit\n[WARNING] Unstaged files detected.\n[INFO] Stashing unstaged files to .../.pre-commit-files/patch1397853050.\nTraceback (most recent call last):\n  File \".../bin/pre-commit\", line 9, in <module>\n    load_entry_point('pre-commit==0.0.0', 'console_scripts', 'pre-commit')()\n  File \".../lib/python2.6/site-packages/pre_commit/util.py\", line 52, in wrapper\n    return func(argv)\n  File \".../lib/python2.6/site-packages/pre_commit/run.py\", line 59, in run\n    return commands.run(runner, args)\n  File \".../lib/python2.6/site-packages/pre_commit/commands.py\", line 254, in run\n    with ctx:\n  File \"/usr/lib64/python2.6/contextlib.py\", line 16, in __enter__\n    return self.gen.next()\n  File \".../lib/python2.6/site-packages/pre_commit/staged_files_only.py\", line 32, in staged_files_only\n    patch_file.write(diff_stdout)\nUnicodeEncodeError: 'ascii' codec can't encode character u'\\xfc' in position 3795: ordinal not in range(128)\n```\n\n", "before_files": [{"content": "import contextlib\nimport logging\nimport time\n\nfrom pre_commit.prefixed_command_runner 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    retcode, diff_stdout, _ = cmd_runner.run(\n        ['git', 'diff', '--ignore-submodules', '--binary', '--exit-code'],\n        retcode=None,\n    )\n    if retcode and diff_stdout.strip():\n        patch_filename = cmd_runner.path('patch{0}'.format(int(time.time())))\n        logger.warning('Unstaged files detected.')\n        logger.info(\n            'Stashing unstaged files to {0}.'.format(patch_filename),\n        )\n        # Save the current unstaged changes as a patch\n        with open(patch_filename, 'w') as patch_file:\n            patch_file.write(diff_stdout)\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(['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_runner.run(['git', 'checkout', '--', '.'])\n                cmd_runner.run(['git', 'apply', patch_filename])\n            logger.info('Restored changes from {0}.'.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": "import contextlib\nimport io\nimport logging\nimport time\n\nfrom pre_commit.prefixed_command_runner 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    retcode, diff_stdout, _ = cmd_runner.run(\n        ['git', 'diff', '--ignore-submodules', '--binary', '--exit-code'],\n        retcode=None,\n    )\n    if retcode and diff_stdout.strip():\n        patch_filename = cmd_runner.path('patch{0}'.format(int(time.time())))\n        logger.warning('Unstaged files detected.')\n        logger.info(\n            'Stashing unstaged files to {0}.'.format(patch_filename),\n        )\n        # Save the current unstaged changes as a patch\n        with io.open(patch_filename, 'w', encoding='utf-8') as patch_file:\n            patch_file.write(diff_stdout)\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(['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_runner.run(['git', 'checkout', '--', '.'])\n                cmd_runner.run(['git', 'apply', patch_filename])\n            logger.info('Restored changes from {0}.'.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"}]}