Debian Codegraph @

hgext/schemes.py

raw
1 # Copyright 2009, Alexander Solovyov <[email protected]>
2 #
3 # This software may be used and distributed according to the terms of the
4 # GNU General Public License version 2 or any later version.
5
6 """extend schemes with shortcuts to repository swarms
7
8 This extension allows you to specify shortcuts for parent URLs with a
9 lot of repositories to act like a scheme, for example::
10
11 [schemes]
12 py = http://code.python.org/hg/
13
14 After that you can use it like::
15
16 hg clone py://trunk/
17
18 Additionally there is support for some more complex schemas, for
19 example used by Google Code::
20
21 [schemes]
22 gcode = http://{1}.googlecode.com/hg/
23
24 The syntax is taken from Mercurial templates, and you have unlimited
25 number of variables, starting with ``{1}`` and continuing with
26 ``{2}``, ``{3}`` and so on. This variables will receive parts of URL
27 supplied, split by ``/``. Anything not specified as ``{part}`` will be
28 just appended to an URL.
29
30 For convenience, the extension adds these schemes by default::
31
32 [schemes]
33 py = http://hg.python.org/
34 bb = https://bitbucket.org/
35 bb+ssh = ssh://[email protected]/
36 gcode = https://{1}.googlecode.com/hg/
37 kiln = https://{1}.kilnhg.com/Repo/
38
39 You can override a predefined scheme by defining a new scheme with the
40 same name.
41 """
42
43 from __future__ import annotations
44
45 import os
46 import re
47
48 from mercurial.i18n import _
49 from mercurial import (
50 error,
51 extensions,
52 pycompat,
53 registrar,
54 templater,
55 )
56 from mercurial.repo import (
57 factory as repo_factory,
58 )
59 from mercurial.utils import (
60 urlutil,
61 )
62
63 cmdtable = {}
64 command = registrar.command(cmdtable)
65 # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
66 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
67 # be specifying the version(s) of Mercurial they are tested with, or
68 # leave the attribute unspecified.
69 testedwith = b'ships-with-hg-core'
70
71 _partre = re.compile(br'{(\d+)\}')
72
73
74 class ShortRepository:
75 def __init__(self, url, scheme, templater):
76 self.scheme = scheme
77 self.templater = templater
78 self.url = url
79 try:
80 self.parts = max(map(int, _partre.findall(self.url)))
81 except ValueError:
82 self.parts = 0
83
84 def __repr__(self):
85 return b'<ShortRepository: %s>' % self.scheme
86
87 def make_peer(self, ui, path, *args, **kwargs):
88 new_url = self.resolve(path.rawloc)
89 path = path.copy(new_raw_location=new_url)
90 cls = repo_factory.peer_schemes.get(path.url.scheme)
91 if cls is not None:
92 return cls.make_peer(ui, path, *args, **kwargs)
93 return None
94
95 def instance(self, ui, url, create, intents=None, createopts=None):
96 url = self.resolve(url)
97 u = urlutil.url(url)
98 scheme = u.scheme or b'file'
99 if scheme in repo_factory.peer_schemes:
100 cls = repo_factory.peer_schemes[scheme]
101 elif scheme in repo_factory.repo_schemes:
102 cls = repo_factory.repo_schemes[scheme]
103 else:
104 cls = repo_factory.LocalFactory
105 return cls.instance(
106 ui, url, create, intents=intents, createopts=createopts
107 )
108
109 def resolve(self, url):
110 # Should this use the urlutil.url class, or is manual parsing better?
111 try:
112 url = url.split(b'://', 1)[1]
113 except IndexError:
114 raise error.Abort(_(b"no '://' in scheme url '%s'") % url)
115 parts = url.split(b'/', self.parts)
116 if len(parts) > self.parts:
117 tail = parts[-1]
118 parts = parts[:-1]
119 else:
120 tail = b''
121 context = {b'%d' % (i + 1): v for i, v in enumerate(parts)}
122 return b''.join(self.templater.process(self.url, context)) + tail
123
124
125 def hasdriveletter(orig, path):
126 if path:
127 for scheme in schemes:
128 if path.startswith(scheme + b':'):
129 return False
130 return orig(path)
131
132
133 schemes = {
134 b'py': b'http://hg.python.org/',
135 b'bb': b'https://bitbucket.org/',
136 b'bb+ssh': b'ssh://[email protected]/',
137 b'gcode': b'https://{1}.googlecode.com/hg/',
138 b'kiln': b'https://{1}.kilnhg.com/Repo/',
139 }
140
141
142 def _check_drive_letter(scheme: bytes) -> None:
143 """check if a scheme conflict with a Windows drive letter"""
144 if (
145 pycompat.iswindows
146 and len(scheme) == 1
147 and scheme.isalpha()
148 and os.path.exists(b'%s:\\' % scheme)
149 ):
150 msg = _(b'custom scheme %s:// conflicts with drive letter %s:\\\n')
151 msg %= (scheme, scheme.upper())
152 raise error.Abort(msg)
153
154
155 def extsetup(ui):
156 schemes.update(dict(ui.configitems(b'schemes')))
157 t = templater.engine(templater.parse)
158 for scheme, url in schemes.items():
159 _check_drive_letter(scheme)
160 url_scheme = urlutil.url(url).scheme
161 if url_scheme in repo_factory.peer_schemes:
162 repo_factory.peer_schemes[scheme] = ShortRepository(url, scheme, t)
163 else:
164 repo_factory.repo_schemes[scheme] = ShortRepository(url, scheme, t)
165
166 extensions.wrapfunction(urlutil, 'hasdriveletter', hasdriveletter)
167
168
169 @command(b'debugexpandscheme', norepo=True)
170 def expandscheme(ui, url, **opts):
171 """given a repo path, provide the scheme-expanded path"""
172 scheme = urlutil.url(url).scheme
173 if scheme in repo_factory.peer_schemes:
174 cls = repo_factory.peer_schemes[scheme]
175 else:
176 cls = repo_factory.repo_schemes.get(scheme)
177 if cls is not None and isinstance(cls, ShortRepository):
178 url = cls.resolve(url)
179 ui.write(url + b'\n')