Debian Codegraph @

hgext/git/__init__.py

raw
1 """grant Mercurial the ability to operate on Git repositories. (EXPERIMENTAL)
2
3 This is currently super experimental. It probably will consume your
4 firstborn a la Rumpelstiltskin, etc.
5 """
6
7 from __future__ import annotations
8
9 import os
10 import typing
11
12 from typing import Callable
13
14 from mercurial.i18n import _
15
16 from mercurial import (
17 commands,
18 error,
19 extensions,
20 localrepo,
21 pycompat,
22 registrar,
23 requirements as requirementsmod,
24 scmutil,
25 store,
26 ui as uimod,
27 util,
28 vfs as vfsmod,
29 )
30
31 from . import (
32 dirstate,
33 gitlog,
34 gitutil,
35 index,
36 )
37
38 if typing.TYPE_CHECKING:
39 from mercurial.interfaces.types import (
40 FileStorageT,
41 FsPathT,
42 HgPathT,
43 )
44
45 # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
46 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
47 # be specifying the version(s) of Mercurial they are tested with, or
48 # leave the attribute unspecified.
49 testedwith = b'ships-with-hg-core'
50
51 configtable = {}
52 configitem = registrar.configitem(configtable)
53 # git.log-index-cache-miss: internal knob for testing
54 configitem(
55 b"git",
56 b"log-index-cache-miss",
57 default=False,
58 )
59
60 getversion = gitutil.pygit2_version
61
62
63 # TODO: extract an interface for this in core
64 class gitstore: # store.basicstore):
65 def __init__(self, path, vfstype):
66 self.vfs = vfstype(path)
67 self.opener = self.vfs
68 self.path = self.vfs.base
69 self.createmode = store._calcmode(self.vfs)
70 # above lines should go away in favor of:
71 # super(gitstore, self).__init__(path, vfstype)
72
73 self.git = gitutil.get_pygit2().Repository(
74 os.path.normpath(os.path.join(path, b'..', b'.git'))
75 )
76 self._progress_factory = lambda *args, **kwargs: None
77 self._logfn = lambda x: None
78
79 @util.propertycache
80 def _db(self):
81 # We lazy-create the database because we want to thread a
82 # progress callback down to the indexing process if it's
83 # required, and we don't have a ui handle in makestore().
84 return index.get_index(self.git, self._logfn, self._progress_factory)
85
86 def join(self, f):
87 """Fake store.join method for git repositories.
88
89 For the most part, store.join is used for @storecache
90 decorators to invalidate caches when various files
91 change. We'll map the ones we care about, and ignore the rest.
92 """
93 if f in (b'00changelog.i', b'00manifest.i'):
94 # This is close enough: in order for the changelog cache
95 # to be invalidated, HEAD will have to change.
96 return os.path.join(self.path, b'HEAD')
97 elif f == b'lock':
98 # TODO: we probably want to map this to a git lock, I
99 # suspect index.lock. We should figure out what the
100 # most-alike file is in git-land. For now we're risking
101 # bad concurrency errors if another git client is used.
102 return os.path.join(self.path, b'hgit-bogus-lock')
103 elif f in (b'obsstore', b'phaseroots', b'narrowspec', b'bookmarks'):
104 return os.path.join(self.path, b'..', b'.hg', f)
105 raise NotImplementedError(b'Need to pick file for %s.' % f)
106
107 def changelog(self, trypending, concurrencychecker):
108 # TODO we don't have a plan for trypending in hg's git support yet
109 return gitlog.changelog(self.git, self._db)
110
111 def manifestlog(self, repo, storenarrowmatch):
112 # TODO handle storenarrowmatch and figure out if we need the repo arg
113 return gitlog.manifestlog(self.git, self._db)
114
115 def invalidatecaches(self):
116 pass
117
118 def write(self, tr=None):
119 # normally this handles things like fncache writes, which we don't have
120 pass
121
122
123 def _makestore(
124 orig,
125 ui: uimod.ui,
126 requirements: set[bytes],
127 storebasepath: FsPathT,
128 vfstype: Callable[..., vfsmod.abstractvfs],
129 try_pending: bool,
130 ):
131 if b'git' in requirements:
132 if not os.path.exists(os.path.join(storebasepath, b'..', b'.git')):
133 raise error.Abort(
134 _(
135 b'repository specified git format in '
136 b'.hg/requires but has no .git directory'
137 )
138 )
139 # Check for presence of pygit2 only here. The assumption is that we'll
140 # run this code iff we'll later need pygit2.
141 if gitutil.get_pygit2() is None:
142 raise error.Abort(
143 _(
144 b'the git extension requires the Python '
145 b'pygit2 library to be installed'
146 )
147 )
148
149 return gitstore(storebasepath, vfstype)
150 return orig(ui, requirements, storebasepath, vfstype, try_pending)
151
152
153 def _setupdothg(ui, path):
154 dothg = os.path.join(path, b'.hg')
155 if os.path.exists(dothg):
156 ui.warn(_(b'git repo already initialized for hg\n'))
157 else:
158 os.mkdir(os.path.join(path, b'.hg'))
159 # TODO is it ok to extend .git/info/exclude like this?
160 with open(
161 os.path.join(path, b'.git', b'info', b'exclude'), 'ab'
162 ) as exclude:
163 exclude.write(b'\n.hg\n')
164 with open(os.path.join(dothg, b'requires'), 'wb') as f:
165 f.write(b'git\n')
166
167
168 _BMS_PREFIX = 'refs/heads/'
169
170
171 class gitbmstore:
172 def __init__(self, gitrepo):
173 self.gitrepo = gitrepo
174 self._aclean = True
175 self._active = gitrepo.references['HEAD'] # git head, not mark
176
177 def __contains__(self, name):
178 return (
179 _BMS_PREFIX + pycompat.fsdecode(name)
180 ) in self.gitrepo.references
181
182 def __iter__(self):
183 for r in self.gitrepo.listall_references():
184 if r.startswith(_BMS_PREFIX):
185 yield pycompat.fsencode(r[len(_BMS_PREFIX) :])
186
187 def __getitem__(self, k):
188 return (
189 self.gitrepo.references[_BMS_PREFIX + pycompat.fsdecode(k)]
190 .peel()
191 .id.raw
192 )
193
194 def get(self, k, default=None):
195 try:
196 if k in self:
197 return self[k]
198 return default
199 except gitutil.get_pygit2().InvalidSpecError:
200 return default
201
202 @property
203 def active(self):
204 h = self.gitrepo.references['HEAD']
205 if not isinstance(h.target, str) or not h.target.startswith(
206 _BMS_PREFIX
207 ):
208 return None
209 return pycompat.fsencode(h.target[len(_BMS_PREFIX) :])
210
211 @active.setter
212 def active(self, mark):
213 githead = None
214 if mark is not None:
215 githead = _BMS_PREFIX + pycompat.fsdecode(mark)
216 if githead is not None and githead not in self.gitrepo.references:
217 raise AssertionError(b'bookmark %s does not exist!' % mark)
218
219 self._active = githead
220 self._aclean = False
221
222 def _writeactive(self):
223 if self._aclean:
224 return
225 self.gitrepo.references.create('HEAD', self._active, True)
226 self._aclean = True
227
228 def names(self, node):
229 r = []
230 for ref in self.gitrepo.listall_references():
231 if not ref.startswith(_BMS_PREFIX):
232 continue
233 if self.gitrepo.references[ref].peel().id.raw != node:
234 continue
235 r.append(pycompat.fsencode(ref[len(_BMS_PREFIX) :]))
236 return r
237
238 # Cleanup opportunity: this is *identical* to core's bookmarks store.
239 def expandname(self, bname):
240 if bname == b'.':
241 if self.active:
242 return self.active
243 raise error.RepoLookupError(_(b"no active bookmark"))
244 return bname
245
246 def applychanges(self, repo, tr, changes):
247 """Apply a list of changes to bookmarks"""
248 # TODO: this should respect transactions, but that's going to
249 # require enlarging the gitbmstore to know how to do in-memory
250 # temporary writes and read those back prior to transaction
251 # finalization.
252 for name, node in changes:
253 if node is None:
254 self.gitrepo.references.delete(
255 _BMS_PREFIX + pycompat.fsdecode(name)
256 )
257 else:
258 self.gitrepo.references.create(
259 _BMS_PREFIX + pycompat.fsdecode(name),
260 gitutil.togitnode(node),
261 force=True,
262 )
263
264 def checkconflict(self, mark, force=False, target=None):
265 githead = _BMS_PREFIX + pycompat.fsdecode(mark)
266 cur = self.gitrepo.references['HEAD']
267 if githead in self.gitrepo.references and not force:
268 if target:
269 if self.gitrepo.references[githead] == target and target == cur:
270 # re-activating a bookmark
271 return []
272 # moving a bookmark - forward?
273 raise NotImplementedError
274 raise error.Abort(
275 _(b"bookmark '%s' already exists (use -f to force)") % mark
276 )
277 if len(mark) > 3 and not force:
278 try:
279 shadowhash = scmutil.isrevsymbol(self._repo, mark)
280 except error.LookupError: # ambiguous identifier
281 shadowhash = False
282 if shadowhash:
283 self._repo.ui.warn(
284 _(
285 b"bookmark %s matches a changeset hash\n"
286 b"(did you leave a -r out of an 'hg bookmark' "
287 b"command?)\n"
288 )
289 % mark
290 )
291 return []
292
293
294 def init(orig, ui, dest=b'.', **opts):
295 if opts.get('git', False):
296 path = util.abspath(dest)
297 # TODO: walk up looking for the git repo
298 _setupdothg(ui, path)
299 return 0
300 return orig(ui, dest=dest, **opts)
301
302
303 def reposetup(ui, repo):
304 if repo.local() and isinstance(repo.store, gitstore):
305 orig = repo.__class__
306 repo.store._progress_factory = repo.ui.makeprogress
307 if ui.configbool(b'git', b'log-index-cache-miss'):
308 repo.store._logfn = repo.ui.warn
309
310 class gitlocalrepo(orig):
311 def _makedirstate(self):
312 v2_req = requirementsmod.DIRSTATE_V2_REQUIREMENT
313 use_dirstate_v2 = v2_req in self.requirements
314
315 # TODO narrow support here
316 return dirstate.gitdirstate(
317 self.ui,
318 self.vfs,
319 self.store.git,
320 use_dirstate_v2,
321 )
322
323 def commit(self, *args, **kwargs):
324 ret = orig.commit(self, *args, **kwargs)
325 if ret is None:
326 # there was nothing to commit, so we should skip
327 # the index fixup logic we'd otherwise do.
328 return None
329 tid = self.store.git[gitutil.togitnode(ret)].tree.id
330 # DANGER! This will flush any writes staged to the
331 # index in Git, but we're sidestepping the index in a
332 # way that confuses git when we commit. Alas.
333 self.store.git.index.read_tree(tid)
334 self.store.git.index.write()
335 return ret
336
337 @property
338 def _bookmarks(self):
339 return gitbmstore(self.store.git)
340
341 def file(
342 self, path: HgPathT, writable: bool = False
343 ) -> FileStorageT:
344 # XXX We could make the store responsible for creating filelog
345 if path[0:1] == b'/':
346 path = path[1:]
347 return gitlog.filelog(self.store.git, self.store._db, path)
348
349 repo.__class__ = gitlocalrepo
350
351
352 def _featuresetup(ui, supported):
353 # don't die on seeing a repo with the git requirement
354 supported |= {b'git'}
355
356
357 def extsetup(ui):
358 extensions.wrapfunction(localrepo, 'makestore', _makestore)
359 # Inject --git flag for `hg init`
360 entry = extensions.wrapcommand(commands.table, b'init', init)
361 entry[1].extend(
362 [(b'', b'git', None, b'setup up a git repository instead of hg')]
363 )
364 localrepo.featuresetupfuncs.add(_featuresetup)