We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
support git refs in @ syntax
We'd like to be able to put paths to gerrit reviews in requirements files.

Given a gerrit like https://review.openstack.org/#/c/345601/6, the path given for a git pull looks like:

   git pull https://git.openstack.org/openstack/oslo.db refs/changes/01/345601/6

pip syntax we'd expect would be:

```
.venv/bin/pip install -e git+https://git.openstack.org/openstack/oslo.db@refs/changes/01/345601/6#egg=oslo.db
```

current output:

```

Obtaining oslo.db from git+https://git.openstack.org/openstack/oslo.db@refs/changes/01/345601/6#egg=oslo.db
  Cloning https://git.openstack.org/openstack/oslo.db (to refs/changes/01/345601/6) to ./.venv/src/oslo.db
  Could not find a tag or branch 'refs/changes/01/345601/6', assuming commit.
error: pathspec 'refs/changes/01/345601/6' did not match any file(s) known to git.
Command "git checkout -q refs/changes/01/345601/6" failed with error code 1 in /home/classic/.venv/src/oslo.db
```


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `pip/vcs/git.py`
Content:
```
1 from __future__ import absolute_import
2 
3 import logging
4 import tempfile
5 import os.path
6 
7 from pip.compat import samefile
8 from pip.exceptions import BadCommand
9 from pip._vendor.six.moves.urllib import parse as urllib_parse
10 from pip._vendor.six.moves.urllib import request as urllib_request
11 from pip._vendor.packaging.version import parse as parse_version
12 
13 from pip.utils import display_path, rmtree
14 from pip.vcs import vcs, VersionControl
15 
16 
17 urlsplit = urllib_parse.urlsplit
18 urlunsplit = urllib_parse.urlunsplit
19 
20 
21 logger = logging.getLogger(__name__)
22 
23 
24 class Git(VersionControl):
25     name = 'git'
26     dirname = '.git'
27     repo_name = 'clone'
28     schemes = (
29         'git', 'git+http', 'git+https', 'git+ssh', 'git+git', 'git+file',
30     )
31 
32     def __init__(self, url=None, *args, **kwargs):
33 
34         # Works around an apparent Git bug
35         # (see http://article.gmane.org/gmane.comp.version-control.git/146500)
36         if url:
37             scheme, netloc, path, query, fragment = urlsplit(url)
38             if scheme.endswith('file'):
39                 initial_slashes = path[:-len(path.lstrip('/'))]
40                 newpath = (
41                     initial_slashes +
42                     urllib_request.url2pathname(path)
43                     .replace('\\', '/').lstrip('/')
44                 )
45                 url = urlunsplit((scheme, netloc, newpath, query, fragment))
46                 after_plus = scheme.find('+') + 1
47                 url = scheme[:after_plus] + urlunsplit(
48                     (scheme[after_plus:], netloc, newpath, query, fragment),
49                 )
50 
51         super(Git, self).__init__(url, *args, **kwargs)
52 
53     def get_git_version(self):
54         VERSION_PFX = 'git version '
55         version = self.run_command(['version'], show_stdout=False)
56         if version.startswith(VERSION_PFX):
57             version = version[len(VERSION_PFX):].split()[0]
58         else:
59             version = ''
60         # get first 3 positions of the git version becasue
61         # on windows it is x.y.z.windows.t, and this parses as
62         # LegacyVersion which always smaller than a Version.
63         version = '.'.join(version.split('.')[:3])
64         return parse_version(version)
65 
66     def export(self, location):
67         """Export the Git repository at the url to the destination location"""
68         temp_dir = tempfile.mkdtemp('-export', 'pip-')
69         self.unpack(temp_dir)
70         try:
71             if not location.endswith('/'):
72                 location = location + '/'
73             self.run_command(
74                 ['checkout-index', '-a', '-f', '--prefix', location],
75                 show_stdout=False, cwd=temp_dir)
76         finally:
77             rmtree(temp_dir)
78 
79     def check_rev_options(self, rev, dest, rev_options):
80         """Check the revision options before checkout to compensate that tags
81         and branches may need origin/ as a prefix.
82         Returns the SHA1 of the branch or tag if found.
83         """
84         revisions = self.get_short_refs(dest)
85 
86         origin_rev = 'origin/%s' % rev
87         if origin_rev in revisions:
88             # remote branch
89             return [revisions[origin_rev]]
90         elif rev in revisions:
91             # a local tag or branch name
92             return [revisions[rev]]
93         else:
94             logger.warning(
95                 "Could not find a tag or branch '%s', assuming commit.", rev,
96             )
97             return rev_options
98 
99     def check_version(self, dest, rev_options):
100         """
101         Compare the current sha to the ref. ref may be a branch or tag name,
102         but current rev will always point to a sha. This means that a branch
103         or tag will never compare as True. So this ultimately only matches
104         against exact shas.
105         """
106         return self.get_revision(dest).startswith(rev_options[0])
107 
108     def switch(self, dest, url, rev_options):
109         self.run_command(['config', 'remote.origin.url', url], cwd=dest)
110         self.run_command(['checkout', '-q'] + rev_options, cwd=dest)
111 
112         self.update_submodules(dest)
113 
114     def update(self, dest, rev_options):
115         # First fetch changes from the default remote
116         if self.get_git_version() >= parse_version('1.9.0'):
117             # fetch tags in addition to everything else
118             self.run_command(['fetch', '-q', '--tags'], cwd=dest)
119         else:
120             self.run_command(['fetch', '-q'], cwd=dest)
121         # Then reset to wanted revision (maybe even origin/master)
122         if rev_options:
123             rev_options = self.check_rev_options(
124                 rev_options[0], dest, rev_options,
125             )
126         self.run_command(['reset', '--hard', '-q'] + rev_options, cwd=dest)
127         #: update submodules
128         self.update_submodules(dest)
129 
130     def obtain(self, dest):
131         url, rev = self.get_url_rev()
132         if rev:
133             rev_options = [rev]
134             rev_display = ' (to %s)' % rev
135         else:
136             rev_options = ['origin/master']
137             rev_display = ''
138         if self.check_destination(dest, url, rev_options, rev_display):
139             logger.info(
140                 'Cloning %s%s to %s', url, rev_display, display_path(dest),
141             )
142             self.run_command(['clone', '-q', url, dest])
143 
144             if rev:
145                 rev_options = self.check_rev_options(rev, dest, rev_options)
146                 # Only do a checkout if rev_options differs from HEAD
147                 if not self.check_version(dest, rev_options):
148                     self.run_command(
149                         ['checkout', '-q'] + rev_options,
150                         cwd=dest,
151                     )
152             #: repo may contain submodules
153             self.update_submodules(dest)
154 
155     def get_url(self, location):
156         """Return URL of the first remote encountered."""
157         remotes = self.run_command(
158             ['config', '--get-regexp', r'remote\..*\.url'],
159             show_stdout=False, cwd=location)
160         remotes = remotes.splitlines()
161         found_remote = remotes[0]
162         for remote in remotes:
163             if remote.startswith('remote.origin.url '):
164                 found_remote = remote
165                 break
166         url = found_remote.split(' ')[1]
167         return url.strip()
168 
169     def get_revision(self, location):
170         current_rev = self.run_command(
171             ['rev-parse', 'HEAD'], show_stdout=False, cwd=location)
172         return current_rev.strip()
173 
174     def get_full_refs(self, location):
175         """Yields tuples of (commit, ref) for branches and tags"""
176         output = self.run_command(['show-ref'],
177                                   show_stdout=False, cwd=location)
178         for line in output.strip().splitlines():
179             commit, ref = line.split(' ', 1)
180             yield commit.strip(), ref.strip()
181 
182     def is_ref_remote(self, ref):
183         return ref.startswith('refs/remotes/')
184 
185     def is_ref_branch(self, ref):
186         return ref.startswith('refs/heads/')
187 
188     def is_ref_tag(self, ref):
189         return ref.startswith('refs/tags/')
190 
191     def is_ref_commit(self, ref):
192         """A ref is a commit sha if it is not anything else"""
193         return not any((
194             self.is_ref_remote(ref),
195             self.is_ref_branch(ref),
196             self.is_ref_tag(ref),
197         ))
198 
199     # Should deprecate `get_refs` since it's ambiguous
200     def get_refs(self, location):
201         return self.get_short_refs(location)
202 
203     def get_short_refs(self, location):
204         """Return map of named refs (branches or tags) to commit hashes."""
205         rv = {}
206         for commit, ref in self.get_full_refs(location):
207             ref_name = None
208             if self.is_ref_remote(ref):
209                 ref_name = ref[len('refs/remotes/'):]
210             elif self.is_ref_branch(ref):
211                 ref_name = ref[len('refs/heads/'):]
212             elif self.is_ref_tag(ref):
213                 ref_name = ref[len('refs/tags/'):]
214             if ref_name is not None:
215                 rv[ref_name] = commit
216         return rv
217 
218     def _get_subdirectory(self, location):
219         """Return the relative path of setup.py to the git repo root."""
220         # find the repo root
221         git_dir = self.run_command(['rev-parse', '--git-dir'],
222                                    show_stdout=False, cwd=location).strip()
223         if not os.path.isabs(git_dir):
224             git_dir = os.path.join(location, git_dir)
225         root_dir = os.path.join(git_dir, '..')
226         # find setup.py
227         orig_location = location
228         while not os.path.exists(os.path.join(location, 'setup.py')):
229             last_location = location
230             location = os.path.dirname(location)
231             if location == last_location:
232                 # We've traversed up to the root of the filesystem without
233                 # finding setup.py
234                 logger.warning(
235                     "Could not find setup.py for directory %s (tried all "
236                     "parent directories)",
237                     orig_location,
238                 )
239                 return None
240         # relative path of setup.py to repo root
241         if samefile(root_dir, location):
242             return None
243         return os.path.relpath(location, root_dir)
244 
245     def get_src_requirement(self, dist, location):
246         repo = self.get_url(location)
247         if not repo.lower().startswith('git:'):
248             repo = 'git+' + repo
249         egg_project_name = dist.egg_name().split('-', 1)[0]
250         if not repo:
251             return None
252         current_rev = self.get_revision(location)
253         req = '%s@%s#egg=%s' % (repo, current_rev, egg_project_name)
254         subdirectory = self._get_subdirectory(location)
255         if subdirectory:
256             req += '&subdirectory=' + subdirectory
257         return req
258 
259     def get_url_rev(self):
260         """
261         Prefixes stub URLs like 'user@hostname:user/repo.git' with 'ssh://'.
262         That's required because although they use SSH they sometimes doesn't
263         work with a ssh:// scheme (e.g. Github). But we need a scheme for
264         parsing. Hence we remove it again afterwards and return it as a stub.
265         """
266         if '://' not in self.url:
267             assert 'file:' not in self.url
268             self.url = self.url.replace('git+', 'git+ssh://')
269             url, rev = super(Git, self).get_url_rev()
270             url = url.replace('ssh://', '')
271         else:
272             url, rev = super(Git, self).get_url_rev()
273 
274         return url, rev
275 
276     def update_submodules(self, location):
277         if not os.path.exists(os.path.join(location, '.gitmodules')):
278             return
279         self.run_command(
280             ['submodule', 'update', '--init', '--recursive', '-q'],
281             cwd=location,
282         )
283 
284     @classmethod
285     def controls_location(cls, location):
286         if super(Git, cls).controls_location(location):
287             return True
288         try:
289             r = cls().run_command(['rev-parse'],
290                                   cwd=location,
291                                   show_stdout=False,
292                                   on_returncode='ignore')
293             return not r
294         except BadCommand:
295             logger.debug("could not determine if %s is under git control "
296                          "because git is not available", location)
297             return False
298 
299 
300 vcs.register(Git)
301
```
--- 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/pip/vcs/git.py b/pip/vcs/git.py
--- a/pip/vcs/git.py
+++ b/pip/vcs/git.py
@@ -92,7 +92,8 @@
             return [revisions[rev]]
         else:
             logger.warning(
-                "Could not find a tag or branch '%s', assuming commit.", rev,
+                "Could not find a tag or branch '%s', assuming commit or ref",
+                rev,
             )
             return rev_options
 
@@ -146,9 +147,14 @@
                 # Only do a checkout if rev_options differs from HEAD
                 if not self.check_version(dest, rev_options):
                     self.run_command(
-                        ['checkout', '-q'] + rev_options,
+                        ['fetch', '-q', url] + rev_options,
                         cwd=dest,
                     )
+                    self.run_command(
+                        ['checkout', '-q', 'FETCH_HEAD'],
+                        cwd=dest,
+                    )
+
             #: repo may contain submodules
             self.update_submodules(dest)

{"golden_diff": "diff --git a/pip/vcs/git.py b/pip/vcs/git.py\n--- a/pip/vcs/git.py\n+++ b/pip/vcs/git.py\n@@ -92,7 +92,8 @@\n             return [revisions[rev]]\n         else:\n             logger.warning(\n-                \"Could not find a tag or branch '%s', assuming commit.\", rev,\n+                \"Could not find a tag or branch '%s', assuming commit or ref\",\n+                rev,\n             )\n             return rev_options\n \n@@ -146,9 +147,14 @@\n                 # Only do a checkout if rev_options differs from HEAD\n                 if not self.check_version(dest, rev_options):\n                     self.run_command(\n-                        ['checkout', '-q'] + rev_options,\n+                        ['fetch', '-q', url] + rev_options,\n                         cwd=dest,\n                     )\n+                    self.run_command(\n+                        ['checkout', '-q', 'FETCH_HEAD'],\n+                        cwd=dest,\n+                    )\n+\n             #: repo may contain submodules\n             self.update_submodules(dest)\n", "issue": "support git refs in @ syntax\nWe'd like to be able to put paths to gerrit reviews in requirements files.\n\nGiven a gerrit like https://review.openstack.org/#/c/345601/6, the path given for a git pull looks like:\n\n   git pull https://git.openstack.org/openstack/oslo.db refs/changes/01/345601/6\n\npip syntax we'd expect would be:\n\n```\n.venv/bin/pip install -e git+https://git.openstack.org/openstack/oslo.db@refs/changes/01/345601/6#egg=oslo.db\n```\n\ncurrent output:\n\n```\n\nObtaining oslo.db from git+https://git.openstack.org/openstack/oslo.db@refs/changes/01/345601/6#egg=oslo.db\n  Cloning https://git.openstack.org/openstack/oslo.db (to refs/changes/01/345601/6) to ./.venv/src/oslo.db\n  Could not find a tag or branch 'refs/changes/01/345601/6', assuming commit.\nerror: pathspec 'refs/changes/01/345601/6' did not match any file(s) known to git.\nCommand \"git checkout -q refs/changes/01/345601/6\" failed with error code 1 in /home/classic/.venv/src/oslo.db\n```\n\n", "before_files": [{"content": "from __future__ import absolute_import\n\nimport logging\nimport tempfile\nimport os.path\n\nfrom pip.compat import samefile\nfrom pip.exceptions import BadCommand\nfrom pip._vendor.six.moves.urllib import parse as urllib_parse\nfrom pip._vendor.six.moves.urllib import request as urllib_request\nfrom pip._vendor.packaging.version import parse as parse_version\n\nfrom pip.utils import display_path, rmtree\nfrom pip.vcs import vcs, VersionControl\n\n\nurlsplit = urllib_parse.urlsplit\nurlunsplit = urllib_parse.urlunsplit\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass Git(VersionControl):\n    name = 'git'\n    dirname = '.git'\n    repo_name = 'clone'\n    schemes = (\n        'git', 'git+http', 'git+https', 'git+ssh', 'git+git', 'git+file',\n    )\n\n    def __init__(self, url=None, *args, **kwargs):\n\n        # Works around an apparent Git bug\n        # (see http://article.gmane.org/gmane.comp.version-control.git/146500)\n        if url:\n            scheme, netloc, path, query, fragment = urlsplit(url)\n            if scheme.endswith('file'):\n                initial_slashes = path[:-len(path.lstrip('/'))]\n                newpath = (\n                    initial_slashes +\n                    urllib_request.url2pathname(path)\n                    .replace('\\\\', '/').lstrip('/')\n                )\n                url = urlunsplit((scheme, netloc, newpath, query, fragment))\n                after_plus = scheme.find('+') + 1\n                url = scheme[:after_plus] + urlunsplit(\n                    (scheme[after_plus:], netloc, newpath, query, fragment),\n                )\n\n        super(Git, self).__init__(url, *args, **kwargs)\n\n    def get_git_version(self):\n        VERSION_PFX = 'git version '\n        version = self.run_command(['version'], show_stdout=False)\n        if version.startswith(VERSION_PFX):\n            version = version[len(VERSION_PFX):].split()[0]\n        else:\n            version = ''\n        # get first 3 positions of the git version becasue\n        # on windows it is x.y.z.windows.t, and this parses as\n        # LegacyVersion which always smaller than a Version.\n        version = '.'.join(version.split('.')[:3])\n        return parse_version(version)\n\n    def export(self, location):\n        \"\"\"Export the Git repository at the url to the destination location\"\"\"\n        temp_dir = tempfile.mkdtemp('-export', 'pip-')\n        self.unpack(temp_dir)\n        try:\n            if not location.endswith('/'):\n                location = location + '/'\n            self.run_command(\n                ['checkout-index', '-a', '-f', '--prefix', location],\n                show_stdout=False, cwd=temp_dir)\n        finally:\n            rmtree(temp_dir)\n\n    def check_rev_options(self, rev, dest, rev_options):\n        \"\"\"Check the revision options before checkout to compensate that tags\n        and branches may need origin/ as a prefix.\n        Returns the SHA1 of the branch or tag if found.\n        \"\"\"\n        revisions = self.get_short_refs(dest)\n\n        origin_rev = 'origin/%s' % rev\n        if origin_rev in revisions:\n            # remote branch\n            return [revisions[origin_rev]]\n        elif rev in revisions:\n            # a local tag or branch name\n            return [revisions[rev]]\n        else:\n            logger.warning(\n                \"Could not find a tag or branch '%s', assuming commit.\", rev,\n            )\n            return rev_options\n\n    def check_version(self, dest, rev_options):\n        \"\"\"\n        Compare the current sha to the ref. ref may be a branch or tag name,\n        but current rev will always point to a sha. This means that a branch\n        or tag will never compare as True. So this ultimately only matches\n        against exact shas.\n        \"\"\"\n        return self.get_revision(dest).startswith(rev_options[0])\n\n    def switch(self, dest, url, rev_options):\n        self.run_command(['config', 'remote.origin.url', url], cwd=dest)\n        self.run_command(['checkout', '-q'] + rev_options, cwd=dest)\n\n        self.update_submodules(dest)\n\n    def update(self, dest, rev_options):\n        # First fetch changes from the default remote\n        if self.get_git_version() >= parse_version('1.9.0'):\n            # fetch tags in addition to everything else\n            self.run_command(['fetch', '-q', '--tags'], cwd=dest)\n        else:\n            self.run_command(['fetch', '-q'], cwd=dest)\n        # Then reset to wanted revision (maybe even origin/master)\n        if rev_options:\n            rev_options = self.check_rev_options(\n                rev_options[0], dest, rev_options,\n            )\n        self.run_command(['reset', '--hard', '-q'] + rev_options, cwd=dest)\n        #: update submodules\n        self.update_submodules(dest)\n\n    def obtain(self, dest):\n        url, rev = self.get_url_rev()\n        if rev:\n            rev_options = [rev]\n            rev_display = ' (to %s)' % rev\n        else:\n            rev_options = ['origin/master']\n            rev_display = ''\n        if self.check_destination(dest, url, rev_options, rev_display):\n            logger.info(\n                'Cloning %s%s to %s', url, rev_display, display_path(dest),\n            )\n            self.run_command(['clone', '-q', url, dest])\n\n            if rev:\n                rev_options = self.check_rev_options(rev, dest, rev_options)\n                # Only do a checkout if rev_options differs from HEAD\n                if not self.check_version(dest, rev_options):\n                    self.run_command(\n                        ['checkout', '-q'] + rev_options,\n                        cwd=dest,\n                    )\n            #: repo may contain submodules\n            self.update_submodules(dest)\n\n    def get_url(self, location):\n        \"\"\"Return URL of the first remote encountered.\"\"\"\n        remotes = self.run_command(\n            ['config', '--get-regexp', r'remote\\..*\\.url'],\n            show_stdout=False, cwd=location)\n        remotes = remotes.splitlines()\n        found_remote = remotes[0]\n        for remote in remotes:\n            if remote.startswith('remote.origin.url '):\n                found_remote = remote\n                break\n        url = found_remote.split(' ')[1]\n        return url.strip()\n\n    def get_revision(self, location):\n        current_rev = self.run_command(\n            ['rev-parse', 'HEAD'], show_stdout=False, cwd=location)\n        return current_rev.strip()\n\n    def get_full_refs(self, location):\n        \"\"\"Yields tuples of (commit, ref) for branches and tags\"\"\"\n        output = self.run_command(['show-ref'],\n                                  show_stdout=False, cwd=location)\n        for line in output.strip().splitlines():\n            commit, ref = line.split(' ', 1)\n            yield commit.strip(), ref.strip()\n\n    def is_ref_remote(self, ref):\n        return ref.startswith('refs/remotes/')\n\n    def is_ref_branch(self, ref):\n        return ref.startswith('refs/heads/')\n\n    def is_ref_tag(self, ref):\n        return ref.startswith('refs/tags/')\n\n    def is_ref_commit(self, ref):\n        \"\"\"A ref is a commit sha if it is not anything else\"\"\"\n        return not any((\n            self.is_ref_remote(ref),\n            self.is_ref_branch(ref),\n            self.is_ref_tag(ref),\n        ))\n\n    # Should deprecate `get_refs` since it's ambiguous\n    def get_refs(self, location):\n        return self.get_short_refs(location)\n\n    def get_short_refs(self, location):\n        \"\"\"Return map of named refs (branches or tags) to commit hashes.\"\"\"\n        rv = {}\n        for commit, ref in self.get_full_refs(location):\n            ref_name = None\n            if self.is_ref_remote(ref):\n                ref_name = ref[len('refs/remotes/'):]\n            elif self.is_ref_branch(ref):\n                ref_name = ref[len('refs/heads/'):]\n            elif self.is_ref_tag(ref):\n                ref_name = ref[len('refs/tags/'):]\n            if ref_name is not None:\n                rv[ref_name] = commit\n        return rv\n\n    def _get_subdirectory(self, location):\n        \"\"\"Return the relative path of setup.py to the git repo root.\"\"\"\n        # find the repo root\n        git_dir = self.run_command(['rev-parse', '--git-dir'],\n                                   show_stdout=False, cwd=location).strip()\n        if not os.path.isabs(git_dir):\n            git_dir = os.path.join(location, git_dir)\n        root_dir = os.path.join(git_dir, '..')\n        # find setup.py\n        orig_location = location\n        while not os.path.exists(os.path.join(location, 'setup.py')):\n            last_location = location\n            location = os.path.dirname(location)\n            if location == last_location:\n                # We've traversed up to the root of the filesystem without\n                # finding setup.py\n                logger.warning(\n                    \"Could not find setup.py for directory %s (tried all \"\n                    \"parent directories)\",\n                    orig_location,\n                )\n                return None\n        # relative path of setup.py to repo root\n        if samefile(root_dir, location):\n            return None\n        return os.path.relpath(location, root_dir)\n\n    def get_src_requirement(self, dist, location):\n        repo = self.get_url(location)\n        if not repo.lower().startswith('git:'):\n            repo = 'git+' + repo\n        egg_project_name = dist.egg_name().split('-', 1)[0]\n        if not repo:\n            return None\n        current_rev = self.get_revision(location)\n        req = '%s@%s#egg=%s' % (repo, current_rev, egg_project_name)\n        subdirectory = self._get_subdirectory(location)\n        if subdirectory:\n            req += '&subdirectory=' + subdirectory\n        return req\n\n    def get_url_rev(self):\n        \"\"\"\n        Prefixes stub URLs like 'user@hostname:user/repo.git' with 'ssh://'.\n        That's required because although they use SSH they sometimes doesn't\n        work with a ssh:// scheme (e.g. Github). But we need a scheme for\n        parsing. Hence we remove it again afterwards and return it as a stub.\n        \"\"\"\n        if '://' not in self.url:\n            assert 'file:' not in self.url\n            self.url = self.url.replace('git+', 'git+ssh://')\n            url, rev = super(Git, self).get_url_rev()\n            url = url.replace('ssh://', '')\n        else:\n            url, rev = super(Git, self).get_url_rev()\n\n        return url, rev\n\n    def update_submodules(self, location):\n        if not os.path.exists(os.path.join(location, '.gitmodules')):\n            return\n        self.run_command(\n            ['submodule', 'update', '--init', '--recursive', '-q'],\n            cwd=location,\n        )\n\n    @classmethod\n    def controls_location(cls, location):\n        if super(Git, cls).controls_location(location):\n            return True\n        try:\n            r = cls().run_command(['rev-parse'],\n                                  cwd=location,\n                                  show_stdout=False,\n                                  on_returncode='ignore')\n            return not r\n        except BadCommand:\n            logger.debug(\"could not determine if %s is under git control \"\n                         \"because git is not available\", location)\n            return False\n\n\nvcs.register(Git)\n", "path": "pip/vcs/git.py"}], "after_files": [{"content": "from __future__ import absolute_import\n\nimport logging\nimport tempfile\nimport os.path\n\nfrom pip.compat import samefile\nfrom pip.exceptions import BadCommand\nfrom pip._vendor.six.moves.urllib import parse as urllib_parse\nfrom pip._vendor.six.moves.urllib import request as urllib_request\nfrom pip._vendor.packaging.version import parse as parse_version\n\nfrom pip.utils import display_path, rmtree\nfrom pip.vcs import vcs, VersionControl\n\n\nurlsplit = urllib_parse.urlsplit\nurlunsplit = urllib_parse.urlunsplit\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass Git(VersionControl):\n    name = 'git'\n    dirname = '.git'\n    repo_name = 'clone'\n    schemes = (\n        'git', 'git+http', 'git+https', 'git+ssh', 'git+git', 'git+file',\n    )\n\n    def __init__(self, url=None, *args, **kwargs):\n\n        # Works around an apparent Git bug\n        # (see http://article.gmane.org/gmane.comp.version-control.git/146500)\n        if url:\n            scheme, netloc, path, query, fragment = urlsplit(url)\n            if scheme.endswith('file'):\n                initial_slashes = path[:-len(path.lstrip('/'))]\n                newpath = (\n                    initial_slashes +\n                    urllib_request.url2pathname(path)\n                    .replace('\\\\', '/').lstrip('/')\n                )\n                url = urlunsplit((scheme, netloc, newpath, query, fragment))\n                after_plus = scheme.find('+') + 1\n                url = scheme[:after_plus] + urlunsplit(\n                    (scheme[after_plus:], netloc, newpath, query, fragment),\n                )\n\n        super(Git, self).__init__(url, *args, **kwargs)\n\n    def get_git_version(self):\n        VERSION_PFX = 'git version '\n        version = self.run_command(['version'], show_stdout=False)\n        if version.startswith(VERSION_PFX):\n            version = version[len(VERSION_PFX):].split()[0]\n        else:\n            version = ''\n        # get first 3 positions of the git version becasue\n        # on windows it is x.y.z.windows.t, and this parses as\n        # LegacyVersion which always smaller than a Version.\n        version = '.'.join(version.split('.')[:3])\n        return parse_version(version)\n\n    def export(self, location):\n        \"\"\"Export the Git repository at the url to the destination location\"\"\"\n        temp_dir = tempfile.mkdtemp('-export', 'pip-')\n        self.unpack(temp_dir)\n        try:\n            if not location.endswith('/'):\n                location = location + '/'\n            self.run_command(\n                ['checkout-index', '-a', '-f', '--prefix', location],\n                show_stdout=False, cwd=temp_dir)\n        finally:\n            rmtree(temp_dir)\n\n    def check_rev_options(self, rev, dest, rev_options):\n        \"\"\"Check the revision options before checkout to compensate that tags\n        and branches may need origin/ as a prefix.\n        Returns the SHA1 of the branch or tag if found.\n        \"\"\"\n        revisions = self.get_short_refs(dest)\n\n        origin_rev = 'origin/%s' % rev\n        if origin_rev in revisions:\n            # remote branch\n            return [revisions[origin_rev]]\n        elif rev in revisions:\n            # a local tag or branch name\n            return [revisions[rev]]\n        else:\n            logger.warning(\n                \"Could not find a tag or branch '%s', assuming commit or ref\",\n                rev,\n            )\n            return rev_options\n\n    def check_version(self, dest, rev_options):\n        \"\"\"\n        Compare the current sha to the ref. ref may be a branch or tag name,\n        but current rev will always point to a sha. This means that a branch\n        or tag will never compare as True. So this ultimately only matches\n        against exact shas.\n        \"\"\"\n        return self.get_revision(dest).startswith(rev_options[0])\n\n    def switch(self, dest, url, rev_options):\n        self.run_command(['config', 'remote.origin.url', url], cwd=dest)\n        self.run_command(['checkout', '-q'] + rev_options, cwd=dest)\n\n        self.update_submodules(dest)\n\n    def update(self, dest, rev_options):\n        # First fetch changes from the default remote\n        if self.get_git_version() >= parse_version('1.9.0'):\n            # fetch tags in addition to everything else\n            self.run_command(['fetch', '-q', '--tags'], cwd=dest)\n        else:\n            self.run_command(['fetch', '-q'], cwd=dest)\n        # Then reset to wanted revision (maybe even origin/master)\n        if rev_options:\n            rev_options = self.check_rev_options(\n                rev_options[0], dest, rev_options,\n            )\n        self.run_command(['reset', '--hard', '-q'] + rev_options, cwd=dest)\n        #: update submodules\n        self.update_submodules(dest)\n\n    def obtain(self, dest):\n        url, rev = self.get_url_rev()\n        if rev:\n            rev_options = [rev]\n            rev_display = ' (to %s)' % rev\n        else:\n            rev_options = ['origin/master']\n            rev_display = ''\n        if self.check_destination(dest, url, rev_options, rev_display):\n            logger.info(\n                'Cloning %s%s to %s', url, rev_display, display_path(dest),\n            )\n            self.run_command(['clone', '-q', url, dest])\n\n            if rev:\n                rev_options = self.check_rev_options(rev, dest, rev_options)\n                # Only do a checkout if rev_options differs from HEAD\n                if not self.check_version(dest, rev_options):\n                    self.run_command(\n                        ['fetch', '-q', url] + rev_options,\n                        cwd=dest,\n                    )\n                    self.run_command(\n                        ['checkout', '-q', 'FETCH_HEAD'],\n                        cwd=dest,\n                    )\n\n            #: repo may contain submodules\n            self.update_submodules(dest)\n\n    def get_url(self, location):\n        \"\"\"Return URL of the first remote encountered.\"\"\"\n        remotes = self.run_command(\n            ['config', '--get-regexp', r'remote\\..*\\.url'],\n            show_stdout=False, cwd=location)\n        remotes = remotes.splitlines()\n        found_remote = remotes[0]\n        for remote in remotes:\n            if remote.startswith('remote.origin.url '):\n                found_remote = remote\n                break\n        url = found_remote.split(' ')[1]\n        return url.strip()\n\n    def get_revision(self, location):\n        current_rev = self.run_command(\n            ['rev-parse', 'HEAD'], show_stdout=False, cwd=location)\n        return current_rev.strip()\n\n    def get_full_refs(self, location):\n        \"\"\"Yields tuples of (commit, ref) for branches and tags\"\"\"\n        output = self.run_command(['show-ref'],\n                                  show_stdout=False, cwd=location)\n        for line in output.strip().splitlines():\n            commit, ref = line.split(' ', 1)\n            yield commit.strip(), ref.strip()\n\n    def is_ref_remote(self, ref):\n        return ref.startswith('refs/remotes/')\n\n    def is_ref_branch(self, ref):\n        return ref.startswith('refs/heads/')\n\n    def is_ref_tag(self, ref):\n        return ref.startswith('refs/tags/')\n\n    def is_ref_commit(self, ref):\n        \"\"\"A ref is a commit sha if it is not anything else\"\"\"\n        return not any((\n            self.is_ref_remote(ref),\n            self.is_ref_branch(ref),\n            self.is_ref_tag(ref),\n        ))\n\n    # Should deprecate `get_refs` since it's ambiguous\n    def get_refs(self, location):\n        return self.get_short_refs(location)\n\n    def get_short_refs(self, location):\n        \"\"\"Return map of named refs (branches or tags) to commit hashes.\"\"\"\n        rv = {}\n        for commit, ref in self.get_full_refs(location):\n            ref_name = None\n            if self.is_ref_remote(ref):\n                ref_name = ref[len('refs/remotes/'):]\n            elif self.is_ref_branch(ref):\n                ref_name = ref[len('refs/heads/'):]\n            elif self.is_ref_tag(ref):\n                ref_name = ref[len('refs/tags/'):]\n            if ref_name is not None:\n                rv[ref_name] = commit\n        return rv\n\n    def _get_subdirectory(self, location):\n        \"\"\"Return the relative path of setup.py to the git repo root.\"\"\"\n        # find the repo root\n        git_dir = self.run_command(['rev-parse', '--git-dir'],\n                                   show_stdout=False, cwd=location).strip()\n        if not os.path.isabs(git_dir):\n            git_dir = os.path.join(location, git_dir)\n        root_dir = os.path.join(git_dir, '..')\n        # find setup.py\n        orig_location = location\n        while not os.path.exists(os.path.join(location, 'setup.py')):\n            last_location = location\n            location = os.path.dirname(location)\n            if location == last_location:\n                # We've traversed up to the root of the filesystem without\n                # finding setup.py\n                logger.warning(\n                    \"Could not find setup.py for directory %s (tried all \"\n                    \"parent directories)\",\n                    orig_location,\n                )\n                return None\n        # relative path of setup.py to repo root\n        if samefile(root_dir, location):\n            return None\n        return os.path.relpath(location, root_dir)\n\n    def get_src_requirement(self, dist, location):\n        repo = self.get_url(location)\n        if not repo.lower().startswith('git:'):\n            repo = 'git+' + repo\n        egg_project_name = dist.egg_name().split('-', 1)[0]\n        if not repo:\n            return None\n        current_rev = self.get_revision(location)\n        req = '%s@%s#egg=%s' % (repo, current_rev, egg_project_name)\n        subdirectory = self._get_subdirectory(location)\n        if subdirectory:\n            req += '&subdirectory=' + subdirectory\n        return req\n\n    def get_url_rev(self):\n        \"\"\"\n        Prefixes stub URLs like 'user@hostname:user/repo.git' with 'ssh://'.\n        That's required because although they use SSH they sometimes doesn't\n        work with a ssh:// scheme (e.g. Github). But we need a scheme for\n        parsing. Hence we remove it again afterwards and return it as a stub.\n        \"\"\"\n        if '://' not in self.url:\n            assert 'file:' not in self.url\n            self.url = self.url.replace('git+', 'git+ssh://')\n            url, rev = super(Git, self).get_url_rev()\n            url = url.replace('ssh://', '')\n        else:\n            url, rev = super(Git, self).get_url_rev()\n\n        return url, rev\n\n    def update_submodules(self, location):\n        if not os.path.exists(os.path.join(location, '.gitmodules')):\n            return\n        self.run_command(\n            ['submodule', 'update', '--init', '--recursive', '-q'],\n            cwd=location,\n        )\n\n    @classmethod\n    def controls_location(cls, location):\n        if super(Git, cls).controls_location(location):\n            return True\n        try:\n            r = cls().run_command(['rev-parse'],\n                                  cwd=location,\n                                  show_stdout=False,\n                                  on_returncode='ignore')\n            return not r\n        except BadCommand:\n            logger.debug(\"could not determine if %s is under git control \"\n                         \"because git is not available\", location)\n            return False\n\n\nvcs.register(Git)\n", "path": "pip/vcs/git.py"}]}