Debian Codegraph @

hgext/keyword.py

raw
1 # keyword.py - $Keyword$ expansion for Mercurial
2 #
3 # Copyright 2007-2015 Christian Ebert <[email protected]>
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 # $Id$
9 #
10 # Keyword expansion hack against the grain of a Distributed SCM
11 #
12 # There are many good reasons why this is not needed in a distributed
13 # SCM, still it may be useful in very small projects based on single
14 # files (like LaTeX packages), that are mostly addressed to an
15 # audience not running a version control system.
16 #
17 # For in-depth discussion refer to
18 # <https://mercurial-scm.org/wiki/KeywordPlan>.
19 #
20 # Keyword expansion is based on Mercurial's changeset template mappings.
21 #
22 # Binary files are not touched.
23 #
24 # Files to act upon/ignore are specified in the [keyword] section.
25 # Customized keyword template mappings in the [keywordmaps] section.
26 #
27 # Run 'hg help keyword' and 'hg kwdemo' to get info on configuration.
28
29 '''expand keywords in tracked files
30
31 This extension expands RCS/CVS-like or self-customized $Keywords$ in
32 tracked text files selected by your configuration.
33
34 Keywords are only expanded in local repositories and not stored in the
35 change history. The mechanism can be regarded as a convenience for the
36 current user or for archive distribution.
37
38 Keywords expand to the changeset data pertaining to the latest change
39 relative to the working directory parent of each file.
40
41 Configuration is done in the [keyword], [keywordset] and [keywordmaps]
42 sections of hgrc files.
43
44 Example::
45
46 [keyword]
47 # expand keywords in every python file except those matching "x*"
48 **.py =
49 x* = ignore
50
51 [keywordset]
52 # prefer svn- over cvs-like default keywordmaps
53 svn = True
54
55 .. note::
56
57 The more specific you are in your filename patterns the less you
58 lose speed in huge repositories.
59
60 For [keywordmaps] template mapping and expansion demonstration and
61 control run :hg:`kwdemo`. See :hg:`help templates` for a list of
62 available templates and filters.
63
64 Three additional date template filters are provided:
65
66 :``utcdate``: "2006/09/18 15:13:13"
67 :``svnutcdate``: "2006-09-18 15:13:13Z"
68 :``svnisodate``: "2006-09-18 08:13:13 -700 (Mon, 18 Sep 2006)"
69
70 The default template mappings (view with :hg:`kwdemo -d`) can be
71 replaced with customized keywords and templates. Again, run
72 :hg:`kwdemo` to control the results of your configuration changes.
73
74 Before changing/disabling active keywords, you must run :hg:`kwshrink`
75 to avoid storing expanded keywords in the change history.
76
77 To force expansion after enabling it, or a configuration change, run
78 :hg:`kwexpand`.
79
80 Expansions spanning more than one line and incremental expansions,
81 like CVS' $Log$, are not supported. A keyword template map "Log =
82 {desc}" expands to the first line of the changeset description.
83 '''
84
85
86 from __future__ import annotations
87
88 import os
89 import re
90 import weakref
91
92 from mercurial.i18n import _
93 from mercurial.hgweb import webcommands
94
95 from mercurial import (
96 cmdutil,
97 context,
98 dispatch,
99 error,
100 extensions,
101 filelog,
102 localrepo,
103 logcmdutil,
104 match,
105 merge,
106 patch,
107 pathutil,
108 pycompat,
109 registrar,
110 scmutil,
111 templatefilters,
112 templateutil,
113 util,
114 )
115 from mercurial.utils import (
116 dateutil,
117 stringutil,
118 )
119 from mercurial.dirstateutils import timestamp
120
121 cmdtable = {}
122 command = registrar.command(cmdtable)
123 # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
124 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
125 # be specifying the version(s) of Mercurial they are tested with, or
126 # leave the attribute unspecified.
127 testedwith = b'ships-with-hg-core'
128
129 # hg commands that do not act on keywords
130 nokwcommands = (
131 b'add addremove annotate bundle export grep incoming init log'
132 b' outgoing push tip verify convert email glog'
133 )
134
135 # webcommands that do not act on keywords
136 nokwwebcommands = 'annotate changeset rev filediff diff comparison'
137
138 # hg commands that trigger expansion only when writing to working dir,
139 # not when reading filelog, and unexpand when reading from working dir
140 restricted = (
141 b'merge kwexpand kwshrink record qrecord resolve transplant'
142 b' unshelve rebase graft backout histedit fetch'
143 )
144
145 # names of extensions using dorecord
146 recordextensions = b'record'
147
148 colortable = {
149 b'kwfiles.enabled': b'green bold',
150 b'kwfiles.deleted': b'cyan bold underline',
151 b'kwfiles.enabledunknown': b'green',
152 b'kwfiles.ignored': b'bold',
153 b'kwfiles.ignoredunknown': b'none',
154 }
155
156 templatefilter = registrar.templatefilter()
157
158 configtable = {}
159 configitem = registrar.configitem(configtable)
160
161 configitem(
162 b'keywordset',
163 b'svn',
164 default=False,
165 )
166
167
168 # date like in cvs' $Date
169 @templatefilter(b'utcdate', intype=templateutil.date)
170 def utcdate(date):
171 """Date. Returns a UTC-date in this format: "2009/08/18 11:00:13"."""
172 dateformat = b'%Y/%m/%d %H:%M:%S'
173 return dateutil.datestr((date[0], 0), dateformat)
174
175
176 # date like in svn's $Date
177 @templatefilter(b'svnisodate', intype=templateutil.date)
178 def svnisodate(date):
179 """Date. Returns a date in this format: "2009-08-18 13:00:13
180 +0200 (Tue, 18 Aug 2009)".
181 """
182 return dateutil.datestr(date, b'%Y-%m-%d %H:%M:%S %1%2 (%a, %d %b %Y)')
183
184
185 # date like in svn's $Id
186 @templatefilter(b'svnutcdate', intype=templateutil.date)
187 def svnutcdate(date):
188 """Date. Returns a UTC-date in this format: "2009-08-18
189 11:00:13Z".
190 """
191 dateformat = b'%Y-%m-%d %H:%M:%SZ'
192 return dateutil.datestr((date[0], 0), dateformat)
193
194
195 # make keyword tools accessible
196 kwtools = {b'hgcmd': b''}
197
198
199 def _defaultkwmaps(ui):
200 '''Returns default keywordmaps according to keywordset configuration.'''
201 templates = {
202 b'Revision': b'{node|short}',
203 b'Author': b'{author|user}',
204 }
205 kwsets = (
206 {
207 b'Date': b'{date|utcdate}',
208 b'RCSfile': b'{file|basename},v',
209 b'RCSFile': b'{file|basename},v', # kept for backwards compatibility
210 # with hg-keyword
211 b'Source': b'{root}/{file},v',
212 b'Id': b'{file|basename},v {node|short} {date|utcdate} {author|user}',
213 b'Header': b'{root}/{file},v {node|short} {date|utcdate} {author|user}',
214 },
215 {
216 b'Date': b'{date|svnisodate}',
217 b'Id': b'{file|basename},v {node|short} {date|svnutcdate} {author|user}',
218 b'LastChangedRevision': b'{node|short}',
219 b'LastChangedBy': b'{author|user}',
220 b'LastChangedDate': b'{date|svnisodate}',
221 },
222 )
223 templates.update(kwsets[ui.configbool(b'keywordset', b'svn')])
224 return templates
225
226
227 def _shrinktext(text, subfunc):
228 """Helper for keyword expansion removal in text.
229 Depending on subfunc also returns number of substitutions."""
230 return subfunc(br'$\1$', text)
231
232
233 def _preselect(wstatus, changed):
234 """Retrieves modified and added files from a working directory state
235 and returns the subset of each contained in given changed files
236 retrieved from a change context."""
237 modified = [f for f in wstatus.modified if f in changed]
238 added = [f for f in wstatus.added if f in changed]
239 return modified, added
240
241
242 class kwtemplater:
243 """
244 Sets up keyword templates, corresponding keyword regex, and
245 provides keyword substitution functions.
246 """
247
248 def __init__(self, ui, repo, inc, exc):
249 self.ui = ui
250 self._repo = weakref.ref(repo)
251 self.match = match.match(repo.root, b'', [], inc, exc)
252 self.restrict = kwtools[b'hgcmd'] in restricted.split()
253 self.postcommit = False
254
255 kwmaps = self.ui.configitems(b'keywordmaps')
256 if kwmaps: # override default templates
257 self.templates = dict(kwmaps)
258 else:
259 self.templates = _defaultkwmaps(self.ui)
260
261 @property
262 def repo(self):
263 return self._repo()
264
265 @util.propertycache
266 def escape(self):
267 '''Returns bar-separated and escaped keywords.'''
268 return b'|'.join(map(stringutil.reescape, self.templates.keys()))
269
270 @util.propertycache
271 def rekw(self):
272 '''Returns regex for unexpanded keywords.'''
273 return re.compile(br'\$(%s)\$' % self.escape)
274
275 @util.propertycache
276 def rekwexp(self):
277 '''Returns regex for expanded keywords.'''
278 return re.compile(br'\$(%s): [^$\n\r]*? \$' % self.escape)
279
280 def substitute(self, data, path, ctx, subfunc):
281 '''Replaces keywords in data with expanded template.'''
282
283 def kwsub(mobj):
284 kw = mobj.group(1)
285 ct = logcmdutil.maketemplater(
286 self.ui, self.repo, self.templates[kw]
287 )
288 self.ui.pushbuffer()
289 ct.show(ctx, root=self.repo.root, file=path)
290 ekw = templatefilters.firstline(self.ui.popbuffer())
291 return b'$%s: %s $' % (kw, ekw)
292
293 return subfunc(kwsub, data)
294
295 def linkctx(self, path, fileid):
296 '''Similar to filelog.linkrev, but returns a changectx.'''
297 return self.repo.filectx(path, fileid=fileid).changectx()
298
299 def expand(self, path, node, data):
300 '''Returns data with keywords expanded.'''
301 if (
302 not self.restrict
303 and self.match(path)
304 and not stringutil.binary(data)
305 ):
306 ctx = self.linkctx(path, node)
307 return self.substitute(data, path, ctx, self.rekw.sub)
308 return data
309
310 def iskwfile(self, cand, ctx):
311 """Returns subset of candidates which are configured for keyword
312 expansion but are not symbolic links."""
313 return [f for f in cand if self.match(f) and b'l' not in ctx.flags(f)]
314
315 def overwrite(self, ctx, candidates, lookup, expand, rekw=False):
316 '''Overwrites selected files expanding/shrinking keywords.'''
317 if self.restrict or lookup or self.postcommit: # exclude kw_copy
318 candidates = self.iskwfile(candidates, ctx)
319 if not candidates:
320 return
321 kwcmd = self.restrict and lookup # kwexpand/kwshrink
322 if self.restrict or expand and lookup:
323 mf = ctx.manifest()
324 if self.restrict or rekw:
325 re_kw = self.rekw
326 else:
327 re_kw = self.rekwexp
328 if expand:
329 msg = _(b'overwriting %s expanding keywords\n')
330 else:
331 msg = _(b'overwriting %s shrinking keywords\n')
332 wctx = self.repo[None]
333 for f in candidates:
334 if self.restrict:
335 data = self.repo.file(f).read(mf[f])
336 else:
337 data = self.repo.wread(f)
338 if stringutil.binary(data):
339 continue
340 if expand:
341 parents = ctx.parents()
342 if lookup:
343 ctx = self.linkctx(f, mf[f])
344 elif self.restrict and len(parents) > 1:
345 # merge commit
346 # in case of conflict f is in modified state during
347 # merge, even if f does not differ from f in parent
348 for p in parents:
349 if f in p and not p[f].cmp(ctx[f]):
350 ctx = p[f].changectx()
351 break
352 data, found = self.substitute(data, f, ctx, re_kw.subn)
353 elif self.restrict:
354 found = re_kw.search(data)
355 else:
356 data, found = _shrinktext(data, re_kw.subn)
357 if found:
358 self.ui.note(msg % f)
359 fp = self.repo.wvfs(f, b"wb", atomictemp=True)
360 fp.write(data)
361 fp.close()
362 if kwcmd:
363 s = wctx[f].lstat()
364 mode = s.st_mode
365 size = s.st_size
366 mtime = timestamp.mtime_of(s)
367 cache_data = (mode, size, mtime)
368 self.repo.dirstate.set_clean(f, cache_data)
369 elif self.postcommit:
370 self.repo.dirstate.update_file_p1(f, p1_tracked=True)
371
372 def shrink(self, fname, text):
373 '''Returns text with all keyword substitutions removed.'''
374 if self.match(fname) and not stringutil.binary(text):
375 return _shrinktext(text, self.rekwexp.sub)
376 return text
377
378 def shrinklines(self, fname, lines):
379 '''Returns lines with keyword substitutions removed.'''
380 if self.match(fname):
381 text = b''.join(lines)
382 if not stringutil.binary(text):
383 return _shrinktext(text, self.rekwexp.sub).splitlines(True)
384 return lines
385
386 def wread(self, fname, data):
387 """If in restricted mode returns data read from wdir with
388 keyword substitutions removed."""
389 if self.restrict:
390 return self.shrink(fname, data)
391 return data
392
393
394 class kwfilelog(filelog.filelog):
395 """
396 Subclass of filelog to hook into its read, add, cmp methods.
397 Keywords are "stored" unexpanded, and processed on reading.
398 """
399
400 def __init__(self, opener, kwt, path, radix, writable=False):
401 super().__init__(opener, path, radix, writable=writable)
402 self.kwt = kwt
403 self.path = path
404
405 def read(self, node):
406 '''Expands keywords when reading filelog.'''
407 data = super().read(node)
408 if self.renamed(node):
409 return data
410 return self.kwt.expand(self.path, node, data)
411
412 def add(self, text, meta, tr, link, p1=None, p2=None):
413 '''Removes keyword substitutions when adding to filelog.'''
414 text = self.kwt.shrink(self.path, text)
415 return super().add(text, meta, tr, link, p1, p2)
416
417 def cmp(self, node, text):
418 '''Removes keyword substitutions for comparison.'''
419 text = self.kwt.shrink(self.path, text)
420 return super().cmp(node, text)
421
422
423 def _status(ui, repo, wctx, kwt, *pats, **opts):
424 """Bails out if [keyword] configuration is not active.
425 Returns status of working directory."""
426 if kwt:
427 return repo.status(
428 match=scmutil.match(wctx, pats, pycompat.byteskwargs(opts)),
429 clean=True,
430 unknown=opts.get('unknown') or opts.get('all'),
431 )
432 if ui.configitems(b'keyword'):
433 raise error.Abort(_(b'[keyword] patterns cannot match'))
434 raise error.Abort(_(b'no [keyword] patterns configured'))
435
436
437 def _kwfwrite(ui, repo, expand, *pats, **opts):
438 '''Selects files and passes them to kwtemplater.overwrite.'''
439 wctx = repo[None]
440 if len(wctx.parents()) > 1:
441 raise error.Abort(_(b'outstanding uncommitted merge'))
442 kwt = getattr(repo, '_keywordkwt', None)
443 with repo.wlock(), repo.dirstate.changing_files(repo):
444 status = _status(ui, repo, wctx, kwt, *pats, **opts)
445 if status.modified or status.added or status.removed or status.deleted:
446 raise error.Abort(_(b'outstanding uncommitted changes'))
447 kwt.overwrite(wctx, status.clean, True, expand)
448
449
450 @command(
451 b'kwdemo',
452 [
453 (b'd', b'default', None, _(b'show default keyword template maps')),
454 (b'f', b'rcfile', b'', _(b'read maps from rcfile'), _(b'FILE')),
455 ],
456 _(b'hg kwdemo [-d] [-f RCFILE] [TEMPLATEMAP]...'),
457 optionalrepo=True,
458 )
459 def demo(ui, repo, *args, **opts):
460 """print [keywordmaps] configuration and an expansion example
461
462 Show current, custom, or default keyword template maps and their
463 expansions.
464
465 Extend the current configuration by specifying maps as arguments
466 and using -f/--rcfile to source an external hgrc file.
467
468 Use -d/--default to disable current configuration.
469
470 See :hg:`help templates` for information on templates and filters.
471 """
472
473 def demoitems(section, items):
474 ui.write(b'[%s]\n' % section)
475 for k, v in sorted(items):
476 if isinstance(v, bool):
477 v = stringutil.pprint(v)
478 ui.write(b'%s = %s\n' % (k, v))
479
480 fn = b'demo.txt'
481 tmpdir = pycompat.mkdtemp(b'', b'kwdemo.')
482 ui.note(_(b'creating temporary repository at %s\n') % tmpdir)
483 if repo is None:
484 baseui = ui
485 else:
486 baseui = repo.baseui
487 repo = localrepo.instance(baseui, tmpdir, create=True)
488 ui.setconfig(b'keyword', fn, b'', b'keyword')
489 svn = ui.configbool(b'keywordset', b'svn')
490 # explicitly set keywordset for demo output
491 ui.setconfig(b'keywordset', b'svn', svn, b'keyword')
492
493 uikwmaps = ui.configitems(b'keywordmaps')
494 if args or opts.get('rcfile'):
495 ui.status(_(b'\n\tconfiguration using custom keyword template maps\n'))
496 if uikwmaps:
497 ui.status(_(b'\textending current template maps\n'))
498 if opts.get('default') or not uikwmaps:
499 if svn:
500 ui.status(_(b'\toverriding default svn keywordset\n'))
501 else:
502 ui.status(_(b'\toverriding default cvs keywordset\n'))
503 if opts.get('rcfile'):
504 ui.readconfig(opts.get(b'rcfile'))
505 if args:
506 # simulate hgrc parsing
507 rcmaps = b'[keywordmaps]\n%s\n' % b'\n'.join(args)
508 repo.vfs.write(b'hgrc', rcmaps)
509 ui.readconfig(repo.vfs.join(b'hgrc'))
510 kwmaps = dict(ui.configitems(b'keywordmaps'))
511 elif opts.get('default'):
512 if svn:
513 ui.status(_(b'\n\tconfiguration using default svn keywordset\n'))
514 else:
515 ui.status(_(b'\n\tconfiguration using default cvs keywordset\n'))
516 kwmaps = _defaultkwmaps(ui)
517 if uikwmaps:
518 ui.status(_(b'\tdisabling current template maps\n'))
519 for k, v in kwmaps.items():
520 ui.setconfig(b'keywordmaps', k, v, b'keyword')
521 else:
522 ui.status(_(b'\n\tconfiguration using current keyword template maps\n'))
523 if uikwmaps:
524 kwmaps = dict(uikwmaps)
525 else:
526 kwmaps = _defaultkwmaps(ui)
527
528 uisetup(ui)
529 reposetup(ui, repo)
530 ui.writenoi18n(b'[extensions]\nkeyword =\n')
531 demoitems(b'keyword', ui.configitems(b'keyword'))
532 demoitems(b'keywordset', ui.configitems(b'keywordset'))
533 demoitems(b'keywordmaps', kwmaps.items())
534 keywords = b'$' + b'$\n$'.join(sorted(kwmaps.keys())) + b'$\n'
535 repo.wvfs.write(fn, keywords)
536 with repo.wlock():
537 with repo.dirstate.changing_files(repo):
538 repo[None].add([fn])
539 ui.note(_(b'\nkeywords written to %s:\n') % fn)
540 ui.note(keywords)
541 repo.dirstate.setbranch(b'demobranch', repo.currenttransaction())
542 for name, cmd in ui.configitems(b'hooks'):
543 if name.split(b'.', 1)[0].find(b'commit') > -1:
544 repo.ui.setconfig(b'hooks', name, b'', b'keyword')
545 msg = _(b'hg keyword configuration and expansion example')
546 ui.notenoi18n(b"hg ci -m '%s'\n" % msg)
547 repo.commit(text=msg)
548 ui.status(_(b'\n\tkeywords expanded\n'))
549 ui.write(repo.wread(fn))
550 repo.wvfs.rmtree(repo.root)
551
552
553 @command(
554 b'kwexpand',
555 cmdutil.walkopts,
556 _(b'hg kwexpand [OPTION]... [FILE]...'),
557 inferrepo=True,
558 )
559 def expand(ui, repo, *pats, **opts):
560 """expand keywords in the working directory
561
562 Run after (re)enabling keyword expansion.
563
564 kwexpand refuses to run if given files contain local changes.
565 """
566 # 3rd argument sets expansion to True
567 _kwfwrite(ui, repo, True, *pats, **opts)
568
569
570 @command(
571 b'kwfiles',
572 [
573 (b'A', b'all', None, _(b'show keyword status flags of all files')),
574 (b'i', b'ignore', None, _(b'show files excluded from expansion')),
575 (b'u', b'unknown', None, _(b'only show unknown (not tracked) files')),
576 ]
577 + cmdutil.walkopts,
578 _(b'hg kwfiles [OPTION]... [FILE]...'),
579 inferrepo=True,
580 )
581 def files(ui, repo, *pats, **opts):
582 """show files configured for keyword expansion
583
584 List which files in the working directory are matched by the
585 [keyword] configuration patterns.
586
587 Useful to prevent inadvertent keyword expansion and to speed up
588 execution by including only files that are actual candidates for
589 expansion.
590
591 See :hg:`help keyword` on how to construct patterns both for
592 inclusion and exclusion of files.
593
594 With -A/--all and -v/--verbose the codes used to show the status
595 of files are::
596
597 K = keyword expansion candidate
598 k = keyword expansion candidate (not tracked)
599 I = ignored
600 i = ignored (not tracked)
601 """
602 kwt = getattr(repo, '_keywordkwt', None)
603 wctx = repo[None]
604 status = _status(ui, repo, wctx, kwt, *pats, **opts)
605 if pats:
606 cwd = repo.getcwd()
607 else:
608 cwd = b''
609 files = []
610
611 if not opts.get('unknown') or opts.get('all'):
612 files = sorted(status.modified + status.added + status.clean)
613 kwfiles = kwt.iskwfile(files, wctx)
614 kwdeleted = kwt.iskwfile(status.deleted, wctx)
615 kwunknown = kwt.iskwfile(status.unknown, wctx)
616 if not opts.get('ignore') or opts.get('all'):
617 showfiles = kwfiles, kwdeleted, kwunknown
618 else:
619 showfiles = [], [], []
620 if opts.get('all') or opts.get('ignore'):
621 showfiles += (
622 [f for f in files if f not in kwfiles],
623 [f for f in status.unknown if f not in kwunknown],
624 )
625 kwlabels = b'enabled deleted enabledunknown ignored ignoredunknown'.split()
626 kwstates = zip(kwlabels, pycompat.bytestr(b'K!kIi'), showfiles)
627 fm = ui.formatter(b'kwfiles', pycompat.byteskwargs(opts))
628 fmt = b'%.0s%s\n'
629 if opts.get('all') or ui.verbose:
630 fmt = b'%s %s\n'
631 for kwstate, char, filenames in kwstates:
632 label = b'kwfiles.' + kwstate
633 for f in filenames:
634 fm.startitem()
635 fm.data(kwstatus=char, path=f)
636 fm.plain(fmt % (char, repo.pathto(f, cwd)), label=label)
637 fm.end()
638
639
640 @command(
641 b'kwshrink',
642 cmdutil.walkopts,
643 _(b'hg kwshrink [OPTION]... [FILE]...'),
644 inferrepo=True,
645 )
646 def shrink(ui, repo, *pats, **opts):
647 """revert expanded keywords in the working directory
648
649 Must be run before changing/disabling active keywords.
650
651 kwshrink refuses to run if given files contain local changes.
652 """
653 # 3rd argument sets expansion to False
654 _kwfwrite(ui, repo, False, *pats, **opts)
655
656
657 # monkeypatches
658
659
660 def kwpatchfile_init(orig, self, ui, gp, backend, store, eolmode=None):
661 """Monkeypatch/wrap patch.patchfile.__init__ to avoid
662 rejects or conflicts due to expanded keywords in working dir."""
663 orig(self, ui, gp, backend, store, eolmode)
664 kwt = getattr(getattr(backend, 'repo', None), '_keywordkwt', None)
665 if kwt:
666 # shrink keywords read from working dir
667 self.lines = kwt.shrinklines(self.fname, self.lines)
668
669
670 def kwdiff(orig, repo, *args, **kwargs):
671 '''Monkeypatch patch.diff to avoid expansion.'''
672 kwt = getattr(repo, '_keywordkwt', None)
673 if kwt:
674 restrict = kwt.restrict
675 kwt.restrict = True
676 try:
677 yield from orig(repo, *args, **kwargs)
678 finally:
679 if kwt:
680 kwt.restrict = restrict
681
682
683 def kwweb_skip(orig, web):
684 '''Wraps webcommands.x turning off keyword expansion.'''
685 kwt = getattr(web.repo, '_keywordkwt', None)
686 if kwt:
687 origmatch = kwt.match
688 kwt.match = util.never
689 try:
690 yield from orig(web)
691 finally:
692 if kwt:
693 kwt.match = origmatch
694
695
696 def kw_amend(orig, ui, repo, old, extra, pats, opts):
697 '''Wraps cmdutil.amend expanding keywords after amend.'''
698 kwt = getattr(repo, '_keywordkwt', None)
699 if kwt is None:
700 return orig(ui, repo, old, extra, pats, opts)
701 with repo.wlock(), repo.dirstate.changing_parents(repo):
702 kwt.postcommit = True
703 newid = orig(ui, repo, old, extra, pats, opts)
704 if newid != old.node():
705 ctx = repo[newid]
706 kwt.restrict = True
707 kwt.overwrite(ctx, ctx.files(), False, True)
708 kwt.restrict = False
709 return newid
710
711
712 def kw_copy(orig, ui, repo, pats, opts, rename=False):
713 """Wraps cmdutil.copy so that copy/rename destinations do not
714 contain expanded keywords.
715 Note that the source of a regular file destination may also be a
716 symlink:
717 hg cp sym x -> x is symlink
718 cp sym x; hg cp -A sym x -> x is file (maybe expanded keywords)
719 For the latter we have to follow the symlink to find out whether its
720 target is configured for expansion and we therefore must unexpand the
721 keywords in the destination."""
722 kwt = getattr(repo, '_keywordkwt', None)
723 if kwt is None:
724 return orig(ui, repo, pats, opts, rename)
725 with repo.wlock():
726 orig(ui, repo, pats, opts, rename)
727 if opts.get(b'dry_run'):
728 return
729 wctx = repo[None]
730 cwd = repo.getcwd()
731
732 def haskwsource(dest):
733 """Returns true if dest is a regular file and configured for
734 expansion or a symlink which points to a file configured for
735 expansion."""
736 source = repo.dirstate.copied(dest)
737 if b'l' in wctx.flags(source):
738 source = pathutil.canonpath(
739 repo.root, cwd, os.path.realpath(source)
740 )
741 return kwt.match(source)
742
743 candidates = [
744 f
745 for f in repo.dirstate.copies()
746 if b'l' not in wctx.flags(f) and haskwsource(f)
747 ]
748 kwt.overwrite(wctx, candidates, False, False)
749
750
751 def kw_dorecord(orig, ui, repo, commitfunc, *pats, **opts):
752 '''Wraps record.dorecord expanding keywords after recording.'''
753 kwt = getattr(repo, '_keywordkwt', None)
754 if kwt is None:
755 return orig(ui, repo, commitfunc, *pats, **opts)
756 with repo.wlock():
757 # record returns 0 even when nothing has changed
758 # therefore compare nodes before and after
759 kwt.postcommit = True
760 ctx = repo[b'.']
761 wstatus = ctx.status()
762 ret = orig(ui, repo, commitfunc, *pats, **opts)
763 recctx = repo[b'.']
764 if ctx != recctx:
765 modified, added = _preselect(wstatus, recctx.files())
766 kwt.restrict = False
767 with repo.dirstate.changing_parents(repo):
768 kwt.overwrite(recctx, modified, False, True)
769 kwt.overwrite(recctx, added, False, True, True)
770 kwt.restrict = True
771 return ret
772
773
774 def kwfilectx_cmp(orig, self, fctx):
775 if fctx._customcmp:
776 return fctx.cmp(self)
777 kwt = getattr(self._repo, '_keywordkwt', None)
778 if kwt is None:
779 return orig(self, fctx)
780 # keyword affects data size, comparing wdir and filelog size does
781 # not make sense
782 if (
783 fctx._filenode is None
784 and (
785 self._repo._encodefilterpats
786 or kwt.match(fctx.path())
787 and b'l' not in fctx.flags()
788 or self.size() - 4 == fctx.size()
789 )
790 or self.size() == fctx.size()
791 ):
792 return self._filelog.cmp(self._filenode, fctx.data())
793 return True
794
795
796 def uisetup(ui):
797 """Monkeypatches dispatch._parse to retrieve user command.
798 Overrides file method to return kwfilelog instead of filelog
799 if file matches user configuration.
800 Wraps commit to overwrite configured files with updated
801 keyword substitutions.
802 Monkeypatches patch and webcommands."""
803
804 def kwdispatch_parse(orig, ui, args):
805 '''Monkeypatch dispatch._parse to obtain running hg command.'''
806 cmd, func, args, options, cmdoptions = orig(ui, args)
807 kwtools[b'hgcmd'] = cmd
808 return cmd, func, args, options, cmdoptions
809
810 extensions.wrapfunction(dispatch, '_parse', kwdispatch_parse)
811
812 extensions.wrapfunction(context.filectx, 'cmp', kwfilectx_cmp)
813 extensions.wrapfunction(patch.patchfile, '__init__', kwpatchfile_init)
814 extensions.wrapfunction(patch, 'diff', kwdiff)
815 extensions.wrapfunction(cmdutil, 'amend', kw_amend)
816 extensions.wrapfunction(cmdutil, 'copy', kw_copy)
817 extensions.wrapfunction(cmdutil, 'dorecord', kw_dorecord)
818 for c in nokwwebcommands.split():
819 extensions.wrapfunction(webcommands, c, kwweb_skip)
820 merge.MAYBE_USE_RUST_UPDATE = False
821
822
823 def reposetup(ui, repo):
824 '''Sets up repo as kwrepo for keyword substitution.'''
825
826 try:
827 if (
828 not repo.local()
829 or kwtools[b'hgcmd'] in nokwcommands.split()
830 or b'.hg' in util.splitpath(repo.root)
831 or repo._url.startswith(b'bundle:')
832 ):
833 return
834 except AttributeError:
835 pass
836
837 inc, exc = [], [b'.hg*']
838 for pat, opt in ui.configitems(b'keyword'):
839 if opt != b'ignore':
840 inc.append(pat)
841 else:
842 exc.append(pat)
843 if not inc:
844 return
845
846 kwt = kwtemplater(ui, repo, inc, exc)
847
848 class kwrepo(repo.__class__):
849 def file(self, f, writable=False):
850 if f[0] == b'/':
851 f = f[1:]
852 if writable:
853 tr = repo.currenttransaction()
854 radix = repo.store.filelog_radix_for_writing(f, tr)
855 else:
856 radix = repo.store.filelog_radix_for_reading(f)
857 return kwfilelog(self.svfs, kwt, f, radix=radix, writable=writable)
858
859 def wread(self, filename: bytes) -> bytes:
860 data = super().wread(filename)
861 return kwt.wread(filename, data)
862
863 def commit(self, *args, **opts):
864 # use custom commitctx for user commands
865 # other extensions can still wrap repo.commitctx directly
866 self.commitctx = self.kwcommitctx
867 try:
868 return super().commit(*args, **opts)
869 finally:
870 del self.commitctx
871
872 def kwcommitctx(self, ctx, error=False, origctx=None):
873 n = super().commitctx(ctx, error, origctx)
874 # no lock needed, only called from repo.commit() which already locks
875 if not kwt.postcommit:
876 restrict = kwt.restrict
877 kwt.restrict = True
878 kwt.overwrite(
879 self[n], sorted(ctx.added() + ctx.modified()), False, True
880 )
881 kwt.restrict = restrict
882 return n
883
884 def rollback(self, dryrun=False, force=False):
885 with self.wlock():
886 origrestrict = kwt.restrict
887 try:
888 if not dryrun:
889 changed = self[b'.'].files()
890 ret = super().rollback(dryrun, force)
891 if not dryrun:
892 ctx = self[b'.']
893 modified, added = _preselect(ctx.status(), changed)
894 kwt.restrict = False
895 kwt.overwrite(ctx, modified, True, True)
896 kwt.overwrite(ctx, added, True, False)
897 return ret
898 finally:
899 kwt.restrict = origrestrict
900
901 repo.__class__ = kwrepo
902 repo._keywordkwt = kwt