Debian Codegraph @

hgext/convert/filemap.py

raw
1 # Copyright 2007 Bryan O'Sullivan <[email protected]>
2 # Copyright 2007 Alexis S. L. Carvalho <[email protected]>
3 #
4 # This software may be used and distributed according to the terms of the
5 # GNU General Public License version 2 or any later version.
6
7 from __future__ import annotations
8
9 import posixpath
10 import typing
11
12 from typing import (
13 Iterator,
14 Mapping,
15 MutableMapping,
16 overload,
17 )
18
19 from mercurial.i18n import _
20 from mercurial import (
21 error,
22 pycompat,
23 )
24 from . import common
25
26 if typing.TYPE_CHECKING:
27 from mercurial import (
28 ui as uimod,
29 )
30
31 SKIPREV = common.SKIPREV
32
33
34 def rpairs(path: bytes) -> Iterator[tuple[bytes, bytes]]:
35 """Yield tuples with path split at '/', starting with the full path.
36 No leading, trailing or double '/', please.
37 >>> for x in rpairs(b'foo/bar/baz'): print(x)
38 ('foo/bar/baz', '')
39 ('foo/bar', 'baz')
40 ('foo', 'bar/baz')
41 ('.', 'foo/bar/baz')
42 """
43 i = len(path)
44 while i != -1:
45 yield path[:i], path[i + 1 :]
46 i = path.rfind(b'/', 0, i)
47 yield b'.', path
48
49
50 if typing.TYPE_CHECKING:
51
52 @overload
53 def normalize(path: bytes) -> bytes:
54 pass
55
56 @overload
57 def normalize(path: None) -> None:
58 pass
59
60
61 def normalize(path):
62 """We use posixpath.normpath to support cross-platform path format.
63 However, it doesn't handle None input. So we wrap it up."""
64 if path is None:
65 return None
66 return posixpath.normpath(path)
67
68
69 class filemapper:
70 """Map and filter filenames when importing.
71 A name can be mapped to itself, a new name, or None (omit from new
72 repository)."""
73
74 rename: MutableMapping[bytes, bytes]
75 targetprefixes: set[bytes] | None
76
77 def __init__(self, ui: uimod.ui, path: bytes | None = None) -> None:
78 self.ui = ui
79 self.include = {}
80 self.exclude = {}
81 self.rename = {}
82 self.targetprefixes = None
83 if path:
84 if self.parse(path):
85 raise error.Abort(_(b'errors in filemap'))
86
87 def parse(self, path: bytes | None) -> int:
88 errs = 0
89
90 def check(name: bytes, mapping, listname: bytes):
91 if not name:
92 self.ui.warn(
93 _(b'%s:%d: path to %s is missing\n')
94 % (lex.infile, lex.lineno, listname)
95 )
96 return 1
97 if name in mapping:
98 self.ui.warn(
99 _(b'%s:%d: %r already in %s list\n')
100 % (lex.infile, lex.lineno, name, listname)
101 )
102 return 1
103 if name.startswith(b'/') or name.endswith(b'/') or b'//' in name:
104 self.ui.warn(
105 _(b'%s:%d: superfluous / in %s %r\n')
106 % (lex.infile, lex.lineno, listname, pycompat.bytestr(name))
107 )
108 return 1
109 return 0
110
111 lex = common.shlexer(
112 filepath=path, wordchars=b'!@#$%^&*()-=+[]{}|;:,./<>?'
113 )
114 cmd = lex.get_token()
115 while cmd:
116 if cmd == b'include':
117 name = normalize(lex.get_token())
118 errs += check(name, self.exclude, b'exclude')
119 self.include[name] = name
120 elif cmd == b'exclude':
121 name = normalize(lex.get_token())
122 errs += check(name, self.include, b'include')
123 errs += check(name, self.rename, b'rename')
124 self.exclude[name] = name
125 elif cmd == b'rename':
126 src = normalize(lex.get_token())
127 dest = normalize(lex.get_token())
128 errs += check(src, self.exclude, b'exclude')
129 self.rename[src] = dest
130 elif cmd == b'source':
131 errs += self.parse(normalize(lex.get_token()))
132 else:
133 self.ui.warn(
134 _(b'%s:%d: unknown directive %r\n')
135 % (lex.infile, lex.lineno, pycompat.bytestr(cmd))
136 )
137 errs += 1
138 cmd = lex.get_token()
139 return errs
140
141 def lookup(
142 self, name: bytes, mapping: Mapping[bytes, bytes]
143 ) -> tuple[bytes, bytes, bytes]:
144 name = normalize(name)
145 for pre, suf in rpairs(name):
146 try:
147 return mapping[pre], pre, suf
148 except KeyError:
149 pass
150 return b'', name, b''
151
152 def istargetfile(self, filename: bytes) -> bool:
153 """Return true if the given target filename is covered as a destination
154 of the filemap. This is useful for identifying what parts of the target
155 repo belong to the source repo and what parts don't."""
156 if self.targetprefixes is None:
157 self.targetprefixes = set()
158 for before, after in self.rename.items():
159 self.targetprefixes.add(after)
160
161 # If "." is a target, then all target files are considered from the
162 # source.
163 if not self.targetprefixes or b'.' in self.targetprefixes:
164 return True
165
166 filename = normalize(filename)
167 for pre, suf in rpairs(filename):
168 # This check is imperfect since it doesn't account for the
169 # include/exclude list, but it should work in filemaps that don't
170 # apply include/exclude to the same source directories they are
171 # renaming.
172 if pre in self.targetprefixes:
173 return True
174 return False
175
176 def __call__(self, name: bytes) -> bytes | None:
177 if self.include:
178 inc = self.lookup(name, self.include)[0]
179 else:
180 inc = name
181 if self.exclude:
182 exc = self.lookup(name, self.exclude)[0]
183 else:
184 exc = b''
185 if (not self.include and exc) or (len(inc) <= len(exc)):
186 return None
187 newpre, pre, suf = self.lookup(name, self.rename)
188 if newpre:
189 if newpre == b'.':
190 return suf
191 if suf:
192 if newpre.endswith(b'/'):
193 return newpre + suf
194 return newpre + b'/' + suf
195 return newpre
196 return name
197
198 def active(self) -> bool:
199 return bool(self.include or self.exclude or self.rename)
200
201
202 # This class does two additional things compared to a regular source:
203 #
204 # - Filter and rename files. This is mostly wrapped by the filemapper
205 # class above. We hide the original filename in the revision that is
206 # returned by getchanges to be able to find things later in getfile.
207 #
208 # - Return only revisions that matter for the files we're interested in.
209 # This involves rewriting the parents of the original revision to
210 # create a graph that is restricted to those revisions.
211 #
212 # This set of revisions includes not only revisions that directly
213 # touch files we're interested in, but also merges that merge two
214 # or more interesting revisions.
215
216
217 class filemap_source(common.converter_source):
218 def __init__(
219 self, ui: uimod.ui, baseconverter, filemap: bytes | None
220 ) -> None:
221 super().__init__(ui, baseconverter.repotype)
222 self.base = baseconverter
223 self.filemapper = filemapper(ui, filemap)
224 self.commits = {}
225 # if a revision rev has parent p in the original revision graph, then
226 # rev will have parent self.parentmap[p] in the restricted graph.
227 self.parentmap = {}
228 # self.wantedancestors[rev] is the set of all ancestors of rev that
229 # are in the restricted graph.
230 self.wantedancestors = {}
231 self.convertedorder = None
232 self._rebuilt = False
233 self.origparents = {}
234 self.children = {}
235 self.seenchildren = {}
236 # experimental config: convert.ignoreancestorcheck
237 self.ignoreancestorcheck = self.ui.configbool(
238 b'convert', b'ignoreancestorcheck'
239 )
240
241 def before(self) -> None:
242 self.base.before()
243
244 def after(self) -> None:
245 self.base.after()
246
247 def setrevmap(self, revmap):
248 # rebuild our state to make things restartable
249 #
250 # To avoid calling getcommit for every revision that has already
251 # been converted, we rebuild only the parentmap, delaying the
252 # rebuild of wantedancestors until we need it (i.e. until a
253 # merge).
254 #
255 # We assume the order argument lists the revisions in
256 # topological order, so that we can infer which revisions were
257 # wanted by previous runs.
258 self._rebuilt = not revmap
259 seen = {SKIPREV: SKIPREV}
260 dummyset = set()
261 converted = []
262 for rev in revmap.order:
263 mapped = revmap[rev]
264 wanted = mapped not in seen
265 if wanted:
266 seen[mapped] = rev
267 self.parentmap[rev] = rev
268 else:
269 self.parentmap[rev] = seen[mapped]
270 self.wantedancestors[rev] = dummyset
271 arg = seen[mapped]
272 if arg == SKIPREV:
273 arg = None
274 converted.append((rev, wanted, arg))
275 self.convertedorder = converted
276 return self.base.setrevmap(revmap)
277
278 def rebuild(self) -> bool:
279 if self._rebuilt:
280 return True
281 self._rebuilt = True
282 self.parentmap.clear()
283 self.wantedancestors.clear()
284 self.seenchildren.clear()
285 for rev, wanted, arg in self.convertedorder:
286 if rev not in self.origparents:
287 try:
288 self.origparents[rev] = self.getcommit(rev).parents
289 except error.RepoLookupError:
290 self.ui.debug(b"unknown revmap source: %s\n" % rev)
291 continue
292 if arg is not None:
293 self.children[arg] = self.children.get(arg, 0) + 1
294
295 for rev, wanted, arg in self.convertedorder:
296 try:
297 parents = self.origparents[rev]
298 except KeyError:
299 continue # unknown revmap source
300 if wanted:
301 self.mark_wanted(rev, parents)
302 else:
303 self.mark_not_wanted(rev, arg)
304 self._discard(arg, *parents)
305
306 return True
307
308 def getheads(self):
309 return self.base.getheads()
310
311 def getcommit(self, rev: bytes):
312 # We want to save a reference to the commit objects to be able
313 # to rewrite their parents later on.
314 c = self.commits[rev] = self.base.getcommit(rev)
315 for p in c.parents:
316 self.children[p] = self.children.get(p, 0) + 1
317 return c
318
319 def numcommits(self):
320 return self.base.numcommits()
321
322 def _cachedcommit(self, rev):
323 if rev in self.commits:
324 return self.commits[rev]
325 return self.base.getcommit(rev)
326
327 def _discard(self, *revs) -> None:
328 for r in revs:
329 if r is None:
330 continue
331 self.seenchildren[r] = self.seenchildren.get(r, 0) + 1
332 if self.seenchildren[r] == self.children[r]:
333 self.wantedancestors.pop(r, None)
334 self.parentmap.pop(r, None)
335 del self.seenchildren[r]
336 if self._rebuilt:
337 del self.children[r]
338
339 def wanted(self, rev, i) -> bool:
340 # Return True if we're directly interested in rev.
341 #
342 # i is an index selecting one of the parents of rev (if rev
343 # has no parents, i is None). getchangedfiles will give us
344 # the list of files that are different in rev and in the parent
345 # indicated by i. If we're interested in any of these files,
346 # we're interested in rev.
347 try:
348 files = self.base.getchangedfiles(rev, i)
349 except NotImplementedError:
350 raise error.Abort(_(b"source repository doesn't support --filemap"))
351 for f in files:
352 if self.filemapper(f):
353 return True
354
355 # The include directive is documented to include nothing else (though
356 # valid branch closes are included).
357 if self.filemapper.include:
358 return False
359
360 # Allow empty commits in the source revision through. The getchanges()
361 # method doesn't even bother calling this if it determines that the
362 # close marker is significant (i.e. all of the branch ancestors weren't
363 # eliminated). Therefore if there *is* a close marker, getchanges()
364 # doesn't consider it significant, and this revision should be dropped.
365 return not files and b'close' not in self.commits[rev].extra
366
367 def mark_not_wanted(self, rev, p) -> None:
368 # Mark rev as not interesting and update data structures.
369
370 if p is None:
371 # A root revision. Use SKIPREV to indicate that it doesn't
372 # map to any revision in the restricted graph. Put SKIPREV
373 # in the set of wanted ancestors to simplify code elsewhere
374 self.parentmap[rev] = SKIPREV
375 self.wantedancestors[rev] = {SKIPREV}
376 return
377
378 # Reuse the data from our parent.
379 self.parentmap[rev] = self.parentmap[p]
380 self.wantedancestors[rev] = self.wantedancestors[p]
381
382 def mark_wanted(self, rev, parents) -> None:
383 # Mark rev ss wanted and update data structures.
384
385 # rev will be in the restricted graph, so children of rev in
386 # the original graph should still have rev as a parent in the
387 # restricted graph.
388 self.parentmap[rev] = rev
389
390 # The set of wanted ancestors of rev is the union of the sets
391 # of wanted ancestors of its parents. Plus rev itself.
392 wrev = set()
393 for p in parents:
394 if p in self.wantedancestors:
395 wrev.update(self.wantedancestors[p])
396 else:
397 self.ui.warn(
398 _(b'warning: %s parent %s is missing\n') % (rev, p)
399 )
400 wrev.add(rev)
401 self.wantedancestors[rev] = wrev
402
403 def getchanges(self, rev, full):
404 parents = self.commits[rev].parents
405 if len(parents) > 1 and not self.ignoreancestorcheck:
406 self.rebuild()
407
408 # To decide whether we're interested in rev we:
409 #
410 # - calculate what parents rev will have if it turns out we're
411 # interested in it. If it's going to have more than 1 parent,
412 # we're interested in it.
413 #
414 # - otherwise, we'll compare it with the single parent we found.
415 # If any of the files we're interested in is different in the
416 # the two revisions, we're interested in rev.
417
418 # A parent p is interesting if its mapped version (self.parentmap[p]):
419 # - is not SKIPREV
420 # - is still not in the list of parents (we don't want duplicates)
421 # - is not an ancestor of the mapped versions of the other parents or
422 # there is no parent in the same branch than the current revision.
423 mparents = []
424 knownparents = set()
425 branch = self.commits[rev].branch
426 hasbranchparent = False
427 for i, p1 in enumerate(parents):
428 mp1 = self.parentmap[p1]
429 if mp1 == SKIPREV or mp1 in knownparents:
430 continue
431
432 isancestor = not self.ignoreancestorcheck and any(
433 p2
434 for p2 in parents
435 if p1 != p2
436 and mp1 != self.parentmap[p2]
437 and mp1 in self.wantedancestors[p2]
438 )
439 if not isancestor and not hasbranchparent and len(parents) > 1:
440 # This could be expensive, avoid unnecessary calls.
441 if self._cachedcommit(p1).branch == branch:
442 hasbranchparent = True
443 mparents.append((p1, mp1, i, isancestor))
444 knownparents.add(mp1)
445 # Discard parents ancestors of other parents if there is a
446 # non-ancestor one on the same branch than current revision.
447 if hasbranchparent:
448 mparents = [p for p in mparents if not p[3]]
449 wp = None
450 if mparents:
451 wp = max(p[2] for p in mparents)
452 mparents = [p[1] for p in mparents]
453 elif parents:
454 wp = 0
455
456 self.origparents[rev] = parents
457
458 closed = False
459 if b'close' in self.commits[rev].extra:
460 # A branch closing revision is only useful if one of its
461 # parents belong to the branch being closed
462 pbranches = [self._cachedcommit(p).branch for p in mparents]
463 if branch in pbranches:
464 closed = True
465
466 if len(mparents) < 2 and not closed and not self.wanted(rev, wp):
467 # We don't want this revision.
468 # Update our state and tell the convert process to map this
469 # revision to the same revision its parent as mapped to.
470 p = None
471 if parents:
472 p = parents[wp]
473 self.mark_not_wanted(rev, p)
474 self.convertedorder.append((rev, False, p))
475 self._discard(*parents)
476 return self.parentmap[rev]
477
478 # We want this revision.
479 # Rewrite the parents of the commit object
480 self.commits[rev].parents = mparents
481 self.mark_wanted(rev, parents)
482 self.convertedorder.append((rev, True, None))
483 self._discard(*parents)
484
485 # Get the real changes and do the filtering/mapping. To be
486 # able to get the files later on in getfile, we hide the
487 # original filename in the rev part of the return value.
488 changes, copies, cleanp2 = self.base.getchanges(rev, full)
489 files = {}
490 ncleanp2 = set(cleanp2)
491 for f, r in changes:
492 newf = self.filemapper(f)
493 if newf and (newf != f or newf not in files):
494 files[newf] = (f, r)
495 if newf != f:
496 ncleanp2.discard(f)
497 files = sorted(files.items())
498
499 ncopies = {}
500 for c in copies:
501 newc = self.filemapper(c)
502 if newc:
503 newsource = self.filemapper(copies[c])
504 if newsource:
505 ncopies[newc] = newsource
506
507 return files, ncopies, ncleanp2
508
509 def targetfilebelongstosource(self, targetfilename: bytes) -> bool:
510 return self.filemapper.istargetfile(targetfilename)
511
512 def getfile(self, name, rev):
513 realname, realrev = rev
514 return self.base.getfile(realname, realrev)
515
516 def gettags(self):
517 return self.base.gettags()
518
519 def hasnativeorder(self) -> bool:
520 return self.base.hasnativeorder()
521
522 def lookuprev(self, rev):
523 return self.base.lookuprev(rev)
524
525 def getbookmarks(self):
526 return self.base.getbookmarks()
527
528 def converted(self, rev, sinkrev):
529 self.base.converted(rev, sinkrev)