We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
2to3 run `itertools_imports` fixer


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `tools/py3tool.py`
Content:
```
1 #!/usr/bin/env python3
2 # -*- python -*-
3 """
4 %prog SUBMODULE...
5 
6 Hack to pipe submodules of Numpy through 2to3 and build them in-place
7 one-by-one.
8 
9 Example usage:
10 
11     python3 tools/py3tool.py testing distutils core
12 
13 This will copy files to _py3k/numpy, add a dummy __init__.py and
14 version.py on the top level, and copy and 2to3 the files of the three
15 submodules.
16 
17 When running py3tool again, only changed files are re-processed, which
18 makes the test-bugfix cycle faster.
19 
20 """
21 from __future__ import division, absolute_import, print_function
22 
23 from optparse import OptionParser
24 import shutil
25 import os
26 import sys
27 import re
28 import subprocess
29 import fnmatch
30 
31 if os.environ.get('USE_2TO3CACHE'):
32     import lib2to3cache
33 
34 BASE = os.path.normpath(os.path.join(os.path.dirname(__file__), '..'))
35 TEMP = os.path.normpath(os.path.join(BASE, '_py3k'))
36 
37 SCRIPT_2TO3 = os.path.join(BASE, 'tools', '2to3.py')
38 
39 EXTRA_2TO3_FLAGS = {
40     'numpy/core/defchararray.py': '-x unicode',
41     'numpy/compat/py3k.py': '-x unicode',
42     'numpy/ma/timer_comparison.py': 'skip',
43 }
44 
45 # Names of fixers to skip when running 2to3.  This is a complete list of
46 # available fixers, with fixers not currently skipped commented out.
47 FIXES_TO_SKIP = [
48     'apply',
49 #    'basestring',
50     'buffer',
51     'callable',
52     'dict',
53     'exec',
54     'execfile',
55     'exitfunc',
56     'filter',
57     'funcattrs',
58     'future',
59     'getcwdu',
60     'has_key',
61 #    'idioms',
62     'import',
63     'imports',
64     'imports2',
65     'input',
66     'intern',
67 #    'isinstance',
68 #    'itertools',
69 #    'itertools_imports',
70 #    'long',
71     'map',
72     'metaclass',
73     'methodattrs',
74     'ne',
75 #    'next',
76 #    'nonzero',
77 #    'numliterals',
78     'operator',
79     'paren',
80     'print',
81     'raise',
82     'raw_input',
83     'reduce',
84 #    'renames',
85     'repr',
86     'setliteral',
87     'standarderror',
88     'sys_exc',
89     'throw',
90     'tuple_params',
91 #    'types',
92 #    'unicode',
93 #    'urllib',
94 #    'ws_comma',
95     'xrange',
96     'xreadlines',
97 #    'zip',
98 ]
99 
100 skip_fixes= []
101 for _t in FIXES_TO_SKIP:
102     skip_fixes.append('-x')
103     skip_fixes.append(_t)
104 
105 
106 def main():
107     p = OptionParser(usage=__doc__.strip())
108     p.add_option("--clean", "-c", action="store_true",
109                  help="clean source directory")
110     options, args = p.parse_args()
111 
112     if not args:
113         p.error('no submodules given')
114     else:
115         dirs = ['numpy/%s' % x for x in map(os.path.basename, args)]
116 
117     # Prepare
118     if not os.path.isdir(TEMP):
119         os.makedirs(TEMP)
120 
121     # Set up dummy files (for building only submodules)
122     dummy_files = {
123         '__init__.py': 'from numpy.version import version as __version__',
124         'version.py': 'version = "1.4.0.dev"'
125     }
126 
127     for fn, content in dummy_files.items():
128         fn = os.path.join(TEMP, 'numpy', fn)
129         if not os.path.isfile(fn):
130             try:
131                 os.makedirs(os.path.dirname(fn))
132             except OSError:
133                 pass
134             f = open(fn, 'wb+')
135             f.write(content.encode('ascii'))
136             f.close()
137 
138     # Environment
139     pp = [os.path.abspath(TEMP)]
140     def getenv():
141         env = dict(os.environ)
142         env.update({'PYTHONPATH': ':'.join(pp)})
143         return env
144 
145     # Copy
146     for d in dirs:
147         src = os.path.join(BASE, d)
148         dst = os.path.join(TEMP, d)
149 
150         # Run 2to3
151         sync_2to3(dst=dst,
152                   src=src,
153                   patchfile=os.path.join(TEMP, os.path.basename(d) + '.patch'),
154                   clean=options.clean)
155 
156         # Run setup.py, falling back to Pdb post-mortem on exceptions
157         setup_py = os.path.join(dst, 'setup.py')
158         if os.path.isfile(setup_py):
159             code = """\
160 import pdb, sys, traceback
161 p = pdb.Pdb()
162 try:
163     import __main__
164     __main__.__dict__.update({
165         "__name__": "__main__", "__file__": "setup.py",
166         "__builtins__": __builtins__})
167     fp = open("setup.py", "rb")
168     try:
169         exec(compile(fp.read(), "setup.py", 'exec'))
170     finally:
171         fp.close()
172 except SystemExit:
173     raise
174 except:
175     traceback.print_exc()
176     t = sys.exc_info()[2]
177     p.interaction(None, t)
178 """
179             ret = subprocess.call([sys.executable, '-c', code,
180                                    'build_ext', '-i'],
181                                   cwd=dst,
182                                   env=getenv())
183             if ret != 0:
184                 raise RuntimeError("Build failed.")
185 
186         # Run nosetests
187         subprocess.call(['nosetests3', '-v', d], cwd=TEMP)
188 
189 
190 def walk_sync(dir1, dir2, _seen=None):
191     if _seen is None:
192         seen = {}
193     else:
194         seen = _seen
195 
196     if not dir1.endswith(os.path.sep):
197         dir1 = dir1 + os.path.sep
198 
199     # Walk through stuff (which we haven't yet gone through) in dir1
200     for root, dirs, files in os.walk(dir1):
201         sub = root[len(dir1):]
202         if sub in seen:
203             dirs = [x for x in dirs if x not in seen[sub][0]]
204             files = [x for x in files if x not in seen[sub][1]]
205             seen[sub][0].extend(dirs)
206             seen[sub][1].extend(files)
207         else:
208             seen[sub] = (dirs, files)
209         if not dirs and not files:
210             continue
211         yield os.path.join(dir1, sub), os.path.join(dir2, sub), dirs, files
212 
213     if _seen is None:
214         # Walk through stuff (which we haven't yet gone through) in dir2
215         for root2, root1, dirs, files in walk_sync(dir2, dir1, _seen=seen):
216             yield root1, root2, dirs, files
217 
218 def sync_2to3(src, dst, patchfile=None, clean=False):
219     import lib2to3.main
220     from io import StringIO
221 
222     to_convert = []
223 
224     for src_dir, dst_dir, dirs, files in walk_sync(src, dst):
225         for fn in dirs + files:
226             src_fn = os.path.join(src_dir, fn)
227             dst_fn = os.path.join(dst_dir, fn)
228 
229             # skip temporary etc. files
230             if fn.startswith('.#') or fn.endswith('~'):
231                 continue
232 
233             # remove non-existing
234             if os.path.exists(dst_fn) and not os.path.exists(src_fn):
235                 if clean:
236                     if os.path.isdir(dst_fn):
237                         shutil.rmtree(dst_fn)
238                     else:
239                         os.unlink(dst_fn)
240                 continue
241 
242             # make directories
243             if os.path.isdir(src_fn):
244                 if not os.path.isdir(dst_fn):
245                     os.makedirs(dst_fn)
246                 continue
247 
248             dst_dir = os.path.dirname(dst_fn)
249             if os.path.isfile(dst_fn) and not os.path.isdir(dst_dir):
250                 os.makedirs(dst_dir)
251 
252             # don't replace up-to-date files
253             try:
254                 if os.path.isfile(dst_fn) and \
255                        os.stat(dst_fn).st_mtime >= os.stat(src_fn).st_mtime:
256                     continue
257             except OSError:
258                 pass
259 
260             # copy file
261             shutil.copyfile(src_fn, dst_fn)
262 
263             # add .py files to 2to3 list
264             if dst_fn.endswith('.py'):
265                 to_convert.append((src_fn, dst_fn))
266 
267     # run 2to3
268     flag_sets = {}
269     for fn, dst_fn in to_convert:
270         flag = ''
271         for pat, opt in EXTRA_2TO3_FLAGS.items():
272             if fnmatch.fnmatch(fn, pat):
273                 flag = opt
274                 break
275         flag_sets.setdefault(flag, []).append(dst_fn)
276 
277     if patchfile:
278         p = open(patchfile, 'wb+')
279     else:
280         p = open(os.devnull, 'wb')
281 
282     for flags, filenames in flag_sets.items():
283         if flags == 'skip':
284             continue
285 
286         _old_stdout = sys.stdout
287         try:
288             sys.stdout = StringIO()
289             opt = []
290             opt.extend(['-w', '-n'])
291             opt.extend(skip_fixes)
292             opt.extend(flags.split())
293             opt.extend(filenames)
294             lib2to3.main.main("lib2to3.fixes", opt)
295         finally:
296             sys.stdout = _old_stdout
297 
298     p.close()
299 
300 if __name__ == "__main__":
301     main()
302
```
--- 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/tools/py3tool.py b/tools/py3tool.py
--- a/tools/py3tool.py
+++ b/tools/py3tool.py
@@ -66,7 +66,7 @@
     'intern',
 #    'isinstance',
 #    'itertools',
-#    'itertools_imports',
+    'itertools_imports',
 #    'long',
     'map',
     'metaclass',

{"golden_diff": "diff --git a/tools/py3tool.py b/tools/py3tool.py\n--- a/tools/py3tool.py\n+++ b/tools/py3tool.py\n@@ -66,7 +66,7 @@\n     'intern',\n #    'isinstance',\n #    'itertools',\n-#    'itertools_imports',\n+    'itertools_imports',\n #    'long',\n     'map',\n     'metaclass',\n", "issue": "2to3 run `itertools_imports` fixer\n\n", "before_files": [{"content": "#!/usr/bin/env python3\n# -*- python -*-\n\"\"\"\n%prog SUBMODULE...\n\nHack to pipe submodules of Numpy through 2to3 and build them in-place\none-by-one.\n\nExample usage:\n\n    python3 tools/py3tool.py testing distutils core\n\nThis will copy files to _py3k/numpy, add a dummy __init__.py and\nversion.py on the top level, and copy and 2to3 the files of the three\nsubmodules.\n\nWhen running py3tool again, only changed files are re-processed, which\nmakes the test-bugfix cycle faster.\n\n\"\"\"\nfrom __future__ import division, absolute_import, print_function\n\nfrom optparse import OptionParser\nimport shutil\nimport os\nimport sys\nimport re\nimport subprocess\nimport fnmatch\n\nif os.environ.get('USE_2TO3CACHE'):\n    import lib2to3cache\n\nBASE = os.path.normpath(os.path.join(os.path.dirname(__file__), '..'))\nTEMP = os.path.normpath(os.path.join(BASE, '_py3k'))\n\nSCRIPT_2TO3 = os.path.join(BASE, 'tools', '2to3.py')\n\nEXTRA_2TO3_FLAGS = {\n    'numpy/core/defchararray.py': '-x unicode',\n    'numpy/compat/py3k.py': '-x unicode',\n    'numpy/ma/timer_comparison.py': 'skip',\n}\n\n# Names of fixers to skip when running 2to3.  This is a complete list of\n# available fixers, with fixers not currently skipped commented out.\nFIXES_TO_SKIP = [\n    'apply',\n#    'basestring',\n    'buffer',\n    'callable',\n    'dict',\n    'exec',\n    'execfile',\n    'exitfunc',\n    'filter',\n    'funcattrs',\n    'future',\n    'getcwdu',\n    'has_key',\n#    'idioms',\n    'import',\n    'imports',\n    'imports2',\n    'input',\n    'intern',\n#    'isinstance',\n#    'itertools',\n#    'itertools_imports',\n#    'long',\n    'map',\n    'metaclass',\n    'methodattrs',\n    'ne',\n#    'next',\n#    'nonzero',\n#    'numliterals',\n    'operator',\n    'paren',\n    'print',\n    'raise',\n    'raw_input',\n    'reduce',\n#    'renames',\n    'repr',\n    'setliteral',\n    'standarderror',\n    'sys_exc',\n    'throw',\n    'tuple_params',\n#    'types',\n#    'unicode',\n#    'urllib',\n#    'ws_comma',\n    'xrange',\n    'xreadlines',\n#    'zip',\n]\n\nskip_fixes= []\nfor _t in FIXES_TO_SKIP:\n    skip_fixes.append('-x')\n    skip_fixes.append(_t)\n\n\ndef main():\n    p = OptionParser(usage=__doc__.strip())\n    p.add_option(\"--clean\", \"-c\", action=\"store_true\",\n                 help=\"clean source directory\")\n    options, args = p.parse_args()\n\n    if not args:\n        p.error('no submodules given')\n    else:\n        dirs = ['numpy/%s' % x for x in map(os.path.basename, args)]\n\n    # Prepare\n    if not os.path.isdir(TEMP):\n        os.makedirs(TEMP)\n\n    # Set up dummy files (for building only submodules)\n    dummy_files = {\n        '__init__.py': 'from numpy.version import version as __version__',\n        'version.py': 'version = \"1.4.0.dev\"'\n    }\n\n    for fn, content in dummy_files.items():\n        fn = os.path.join(TEMP, 'numpy', fn)\n        if not os.path.isfile(fn):\n            try:\n                os.makedirs(os.path.dirname(fn))\n            except OSError:\n                pass\n            f = open(fn, 'wb+')\n            f.write(content.encode('ascii'))\n            f.close()\n\n    # Environment\n    pp = [os.path.abspath(TEMP)]\n    def getenv():\n        env = dict(os.environ)\n        env.update({'PYTHONPATH': ':'.join(pp)})\n        return env\n\n    # Copy\n    for d in dirs:\n        src = os.path.join(BASE, d)\n        dst = os.path.join(TEMP, d)\n\n        # Run 2to3\n        sync_2to3(dst=dst,\n                  src=src,\n                  patchfile=os.path.join(TEMP, os.path.basename(d) + '.patch'),\n                  clean=options.clean)\n\n        # Run setup.py, falling back to Pdb post-mortem on exceptions\n        setup_py = os.path.join(dst, 'setup.py')\n        if os.path.isfile(setup_py):\n            code = \"\"\"\\\nimport pdb, sys, traceback\np = pdb.Pdb()\ntry:\n    import __main__\n    __main__.__dict__.update({\n        \"__name__\": \"__main__\", \"__file__\": \"setup.py\",\n        \"__builtins__\": __builtins__})\n    fp = open(\"setup.py\", \"rb\")\n    try:\n        exec(compile(fp.read(), \"setup.py\", 'exec'))\n    finally:\n        fp.close()\nexcept SystemExit:\n    raise\nexcept:\n    traceback.print_exc()\n    t = sys.exc_info()[2]\n    p.interaction(None, t)\n\"\"\"\n            ret = subprocess.call([sys.executable, '-c', code,\n                                   'build_ext', '-i'],\n                                  cwd=dst,\n                                  env=getenv())\n            if ret != 0:\n                raise RuntimeError(\"Build failed.\")\n\n        # Run nosetests\n        subprocess.call(['nosetests3', '-v', d], cwd=TEMP)\n\n\ndef walk_sync(dir1, dir2, _seen=None):\n    if _seen is None:\n        seen = {}\n    else:\n        seen = _seen\n\n    if not dir1.endswith(os.path.sep):\n        dir1 = dir1 + os.path.sep\n\n    # Walk through stuff (which we haven't yet gone through) in dir1\n    for root, dirs, files in os.walk(dir1):\n        sub = root[len(dir1):]\n        if sub in seen:\n            dirs = [x for x in dirs if x not in seen[sub][0]]\n            files = [x for x in files if x not in seen[sub][1]]\n            seen[sub][0].extend(dirs)\n            seen[sub][1].extend(files)\n        else:\n            seen[sub] = (dirs, files)\n        if not dirs and not files:\n            continue\n        yield os.path.join(dir1, sub), os.path.join(dir2, sub), dirs, files\n\n    if _seen is None:\n        # Walk through stuff (which we haven't yet gone through) in dir2\n        for root2, root1, dirs, files in walk_sync(dir2, dir1, _seen=seen):\n            yield root1, root2, dirs, files\n\ndef sync_2to3(src, dst, patchfile=None, clean=False):\n    import lib2to3.main\n    from io import StringIO\n\n    to_convert = []\n\n    for src_dir, dst_dir, dirs, files in walk_sync(src, dst):\n        for fn in dirs + files:\n            src_fn = os.path.join(src_dir, fn)\n            dst_fn = os.path.join(dst_dir, fn)\n\n            # skip temporary etc. files\n            if fn.startswith('.#') or fn.endswith('~'):\n                continue\n\n            # remove non-existing\n            if os.path.exists(dst_fn) and not os.path.exists(src_fn):\n                if clean:\n                    if os.path.isdir(dst_fn):\n                        shutil.rmtree(dst_fn)\n                    else:\n                        os.unlink(dst_fn)\n                continue\n\n            # make directories\n            if os.path.isdir(src_fn):\n                if not os.path.isdir(dst_fn):\n                    os.makedirs(dst_fn)\n                continue\n\n            dst_dir = os.path.dirname(dst_fn)\n            if os.path.isfile(dst_fn) and not os.path.isdir(dst_dir):\n                os.makedirs(dst_dir)\n\n            # don't replace up-to-date files\n            try:\n                if os.path.isfile(dst_fn) and \\\n                       os.stat(dst_fn).st_mtime >= os.stat(src_fn).st_mtime:\n                    continue\n            except OSError:\n                pass\n\n            # copy file\n            shutil.copyfile(src_fn, dst_fn)\n\n            # add .py files to 2to3 list\n            if dst_fn.endswith('.py'):\n                to_convert.append((src_fn, dst_fn))\n\n    # run 2to3\n    flag_sets = {}\n    for fn, dst_fn in to_convert:\n        flag = ''\n        for pat, opt in EXTRA_2TO3_FLAGS.items():\n            if fnmatch.fnmatch(fn, pat):\n                flag = opt\n                break\n        flag_sets.setdefault(flag, []).append(dst_fn)\n\n    if patchfile:\n        p = open(patchfile, 'wb+')\n    else:\n        p = open(os.devnull, 'wb')\n\n    for flags, filenames in flag_sets.items():\n        if flags == 'skip':\n            continue\n\n        _old_stdout = sys.stdout\n        try:\n            sys.stdout = StringIO()\n            opt = []\n            opt.extend(['-w', '-n'])\n            opt.extend(skip_fixes)\n            opt.extend(flags.split())\n            opt.extend(filenames)\n            lib2to3.main.main(\"lib2to3.fixes\", opt)\n        finally:\n            sys.stdout = _old_stdout\n\n    p.close()\n\nif __name__ == \"__main__\":\n    main()\n", "path": "tools/py3tool.py"}], "after_files": [{"content": "#!/usr/bin/env python3\n# -*- python -*-\n\"\"\"\n%prog SUBMODULE...\n\nHack to pipe submodules of Numpy through 2to3 and build them in-place\none-by-one.\n\nExample usage:\n\n    python3 tools/py3tool.py testing distutils core\n\nThis will copy files to _py3k/numpy, add a dummy __init__.py and\nversion.py on the top level, and copy and 2to3 the files of the three\nsubmodules.\n\nWhen running py3tool again, only changed files are re-processed, which\nmakes the test-bugfix cycle faster.\n\n\"\"\"\nfrom __future__ import division, absolute_import, print_function\n\nfrom optparse import OptionParser\nimport shutil\nimport os\nimport sys\nimport re\nimport subprocess\nimport fnmatch\n\nif os.environ.get('USE_2TO3CACHE'):\n    import lib2to3cache\n\nBASE = os.path.normpath(os.path.join(os.path.dirname(__file__), '..'))\nTEMP = os.path.normpath(os.path.join(BASE, '_py3k'))\n\nSCRIPT_2TO3 = os.path.join(BASE, 'tools', '2to3.py')\n\nEXTRA_2TO3_FLAGS = {\n    'numpy/core/defchararray.py': '-x unicode',\n    'numpy/compat/py3k.py': '-x unicode',\n    'numpy/ma/timer_comparison.py': 'skip',\n}\n\n# Names of fixers to skip when running 2to3.  This is a complete list of\n# available fixers, with fixers not currently skipped commented out.\nFIXES_TO_SKIP = [\n    'apply',\n#    'basestring',\n    'buffer',\n    'callable',\n    'dict',\n    'exec',\n    'execfile',\n    'exitfunc',\n    'filter',\n    'funcattrs',\n    'future',\n    'getcwdu',\n    'has_key',\n#    'idioms',\n    'import',\n    'imports',\n    'imports2',\n    'input',\n    'intern',\n#    'isinstance',\n#    'itertools',\n    'itertools_imports',\n#    'long',\n    'map',\n    'metaclass',\n    'methodattrs',\n    'ne',\n#    'next',\n#    'nonzero',\n#    'numliterals',\n    'operator',\n    'paren',\n    'print',\n    'raise',\n    'raw_input',\n    'reduce',\n#    'renames',\n    'repr',\n    'setliteral',\n    'standarderror',\n    'sys_exc',\n    'throw',\n    'tuple_params',\n#    'types',\n#    'unicode',\n#    'urllib',\n#    'ws_comma',\n    'xrange',\n    'xreadlines',\n#    'zip',\n]\n\nskip_fixes= []\nfor _t in FIXES_TO_SKIP:\n    skip_fixes.append('-x')\n    skip_fixes.append(_t)\n\n\ndef main():\n    p = OptionParser(usage=__doc__.strip())\n    p.add_option(\"--clean\", \"-c\", action=\"store_true\",\n                 help=\"clean source directory\")\n    options, args = p.parse_args()\n\n    if not args:\n        p.error('no submodules given')\n    else:\n        dirs = ['numpy/%s' % x for x in map(os.path.basename, args)]\n\n    # Prepare\n    if not os.path.isdir(TEMP):\n        os.makedirs(TEMP)\n\n    # Set up dummy files (for building only submodules)\n    dummy_files = {\n        '__init__.py': 'from numpy.version import version as __version__',\n        'version.py': 'version = \"1.4.0.dev\"'\n    }\n\n    for fn, content in dummy_files.items():\n        fn = os.path.join(TEMP, 'numpy', fn)\n        if not os.path.isfile(fn):\n            try:\n                os.makedirs(os.path.dirname(fn))\n            except OSError:\n                pass\n            f = open(fn, 'wb+')\n            f.write(content.encode('ascii'))\n            f.close()\n\n    # Environment\n    pp = [os.path.abspath(TEMP)]\n    def getenv():\n        env = dict(os.environ)\n        env.update({'PYTHONPATH': ':'.join(pp)})\n        return env\n\n    # Copy\n    for d in dirs:\n        src = os.path.join(BASE, d)\n        dst = os.path.join(TEMP, d)\n\n        # Run 2to3\n        sync_2to3(dst=dst,\n                  src=src,\n                  patchfile=os.path.join(TEMP, os.path.basename(d) + '.patch'),\n                  clean=options.clean)\n\n        # Run setup.py, falling back to Pdb post-mortem on exceptions\n        setup_py = os.path.join(dst, 'setup.py')\n        if os.path.isfile(setup_py):\n            code = \"\"\"\\\nimport pdb, sys, traceback\np = pdb.Pdb()\ntry:\n    import __main__\n    __main__.__dict__.update({\n        \"__name__\": \"__main__\", \"__file__\": \"setup.py\",\n        \"__builtins__\": __builtins__})\n    fp = open(\"setup.py\", \"rb\")\n    try:\n        exec(compile(fp.read(), \"setup.py\", 'exec'))\n    finally:\n        fp.close()\nexcept SystemExit:\n    raise\nexcept:\n    traceback.print_exc()\n    t = sys.exc_info()[2]\n    p.interaction(None, t)\n\"\"\"\n            ret = subprocess.call([sys.executable, '-c', code,\n                                   'build_ext', '-i'],\n                                  cwd=dst,\n                                  env=getenv())\n            if ret != 0:\n                raise RuntimeError(\"Build failed.\")\n\n        # Run nosetests\n        subprocess.call(['nosetests3', '-v', d], cwd=TEMP)\n\n\ndef walk_sync(dir1, dir2, _seen=None):\n    if _seen is None:\n        seen = {}\n    else:\n        seen = _seen\n\n    if not dir1.endswith(os.path.sep):\n        dir1 = dir1 + os.path.sep\n\n    # Walk through stuff (which we haven't yet gone through) in dir1\n    for root, dirs, files in os.walk(dir1):\n        sub = root[len(dir1):]\n        if sub in seen:\n            dirs = [x for x in dirs if x not in seen[sub][0]]\n            files = [x for x in files if x not in seen[sub][1]]\n            seen[sub][0].extend(dirs)\n            seen[sub][1].extend(files)\n        else:\n            seen[sub] = (dirs, files)\n        if not dirs and not files:\n            continue\n        yield os.path.join(dir1, sub), os.path.join(dir2, sub), dirs, files\n\n    if _seen is None:\n        # Walk through stuff (which we haven't yet gone through) in dir2\n        for root2, root1, dirs, files in walk_sync(dir2, dir1, _seen=seen):\n            yield root1, root2, dirs, files\n\ndef sync_2to3(src, dst, patchfile=None, clean=False):\n    import lib2to3.main\n    from io import StringIO\n\n    to_convert = []\n\n    for src_dir, dst_dir, dirs, files in walk_sync(src, dst):\n        for fn in dirs + files:\n            src_fn = os.path.join(src_dir, fn)\n            dst_fn = os.path.join(dst_dir, fn)\n\n            # skip temporary etc. files\n            if fn.startswith('.#') or fn.endswith('~'):\n                continue\n\n            # remove non-existing\n            if os.path.exists(dst_fn) and not os.path.exists(src_fn):\n                if clean:\n                    if os.path.isdir(dst_fn):\n                        shutil.rmtree(dst_fn)\n                    else:\n                        os.unlink(dst_fn)\n                continue\n\n            # make directories\n            if os.path.isdir(src_fn):\n                if not os.path.isdir(dst_fn):\n                    os.makedirs(dst_fn)\n                continue\n\n            dst_dir = os.path.dirname(dst_fn)\n            if os.path.isfile(dst_fn) and not os.path.isdir(dst_dir):\n                os.makedirs(dst_dir)\n\n            # don't replace up-to-date files\n            try:\n                if os.path.isfile(dst_fn) and \\\n                       os.stat(dst_fn).st_mtime >= os.stat(src_fn).st_mtime:\n                    continue\n            except OSError:\n                pass\n\n            # copy file\n            shutil.copyfile(src_fn, dst_fn)\n\n            # add .py files to 2to3 list\n            if dst_fn.endswith('.py'):\n                to_convert.append((src_fn, dst_fn))\n\n    # run 2to3\n    flag_sets = {}\n    for fn, dst_fn in to_convert:\n        flag = ''\n        for pat, opt in EXTRA_2TO3_FLAGS.items():\n            if fnmatch.fnmatch(fn, pat):\n                flag = opt\n                break\n        flag_sets.setdefault(flag, []).append(dst_fn)\n\n    if patchfile:\n        p = open(patchfile, 'wb+')\n    else:\n        p = open(os.devnull, 'wb')\n\n    for flags, filenames in flag_sets.items():\n        if flags == 'skip':\n            continue\n\n        _old_stdout = sys.stdout\n        try:\n            sys.stdout = StringIO()\n            opt = []\n            opt.extend(['-w', '-n'])\n            opt.extend(skip_fixes)\n            opt.extend(flags.split())\n            opt.extend(filenames)\n            lib2to3.main.main(\"lib2to3.fixes\", opt)\n        finally:\n            sys.stdout = _old_stdout\n\n    p.close()\n\nif __name__ == \"__main__\":\n    main()\n", "path": "tools/py3tool.py"}]}