Debian Codegraph @

hgext/git/dirstate.py

raw
1 from __future__ import annotations
2
3 import contextlib
4 import os
5
6 from typing import (
7 Any,
8 Iterable,
9 Iterator,
10 )
11
12 from mercurial.interfaces.types import (
13 MatcherT,
14 TransactionT,
15 )
16 from mercurial.node import sha1nodeconstants
17 from mercurial import (
18 dirstatemap,
19 error,
20 extensions,
21 match as matchmod,
22 pycompat,
23 scmutil,
24 util,
25 )
26 from mercurial.dirstateutils import (
27 timestamp,
28 )
29 from mercurial.interfaces import (
30 dirstate as intdirstate,
31 )
32
33 from . import gitutil
34
35
36 DirstateItem = dirstatemap.DirstateItem
37 propertycache = util.propertycache
38 pygit2 = gitutil.get_pygit2()
39
40
41 def readpatternfile(orig, filepath, warn, sourceinfo=False):
42 if not (b'info/exclude' in filepath or filepath.endswith(b'.gitignore')):
43 return orig(filepath, warn, sourceinfo=False)
44 result = []
45 warnings = []
46 with open(filepath, 'rb') as fp:
47 for l in fp:
48 l = l.strip()
49 if not l or l.startswith(b'#'):
50 continue
51 if l.startswith(b'!'):
52 warnings.append(b'unsupported ignore pattern %s' % l)
53 continue
54 if l.startswith(b'/'):
55 result.append(b'rootglob:' + l[1:])
56 else:
57 result.append(b'relglob:' + l)
58 return result, warnings
59
60
61 extensions.wrapfunction(matchmod, 'readpatternfile', readpatternfile)
62
63
64 _STATUS_MAP = {}
65 if pygit2:
66 _STATUS_MAP = {
67 pygit2.GIT_STATUS_CONFLICTED: b'm',
68 pygit2.GIT_STATUS_CURRENT: b'n',
69 pygit2.GIT_STATUS_IGNORED: b'?',
70 pygit2.GIT_STATUS_INDEX_DELETED: b'r',
71 pygit2.GIT_STATUS_INDEX_MODIFIED: b'n',
72 pygit2.GIT_STATUS_INDEX_NEW: b'a',
73 pygit2.GIT_STATUS_INDEX_RENAMED: b'a',
74 pygit2.GIT_STATUS_INDEX_TYPECHANGE: b'n',
75 pygit2.GIT_STATUS_WT_DELETED: b'r',
76 pygit2.GIT_STATUS_WT_MODIFIED: b'n',
77 pygit2.GIT_STATUS_WT_NEW: b'?',
78 pygit2.GIT_STATUS_WT_RENAMED: b'a',
79 pygit2.GIT_STATUS_WT_TYPECHANGE: b'n',
80 pygit2.GIT_STATUS_WT_UNREADABLE: b'?',
81 pygit2.GIT_STATUS_INDEX_MODIFIED | pygit2.GIT_STATUS_WT_MODIFIED: b'm',
82 }
83
84
85 class gitdirstate(intdirstate.idirstate):
86 def __init__(self, ui, vfs, gitrepo, use_dirstate_v2):
87 self._ui = ui
88 self._root = os.path.dirname(vfs.base)
89 self._opener = vfs
90 self.git = gitrepo
91 self._plchangecallbacks = {}
92 # TODO: context.poststatusfixup is bad and uses this attribute
93 self._dirty = False
94 self._mapcls = dirstatemap.dirstatemap
95 self._use_dirstate_v2 = use_dirstate_v2
96
97 @propertycache
98 def _map(self):
99 """Return the dirstate contents (see documentation for dirstatemap)."""
100 self._map = self._mapcls(
101 self._ui,
102 self._opener,
103 self._root,
104 sha1nodeconstants,
105 self._use_dirstate_v2,
106 )
107 return self._map
108
109 def p1(self) -> bytes:
110 try:
111 return self.git.head.peel().id.raw
112 except pygit2.GitError:
113 # Typically happens when peeling HEAD fails, as in an
114 # empty repository.
115 return sha1nodeconstants.nullid
116
117 def p2(self) -> bytes:
118 # TODO: MERGE_HEAD? something like that, right?
119 return sha1nodeconstants.nullid
120
121 def setparents(self, p1: bytes, p2: bytes | None = None):
122 if p2 is None:
123 p2 = sha1nodeconstants.nullid
124 assert p2 == sha1nodeconstants.nullid, b'TODO merging support'
125 self.git.head.set_target(gitutil.togitnode(p1))
126
127 @util.propertycache
128 def identity(self):
129 return util.filestat.frompath(
130 os.path.join(self._root, b'.git', b'index')
131 )
132
133 def branch(self) -> bytes:
134 return b'default'
135
136 def parents(self) -> list[bytes]:
137 # TODO how on earth do we find p2 if a merge is in flight?
138 return [self.p1(), sha1nodeconstants.nullid]
139
140 def __iter__(self) -> Iterator[bytes]:
141 return (pycompat.fsencode(f.path) for f in self.git.index)
142
143 def items(self) -> Iterator[tuple[bytes, intdirstate.DirstateItemT]]:
144 for ie in self.git.index:
145 yield ie.path, None # value should be a DirstateItem
146
147 # py2,3 compat forward
148 iteritems = items
149
150 def __getitem__(self, filename):
151 try:
152 gs = self.git.status_file(filename)
153 except KeyError:
154 return b'?'
155 return _STATUS_MAP[gs]
156
157 def __contains__(self, filename: Any) -> bool:
158 try:
159 gs = self.git.status_file(filename)
160 return _STATUS_MAP[gs] != b'?'
161 except KeyError:
162 return False
163
164 def status(
165 self,
166 match: MatcherT,
167 subrepos: bool,
168 ignored: bool,
169 clean: bool,
170 unknown: bool,
171 empty_dirs_keep_files: bool = False,
172 ) -> intdirstate.StatusReturnT:
173 listclean = clean
174 # TODO handling of clean files - can we get that from git.status()?
175 modified, added, removed, deleted, unknown, ignored, clean = (
176 [],
177 [],
178 [],
179 [],
180 [],
181 [],
182 [],
183 )
184
185 try:
186 mtime_boundary = timestamp.get_fs_now(self._opener)
187 except OSError:
188 # In largefiles or readonly context
189 mtime_boundary = None
190
191 gstatus = self.git.status()
192 for path, status in gstatus.items():
193 path = pycompat.fsencode(path)
194 if not match(path):
195 continue
196 if status == pygit2.GIT_STATUS_IGNORED:
197 if path.endswith(b'/'):
198 continue
199 ignored.append(path)
200 elif status in (
201 pygit2.GIT_STATUS_WT_MODIFIED,
202 pygit2.GIT_STATUS_INDEX_MODIFIED,
203 pygit2.GIT_STATUS_WT_MODIFIED
204 | pygit2.GIT_STATUS_INDEX_MODIFIED,
205 ):
206 modified.append(path)
207 elif status == pygit2.GIT_STATUS_INDEX_NEW:
208 added.append(path)
209 elif status == pygit2.GIT_STATUS_WT_NEW:
210 unknown.append(path)
211 elif status == pygit2.GIT_STATUS_WT_DELETED:
212 deleted.append(path)
213 elif status == pygit2.GIT_STATUS_INDEX_DELETED:
214 removed.append(path)
215 else:
216 raise error.Abort(
217 b'unhandled case: status for %r is %r' % (path, status)
218 )
219
220 if listclean:
221 observed = set(
222 modified + added + removed + deleted + unknown + ignored
223 )
224 index = self.git.index
225 index.read()
226 for entry in index:
227 path = pycompat.fsencode(entry.path)
228 if not match(path):
229 continue
230 if path in observed:
231 continue # already in some other set
232 if path[-1] == b'/':
233 continue # directory
234 clean.append(path)
235
236 # TODO are we really always sure of status here?
237 return (
238 False,
239 scmutil.status(
240 modified, added, removed, deleted, unknown, ignored, clean
241 ),
242 mtime_boundary,
243 )
244
245 def flagfunc(
246 self, buildfallback: intdirstate.FlagFuncFallbackT
247 ) -> intdirstate.FlagFuncReturnT:
248 # TODO we can do better
249 return buildfallback()
250
251 def getcwd(self) -> bytes:
252 # TODO is this a good way to do this?
253 return os.path.dirname(
254 os.path.dirname(pycompat.fsencode(self.git.path))
255 )
256
257 def get_entry(self, path: bytes) -> intdirstate.DirstateItemT:
258 """return a DirstateItem for the associated path"""
259 entry = self._map.get(path)
260 if entry is None:
261 return DirstateItem()
262 return entry
263
264 def normalize(
265 self, path: bytes, isknown: bool = False, ignoremissing: bool = False
266 ) -> bytes:
267 normed = util.normcase(path)
268 assert normed == path, b"TODO handling of case folding: %s != %s" % (
269 normed,
270 path,
271 )
272 return path
273
274 def is_changing_files(self) -> bool:
275 raise NotImplementedError
276
277 def _ignorefileandline(self, f: bytes) -> intdirstate.IgnoreFileAndLineT:
278 raise NotImplementedError
279
280 @property
281 def _checklink(self) -> bool:
282 return util.checklink(os.path.dirname(pycompat.fsencode(self.git.path)))
283
284 def invalidate(self) -> None:
285 raise NotImplementedError
286
287 def copy(self, source: bytes | None, dest: bytes) -> None:
288 raise NotImplementedError
289
290 def copies(self) -> dict[bytes, bytes]:
291 # TODO support copies?
292 return {}
293
294 # # TODO what the heck is this
295 _filecache = set()
296
297 @property
298 def is_changing_parents(self) -> bool:
299 # TODO: we need to implement the context manager bits and
300 # correctly stage/revert index edits.
301 return False
302
303 @property
304 def is_changing_any(self) -> bool:
305 # TODO: we need to implement the context manager bits and
306 # correctly stage/revert index edits.
307 return False
308
309 def clear(self) -> None:
310 raise NotImplementedError
311
312 def rebuild(
313 self,
314 parent: bytes,
315 allfiles: Iterable[bytes], # TODO: more than iterable? (uses len())
316 changedfiles: Iterable[bytes] | None = None,
317 ) -> None:
318 raise NotImplementedError
319
320 def write(self, tr: TransactionT | None) -> None:
321 # TODO: call parent change callbacks
322
323 if tr:
324
325 def writeinner(category):
326 self.git.index.write()
327
328 tr.addpending(b'gitdirstate', writeinner)
329 else:
330 self.git.index.write()
331
332 def pathto(self, f: bytes, cwd: bytes | None = None) -> bytes:
333 if cwd is None:
334 cwd = self.getcwd()
335 # TODO core dirstate does something about slashes here
336 assert isinstance(f, bytes)
337 r = util.pathto(self._root, cwd, f)
338 return r
339
340 def matches(self, match: MatcherT) -> Iterable[bytes]:
341 for x in self.git.index:
342 p = pycompat.fsencode(x.path)
343 if match(p):
344 yield p # TODO: return list instead of yielding?
345
346 def set_clean(self, f, parentfiledata):
347 """Mark a file normal and clean."""
348 # TODO: for now we just let libgit2 re-stat the file. We can
349 # clearly do better.
350
351 def set_possibly_dirty(self, f):
352 """Mark a file normal, but possibly dirty."""
353 # TODO: for now we just let libgit2 re-stat the file. We can
354 # clearly do better.
355
356 def walk(
357 self,
358 match: MatcherT,
359 subrepos: Any,
360 unknown: bool,
361 ignored: bool,
362 full: bool = True,
363 ) -> intdirstate.WalkReturnT:
364 # TODO: we need to use .status() and not iterate the index,
365 # because the index doesn't force a re-walk and so `hg add` of
366 # a new file without an intervening call to status will
367 # silently do nothing.
368 r = {}
369 cwd = self.getcwd()
370 for path, status in self.git.status().items():
371 if path.startswith('.hg/'):
372 continue
373 path = pycompat.fsencode(path)
374 if not match(path):
375 continue
376 # TODO construct the stat info from the status object?
377 try:
378 s = os.stat(os.path.join(cwd, path))
379 except FileNotFoundError:
380 continue
381 r[path] = s
382 return r
383
384 def set_tracked(self, f, reset_copy=False):
385 # TODO: support copies and reset_copy=True
386 uf = pycompat.fsdecode(f)
387 if uf in self.git.index:
388 return False
389 index = self.git.index
390 index.read()
391 index.add(uf)
392 index.write()
393 return True
394
395 def add(self, f):
396 index = self.git.index
397 index.read()
398 index.add(pycompat.fsdecode(f))
399 index.write()
400
401 def drop(self, f):
402 index = self.git.index
403 index.read()
404 fs = pycompat.fsdecode(f)
405 if fs in index:
406 index.remove(fs)
407 index.write()
408
409 def set_untracked(self, f):
410 index = self.git.index
411 index.read()
412 fs = pycompat.fsdecode(f)
413 if fs in index:
414 index.remove(fs)
415 index.write()
416 return True
417 return False
418
419 def remove(self, f):
420 index = self.git.index
421 index.read()
422 index.remove(pycompat.fsdecode(f))
423 index.write()
424
425 def copied(self, file: bytes) -> bytes | None:
426 # TODO: track copies?
427 return None
428
429 def prefetch_parents(self):
430 # TODO
431 pass
432
433 def update_file(self, *args, **kwargs):
434 # TODO
435 pass
436
437 def _checkexec(self) -> bool:
438 raise NotImplementedError
439
440 @contextlib.contextmanager
441 def changing_parents(self, repo):
442 # TODO: track this maybe?
443 yield
444
445 @contextlib.contextmanager
446 def changing_files(self, repo) -> Iterator: # TODO: typehint this
447 raise NotImplementedError
448
449 def hasdir(self, d: bytes) -> bool:
450 raise NotImplementedError
451
452 def addparentchangecallback(
453 self, category: bytes, callback: intdirstate.AddParentChangeCallbackT
454 ) -> None:
455 # TODO: should this be added to the dirstate interface?
456 self._plchangecallbacks[category] = callback
457
458 def setbranch(
459 self, branch: bytes, transaction: TransactionT | None
460 ) -> None:
461 raise error.Abort(
462 b'git repos do not support branches. try using bookmarks'
463 )
464
465 def verify(
466 self, m1, m2, p1: bytes, narrow_matcher: Any | None = None
467 ) -> Iterator[bytes]:
468 raise NotImplementedError
469
470 def running_status(self, repo):
471 raise NotImplementedError
472
473 def refresh(self):
474 pass