Debian Codegraph @

hgext/narrow/narrowcommands.py

raw
1 # narrowcommands.py - command modifications for narrowhg extension
2 #
3 # Copyright 2017 Google, Inc.
4 #
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
7
8 from __future__ import annotations
9
10 import itertools
11 import os
12
13 from mercurial.i18n import _
14 from mercurial.node import (
15 hex,
16 short,
17 )
18 from mercurial import (
19 bundle2,
20 commands,
21 discovery,
22 encoding,
23 error,
24 exchange,
25 extensions,
26 narrowspec,
27 pathutil,
28 pycompat,
29 registrar,
30 repair,
31 repoview,
32 scmutil,
33 sparse,
34 util,
35 wireprototypes,
36 )
37 from mercurial.cmd_impls import (
38 update as up_impl,
39 )
40 from mercurial.repo import (
41 factory as repo_factory,
42 )
43 from mercurial.utils import (
44 urlutil,
45 )
46 from mercurial.narrow import (
47 working_copy as narrow_wc,
48 )
49
50 table = {}
51 command = registrar.command(table)
52
53
54 def setup():
55 """Wraps user-facing mercurial commands with narrow-aware versions."""
56
57 entry = extensions.wrapcommand(commands.table, b'clone', clonenarrowcmd)
58 entry[1].append(
59 (b'', b'narrow', None, _(b"create a narrow clone of select files"))
60 )
61 entry[1].append(
62 (
63 b'',
64 b'depth',
65 b'',
66 _(b"limit the history fetched by distance from heads"),
67 )
68 )
69 entry[1].append((b'', b'narrowspec', b'', _(b"read narrowspecs from file")))
70 # TODO(durin42): unify sparse/narrow --include/--exclude logic a bit
71 if b'sparse' not in extensions.enabled():
72 entry[1].append(
73 (b'', b'include', [], _(b"specifically fetch this file/directory"))
74 )
75 entry[1].append(
76 (
77 b'',
78 b'exclude',
79 [],
80 _(b"do not fetch this file/directory, even if included"),
81 )
82 )
83
84 entry = extensions.wrapcommand(commands.table, b'pull', pullnarrowcmd)
85 entry[1].append(
86 (
87 b'',
88 b'depth',
89 b'',
90 _(b"limit the history fetched by distance from heads"),
91 )
92 )
93
94 extensions.wrapcommand(commands.table, b'archive', archivenarrowcmd)
95
96
97 def clonenarrowcmd(orig, ui, repo, *args, **opts):
98 """Wraps clone command, so 'hg clone' first wraps localrepo.clone()."""
99 wrappedextraprepare = util.nullcontextmanager()
100 narrowspecfile = opts['narrowspec']
101
102 if narrowspecfile:
103 filepath = os.path.join(encoding.getcwd(), narrowspecfile)
104 ui.status(_(b"reading narrowspec from '%s'\n") % filepath)
105 try:
106 fdata = util.readfile(filepath)
107 except OSError as inst:
108 raise error.Abort(
109 _(b"cannot read narrowspecs from '%s': %s")
110 % (filepath, encoding.strtolocal(inst.strerror))
111 )
112
113 includes, excludes, profiles = sparse.parseconfig(ui, fdata, b'narrow')
114 if profiles:
115 raise error.ConfigError(
116 _(
117 b"cannot specify other files using '%include' in"
118 b" narrowspec"
119 )
120 )
121
122 narrowspec.validatepatterns(includes)
123 narrowspec.validatepatterns(excludes)
124
125 # narrowspec is passed so we should assume that user wants narrow clone
126 opts['narrow'] = True
127 opts['include'].extend(includes)
128 opts['exclude'].extend(excludes)
129
130 if opts['narrow']:
131
132 def pullbundle2extraprepare_widen(orig, pullop, kwargs):
133 orig(pullop, kwargs)
134
135 if opts.get('depth'):
136 # TODO: fix exchange._pullbundle2extraprepare()
137 kwargs[b'depth'] = opts['depth']
138
139 wrappedextraprepare = extensions.wrappedfunction(
140 exchange, '_pullbundle2extraprepare', pullbundle2extraprepare_widen
141 )
142
143 with wrappedextraprepare:
144 return orig(ui, repo, *args, **opts)
145
146
147 def pullnarrowcmd(orig, ui, repo, *args, **opts):
148 """Wraps pull command to allow modifying narrow spec."""
149 wrappedextraprepare = util.nullcontextmanager()
150 if repo.is_narrow:
151
152 def pullbundle2extraprepare_widen(orig, pullop, kwargs):
153 orig(pullop, kwargs)
154 if opts.get('depth'):
155 kwargs[b'depth'] = opts['depth']
156
157 wrappedextraprepare = extensions.wrappedfunction(
158 exchange, '_pullbundle2extraprepare', pullbundle2extraprepare_widen
159 )
160
161 with wrappedextraprepare:
162 return orig(ui, repo, *args, **opts)
163
164
165 def archivenarrowcmd(orig, ui, repo, *args, **opts):
166 """Wraps archive command to narrow the default includes."""
167 if repo.is_narrow:
168 repo_includes, repo_excludes = repo.narrowpats
169 includes = set(opts.get('include', []))
170 excludes = set(opts.get('exclude', []))
171 includes, excludes, unused_invalid = narrowspec.restrictpatterns(
172 includes, excludes, repo_includes, repo_excludes
173 )
174 if includes:
175 opts['include'] = includes
176 if excludes:
177 opts['exclude'] = excludes
178 return orig(ui, repo, *args, **opts)
179
180
181 def pullbundle2extraprepare(orig, pullop, kwargs):
182 repo = pullop.repo
183 if not repo.is_narrow:
184 return orig(pullop, kwargs)
185
186 if wireprototypes.NARROWCAP not in pullop.remote.capabilities():
187 raise error.Abort(_(b"server does not support narrow clones"))
188 orig(pullop, kwargs)
189 kwargs[b'narrow'] = True
190 include, exclude = repo.narrowpats
191 kwargs[b'oldincludepats'] = include
192 kwargs[b'oldexcludepats'] = exclude
193 if include:
194 kwargs[b'includepats'] = include
195 if exclude:
196 kwargs[b'excludepats'] = exclude
197 # calculate known nodes only in ellipses cases because in non-ellipses cases
198 # we have all the nodes
199 if wireprototypes.ELLIPSESCAP1 in pullop.remote.capabilities():
200 kwargs[b'known'] = [
201 hex(ctx.node())
202 for ctx in repo.set(b'::%ln', pullop.common)
203 if ctx.node() != repo.nullid
204 ]
205 if not kwargs[b'known']:
206 # Mercurial serializes an empty list as '' and deserializes it as
207 # [''], so delete it instead to avoid handling the empty string on
208 # the server.
209 del kwargs[b'known']
210
211
212 extensions.wrapfunction(
213 exchange, '_pullbundle2extraprepare', pullbundle2extraprepare
214 )
215
216
217 def _narrow(
218 ui,
219 repo,
220 remote,
221 commoninc,
222 oldincludes,
223 oldexcludes,
224 newincludes,
225 newexcludes,
226 force,
227 backup,
228 ):
229 oldmatch = narrowspec.match(repo.root, oldincludes, oldexcludes)
230 newmatch = narrowspec.match(repo.root, newincludes, newexcludes)
231
232 # This is essentially doing "hg outgoing" to find all local-only
233 # commits. We will then check that the local-only commits don't
234 # have any changes to files that will be untracked.
235 unfi = repo.unfiltered()
236 outgoing = discovery.findcommonoutgoing(unfi, remote, commoninc=commoninc)
237 ui.status(_(b'looking for local changes to affected paths\n'))
238 progress = ui.makeprogress(
239 topic=_(b'changesets'),
240 unit=_(b'changesets'),
241 total=len(outgoing.missing) + len(outgoing.excluded),
242 )
243 localnodes = []
244 with progress:
245 for n in itertools.chain(outgoing.missing, outgoing.excluded):
246 progress.increment()
247 if any(oldmatch(f) and not newmatch(f) for f in unfi[n].files()):
248 localnodes.append(n)
249 revstostrip = unfi.revs(b'descendants(%ln)', localnodes)
250 hiddenrevs = repoview.filterrevs(repo, b'visible')
251 visibletostrip = list(
252 repo.changelog.node(r) for r in (revstostrip - hiddenrevs)
253 )
254 if visibletostrip:
255 ui.status(
256 _(
257 b'The following changeset(s) or their ancestors have '
258 b'local changes not on the remote:\n'
259 )
260 )
261 maxnodes = 10
262 if ui.verbose or len(visibletostrip) <= maxnodes:
263 for n in visibletostrip:
264 ui.status(b'%s\n' % short(n))
265 else:
266 for n in visibletostrip[:maxnodes]:
267 ui.status(b'%s\n' % short(n))
268 ui.status(
269 _(b'...and %d more, use --verbose to list all\n')
270 % (len(visibletostrip) - maxnodes)
271 )
272 if not force:
273 raise error.StateError(
274 _(b'local changes found'),
275 hint=_(b'use --force-delete-local-changes to ignore'),
276 )
277
278 with ui.uninterruptible():
279 if revstostrip:
280 tostrip = [unfi.changelog.node(r) for r in revstostrip]
281 if repo[b'.'].node() in tostrip:
282 # stripping working copy, so move to a different commit first
283 urev = max(
284 repo.revs(
285 b'(::%n) - %ln + null',
286 repo[b'.'].node(),
287 visibletostrip,
288 )
289 )
290 up_impl.clean(repo, urev)
291 overrides = {(b'devel', b'strip-obsmarkers'): False}
292 if backup:
293 ui.status(_(b'moving unwanted changesets to backup\n'))
294 else:
295 ui.status(_(b'deleting unwanted changesets\n'))
296 with ui.configoverride(overrides, b'narrow'):
297 repair.strip(ui, unfi, tostrip, topic=b'narrow', backup=backup)
298
299 todelete = []
300 to_remove_from_file_index = []
301 for entry in repo.store.data_entries():
302 if entry.is_filelog:
303 if not newmatch(entry.target_id):
304 to_remove_from_file_index.append(entry.target_id)
305 for file_ in entry.files(repo.svfs):
306 todelete.append(file_.unencoded_path)
307 elif entry.is_manifestlog:
308 dir = entry.target_id[:-1]
309 dirs = sorted(pathutil.dirs({dir})) + [dir]
310 include = True
311 for d in dirs:
312 visit = newmatch.visitdir(d)
313 if not visit:
314 include = False
315 break
316 if visit == b'all':
317 break
318 if not include:
319 for file_ in entry.files(repo.svfs):
320 todelete.append(file_.unencoded_path)
321
322 repo.destroying()
323
324 with repo.transaction(b'narrowing') as tr:
325 # Update narrowspec before removing revlogs, so repo won't be
326 # corrupt in case of crash
327 repo.setnarrowpats(newincludes, newexcludes)
328
329 fileindex = repo.store.fileindex
330 if fileindex:
331 for path in to_remove_from_file_index:
332 fileindex.remove(path, tr)
333
334 for f in todelete:
335 ui.status(_(b'deleting %s\n') % f)
336 util.unlinkpath(repo.svfs.join(f))
337 repo.store.markremoved(f)
338
339 ui.status(_(b'deleting unwanted files from working copy\n'))
340 with repo.dirstate.changing_parents(repo):
341 narrow_wc.update_working_copy(repo, assumeclean=True)
342 narrowspec.copytoworkingcopy(repo)
343
344 repo.destroyed()
345
346
347 def _widen(
348 ui,
349 repo,
350 remote,
351 commoninc,
352 oldincludes,
353 oldexcludes,
354 newincludes,
355 newexcludes,
356 ):
357 # for now we assume that if a server has ellipses enabled, we will be
358 # exchanging ellipses nodes. In future we should add ellipses as a client
359 # side requirement (maybe) to distinguish a client is shallow or not and
360 # then send that information to server whether we want ellipses or not.
361 # Theoretically a non-ellipses repo should be able to use narrow
362 # functionality from an ellipses enabled server
363 remotecap = remote.capabilities()
364 ellipsesremote = any(
365 cap in remotecap for cap in wireprototypes.SUPPORTED_ELLIPSESCAP
366 )
367
368 # check whether we are talking to a server which supports old version of
369 # ellipses capabilities
370 isoldellipses = (
371 ellipsesremote
372 and wireprototypes.ELLIPSESCAP1 in remotecap
373 and wireprototypes.ELLIPSESCAP not in remotecap
374 )
375
376 def pullbundle2extraprepare_widen(orig, pullop, kwargs):
377 orig(pullop, kwargs)
378 # The old{in,ex}cludepats have already been set by orig()
379 kwargs[b'includepats'] = newincludes
380 kwargs[b'excludepats'] = newexcludes
381
382 wrappedextraprepare = extensions.wrappedfunction(
383 exchange, '_pullbundle2extraprepare', pullbundle2extraprepare_widen
384 )
385
386 # define a function that narrowbundle2 can call after creating the
387 # backup bundle, but before applying the bundle from the server
388 def setnewnarrowpats():
389 repo.setnarrowpats(newincludes, newexcludes)
390
391 repo.setnewnarrowpats = setnewnarrowpats
392 # silence the devel-warning of applying an empty changegroup
393 overrides = {(b'devel', b'all-warnings'): False}
394
395 common = commoninc[0]
396 with ui.uninterruptible():
397 if ellipsesremote:
398 ds = repo.dirstate
399 p1, p2 = ds.p1(), ds.p2()
400 with ds.changing_parents(repo):
401 ds.setparents(repo.nullid, repo.nullid)
402 if isoldellipses:
403 with wrappedextraprepare:
404 exchange.pull(repo, remote, heads=common)
405 else:
406 known = []
407 if ellipsesremote:
408 known = [
409 ctx.node()
410 for ctx in repo.set(b'::%ln', common)
411 if ctx.node() != repo.nullid
412 ]
413 with remote.commandexecutor() as e:
414 bundle = e.callcommand(
415 b'narrow_widen',
416 {
417 b'oldincludes': oldincludes,
418 b'oldexcludes': oldexcludes,
419 b'newincludes': newincludes,
420 b'newexcludes': newexcludes,
421 b'cgversion': b'03',
422 b'commonheads': common,
423 b'known': known,
424 b'ellipses': ellipsesremote,
425 },
426 ).result()
427
428 trmanager = exchange.transactionmanager(
429 repo, b'widen', remote.url()
430 )
431 with trmanager, repo.ui.configoverride(overrides, b'widen'):
432 op = bundle2.bundleoperation(
433 repo, trmanager.transaction, source=b'widen'
434 )
435 # TODO: we should catch error.Abort here
436 bundle2.processbundle(repo, bundle, op=op, remote=remote)
437
438 if ellipsesremote:
439 with ds.changing_parents(repo):
440 ds.setparents(p1, p2)
441
442 with repo.transaction(b'widening'), repo.dirstate.changing_parents(
443 repo
444 ):
445 repo.setnewnarrowpats()
446 narrow_wc.update_working_copy(repo)
447 narrowspec.copytoworkingcopy(repo)
448
449
450 # TODO(rdamazio): Make new matcher format and update description
451 @command(
452 b'tracked',
453 [
454 (b'', b'addinclude', [], _(b'new paths to include')),
455 (b'', b'removeinclude', [], _(b'old paths to no longer include')),
456 (
457 b'',
458 b'auto-remove-includes',
459 False,
460 _(b'automatically choose unused includes to remove'),
461 ),
462 (b'', b'addexclude', [], _(b'new paths to exclude')),
463 (b'', b'import-rules', b'', _(b'import narrowspecs from a file')),
464 (b'', b'removeexclude', [], _(b'old paths to no longer exclude')),
465 (
466 b'',
467 b'clear',
468 False,
469 _(b'whether to replace the existing narrowspec'),
470 ),
471 (
472 b'',
473 b'force-delete-local-changes',
474 False,
475 _(b'forces deletion of local changes when narrowing'),
476 ),
477 (
478 b'',
479 b'backup',
480 True,
481 _(b'back up local changes when narrowing'),
482 ),
483 (
484 b'',
485 b'update-working-copy',
486 False,
487 _(b'update working copy when the store has changed'),
488 ),
489 ]
490 + commands.remoteopts,
491 _(b'[OPTIONS]... [REMOTE]'),
492 inferrepo=True,
493 helpcategory=command.CATEGORY_MAINTENANCE,
494 )
495 def trackedcmd(ui, repo, remotepath=None, *pats, **opts):
496 """show or change the current narrowspec
497
498 With no argument, shows the current narrowspec entries, one per line. Each
499 line will be prefixed with 'I' or 'X' for included or excluded patterns,
500 respectively.
501
502 The narrowspec is comprised of expressions to match remote files and/or
503 directories that should be pulled into your client.
504 The narrowspec has *include* and *exclude* expressions, with excludes always
505 trumping includes: that is, if a file matches an exclude expression, it will
506 be excluded even if it also matches an include expression.
507 Excluding files that were never included has no effect.
508
509 Each included or excluded entry is in the format described by
510 'hg help patterns'.
511
512 The options allow you to add or remove included and excluded expressions.
513
514 If --clear is specified, then all previous includes and excludes are DROPPED
515 and replaced by the new ones specified to --addinclude and --addexclude.
516 If --clear is specified without any further options, the narrowspec will be
517 empty and will not match any files.
518
519 If --auto-remove-includes is specified, then those includes that don't match
520 any files modified by currently visible local commits (those not shared by
521 the remote) will be added to the set of explicitly specified includes to
522 remove.
523
524 --import-rules accepts a path to a file containing rules, allowing you to
525 add --addinclude, --addexclude rules in bulk. Like the other include and
526 exclude switches, the changes are applied immediately.
527 """
528 if not repo.is_narrow:
529 raise error.InputError(
530 _(
531 b'the tracked command is only supported on '
532 b'repositories cloned with --narrow'
533 )
534 )
535
536 # Before supporting, decide whether it "hg tracked --clear" should mean
537 # tracking no paths or all paths.
538 if opts['clear']:
539 raise error.InputError(_(b'the --clear option is not yet supported'))
540
541 # import rules from a file
542 newrules = opts.get('import_rules')
543 if newrules:
544 filepath = os.path.join(encoding.getcwd(), newrules)
545 try:
546 fdata = util.readfile(filepath)
547 except OSError as inst:
548 raise error.StorageError(
549 _(b"cannot read narrowspecs from '%s': %s")
550 % (filepath, encoding.strtolocal(inst.strerror))
551 )
552 includepats, excludepats, profiles = sparse.parseconfig(
553 ui, fdata, b'narrow'
554 )
555 if profiles:
556 raise error.InputError(
557 _(
558 b"including other spec files using '%include' "
559 b"is not supported in narrowspec"
560 )
561 )
562 opts['addinclude'].extend(includepats)
563 opts['addexclude'].extend(excludepats)
564
565 addedincludes = narrowspec.parsepatterns(opts['addinclude'])
566 removedincludes = narrowspec.parsepatterns(opts['removeinclude'])
567 addedexcludes = narrowspec.parsepatterns(opts['addexclude'])
568 removedexcludes = narrowspec.parsepatterns(opts['removeexclude'])
569 autoremoveincludes = opts['auto_remove_includes']
570
571 update_working_copy = opts['update_working_copy']
572 only_show = not (
573 addedincludes
574 or removedincludes
575 or addedexcludes
576 or removedexcludes
577 or newrules
578 or autoremoveincludes
579 or update_working_copy
580 )
581
582 # Only print the current narrowspec.
583 if only_show:
584 oldincludes, oldexcludes = repo.narrowpats
585 ui.pager(b'tracked')
586 fm = ui.formatter(b'narrow', pycompat.byteskwargs(opts))
587 for i in sorted(oldincludes):
588 fm.startitem()
589 fm.write(b'status', b'%s ', b'I', label=b'narrow.included')
590 fm.write(b'pat', b'%s\n', i, label=b'narrow.included')
591 for i in sorted(oldexcludes):
592 fm.startitem()
593 fm.write(b'status', b'%s ', b'X', label=b'narrow.excluded')
594 fm.write(b'pat', b'%s\n', i, label=b'narrow.excluded')
595 fm.end()
596 return 0
597
598 with repo.wlock(), repo.lock():
599 oldincludes, oldexcludes = repo.narrowpats
600
601 # filter the user passed additions and deletions into actual additions and
602 # deletions of excludes and includes
603 addedincludes -= oldincludes
604 removedincludes &= oldincludes
605 addedexcludes -= oldexcludes
606 removedexcludes &= oldexcludes
607
608 widening = addedincludes or removedexcludes
609 narrowing = removedincludes or addedexcludes
610
611 if update_working_copy:
612 with repo.transaction(b'narrow-wc'), repo.dirstate.changing_parents(
613 repo
614 ):
615 narrow_wc.update_working_copy(repo)
616 narrowspec.copytoworkingcopy(repo)
617 return 0
618
619 if not (widening or narrowing or autoremoveincludes):
620 ui.status(_(b"nothing to widen or narrow\n"))
621 return 0
622
623 scmutil.bail_if_changed(repo)
624
625 # Find the revisions we have in common with the remote. These will
626 # be used for finding local-only changes for narrowing. They will
627 # also define the set of revisions to update for widening.
628 path = urlutil.get_unique_pull_path_obj(b'tracked', ui, remotepath)
629 ui.status(_(b'comparing with %s\n') % urlutil.hidepassword(path.loc))
630 remote = repo_factory.peer(repo, pycompat.byteskwargs(opts), path)
631
632 try:
633 # check narrow support before doing anything if widening needs to be
634 # performed. In future we should also abort if client is ellipses and
635 # server does not support ellipses
636 if (
637 widening
638 and wireprototypes.NARROWCAP not in remote.capabilities()
639 ):
640 raise error.Abort(_(b"server does not support narrow clones"))
641
642 commoninc = discovery.findcommonincoming(repo, remote)
643
644 if autoremoveincludes:
645 outgoing = discovery.findcommonoutgoing(
646 repo, remote, commoninc=commoninc
647 )
648 ui.status(_(b'looking for unused includes to remove\n'))
649 localfiles = set()
650 for n in itertools.chain(outgoing.missing, outgoing.excluded):
651 localfiles.update(repo[n].files())
652 suggestedremovals = []
653 for include in sorted(oldincludes):
654 match = narrowspec.match(repo.root, [include], oldexcludes)
655 if not any(match(f) for f in localfiles):
656 suggestedremovals.append(include)
657 if suggestedremovals:
658 for s in suggestedremovals:
659 ui.status(b'%s\n' % s)
660 if (
661 ui.promptchoice(
662 _(
663 b'remove these unused includes (Yn)?'
664 b'$$ &Yes $$ &No'
665 )
666 )
667 == 0
668 ):
669 removedincludes.update(suggestedremovals)
670 narrowing = True
671 else:
672 ui.status(_(b'found no unused includes\n'))
673
674 if narrowing:
675 newincludes = oldincludes - removedincludes
676 newexcludes = oldexcludes | addedexcludes
677 _narrow(
678 ui,
679 repo,
680 remote,
681 commoninc,
682 oldincludes,
683 oldexcludes,
684 newincludes,
685 newexcludes,
686 opts['force_delete_local_changes'],
687 opts['backup'],
688 )
689 # _narrow() updated the narrowspec and _widen() below needs to
690 # use the updated values as its base (otherwise removed includes
691 # and addedexcludes will be lost in the resulting narrowspec)
692 oldincludes = newincludes
693 oldexcludes = newexcludes
694
695 if widening:
696 newincludes = oldincludes | addedincludes
697 newexcludes = oldexcludes - removedexcludes
698 _widen(
699 ui,
700 repo,
701 remote,
702 commoninc,
703 oldincludes,
704 oldexcludes,
705 newincludes,
706 newexcludes,
707 )
708 finally:
709 remote.close()
710
711 return 0