We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Pip fails to install package using git and short commit hash 
* Pip version: 10.0.0b1
* Python version: 3.5.2
* Operating system: Ubuntu 16.04

### Description:

Installing a package from a git repository specifying a commit hash using 7 characters.
`pip` shows an error and do not install the package.
I expect `pip` to install the package using the specified commit.
 
### What I've run:

```
pip install git+git://git.myproject.org/MyProject@0abcdef
Collecting git+git://git.myproject.org/MyProject@0abcdef
  Cloning git://git.myproject.org/MyProject (to revision 0abcdef) to /tmp/pip-req-build-xxxxxxxx
  Did not find branch or tag '0abcdef', assuming revision or ref.
fatal: Couldn't find remote ref 0abcdef
Command "git fetch -q git+git://git.myproject.org/MyProject 0abcdef" failed with error code 128 in /tmp/pip-req-build-xxxxxxxxx
```

The issue seems to be related to this PR https://github.com/pypa/pip/pull/4674

--- END ISSUE ---

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

{"golden_diff": "diff --git a/src/pip/_internal/vcs/git.py b/src/pip/_internal/vcs/git.py\n--- a/src/pip/_internal/vcs/git.py\n+++ b/src/pip/_internal/vcs/git.py\n@@ -191,12 +191,16 @@\n                 # Only do a checkout if the current commit id doesn't match\n                 # the requested revision.\n                 if not self.is_commit_id_equal(dest, rev_options.rev):\n-                    cmd_args = ['fetch', '-q', url] + rev_options.to_args()\n-                    self.run_command(cmd_args, cwd=dest)\n-                    self.run_command(\n-                        ['checkout', '-q', 'FETCH_HEAD'],\n-                        cwd=dest,\n-                    )\n+                    rev = rev_options.rev\n+                    # Only fetch the revision if it's a ref\n+                    if rev.startswith('refs/'):\n+                        self.run_command(\n+                            ['fetch', '-q', url] + rev_options.to_args(),\n+                            cwd=dest,\n+                        )\n+                        # Change the revision to the SHA of the ref we fetched\n+                        rev = 'FETCH_HEAD'\n+                    self.run_command(['checkout', '-q', rev], cwd=dest)\n \n             #: repo may contain submodules\n             self.update_submodules(dest)\n", "issue": "Pip fails to install package using git and short commit hash \n* Pip version: 10.0.0b1\r\n* Python version: 3.5.2\r\n* Operating system: Ubuntu 16.04\r\n\r\n### Description:\r\n\r\nInstalling a package from a git repository specifying a commit hash using 7 characters.\r\n`pip` shows an error and do not install the package.\r\nI expect `pip` to install the package using the specified commit.\r\n \r\n### What I've run:\r\n\r\n```\r\npip install git+git://git.myproject.org/MyProject@0abcdef\r\nCollecting git+git://git.myproject.org/MyProject@0abcdef\r\n  Cloning git://git.myproject.org/MyProject (to revision 0abcdef) to /tmp/pip-req-build-xxxxxxxx\r\n  Did not find branch or tag '0abcdef', assuming revision or ref.\r\nfatal: Couldn't find remote ref 0abcdef\r\nCommand \"git fetch -q git+git://git.myproject.org/MyProject 0abcdef\" failed with error code 128 in /tmp/pip-req-build-xxxxxxxxx\r\n```\r\n\r\nThe issue seems to be related to this PR https://github.com/pypa/pip/pull/4674\n", "before_files": [{"content": "from __future__ import absolute_import\n\nimport logging\nimport os.path\nimport re\n\nfrom pip._vendor.packaging.version import parse as parse_version\nfrom pip._vendor.six.moves.urllib import parse as urllib_parse\nfrom pip._vendor.six.moves.urllib import request as urllib_request\n\nfrom pip._internal.compat import samefile\nfrom pip._internal.exceptions import BadCommand\nfrom pip._internal.utils.misc import display_path\nfrom pip._internal.utils.temp_dir import TempDirectory\nfrom pip._internal.vcs import VersionControl, vcs\n\nurlsplit = urllib_parse.urlsplit\nurlunsplit = urllib_parse.urlunsplit\n\n\nlogger = logging.getLogger(__name__)\n\n\nHASH_REGEX = re.compile('[a-fA-F0-9]{40}')\n\n\ndef looks_like_hash(sha):\n    return bool(HASH_REGEX.match(sha))\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    # Prevent the user's environment variables from interfering with pip:\n    # https://github.com/pypa/pip/issues/1130\n    unset_environ = ('GIT_DIR', 'GIT_WORK_TREE')\n    default_arg_rev = 'HEAD'\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_base_rev_args(self, rev):\n        return [rev]\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        if not location.endswith('/'):\n            location = location + '/'\n\n        with TempDirectory(kind=\"export\") as temp_dir:\n            self.unpack(temp_dir.path)\n            self.run_command(\n                ['checkout-index', '-a', '-f', '--prefix', location],\n                show_stdout=False, cwd=temp_dir.path\n            )\n\n    def get_revision_sha(self, dest, rev):\n        \"\"\"\n        Return a commit hash for the given revision if it names a remote\n        branch or tag.  Otherwise, return None.\n\n        Args:\n          dest: the repository directory.\n          rev: the revision name.\n        \"\"\"\n        # Pass rev to pre-filter the list.\n        output = self.run_command(['show-ref', rev], cwd=dest,\n                                  show_stdout=False, on_returncode='ignore')\n        refs = {}\n        for line in output.strip().splitlines():\n            try:\n                sha, ref = line.split()\n            except ValueError:\n                # Include the offending line to simplify troubleshooting if\n                # this error ever occurs.\n                raise ValueError('unexpected show-ref line: {!r}'.format(line))\n\n            refs[ref] = sha\n\n        branch_ref = 'refs/remotes/origin/{}'.format(rev)\n        tag_ref = 'refs/tags/{}'.format(rev)\n\n        return refs.get(branch_ref) or refs.get(tag_ref)\n\n    def check_rev_options(self, dest, rev_options):\n        \"\"\"Check the revision options before checkout.\n\n        Returns a new RevOptions object for the SHA1 of the branch or tag\n        if found.\n\n        Args:\n          rev_options: a RevOptions object.\n        \"\"\"\n        rev = rev_options.arg_rev\n        sha = self.get_revision_sha(dest, rev)\n\n        if sha is not None:\n            return rev_options.make_new(sha)\n\n        # Do not show a warning for the common case of something that has\n        # the form of a Git commit hash.\n        if not looks_like_hash(rev):\n            logger.warning(\n                \"Did not find branch or tag '%s', assuming revision or ref.\",\n                rev,\n            )\n        return rev_options\n\n    def is_commit_id_equal(self, dest, name):\n        \"\"\"\n        Return whether the current commit hash equals the given name.\n\n        Args:\n          dest: the repository directory.\n          name: a string name.\n        \"\"\"\n        if not name:\n            # Then avoid an unnecessary subprocess call.\n            return False\n\n        return self.get_revision(dest) == name\n\n    def switch(self, dest, url, rev_options):\n        self.run_command(['config', 'remote.origin.url', url], cwd=dest)\n        cmd_args = ['checkout', '-q'] + rev_options.to_args()\n        self.run_command(cmd_args, 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        rev_options = self.check_rev_options(dest, rev_options)\n        cmd_args = ['reset', '--hard', '-q'] + rev_options.to_args()\n        self.run_command(cmd_args, cwd=dest)\n        #: update submodules\n        self.update_submodules(dest)\n\n    def obtain(self, dest):\n        url, rev = self.get_url_rev()\n        rev_options = self.make_rev_options(rev)\n        if self.check_destination(dest, url, rev_options):\n            rev_display = rev_options.to_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(dest, rev_options)\n                # Only do a checkout if the current commit id doesn't match\n                # the requested revision.\n                if not self.is_commit_id_equal(dest, rev_options.rev):\n                    cmd_args = ['fetch', '-q', url] + rev_options.to_args()\n                    self.run_command(cmd_args, cwd=dest)\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        )\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        )\n        return current_rev.strip()\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": "src/pip/_internal/vcs/git.py"}], "after_files": [{"content": "from __future__ import absolute_import\n\nimport logging\nimport os.path\nimport re\n\nfrom pip._vendor.packaging.version import parse as parse_version\nfrom pip._vendor.six.moves.urllib import parse as urllib_parse\nfrom pip._vendor.six.moves.urllib import request as urllib_request\n\nfrom pip._internal.compat import samefile\nfrom pip._internal.exceptions import BadCommand\nfrom pip._internal.utils.misc import display_path\nfrom pip._internal.utils.temp_dir import TempDirectory\nfrom pip._internal.vcs import VersionControl, vcs\n\nurlsplit = urllib_parse.urlsplit\nurlunsplit = urllib_parse.urlunsplit\n\n\nlogger = logging.getLogger(__name__)\n\n\nHASH_REGEX = re.compile('[a-fA-F0-9]{40}')\n\n\ndef looks_like_hash(sha):\n    return bool(HASH_REGEX.match(sha))\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    # Prevent the user's environment variables from interfering with pip:\n    # https://github.com/pypa/pip/issues/1130\n    unset_environ = ('GIT_DIR', 'GIT_WORK_TREE')\n    default_arg_rev = 'HEAD'\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_base_rev_args(self, rev):\n        return [rev]\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        if not location.endswith('/'):\n            location = location + '/'\n\n        with TempDirectory(kind=\"export\") as temp_dir:\n            self.unpack(temp_dir.path)\n            self.run_command(\n                ['checkout-index', '-a', '-f', '--prefix', location],\n                show_stdout=False, cwd=temp_dir.path\n            )\n\n    def get_revision_sha(self, dest, rev):\n        \"\"\"\n        Return a commit hash for the given revision if it names a remote\n        branch or tag.  Otherwise, return None.\n\n        Args:\n          dest: the repository directory.\n          rev: the revision name.\n        \"\"\"\n        # Pass rev to pre-filter the list.\n        output = self.run_command(['show-ref', rev], cwd=dest,\n                                  show_stdout=False, on_returncode='ignore')\n        refs = {}\n        for line in output.strip().splitlines():\n            try:\n                sha, ref = line.split()\n            except ValueError:\n                # Include the offending line to simplify troubleshooting if\n                # this error ever occurs.\n                raise ValueError('unexpected show-ref line: {!r}'.format(line))\n\n            refs[ref] = sha\n\n        branch_ref = 'refs/remotes/origin/{}'.format(rev)\n        tag_ref = 'refs/tags/{}'.format(rev)\n\n        return refs.get(branch_ref) or refs.get(tag_ref)\n\n    def check_rev_options(self, dest, rev_options):\n        \"\"\"Check the revision options before checkout.\n\n        Returns a new RevOptions object for the SHA1 of the branch or tag\n        if found.\n\n        Args:\n          rev_options: a RevOptions object.\n        \"\"\"\n        rev = rev_options.arg_rev\n        sha = self.get_revision_sha(dest, rev)\n\n        if sha is not None:\n            return rev_options.make_new(sha)\n\n        # Do not show a warning for the common case of something that has\n        # the form of a Git commit hash.\n        if not looks_like_hash(rev):\n            logger.warning(\n                \"Did not find branch or tag '%s', assuming revision or ref.\",\n                rev,\n            )\n        return rev_options\n\n    def is_commit_id_equal(self, dest, name):\n        \"\"\"\n        Return whether the current commit hash equals the given name.\n\n        Args:\n          dest: the repository directory.\n          name: a string name.\n        \"\"\"\n        if not name:\n            # Then avoid an unnecessary subprocess call.\n            return False\n\n        return self.get_revision(dest) == name\n\n    def switch(self, dest, url, rev_options):\n        self.run_command(['config', 'remote.origin.url', url], cwd=dest)\n        cmd_args = ['checkout', '-q'] + rev_options.to_args()\n        self.run_command(cmd_args, 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        rev_options = self.check_rev_options(dest, rev_options)\n        cmd_args = ['reset', '--hard', '-q'] + rev_options.to_args()\n        self.run_command(cmd_args, cwd=dest)\n        #: update submodules\n        self.update_submodules(dest)\n\n    def obtain(self, dest):\n        url, rev = self.get_url_rev()\n        rev_options = self.make_rev_options(rev)\n        if self.check_destination(dest, url, rev_options):\n            rev_display = rev_options.to_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(dest, rev_options)\n                # Only do a checkout if the current commit id doesn't match\n                # the requested revision.\n                if not self.is_commit_id_equal(dest, rev_options.rev):\n                    rev = rev_options.rev\n                    # Only fetch the revision if it's a ref\n                    if rev.startswith('refs/'):\n                        self.run_command(\n                            ['fetch', '-q', url] + rev_options.to_args(),\n                            cwd=dest,\n                        )\n                        # Change the revision to the SHA of the ref we fetched\n                        rev = 'FETCH_HEAD'\n                    self.run_command(['checkout', '-q', rev], 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        )\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        )\n        return current_rev.strip()\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": "src/pip/_internal/vcs/git.py"}]}