We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
pip freeze changed behaviour in 8.1.0
- Pip version: >=8.1.0
- Python version: any
- Operating System: any
### Description:

https://github.com/pypa/pip/commit/0c221076e54cd510b51c4d92374c44d7664d5516 introduced a regression in the sense that pip freeze now returns a different remote than before even when origin is present. This breaks existing workflows.
### What I've run:

Before: pip freeze returned the origin remote
After: pip freeze return the "first" remote

Is there a chance to have the new code trigger only when origin is not found?

cc/ @hashar 

pip freeze changed behaviour in 8.1.0
- Pip version: >=8.1.0
- Python version: any
- Operating System: any
### Description:

https://github.com/pypa/pip/commit/0c221076e54cd510b51c4d92374c44d7664d5516 introduced a regression in the sense that pip freeze now returns a different remote than before even when origin is present. This breaks existing workflows.
### What I've run:

Before: pip freeze returned the origin remote
After: pip freeze return the "first" remote

Is there a chance to have the new code trigger only when origin is not found?

cc/ @hashar 


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

{"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@@ -139,8 +139,13 @@\n         remotes = self.run_command(\n             ['config', '--get-regexp', 'remote\\..*\\.url'],\n             show_stdout=False, cwd=location)\n-        first_remote = remotes.splitlines()[0]\n-        url = first_remote.split(' ')[1]\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", "issue": "pip freeze changed behaviour in 8.1.0\n- Pip version: >=8.1.0\n- Python version: any\n- Operating System: any\n### Description:\n\nhttps://github.com/pypa/pip/commit/0c221076e54cd510b51c4d92374c44d7664d5516 introduced a regression in the sense that pip freeze now returns a different remote than before even when origin is present. This breaks existing workflows.\n### What I've run:\n\nBefore: pip freeze returned the origin remote\nAfter: pip freeze return the \"first\" remote\n\nIs there a chance to have the new code trigger only when origin is not found?\n\ncc/ @hashar \n\npip freeze changed behaviour in 8.1.0\n- Pip version: >=8.1.0\n- Python version: any\n- Operating System: any\n### Description:\n\nhttps://github.com/pypa/pip/commit/0c221076e54cd510b51c4d92374c44d7664d5516 introduced a regression in the sense that pip freeze now returns a different remote than before even when origin is present. This breaks existing workflows.\n### What I've run:\n\nBefore: pip freeze returned the origin remote\nAfter: pip freeze return the \"first\" remote\n\nIs there a chance to have the new code trigger only when origin is not found?\n\ncc/ @hashar \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\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 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        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', 'remote\\..*\\.url'],\n            show_stdout=False, cwd=location)\n        first_remote = remotes.splitlines()[0]\n        url = first_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\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 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        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', '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"}]}