We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Unable to build source.git_url based build recipes
See for an example: https://binstar.org/conda/conda-env/builds/2/3


--- 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/source.py`
Content:
```
1 from __future__ import absolute_import, division, print_function
2 
3 import os
4 import sys
5 from os.path import join, isdir, isfile, abspath, expanduser
6 from shutil import copytree, ignore_patterns, copy2
7 from subprocess import check_call, Popen, PIPE
8 
9 from conda.fetch import download
10 from conda.utils import hashsum_file
11 
12 from conda_build import external
13 from conda_build.config import config
14 from conda_build.utils import rm_rf, tar_xf, unzip
15 
16 
17 SRC_CACHE = join(config.croot, 'src_cache')
18 GIT_CACHE = join(config.croot, 'git_cache')
19 HG_CACHE = join(config.croot, 'hg_cache')
20 SVN_CACHE = join(config.croot, 'svn_cache')
21 WORK_DIR = join(config.croot, 'work')
22 
23 
24 def get_dir():
25     if not isdir(WORK_DIR):
26         os.makedirs(WORK_DIR)
27     lst = [fn for fn in os.listdir(WORK_DIR) if not fn.startswith('.')]
28     if len(lst) == 1:
29         dir_path = join(WORK_DIR, lst[0])
30         if isdir(dir_path):
31             return dir_path
32     return WORK_DIR
33 
34 
35 def download_to_cache(meta):
36     ''' Download a source to the local cache. '''
37     print('Source cache directory is: %s' % SRC_CACHE)
38     if not isdir(SRC_CACHE):
39         os.makedirs(SRC_CACHE)
40 
41     fn = meta['fn']
42     path = join(SRC_CACHE, fn)
43 
44     if isfile(path):
45         print('Found source in cache: %s' % fn)
46     else:
47         print('Downloading source to cache: %s' % fn)
48         download(meta['url'], path)
49 
50     for tp in 'md5', 'sha1', 'sha256':
51         if meta.get(tp) and hashsum_file(path, tp) != meta[tp]:
52             raise RuntimeError("%s mismatch: '%s' != '%s'" %
53                                (tp.upper(), hashsum_file(path, tp), meta[tp]))
54 
55     return path
56 
57 
58 def unpack(meta):
59     ''' Uncompress a downloaded source. '''
60     src_path = download_to_cache(meta)
61 
62     os.makedirs(WORK_DIR)
63     print("Extracting download")
64     if src_path.lower().endswith(('.tar.gz', '.tar.bz2', '.tgz', '.tar.xz', '.tar')):
65         tar_xf(src_path, WORK_DIR)
66     elif src_path.lower().endswith('.zip'):
67         unzip(src_path, WORK_DIR)
68     else:
69         # In this case, the build script will need to deal with unpacking the source
70         print("Warning: Unrecognized source format. Source file will be copied to the SRC_DIR")
71         copy2(src_path, WORK_DIR)
72 
73 
74 def git_source(meta, recipe_dir):
75     ''' Download a source from Git repo. '''
76     if not isdir(GIT_CACHE):
77         os.makedirs(GIT_CACHE)
78 
79     git = external.find_executable('git')
80     if not git:
81         sys.exit("Error: git is not installed")
82     git_url = meta['git_url']
83     if git_url.startswith('.'):
84         # It's a relative path from the conda recipe
85         os.chdir(recipe_dir)
86         git_dn = abspath(expanduser(git_url)).replace('/', '_')
87     else:
88         git_dn = git_url.split(':')[-1].replace('/', '_')
89     cache_repo = cache_repo_arg = join(GIT_CACHE, git_dn)
90     if sys.platform == 'win32':
91         cache_repo_arg = cache_repo_arg.replace('\\', '/')
92         if os.getenv('USERNAME') == 'builder':
93             cache_repo_arg = '/cygdrive/c/' + cache_repo_arg[3:]
94 
95     # update (or create) the cache repo
96     if isdir(cache_repo):
97         check_call([git, 'fetch'], cwd=cache_repo)
98     else:
99         check_call([git, 'clone', '--mirror', git_url, cache_repo_arg], cwd=recipe_dir)
100         assert isdir(cache_repo)
101 
102     # now clone into the work directory
103     checkout = meta.get('git_rev')
104     # if rev is not specified, and the git_url is local,
105     # assume the user wants the current HEAD
106     if not checkout and git_url.startswith('.'):
107         process = Popen(["git", "rev-parse", "HEAD"],
108                     stdout=PIPE, stderr=PIPE,
109                                cwd=git_url)
110         output = process.communicate()[0].strip()
111         checkout = output.decode('utf-8')
112     if checkout:
113         print('checkout: %r' % checkout)
114 
115     check_call([git, 'clone', cache_repo_arg, WORK_DIR])
116     if checkout:
117         check_call([git, 'checkout', checkout], cwd=WORK_DIR)
118 
119     git_info()
120     return WORK_DIR
121 
122 
123 def git_info(fo=None):
124     ''' Print info about a Git repo. '''
125     assert isdir(WORK_DIR)
126 
127     # Ensure to explicitly set GIT_DIR as some Linux machines will not
128     # properly execute without it.
129     env = os.environ.copy()
130     env['GIT_DIR'] = join(WORK_DIR, '.git')
131     env = {str(key): str(value) for key, value in env.items()}
132     for cmd, check_error in [
133                 ('git log -n1', True),
134                 ('git describe --tags --dirty', False),
135                 ('git status', True)]:
136         p = Popen(cmd.split(), stdout=PIPE, stderr=PIPE, cwd=WORK_DIR, env=env)
137         stdout, stderr = p.communicate()
138         stdout = stdout.decode('utf-8')
139         stderr = stderr.decode('utf-8')
140         if check_error and stderr and stderr.strip():
141             raise Exception("git error: %s" % stderr)
142         if fo:
143             fo.write(u'==> %s <==\n' % cmd)
144             fo.write(stdout + u'\n')
145         else:
146             print(u'==> %s <==\n' % cmd)
147             print(stdout + u'\n')
148 
149 
150 def hg_source(meta):
151     ''' Download a source from Mercurial repo. '''
152     hg = external.find_executable('hg')
153     if not hg:
154         sys.exit('Error: hg not installed')
155     hg_url = meta['hg_url']
156     if not isdir(HG_CACHE):
157         os.makedirs(HG_CACHE)
158     hg_dn = hg_url.split(':')[-1].replace('/', '_')
159     cache_repo = join(HG_CACHE, hg_dn)
160     if isdir(cache_repo):
161         check_call([hg, 'pull'], cwd=cache_repo)
162     else:
163         check_call([hg, 'clone', hg_url, cache_repo])
164         assert isdir(cache_repo)
165 
166     # now clone in to work directory
167     update = meta.get('hg_tag') or 'tip'
168     print('checkout: %r' % update)
169 
170     check_call([hg, 'clone', cache_repo, WORK_DIR])
171     check_call([hg, 'update', '-C', update], cwd=WORK_DIR)
172     return WORK_DIR
173 
174 
175 
176 def svn_source(meta):
177     ''' Download a source from SVN repo. '''
178     def parse_bool(s):
179         return str(s).lower().strip() in ('yes', 'true', '1', 'on')
180 
181     svn = external.find_executable('svn')
182     if not svn:
183         sys.exit("Error: svn is not installed")
184     svn_url = meta['svn_url']
185     svn_revision = meta.get('svn_rev') or 'head'
186     svn_ignore_externals = parse_bool(meta.get('svn_ignore_externals') or 'no')
187     if not isdir(SVN_CACHE):
188         os.makedirs(SVN_CACHE)
189     svn_dn = svn_url.split(':', 1)[-1].replace('/', '_').replace(':', '_')
190     cache_repo = join(SVN_CACHE, svn_dn)
191     if svn_ignore_externals:
192         extra_args = ['--ignore-externals']
193     else:
194         extra_args = []
195     if isdir(cache_repo):
196         check_call([svn, 'up', '-r', svn_revision] + extra_args, cwd=cache_repo)
197     else:
198         check_call([svn, 'co', '-r', svn_revision] + extra_args + [svn_url,
199                                                                    cache_repo])
200         assert isdir(cache_repo)
201 
202     # now copy into work directory
203     copytree(cache_repo, WORK_DIR)
204     return WORK_DIR
205 
206 
207 def apply_patch(src_dir, path):
208     print('Applying patch: %r' % path)
209     if not isfile(path):
210         sys.exit('Error: no such patch: %s' % path)
211 
212     patch = external.find_executable('patch')
213     if patch is None:
214         sys.exit("""\
215 Error:
216     Did not find 'patch' in: %s
217     You can install 'patch' using apt-get, yum (Linux), Xcode (MacOSX),
218     or conda, cygwin (Windows),
219 """ % (os.pathsep.join(external.dir_paths)))
220     check_call([patch, '-p0', '-i', path], cwd=src_dir)
221 
222 
223 def provide(recipe_dir, meta, patch=True):
224     """
225     given a recipe_dir:
226       - download (if necessary)
227       - unpack
228       - apply patches (if any)
229     """
230     print("Removing old work directory")
231     rm_rf(WORK_DIR)
232     if 'fn' in meta:
233         unpack(meta)
234     elif 'git_url' in meta:
235         git_source(meta, recipe_dir)
236     elif 'hg_url' in meta:
237         hg_source(meta)
238     elif 'svn_url' in meta:
239         svn_source(meta)
240     elif 'path' in meta:
241         print("Copying %s to %s" % (abspath(join(recipe_dir, meta.get('path'))), WORK_DIR))
242         copytree(abspath(join(recipe_dir, meta.get('path'))), WORK_DIR)
243     else: # no source
244         os.makedirs(WORK_DIR)
245 
246     if patch:
247         src_dir = get_dir()
248         for patch in meta.get('patches', []):
249             apply_patch(src_dir, join(recipe_dir, patch))
250 
251 
252 if __name__ == '__main__':
253     print(provide('.',
254                   {'url': 'http://pypi.python.org/packages/source/b/bitarray/bitarray-0.8.0.tar.gz',
255                    'git_url': 'git@github.com:ilanschnell/bitarray.git',
256                    'git_tag': '0.5.2'}))
257
```
--- 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/source.py b/conda_build/source.py
--- a/conda_build/source.py
+++ b/conda_build/source.py
@@ -83,7 +83,8 @@
     if git_url.startswith('.'):
         # It's a relative path from the conda recipe
         os.chdir(recipe_dir)
-        git_dn = abspath(expanduser(git_url)).replace('/', '_')
+        git_dn = abspath(expanduser(git_url))
+        git_dn = "_".join(git_dn.split(os.path.sep)[1:])
     else:
         git_dn = git_url.split(':')[-1].replace('/', '_')
     cache_repo = cache_repo_arg = join(GIT_CACHE, git_dn)

{"golden_diff": "diff --git a/conda_build/source.py b/conda_build/source.py\n--- a/conda_build/source.py\n+++ b/conda_build/source.py\n@@ -83,7 +83,8 @@\n     if git_url.startswith('.'):\n         # It's a relative path from the conda recipe\n         os.chdir(recipe_dir)\n-        git_dn = abspath(expanduser(git_url)).replace('/', '_')\n+        git_dn = abspath(expanduser(git_url))\n+        git_dn = \"_\".join(git_dn.split(os.path.sep)[1:])\n     else:\n         git_dn = git_url.split(':')[-1].replace('/', '_')\n     cache_repo = cache_repo_arg = join(GIT_CACHE, git_dn)\n", "issue": "Unable to build source.git_url based build recipes\nSee for an example: https://binstar.org/conda/conda-env/builds/2/3\n\n", "before_files": [{"content": "from __future__ import absolute_import, division, print_function\n\nimport os\nimport sys\nfrom os.path import join, isdir, isfile, abspath, expanduser\nfrom shutil import copytree, ignore_patterns, copy2\nfrom subprocess import check_call, Popen, PIPE\n\nfrom conda.fetch import download\nfrom conda.utils import hashsum_file\n\nfrom conda_build import external\nfrom conda_build.config import config\nfrom conda_build.utils import rm_rf, tar_xf, unzip\n\n\nSRC_CACHE = join(config.croot, 'src_cache')\nGIT_CACHE = join(config.croot, 'git_cache')\nHG_CACHE = join(config.croot, 'hg_cache')\nSVN_CACHE = join(config.croot, 'svn_cache')\nWORK_DIR = join(config.croot, 'work')\n\n\ndef get_dir():\n    if not isdir(WORK_DIR):\n        os.makedirs(WORK_DIR)\n    lst = [fn for fn in os.listdir(WORK_DIR) if not fn.startswith('.')]\n    if len(lst) == 1:\n        dir_path = join(WORK_DIR, lst[0])\n        if isdir(dir_path):\n            return dir_path\n    return WORK_DIR\n\n\ndef download_to_cache(meta):\n    ''' Download a source to the local cache. '''\n    print('Source cache directory is: %s' % SRC_CACHE)\n    if not isdir(SRC_CACHE):\n        os.makedirs(SRC_CACHE)\n\n    fn = meta['fn']\n    path = join(SRC_CACHE, fn)\n\n    if isfile(path):\n        print('Found source in cache: %s' % fn)\n    else:\n        print('Downloading source to cache: %s' % fn)\n        download(meta['url'], path)\n\n    for tp in 'md5', 'sha1', 'sha256':\n        if meta.get(tp) and hashsum_file(path, tp) != meta[tp]:\n            raise RuntimeError(\"%s mismatch: '%s' != '%s'\" %\n                               (tp.upper(), hashsum_file(path, tp), meta[tp]))\n\n    return path\n\n\ndef unpack(meta):\n    ''' Uncompress a downloaded source. '''\n    src_path = download_to_cache(meta)\n\n    os.makedirs(WORK_DIR)\n    print(\"Extracting download\")\n    if src_path.lower().endswith(('.tar.gz', '.tar.bz2', '.tgz', '.tar.xz', '.tar')):\n        tar_xf(src_path, WORK_DIR)\n    elif src_path.lower().endswith('.zip'):\n        unzip(src_path, WORK_DIR)\n    else:\n        # In this case, the build script will need to deal with unpacking the source\n        print(\"Warning: Unrecognized source format. Source file will be copied to the SRC_DIR\")\n        copy2(src_path, WORK_DIR)\n\n\ndef git_source(meta, recipe_dir):\n    ''' Download a source from Git repo. '''\n    if not isdir(GIT_CACHE):\n        os.makedirs(GIT_CACHE)\n\n    git = external.find_executable('git')\n    if not git:\n        sys.exit(\"Error: git is not installed\")\n    git_url = meta['git_url']\n    if git_url.startswith('.'):\n        # It's a relative path from the conda recipe\n        os.chdir(recipe_dir)\n        git_dn = abspath(expanduser(git_url)).replace('/', '_')\n    else:\n        git_dn = git_url.split(':')[-1].replace('/', '_')\n    cache_repo = cache_repo_arg = join(GIT_CACHE, git_dn)\n    if sys.platform == 'win32':\n        cache_repo_arg = cache_repo_arg.replace('\\\\', '/')\n        if os.getenv('USERNAME') == 'builder':\n            cache_repo_arg = '/cygdrive/c/' + cache_repo_arg[3:]\n\n    # update (or create) the cache repo\n    if isdir(cache_repo):\n        check_call([git, 'fetch'], cwd=cache_repo)\n    else:\n        check_call([git, 'clone', '--mirror', git_url, cache_repo_arg], cwd=recipe_dir)\n        assert isdir(cache_repo)\n\n    # now clone into the work directory\n    checkout = meta.get('git_rev')\n    # if rev is not specified, and the git_url is local,\n    # assume the user wants the current HEAD\n    if not checkout and git_url.startswith('.'):\n        process = Popen([\"git\", \"rev-parse\", \"HEAD\"],\n                    stdout=PIPE, stderr=PIPE,\n                               cwd=git_url)\n        output = process.communicate()[0].strip()\n        checkout = output.decode('utf-8')\n    if checkout:\n        print('checkout: %r' % checkout)\n\n    check_call([git, 'clone', cache_repo_arg, WORK_DIR])\n    if checkout:\n        check_call([git, 'checkout', checkout], cwd=WORK_DIR)\n\n    git_info()\n    return WORK_DIR\n\n\ndef git_info(fo=None):\n    ''' Print info about a Git repo. '''\n    assert isdir(WORK_DIR)\n\n    # Ensure to explicitly set GIT_DIR as some Linux machines will not\n    # properly execute without it.\n    env = os.environ.copy()\n    env['GIT_DIR'] = join(WORK_DIR, '.git')\n    env = {str(key): str(value) for key, value in env.items()}\n    for cmd, check_error in [\n                ('git log -n1', True),\n                ('git describe --tags --dirty', False),\n                ('git status', True)]:\n        p = Popen(cmd.split(), stdout=PIPE, stderr=PIPE, cwd=WORK_DIR, env=env)\n        stdout, stderr = p.communicate()\n        stdout = stdout.decode('utf-8')\n        stderr = stderr.decode('utf-8')\n        if check_error and stderr and stderr.strip():\n            raise Exception(\"git error: %s\" % stderr)\n        if fo:\n            fo.write(u'==> %s <==\\n' % cmd)\n            fo.write(stdout + u'\\n')\n        else:\n            print(u'==> %s <==\\n' % cmd)\n            print(stdout + u'\\n')\n\n\ndef hg_source(meta):\n    ''' Download a source from Mercurial repo. '''\n    hg = external.find_executable('hg')\n    if not hg:\n        sys.exit('Error: hg not installed')\n    hg_url = meta['hg_url']\n    if not isdir(HG_CACHE):\n        os.makedirs(HG_CACHE)\n    hg_dn = hg_url.split(':')[-1].replace('/', '_')\n    cache_repo = join(HG_CACHE, hg_dn)\n    if isdir(cache_repo):\n        check_call([hg, 'pull'], cwd=cache_repo)\n    else:\n        check_call([hg, 'clone', hg_url, cache_repo])\n        assert isdir(cache_repo)\n\n    # now clone in to work directory\n    update = meta.get('hg_tag') or 'tip'\n    print('checkout: %r' % update)\n\n    check_call([hg, 'clone', cache_repo, WORK_DIR])\n    check_call([hg, 'update', '-C', update], cwd=WORK_DIR)\n    return WORK_DIR\n\n\n\ndef svn_source(meta):\n    ''' Download a source from SVN repo. '''\n    def parse_bool(s):\n        return str(s).lower().strip() in ('yes', 'true', '1', 'on')\n\n    svn = external.find_executable('svn')\n    if not svn:\n        sys.exit(\"Error: svn is not installed\")\n    svn_url = meta['svn_url']\n    svn_revision = meta.get('svn_rev') or 'head'\n    svn_ignore_externals = parse_bool(meta.get('svn_ignore_externals') or 'no')\n    if not isdir(SVN_CACHE):\n        os.makedirs(SVN_CACHE)\n    svn_dn = svn_url.split(':', 1)[-1].replace('/', '_').replace(':', '_')\n    cache_repo = join(SVN_CACHE, svn_dn)\n    if svn_ignore_externals:\n        extra_args = ['--ignore-externals']\n    else:\n        extra_args = []\n    if isdir(cache_repo):\n        check_call([svn, 'up', '-r', svn_revision] + extra_args, cwd=cache_repo)\n    else:\n        check_call([svn, 'co', '-r', svn_revision] + extra_args + [svn_url,\n                                                                   cache_repo])\n        assert isdir(cache_repo)\n\n    # now copy into work directory\n    copytree(cache_repo, WORK_DIR)\n    return WORK_DIR\n\n\ndef apply_patch(src_dir, path):\n    print('Applying patch: %r' % path)\n    if not isfile(path):\n        sys.exit('Error: no such patch: %s' % path)\n\n    patch = external.find_executable('patch')\n    if patch is None:\n        sys.exit(\"\"\"\\\nError:\n    Did not find 'patch' in: %s\n    You can install 'patch' using apt-get, yum (Linux), Xcode (MacOSX),\n    or conda, cygwin (Windows),\n\"\"\" % (os.pathsep.join(external.dir_paths)))\n    check_call([patch, '-p0', '-i', path], cwd=src_dir)\n\n\ndef provide(recipe_dir, meta, patch=True):\n    \"\"\"\n    given a recipe_dir:\n      - download (if necessary)\n      - unpack\n      - apply patches (if any)\n    \"\"\"\n    print(\"Removing old work directory\")\n    rm_rf(WORK_DIR)\n    if 'fn' in meta:\n        unpack(meta)\n    elif 'git_url' in meta:\n        git_source(meta, recipe_dir)\n    elif 'hg_url' in meta:\n        hg_source(meta)\n    elif 'svn_url' in meta:\n        svn_source(meta)\n    elif 'path' in meta:\n        print(\"Copying %s to %s\" % (abspath(join(recipe_dir, meta.get('path'))), WORK_DIR))\n        copytree(abspath(join(recipe_dir, meta.get('path'))), WORK_DIR)\n    else: # no source\n        os.makedirs(WORK_DIR)\n\n    if patch:\n        src_dir = get_dir()\n        for patch in meta.get('patches', []):\n            apply_patch(src_dir, join(recipe_dir, patch))\n\n\nif __name__ == '__main__':\n    print(provide('.',\n                  {'url': 'http://pypi.python.org/packages/source/b/bitarray/bitarray-0.8.0.tar.gz',\n                   'git_url': 'git@github.com:ilanschnell/bitarray.git',\n                   'git_tag': '0.5.2'}))\n", "path": "conda_build/source.py"}], "after_files": [{"content": "from __future__ import absolute_import, division, print_function\n\nimport os\nimport sys\nfrom os.path import join, isdir, isfile, abspath, expanduser\nfrom shutil import copytree, ignore_patterns, copy2\nfrom subprocess import check_call, Popen, PIPE\n\nfrom conda.fetch import download\nfrom conda.utils import hashsum_file\n\nfrom conda_build import external\nfrom conda_build.config import config\nfrom conda_build.utils import rm_rf, tar_xf, unzip\n\n\nSRC_CACHE = join(config.croot, 'src_cache')\nGIT_CACHE = join(config.croot, 'git_cache')\nHG_CACHE = join(config.croot, 'hg_cache')\nSVN_CACHE = join(config.croot, 'svn_cache')\nWORK_DIR = join(config.croot, 'work')\n\n\ndef get_dir():\n    if not isdir(WORK_DIR):\n        os.makedirs(WORK_DIR)\n    lst = [fn for fn in os.listdir(WORK_DIR) if not fn.startswith('.')]\n    if len(lst) == 1:\n        dir_path = join(WORK_DIR, lst[0])\n        if isdir(dir_path):\n            return dir_path\n    return WORK_DIR\n\n\ndef download_to_cache(meta):\n    ''' Download a source to the local cache. '''\n    print('Source cache directory is: %s' % SRC_CACHE)\n    if not isdir(SRC_CACHE):\n        os.makedirs(SRC_CACHE)\n\n    fn = meta['fn']\n    path = join(SRC_CACHE, fn)\n\n    if isfile(path):\n        print('Found source in cache: %s' % fn)\n    else:\n        print('Downloading source to cache: %s' % fn)\n        download(meta['url'], path)\n\n    for tp in 'md5', 'sha1', 'sha256':\n        if meta.get(tp) and hashsum_file(path, tp) != meta[tp]:\n            raise RuntimeError(\"%s mismatch: '%s' != '%s'\" %\n                               (tp.upper(), hashsum_file(path, tp), meta[tp]))\n\n    return path\n\n\ndef unpack(meta):\n    ''' Uncompress a downloaded source. '''\n    src_path = download_to_cache(meta)\n\n    os.makedirs(WORK_DIR)\n    print(\"Extracting download\")\n    if src_path.lower().endswith(('.tar.gz', '.tar.bz2', '.tgz', '.tar.xz', '.tar')):\n        tar_xf(src_path, WORK_DIR)\n    elif src_path.lower().endswith('.zip'):\n        unzip(src_path, WORK_DIR)\n    else:\n        # In this case, the build script will need to deal with unpacking the source\n        print(\"Warning: Unrecognized source format. Source file will be copied to the SRC_DIR\")\n        copy2(src_path, WORK_DIR)\n\n\ndef git_source(meta, recipe_dir):\n    ''' Download a source from Git repo. '''\n    if not isdir(GIT_CACHE):\n        os.makedirs(GIT_CACHE)\n\n    git = external.find_executable('git')\n    if not git:\n        sys.exit(\"Error: git is not installed\")\n    git_url = meta['git_url']\n    if git_url.startswith('.'):\n        # It's a relative path from the conda recipe\n        os.chdir(recipe_dir)\n        git_dn = abspath(expanduser(git_url))\n        git_dn = \"_\".join(git_dn.split(os.path.sep)[1:])\n    else:\n        git_dn = git_url.split(':')[-1].replace('/', '_')\n    cache_repo = cache_repo_arg = join(GIT_CACHE, git_dn)\n    if sys.platform == 'win32':\n        cache_repo_arg = cache_repo_arg.replace('\\\\', '/')\n        if os.getenv('USERNAME') == 'builder':\n            cache_repo_arg = '/cygdrive/c/' + cache_repo_arg[3:]\n\n    # update (or create) the cache repo\n    if isdir(cache_repo):\n        check_call([git, 'fetch'], cwd=cache_repo)\n    else:\n        check_call([git, 'clone', '--mirror', git_url, cache_repo_arg], cwd=recipe_dir)\n        assert isdir(cache_repo)\n\n    # now clone into the work directory\n    checkout = meta.get('git_rev')\n    # if rev is not specified, and the git_url is local,\n    # assume the user wants the current HEAD\n    if not checkout and git_url.startswith('.'):\n        process = Popen([\"git\", \"rev-parse\", \"HEAD\"],\n                    stdout=PIPE, stderr=PIPE,\n                               cwd=git_url)\n        output = process.communicate()[0].strip()\n        checkout = output.decode('utf-8')\n    if checkout:\n        print('checkout: %r' % checkout)\n\n    check_call([git, 'clone', cache_repo_arg, WORK_DIR])\n    if checkout:\n        check_call([git, 'checkout', checkout], cwd=WORK_DIR)\n\n    git_info()\n    return WORK_DIR\n\n\ndef git_info(fo=None):\n    ''' Print info about a Git repo. '''\n    assert isdir(WORK_DIR)\n\n    # Ensure to explicitly set GIT_DIR as some Linux machines will not\n    # properly execute without it.\n    env = os.environ.copy()\n    env['GIT_DIR'] = join(WORK_DIR, '.git')\n    env = {str(key): str(value) for key, value in env.items()}\n    for cmd, check_error in [\n                ('git log -n1', True),\n                ('git describe --tags --dirty', False),\n                ('git status', True)]:\n        p = Popen(cmd.split(), stdout=PIPE, stderr=PIPE, cwd=WORK_DIR, env=env)\n        stdout, stderr = p.communicate()\n        stdout = stdout.decode('utf-8')\n        stderr = stderr.decode('utf-8')\n        if check_error and stderr and stderr.strip():\n            raise Exception(\"git error: %s\" % stderr)\n        if fo:\n            fo.write(u'==> %s <==\\n' % cmd)\n            fo.write(stdout + u'\\n')\n        else:\n            print(u'==> %s <==\\n' % cmd)\n            print(stdout + u'\\n')\n\n\ndef hg_source(meta):\n    ''' Download a source from Mercurial repo. '''\n    hg = external.find_executable('hg')\n    if not hg:\n        sys.exit('Error: hg not installed')\n    hg_url = meta['hg_url']\n    if not isdir(HG_CACHE):\n        os.makedirs(HG_CACHE)\n    hg_dn = hg_url.split(':')[-1].replace('/', '_')\n    cache_repo = join(HG_CACHE, hg_dn)\n    if isdir(cache_repo):\n        check_call([hg, 'pull'], cwd=cache_repo)\n    else:\n        check_call([hg, 'clone', hg_url, cache_repo])\n        assert isdir(cache_repo)\n\n    # now clone in to work directory\n    update = meta.get('hg_tag') or 'tip'\n    print('checkout: %r' % update)\n\n    check_call([hg, 'clone', cache_repo, WORK_DIR])\n    check_call([hg, 'update', '-C', update], cwd=WORK_DIR)\n    return WORK_DIR\n\n\n\ndef svn_source(meta):\n    ''' Download a source from SVN repo. '''\n    def parse_bool(s):\n        return str(s).lower().strip() in ('yes', 'true', '1', 'on')\n\n    svn = external.find_executable('svn')\n    if not svn:\n        sys.exit(\"Error: svn is not installed\")\n    svn_url = meta['svn_url']\n    svn_revision = meta.get('svn_rev') or 'head'\n    svn_ignore_externals = parse_bool(meta.get('svn_ignore_externals') or 'no')\n    if not isdir(SVN_CACHE):\n        os.makedirs(SVN_CACHE)\n    svn_dn = svn_url.split(':', 1)[-1].replace('/', '_').replace(':', '_')\n    cache_repo = join(SVN_CACHE, svn_dn)\n    if svn_ignore_externals:\n        extra_args = ['--ignore-externals']\n    else:\n        extra_args = []\n    if isdir(cache_repo):\n        check_call([svn, 'up', '-r', svn_revision] + extra_args, cwd=cache_repo)\n    else:\n        check_call([svn, 'co', '-r', svn_revision] + extra_args + [svn_url,\n                                                                   cache_repo])\n        assert isdir(cache_repo)\n\n    # now copy into work directory\n    copytree(cache_repo, WORK_DIR)\n    return WORK_DIR\n\n\ndef apply_patch(src_dir, path):\n    print('Applying patch: %r' % path)\n    if not isfile(path):\n        sys.exit('Error: no such patch: %s' % path)\n\n    patch = external.find_executable('patch')\n    if patch is None:\n        sys.exit(\"\"\"\\\nError:\n    Did not find 'patch' in: %s\n    You can install 'patch' using apt-get, yum (Linux), Xcode (MacOSX),\n    or conda, cygwin (Windows),\n\"\"\" % (os.pathsep.join(external.dir_paths)))\n    check_call([patch, '-p0', '-i', path], cwd=src_dir)\n\n\ndef provide(recipe_dir, meta, patch=True):\n    \"\"\"\n    given a recipe_dir:\n      - download (if necessary)\n      - unpack\n      - apply patches (if any)\n    \"\"\"\n    print(\"Removing old work directory\")\n    rm_rf(WORK_DIR)\n    if 'fn' in meta:\n        unpack(meta)\n    elif 'git_url' in meta:\n        git_source(meta, recipe_dir)\n    elif 'hg_url' in meta:\n        hg_source(meta)\n    elif 'svn_url' in meta:\n        svn_source(meta)\n    elif 'path' in meta:\n        print(\"Copying %s to %s\" % (abspath(join(recipe_dir, meta.get('path'))), WORK_DIR))\n        copytree(abspath(join(recipe_dir, meta.get('path'))), WORK_DIR)\n    else: # no source\n        os.makedirs(WORK_DIR)\n\n    if patch:\n        src_dir = get_dir()\n        for patch in meta.get('patches', []):\n            apply_patch(src_dir, join(recipe_dir, patch))\n\n\nif __name__ == '__main__':\n    print(provide('.',\n                  {'url': 'http://pypi.python.org/packages/source/b/bitarray/bitarray-0.8.0.tar.gz',\n                   'git_url': 'git@github.com:ilanschnell/bitarray.git',\n                   'git_tag': '0.5.2'}))\n", "path": "conda_build/source.py"}]}