We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Encoding issues on Windows build in the fix_staged_scripts step
Hello.

I'm trying to build the [waf package on windows](https://github.com/conda-forge/waf-feedstock/pull/4), but I'm having some trouble with ```conda_build``` in the ```fix_staged_scripts``` step. I couldn't find any similar issue. I'll follow with some details:

While building, there is a file named ```waf``` that is meant to be moved to the ```%SCRIPTS%``` folder. The problem seems to be that ```conda-build``` tries to read the file to do some checking, but fails to do so because of the file encoding (https://github.com/conda/conda-build/blob/master/conda_build/windows.py#L45)

I believe the waf file should be opened with encoding='iso-8859-1'. Making a local change replacing with the code bellow builds the package successfully, but is not a solution:

```
with open(join(scripts_dir, fn), encoding='iso-8859-1') as f:
```

Any suggestions here? I'm unsure how this case should be handled.
I'll leave some suggestions that occurred me:

1- Fix this at package level, by avoiding running into the ```fix_staged_scripts``` function, somehow. (I don't like this solution because it'll not really fix anything besides this specific package)

2- Do some try...catch with several encodings near the presented code above

3- Have a metadata somewhere (maybe in the recipe?) to handle the file encoding. Fallback to the current case if none.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `conda_build/windows.py`
Content:
```
1 from __future__ import absolute_import, division, print_function
2 
3 import os
4 import sys
5 from os.path import isdir, join, dirname, isfile
6 
7 import bs4
8 # importing setuptools patches distutils so that it knows how to find VC for python 2.7
9 import setuptools  # noqa
10 # Leverage the hard work done by setuptools/distutils to find vcvarsall using
11 # either the registry or the VS**COMNTOOLS environment variable
12 from distutils.msvc9compiler import find_vcvarsall as distutils_find_vcvarsall
13 from distutils.msvc9compiler import Reg, WINSDK_BASE
14 
15 from .conda_interface import bits
16 
17 from conda_build import environ
18 from conda_build.utils import check_call_env, root_script_dir, path_prepended, copy_into
19 
20 
21 assert sys.platform == 'win32'
22 
23 
24 VS_VERSION_STRING = {
25     '8.0': 'Visual Studio 8 2005',
26     '9.0': 'Visual Studio 9 2008',
27     '10.0': 'Visual Studio 10 2010',
28     '11.0': 'Visual Studio 11 2012',
29     '12.0': 'Visual Studio 12 2013',
30     '14.0': 'Visual Studio 14 2015'
31 }
32 
33 
34 def fix_staged_scripts(scripts_dir):
35     """
36     Fixes scripts which have been installed unix-style to have a .bat
37     helper
38     """
39     if not isdir(scripts_dir):
40         return
41     for fn in os.listdir(scripts_dir):
42         # process all the extensionless files
43         if not isfile(join(scripts_dir, fn)) or '.' in fn:
44             continue
45 
46         with open(join(scripts_dir, fn)) as f:
47             line = bs4.UnicodeDammit(f.readline()).unicode_markup.lower()
48             # If it's a #!python script
49             if not (line.startswith('#!') and 'python' in line.lower()):
50                 continue
51             print('Adjusting unix-style #! script %s, '
52                   'and adding a .bat file for it' % fn)
53             # copy it with a .py extension (skipping that first #! line)
54             with open(join(scripts_dir, fn + '-script.py'), 'w') as fo:
55                 fo.write(f.read())
56             # now create the .exe file
57             copy_into(join(dirname(__file__), 'cli-%d.exe' % bits),
58                             join(scripts_dir, fn + '.exe'))
59 
60         # remove the original script
61         os.remove(join(scripts_dir, fn))
62 
63 
64 def build_vcvarsall_vs_path(version):
65     """
66     Given the Visual Studio version, returns the default path to the
67     Microsoft Visual Studio vcvarsall.bat file.
68     Expected versions are of the form {9.0, 10.0, 12.0, 14.0}
69     """
70     # Set up a load of paths that can be imported from the tests
71     if 'ProgramFiles(x86)' in os.environ:
72         PROGRAM_FILES_PATH = os.environ['ProgramFiles(x86)']
73     else:
74         PROGRAM_FILES_PATH = os.environ['ProgramFiles']
75 
76     flatversion = str(version).replace('.', '')
77     vstools = "VS{0}COMNTOOLS".format(flatversion)
78 
79     if vstools in os.environ:
80         return os.path.join(os.environ[vstools], '..\\..\\VC\\vcvarsall.bat')
81     else:
82         # prefer looking at env var; fall back to program files defaults
83         return os.path.join(PROGRAM_FILES_PATH,
84                             'Microsoft Visual Studio {}'.format(version), 'VC',
85                             'vcvarsall.bat')
86 
87 
88 def msvc_env_cmd(bits, config, override=None):
89     arch_selector = 'x86' if bits == 32 else 'amd64'
90 
91     msvc_env_lines = []
92 
93     version = None
94     if override is not None:
95         version = override
96 
97     # The DISTUTILS_USE_SDK variable tells distutils to not try and validate
98     # the MSVC compiler. For < 3.5 this still forcibly looks for 'cl.exe'.
99     # For > 3.5 it literally just skips the validation logic.
100     # See distutils _msvccompiler.py and msvc9compiler.py / msvccompiler.py
101     # for more information.
102     msvc_env_lines.append('set DISTUTILS_USE_SDK=1')
103     # This is also required to hit the 'don't validate' logic on < 3.5.
104     # For > 3.5 this is ignored.
105     msvc_env_lines.append('set MSSdk=1')
106 
107     if not version:
108         if config.PY3K and config.use_MSVC2015:
109             version = '14.0'
110         elif config.PY3K:
111             version = '10.0'
112         else:
113             version = '9.0'
114 
115     if float(version) >= 14.0:
116         # For Python 3.5+, ensure that we link with the dynamic runtime.  See
117         # http://stevedower.id.au/blog/building-for-python-3-5-part-two/ for more info
118         msvc_env_lines.append('set PY_VCRUNTIME_REDIST=%LIBRARY_BIN%\\vcruntime{0}.dll'.format(
119             version.replace('.', '')))
120 
121     vcvarsall_vs_path = build_vcvarsall_vs_path(version)
122 
123     def build_vcvarsall_cmd(cmd, arch=arch_selector):
124         # Default argument `arch_selector` is defined above
125         return 'call "{cmd}" {arch}'.format(cmd=cmd, arch=arch)
126 
127     msvc_env_lines.append('set "VS_VERSION={}"'.format(version))
128     msvc_env_lines.append('set "VS_MAJOR={}"'.format(version.split('.')[0]))
129     msvc_env_lines.append('set "VS_YEAR={}"'.format(VS_VERSION_STRING[version][-4:]))
130     msvc_env_lines.append('set "CMAKE_GENERATOR={}"'.format(VS_VERSION_STRING[version] +
131                                                             {64: ' Win64', 32: ''}[bits]))
132     # tell msys2 to ignore path conversions for issue-causing windows-style flags in build
133     #   See https://github.com/conda-forge/icu-feedstock/pull/5
134     msvc_env_lines.append('set "MSYS2_ARG_CONV_EXCL=/AI;/AL;/OUT;/out"')
135     msvc_env_lines.append('set "MSYS2_ENV_CONV_EXCL=CL"')
136     if version == '10.0':
137         try:
138             WIN_SDK_71_PATH = Reg.get_value(os.path.join(WINSDK_BASE, 'v7.1'),
139                                             'installationfolder')
140             WIN_SDK_71_BAT_PATH = os.path.join(WIN_SDK_71_PATH, 'Bin', 'SetEnv.cmd')
141 
142             win_sdk_arch = '/Release /x86' if bits == 32 else '/Release /x64'
143             win_sdk_cmd = build_vcvarsall_cmd(WIN_SDK_71_BAT_PATH, arch=win_sdk_arch)
144 
145             # There are two methods of building Python 3.3 and 3.4 extensions (both
146             # of which required Visual Studio 2010 - as explained in the Python wiki
147             # https://wiki.python.org/moin/WindowsCompilers)
148             # 1) Use the Windows SDK 7.1
149             # 2) Use Visual Studio 2010 (any edition)
150             # However, VS2010 never shipped with a 64-bit compiler, so in this case
151             # **only** option (1) applies. For this reason, we always try and
152             # activate the Windows SDK first. Unfortunately, unsuccessfully setting
153             # up the environment does **not EXIT 1** and therefore we must fall
154             # back to attempting to set up VS2010.
155             # DelayedExpansion is required for the SetEnv.cmd
156             msvc_env_lines.append('Setlocal EnableDelayedExpansion')
157             msvc_env_lines.append(win_sdk_cmd)
158             # If the WindowsSDKDir environment variable has not been successfully
159             # set then try activating VS2010
160             msvc_env_lines.append('if not "%WindowsSDKDir%" == "{}" ( {} )'.format(
161                 WIN_SDK_71_PATH, build_vcvarsall_cmd(vcvarsall_vs_path)))
162         # sdk is not installed.  Fall back to only trying VS 2010
163         except KeyError:
164             msvc_env_lines.append(build_vcvarsall_cmd(vcvarsall_vs_path))
165     elif version == '9.0':
166         # Get the Visual Studio 2008 path (not the Visual C++ for Python path)
167         # and get the 'vcvars64.bat' from inside the bin (in the directory above
168         # that returned by distutils_find_vcvarsall)
169         try:
170             VCVARS64_VS9_BAT_PATH = os.path.join(os.path.dirname(distutils_find_vcvarsall(9)),
171                                                 'bin', 'vcvars64.bat')
172         # there's an exception if VS or the VC compiler for python are not actually installed.
173         except (KeyError, TypeError):
174             VCVARS64_VS9_BAT_PATH = None
175 
176         error1 = 'if errorlevel 1 {}'
177 
178         # Prefer VS9 proper over Microsoft Visual C++ Compiler for Python 2.7
179         msvc_env_lines.append(build_vcvarsall_cmd(vcvarsall_vs_path))
180         # The Visual Studio 2008 Express edition does not properly contain
181         # the amd64 build files, so we call the vcvars64.bat manually,
182         # rather than using the vcvarsall.bat which would try and call the
183         # missing bat file.
184         if arch_selector == 'amd64' and VCVARS64_VS9_BAT_PATH:
185             msvc_env_lines.append(error1.format(
186                 build_vcvarsall_cmd(VCVARS64_VS9_BAT_PATH)))
187         # Otherwise, fall back to icrosoft Visual C++ Compiler for Python 2.7+
188         # by using the logic provided by setuptools
189         msvc_env_lines.append(error1.format(
190             build_vcvarsall_cmd(distutils_find_vcvarsall(9))))
191     else:
192         # Visual Studio 14 or otherwise
193         msvc_env_lines.append(build_vcvarsall_cmd(vcvarsall_vs_path))
194 
195     return '\n'.join(msvc_env_lines) + '\n'
196 
197 
198 def build(m, bld_bat, config):
199     with path_prepended(config.build_prefix):
200         env = environ.get_dict(config=config, m=m)
201     env["CONDA_BUILD_STATE"] = "BUILD"
202 
203     for name in 'BIN', 'INC', 'LIB':
204         path = env['LIBRARY_' + name]
205         if not isdir(path):
206             os.makedirs(path)
207 
208     src_dir = config.work_dir
209     if os.path.isfile(bld_bat):
210         with open(bld_bat) as fi:
211             data = fi.read()
212         with open(join(src_dir, 'bld.bat'), 'w') as fo:
213             # more debuggable with echo on
214             fo.write('@echo on\n')
215             for key, value in env.items():
216                 fo.write('set "{key}={value}"\n'.format(key=key, value=value))
217             fo.write(msvc_env_cmd(bits=bits, config=config,
218                                   override=m.get_value('build/msvc_compiler', None)))
219             # Reset echo on, because MSVC scripts might have turned it off
220             fo.write('@echo on\n')
221             fo.write('set "INCLUDE={};%INCLUDE%"\n'.format(env["LIBRARY_INC"]))
222             fo.write('set "LIB={};%LIB%"\n'.format(env["LIBRARY_LIB"]))
223             if config.activate:
224                 fo.write('call "{conda_root}\\activate.bat" "{prefix}"\n'.format(
225                     conda_root=root_script_dir,
226                     prefix=config.build_prefix))
227             fo.write("REM ===== end generated header =====\n")
228             fo.write(data)
229 
230         cmd = ['cmd.exe', '/c', 'bld.bat']
231         check_call_env(cmd, cwd=src_dir)
232 
233     fix_staged_scripts(join(config.build_prefix, 'Scripts'))
234
```
--- 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/conda_build/windows.py b/conda_build/windows.py
--- a/conda_build/windows.py
+++ b/conda_build/windows.py
@@ -43,15 +43,16 @@
         if not isfile(join(scripts_dir, fn)) or '.' in fn:
             continue
 
-        with open(join(scripts_dir, fn)) as f:
-            line = bs4.UnicodeDammit(f.readline()).unicode_markup.lower()
+        # read as binary file to ensure we don't run into encoding errors, see #1632
+        with open(join(scripts_dir, fn), 'rb') as f:
+            line = f.readline()
             # If it's a #!python script
-            if not (line.startswith('#!') and 'python' in line.lower()):
+            if not (line.startswith(b'#!') and b'python' in line.lower()):
                 continue
             print('Adjusting unix-style #! script %s, '
                   'and adding a .bat file for it' % fn)
             # copy it with a .py extension (skipping that first #! line)
-            with open(join(scripts_dir, fn + '-script.py'), 'w') as fo:
+            with open(join(scripts_dir, fn + '-script.py'), 'wb') as fo:
                 fo.write(f.read())
             # now create the .exe file
             copy_into(join(dirname(__file__), 'cli-%d.exe' % bits),

{"golden_diff": "diff --git a/conda_build/windows.py b/conda_build/windows.py\n--- a/conda_build/windows.py\n+++ b/conda_build/windows.py\n@@ -43,15 +43,16 @@\n         if not isfile(join(scripts_dir, fn)) or '.' in fn:\n             continue\n \n-        with open(join(scripts_dir, fn)) as f:\n-            line = bs4.UnicodeDammit(f.readline()).unicode_markup.lower()\n+        # read as binary file to ensure we don't run into encoding errors, see #1632\n+        with open(join(scripts_dir, fn), 'rb') as f:\n+            line = f.readline()\n             # If it's a #!python script\n-            if not (line.startswith('#!') and 'python' in line.lower()):\n+            if not (line.startswith(b'#!') and b'python' in line.lower()):\n                 continue\n             print('Adjusting unix-style #! script %s, '\n                   'and adding a .bat file for it' % fn)\n             # copy it with a .py extension (skipping that first #! line)\n-            with open(join(scripts_dir, fn + '-script.py'), 'w') as fo:\n+            with open(join(scripts_dir, fn + '-script.py'), 'wb') as fo:\n                 fo.write(f.read())\n             # now create the .exe file\n             copy_into(join(dirname(__file__), 'cli-%d.exe' % bits),\n", "issue": "Encoding issues on Windows build in the fix_staged_scripts step\nHello.\r\n\r\nI'm trying to build the [waf package on windows](https://github.com/conda-forge/waf-feedstock/pull/4), but I'm having some trouble with ```conda_build``` in the ```fix_staged_scripts``` step. I couldn't find any similar issue. I'll follow with some details:\r\n\r\nWhile building, there is a file named ```waf``` that is meant to be moved to the ```%SCRIPTS%``` folder. The problem seems to be that ```conda-build``` tries to read the file to do some checking, but fails to do so because of the file encoding (https://github.com/conda/conda-build/blob/master/conda_build/windows.py#L45)\r\n\r\nI believe the waf file should be opened with encoding='iso-8859-1'. Making a local change replacing with the code bellow builds the package successfully, but is not a solution:\r\n\r\n```\r\nwith open(join(scripts_dir, fn), encoding='iso-8859-1') as f:\r\n```\r\n\r\nAny suggestions here? I'm unsure how this case should be handled.\r\nI'll leave some suggestions that occurred me:\r\n\r\n1- Fix this at package level, by avoiding running into the ```fix_staged_scripts``` function, somehow. (I don't like this solution because it'll not really fix anything besides this specific package)\r\n\r\n2- Do some try...catch with several encodings near the presented code above\r\n\r\n3- Have a metadata somewhere (maybe in the recipe?) to handle the file encoding. Fallback to the current case if none.\n", "before_files": [{"content": "from __future__ import absolute_import, division, print_function\n\nimport os\nimport sys\nfrom os.path import isdir, join, dirname, isfile\n\nimport bs4\n# importing setuptools patches distutils so that it knows how to find VC for python 2.7\nimport setuptools  # noqa\n# Leverage the hard work done by setuptools/distutils to find vcvarsall using\n# either the registry or the VS**COMNTOOLS environment variable\nfrom distutils.msvc9compiler import find_vcvarsall as distutils_find_vcvarsall\nfrom distutils.msvc9compiler import Reg, WINSDK_BASE\n\nfrom .conda_interface import bits\n\nfrom conda_build import environ\nfrom conda_build.utils import check_call_env, root_script_dir, path_prepended, copy_into\n\n\nassert sys.platform == 'win32'\n\n\nVS_VERSION_STRING = {\n    '8.0': 'Visual Studio 8 2005',\n    '9.0': 'Visual Studio 9 2008',\n    '10.0': 'Visual Studio 10 2010',\n    '11.0': 'Visual Studio 11 2012',\n    '12.0': 'Visual Studio 12 2013',\n    '14.0': 'Visual Studio 14 2015'\n}\n\n\ndef fix_staged_scripts(scripts_dir):\n    \"\"\"\n    Fixes scripts which have been installed unix-style to have a .bat\n    helper\n    \"\"\"\n    if not isdir(scripts_dir):\n        return\n    for fn in os.listdir(scripts_dir):\n        # process all the extensionless files\n        if not isfile(join(scripts_dir, fn)) or '.' in fn:\n            continue\n\n        with open(join(scripts_dir, fn)) as f:\n            line = bs4.UnicodeDammit(f.readline()).unicode_markup.lower()\n            # If it's a #!python script\n            if not (line.startswith('#!') and 'python' in line.lower()):\n                continue\n            print('Adjusting unix-style #! script %s, '\n                  'and adding a .bat file for it' % fn)\n            # copy it with a .py extension (skipping that first #! line)\n            with open(join(scripts_dir, fn + '-script.py'), 'w') as fo:\n                fo.write(f.read())\n            # now create the .exe file\n            copy_into(join(dirname(__file__), 'cli-%d.exe' % bits),\n                            join(scripts_dir, fn + '.exe'))\n\n        # remove the original script\n        os.remove(join(scripts_dir, fn))\n\n\ndef build_vcvarsall_vs_path(version):\n    \"\"\"\n    Given the Visual Studio version, returns the default path to the\n    Microsoft Visual Studio vcvarsall.bat file.\n    Expected versions are of the form {9.0, 10.0, 12.0, 14.0}\n    \"\"\"\n    # Set up a load of paths that can be imported from the tests\n    if 'ProgramFiles(x86)' in os.environ:\n        PROGRAM_FILES_PATH = os.environ['ProgramFiles(x86)']\n    else:\n        PROGRAM_FILES_PATH = os.environ['ProgramFiles']\n\n    flatversion = str(version).replace('.', '')\n    vstools = \"VS{0}COMNTOOLS\".format(flatversion)\n\n    if vstools in os.environ:\n        return os.path.join(os.environ[vstools], '..\\\\..\\\\VC\\\\vcvarsall.bat')\n    else:\n        # prefer looking at env var; fall back to program files defaults\n        return os.path.join(PROGRAM_FILES_PATH,\n                            'Microsoft Visual Studio {}'.format(version), 'VC',\n                            'vcvarsall.bat')\n\n\ndef msvc_env_cmd(bits, config, override=None):\n    arch_selector = 'x86' if bits == 32 else 'amd64'\n\n    msvc_env_lines = []\n\n    version = None\n    if override is not None:\n        version = override\n\n    # The DISTUTILS_USE_SDK variable tells distutils to not try and validate\n    # the MSVC compiler. For < 3.5 this still forcibly looks for 'cl.exe'.\n    # For > 3.5 it literally just skips the validation logic.\n    # See distutils _msvccompiler.py and msvc9compiler.py / msvccompiler.py\n    # for more information.\n    msvc_env_lines.append('set DISTUTILS_USE_SDK=1')\n    # This is also required to hit the 'don't validate' logic on < 3.5.\n    # For > 3.5 this is ignored.\n    msvc_env_lines.append('set MSSdk=1')\n\n    if not version:\n        if config.PY3K and config.use_MSVC2015:\n            version = '14.0'\n        elif config.PY3K:\n            version = '10.0'\n        else:\n            version = '9.0'\n\n    if float(version) >= 14.0:\n        # For Python 3.5+, ensure that we link with the dynamic runtime.  See\n        # http://stevedower.id.au/blog/building-for-python-3-5-part-two/ for more info\n        msvc_env_lines.append('set PY_VCRUNTIME_REDIST=%LIBRARY_BIN%\\\\vcruntime{0}.dll'.format(\n            version.replace('.', '')))\n\n    vcvarsall_vs_path = build_vcvarsall_vs_path(version)\n\n    def build_vcvarsall_cmd(cmd, arch=arch_selector):\n        # Default argument `arch_selector` is defined above\n        return 'call \"{cmd}\" {arch}'.format(cmd=cmd, arch=arch)\n\n    msvc_env_lines.append('set \"VS_VERSION={}\"'.format(version))\n    msvc_env_lines.append('set \"VS_MAJOR={}\"'.format(version.split('.')[0]))\n    msvc_env_lines.append('set \"VS_YEAR={}\"'.format(VS_VERSION_STRING[version][-4:]))\n    msvc_env_lines.append('set \"CMAKE_GENERATOR={}\"'.format(VS_VERSION_STRING[version] +\n                                                            {64: ' Win64', 32: ''}[bits]))\n    # tell msys2 to ignore path conversions for issue-causing windows-style flags in build\n    #   See https://github.com/conda-forge/icu-feedstock/pull/5\n    msvc_env_lines.append('set \"MSYS2_ARG_CONV_EXCL=/AI;/AL;/OUT;/out\"')\n    msvc_env_lines.append('set \"MSYS2_ENV_CONV_EXCL=CL\"')\n    if version == '10.0':\n        try:\n            WIN_SDK_71_PATH = Reg.get_value(os.path.join(WINSDK_BASE, 'v7.1'),\n                                            'installationfolder')\n            WIN_SDK_71_BAT_PATH = os.path.join(WIN_SDK_71_PATH, 'Bin', 'SetEnv.cmd')\n\n            win_sdk_arch = '/Release /x86' if bits == 32 else '/Release /x64'\n            win_sdk_cmd = build_vcvarsall_cmd(WIN_SDK_71_BAT_PATH, arch=win_sdk_arch)\n\n            # There are two methods of building Python 3.3 and 3.4 extensions (both\n            # of which required Visual Studio 2010 - as explained in the Python wiki\n            # https://wiki.python.org/moin/WindowsCompilers)\n            # 1) Use the Windows SDK 7.1\n            # 2) Use Visual Studio 2010 (any edition)\n            # However, VS2010 never shipped with a 64-bit compiler, so in this case\n            # **only** option (1) applies. For this reason, we always try and\n            # activate the Windows SDK first. Unfortunately, unsuccessfully setting\n            # up the environment does **not EXIT 1** and therefore we must fall\n            # back to attempting to set up VS2010.\n            # DelayedExpansion is required for the SetEnv.cmd\n            msvc_env_lines.append('Setlocal EnableDelayedExpansion')\n            msvc_env_lines.append(win_sdk_cmd)\n            # If the WindowsSDKDir environment variable has not been successfully\n            # set then try activating VS2010\n            msvc_env_lines.append('if not \"%WindowsSDKDir%\" == \"{}\" ( {} )'.format(\n                WIN_SDK_71_PATH, build_vcvarsall_cmd(vcvarsall_vs_path)))\n        # sdk is not installed.  Fall back to only trying VS 2010\n        except KeyError:\n            msvc_env_lines.append(build_vcvarsall_cmd(vcvarsall_vs_path))\n    elif version == '9.0':\n        # Get the Visual Studio 2008 path (not the Visual C++ for Python path)\n        # and get the 'vcvars64.bat' from inside the bin (in the directory above\n        # that returned by distutils_find_vcvarsall)\n        try:\n            VCVARS64_VS9_BAT_PATH = os.path.join(os.path.dirname(distutils_find_vcvarsall(9)),\n                                                'bin', 'vcvars64.bat')\n        # there's an exception if VS or the VC compiler for python are not actually installed.\n        except (KeyError, TypeError):\n            VCVARS64_VS9_BAT_PATH = None\n\n        error1 = 'if errorlevel 1 {}'\n\n        # Prefer VS9 proper over Microsoft Visual C++ Compiler for Python 2.7\n        msvc_env_lines.append(build_vcvarsall_cmd(vcvarsall_vs_path))\n        # The Visual Studio 2008 Express edition does not properly contain\n        # the amd64 build files, so we call the vcvars64.bat manually,\n        # rather than using the vcvarsall.bat which would try and call the\n        # missing bat file.\n        if arch_selector == 'amd64' and VCVARS64_VS9_BAT_PATH:\n            msvc_env_lines.append(error1.format(\n                build_vcvarsall_cmd(VCVARS64_VS9_BAT_PATH)))\n        # Otherwise, fall back to icrosoft Visual C++ Compiler for Python 2.7+\n        # by using the logic provided by setuptools\n        msvc_env_lines.append(error1.format(\n            build_vcvarsall_cmd(distutils_find_vcvarsall(9))))\n    else:\n        # Visual Studio 14 or otherwise\n        msvc_env_lines.append(build_vcvarsall_cmd(vcvarsall_vs_path))\n\n    return '\\n'.join(msvc_env_lines) + '\\n'\n\n\ndef build(m, bld_bat, config):\n    with path_prepended(config.build_prefix):\n        env = environ.get_dict(config=config, m=m)\n    env[\"CONDA_BUILD_STATE\"] = \"BUILD\"\n\n    for name in 'BIN', 'INC', 'LIB':\n        path = env['LIBRARY_' + name]\n        if not isdir(path):\n            os.makedirs(path)\n\n    src_dir = config.work_dir\n    if os.path.isfile(bld_bat):\n        with open(bld_bat) as fi:\n            data = fi.read()\n        with open(join(src_dir, 'bld.bat'), 'w') as fo:\n            # more debuggable with echo on\n            fo.write('@echo on\\n')\n            for key, value in env.items():\n                fo.write('set \"{key}={value}\"\\n'.format(key=key, value=value))\n            fo.write(msvc_env_cmd(bits=bits, config=config,\n                                  override=m.get_value('build/msvc_compiler', None)))\n            # Reset echo on, because MSVC scripts might have turned it off\n            fo.write('@echo on\\n')\n            fo.write('set \"INCLUDE={};%INCLUDE%\"\\n'.format(env[\"LIBRARY_INC\"]))\n            fo.write('set \"LIB={};%LIB%\"\\n'.format(env[\"LIBRARY_LIB\"]))\n            if config.activate:\n                fo.write('call \"{conda_root}\\\\activate.bat\" \"{prefix}\"\\n'.format(\n                    conda_root=root_script_dir,\n                    prefix=config.build_prefix))\n            fo.write(\"REM ===== end generated header =====\\n\")\n            fo.write(data)\n\n        cmd = ['cmd.exe', '/c', 'bld.bat']\n        check_call_env(cmd, cwd=src_dir)\n\n    fix_staged_scripts(join(config.build_prefix, 'Scripts'))\n", "path": "conda_build/windows.py"}], "after_files": [{"content": "from __future__ import absolute_import, division, print_function\n\nimport os\nimport sys\nfrom os.path import isdir, join, dirname, isfile\n\nimport bs4\n# importing setuptools patches distutils so that it knows how to find VC for python 2.7\nimport setuptools  # noqa\n# Leverage the hard work done by setuptools/distutils to find vcvarsall using\n# either the registry or the VS**COMNTOOLS environment variable\nfrom distutils.msvc9compiler import find_vcvarsall as distutils_find_vcvarsall\nfrom distutils.msvc9compiler import Reg, WINSDK_BASE\n\nfrom .conda_interface import bits\n\nfrom conda_build import environ\nfrom conda_build.utils import check_call_env, root_script_dir, path_prepended, copy_into\n\n\nassert sys.platform == 'win32'\n\n\nVS_VERSION_STRING = {\n    '8.0': 'Visual Studio 8 2005',\n    '9.0': 'Visual Studio 9 2008',\n    '10.0': 'Visual Studio 10 2010',\n    '11.0': 'Visual Studio 11 2012',\n    '12.0': 'Visual Studio 12 2013',\n    '14.0': 'Visual Studio 14 2015'\n}\n\n\ndef fix_staged_scripts(scripts_dir):\n    \"\"\"\n    Fixes scripts which have been installed unix-style to have a .bat\n    helper\n    \"\"\"\n    if not isdir(scripts_dir):\n        return\n    for fn in os.listdir(scripts_dir):\n        # process all the extensionless files\n        if not isfile(join(scripts_dir, fn)) or '.' in fn:\n            continue\n\n        # read as binary file to ensure we don't run into encoding errors, see #1632\n        with open(join(scripts_dir, fn), 'rb') as f:\n            line = f.readline()\n            # If it's a #!python script\n            if not (line.startswith(b'#!') and b'python' in line.lower()):\n                continue\n            print('Adjusting unix-style #! script %s, '\n                  'and adding a .bat file for it' % fn)\n            # copy it with a .py extension (skipping that first #! line)\n            with open(join(scripts_dir, fn + '-script.py'), 'wb') as fo:\n                fo.write(f.read())\n            # now create the .exe file\n            copy_into(join(dirname(__file__), 'cli-%d.exe' % bits),\n                            join(scripts_dir, fn + '.exe'))\n\n        # remove the original script\n        os.remove(join(scripts_dir, fn))\n\n\ndef build_vcvarsall_vs_path(version):\n    \"\"\"\n    Given the Visual Studio version, returns the default path to the\n    Microsoft Visual Studio vcvarsall.bat file.\n    Expected versions are of the form {9.0, 10.0, 12.0, 14.0}\n    \"\"\"\n    # Set up a load of paths that can be imported from the tests\n    if 'ProgramFiles(x86)' in os.environ:\n        PROGRAM_FILES_PATH = os.environ['ProgramFiles(x86)']\n    else:\n        PROGRAM_FILES_PATH = os.environ['ProgramFiles']\n\n    flatversion = str(version).replace('.', '')\n    vstools = \"VS{0}COMNTOOLS\".format(flatversion)\n\n    if vstools in os.environ:\n        return os.path.join(os.environ[vstools], '..\\\\..\\\\VC\\\\vcvarsall.bat')\n    else:\n        # prefer looking at env var; fall back to program files defaults\n        return os.path.join(PROGRAM_FILES_PATH,\n                            'Microsoft Visual Studio {}'.format(version), 'VC',\n                            'vcvarsall.bat')\n\n\ndef msvc_env_cmd(bits, config, override=None):\n    arch_selector = 'x86' if bits == 32 else 'amd64'\n\n    msvc_env_lines = []\n\n    version = None\n    if override is not None:\n        version = override\n\n    # The DISTUTILS_USE_SDK variable tells distutils to not try and validate\n    # the MSVC compiler. For < 3.5 this still forcibly looks for 'cl.exe'.\n    # For > 3.5 it literally just skips the validation logic.\n    # See distutils _msvccompiler.py and msvc9compiler.py / msvccompiler.py\n    # for more information.\n    msvc_env_lines.append('set DISTUTILS_USE_SDK=1')\n    # This is also required to hit the 'don't validate' logic on < 3.5.\n    # For > 3.5 this is ignored.\n    msvc_env_lines.append('set MSSdk=1')\n\n    if not version:\n        if config.PY3K and config.use_MSVC2015:\n            version = '14.0'\n        elif config.PY3K:\n            version = '10.0'\n        else:\n            version = '9.0'\n\n    if float(version) >= 14.0:\n        # For Python 3.5+, ensure that we link with the dynamic runtime.  See\n        # http://stevedower.id.au/blog/building-for-python-3-5-part-two/ for more info\n        msvc_env_lines.append('set PY_VCRUNTIME_REDIST=%LIBRARY_BIN%\\\\vcruntime{0}.dll'.format(\n            version.replace('.', '')))\n\n    vcvarsall_vs_path = build_vcvarsall_vs_path(version)\n\n    def build_vcvarsall_cmd(cmd, arch=arch_selector):\n        # Default argument `arch_selector` is defined above\n        return 'call \"{cmd}\" {arch}'.format(cmd=cmd, arch=arch)\n\n    msvc_env_lines.append('set \"VS_VERSION={}\"'.format(version))\n    msvc_env_lines.append('set \"VS_MAJOR={}\"'.format(version.split('.')[0]))\n    msvc_env_lines.append('set \"VS_YEAR={}\"'.format(VS_VERSION_STRING[version][-4:]))\n    msvc_env_lines.append('set \"CMAKE_GENERATOR={}\"'.format(VS_VERSION_STRING[version] +\n                                                            {64: ' Win64', 32: ''}[bits]))\n    # tell msys2 to ignore path conversions for issue-causing windows-style flags in build\n    #   See https://github.com/conda-forge/icu-feedstock/pull/5\n    msvc_env_lines.append('set \"MSYS2_ARG_CONV_EXCL=/AI;/AL;/OUT;/out;%MSYS2_ARG_CONV_EXCL%\"')\n    msvc_env_lines.append('set \"MSYS2_ENV_CONV_EXCL=CL\"')\n    if version == '10.0':\n        try:\n            WIN_SDK_71_PATH = Reg.get_value(os.path.join(WINSDK_BASE, 'v7.1'),\n                                            'installationfolder')\n            WIN_SDK_71_BAT_PATH = os.path.join(WIN_SDK_71_PATH, 'Bin', 'SetEnv.cmd')\n\n            win_sdk_arch = '/Release /x86' if bits == 32 else '/Release /x64'\n            win_sdk_cmd = build_vcvarsall_cmd(WIN_SDK_71_BAT_PATH, arch=win_sdk_arch)\n\n            # There are two methods of building Python 3.3 and 3.4 extensions (both\n            # of which required Visual Studio 2010 - as explained in the Python wiki\n            # https://wiki.python.org/moin/WindowsCompilers)\n            # 1) Use the Windows SDK 7.1\n            # 2) Use Visual Studio 2010 (any edition)\n            # However, VS2010 never shipped with a 64-bit compiler, so in this case\n            # **only** option (1) applies. For this reason, we always try and\n            # activate the Windows SDK first. Unfortunately, unsuccessfully setting\n            # up the environment does **not EXIT 1** and therefore we must fall\n            # back to attempting to set up VS2010.\n            # DelayedExpansion is required for the SetEnv.cmd\n            msvc_env_lines.append('Setlocal EnableDelayedExpansion')\n            msvc_env_lines.append(win_sdk_cmd)\n            # If the WindowsSDKDir environment variable has not been successfully\n            # set then try activating VS2010\n            msvc_env_lines.append('if not \"%WindowsSDKDir%\" == \"{}\" ( {} )'.format(\n                WIN_SDK_71_PATH, build_vcvarsall_cmd(vcvarsall_vs_path)))\n        # sdk is not installed.  Fall back to only trying VS 2010\n        except KeyError:\n            msvc_env_lines.append(build_vcvarsall_cmd(vcvarsall_vs_path))\n    elif version == '9.0':\n        # Get the Visual Studio 2008 path (not the Visual C++ for Python path)\n        # and get the 'vcvars64.bat' from inside the bin (in the directory above\n        # that returned by distutils_find_vcvarsall)\n        try:\n            VCVARS64_VS9_BAT_PATH = os.path.join(os.path.dirname(distutils_find_vcvarsall(9)),\n                                                'bin', 'vcvars64.bat')\n        # there's an exception if VS or the VC compiler for python are not actually installed.\n        except (KeyError, TypeError):\n            VCVARS64_VS9_BAT_PATH = None\n\n        error1 = 'if errorlevel 1 {}'\n\n        # Prefer VS9 proper over Microsoft Visual C++ Compiler for Python 2.7\n        msvc_env_lines.append(build_vcvarsall_cmd(vcvarsall_vs_path))\n        # The Visual Studio 2008 Express edition does not properly contain\n        # the amd64 build files, so we call the vcvars64.bat manually,\n        # rather than using the vcvarsall.bat which would try and call the\n        # missing bat file.\n        if arch_selector == 'amd64' and VCVARS64_VS9_BAT_PATH:\n            msvc_env_lines.append(error1.format(\n                build_vcvarsall_cmd(VCVARS64_VS9_BAT_PATH)))\n        # Otherwise, fall back to icrosoft Visual C++ Compiler for Python 2.7+\n        # by using the logic provided by setuptools\n        msvc_env_lines.append(error1.format(\n            build_vcvarsall_cmd(distutils_find_vcvarsall(9))))\n    else:\n        # Visual Studio 14 or otherwise\n        msvc_env_lines.append(build_vcvarsall_cmd(vcvarsall_vs_path))\n\n    return '\\n'.join(msvc_env_lines) + '\\n'\n\n\ndef build(m, bld_bat, config):\n    with path_prepended(config.build_prefix):\n        env = environ.get_dict(config=config, m=m)\n    env[\"CONDA_BUILD_STATE\"] = \"BUILD\"\n\n    for name in 'BIN', 'INC', 'LIB':\n        path = env['LIBRARY_' + name]\n        if not isdir(path):\n            os.makedirs(path)\n\n    src_dir = config.work_dir\n    if os.path.isfile(bld_bat):\n        with open(bld_bat) as fi:\n            data = fi.read()\n        with open(join(src_dir, 'bld.bat'), 'w') as fo:\n            # more debuggable with echo on\n            fo.write('@echo on\\n')\n            for key, value in env.items():\n                fo.write('set \"{key}={value}\"\\n'.format(key=key, value=value))\n            fo.write(msvc_env_cmd(bits=bits, config=config,\n                                  override=m.get_value('build/msvc_compiler', None)))\n            # Reset echo on, because MSVC scripts might have turned it off\n            fo.write('@echo on\\n')\n            fo.write('set \"INCLUDE={};%INCLUDE%\"\\n'.format(env[\"LIBRARY_INC\"]))\n            fo.write('set \"LIB={};%LIB%\"\\n'.format(env[\"LIBRARY_LIB\"]))\n            if config.activate:\n                fo.write('call \"{conda_root}\\\\activate.bat\" \"{prefix}\"\\n'.format(\n                    conda_root=root_script_dir,\n                    prefix=config.build_prefix))\n            fo.write(\"REM ===== end generated header =====\\n\")\n            fo.write(data)\n\n        cmd = ['cmd.exe', '/c', 'bld.bat']\n        check_call_env(cmd, cwd=src_dir)\n\n    fix_staged_scripts(join(config.build_prefix, 'Scripts'))\n", "path": "conda_build/windows.py"}]}