PageRenderTime 52ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/hgext/keyword.py

https://bitbucket.org/mirror/mercurial/
Python | 741 lines | 695 code | 1 blank | 45 comment | 0 complexity | cb5f67a88e1ef5f8aab48c92ddc64d36 MD5 | raw file
Possible License(s): GPL-2.0
  1. # keyword.py - $Keyword$ expansion for Mercurial
  2. #
  3. # Copyright 2007-2012 Christian Ebert <blacktrash@gmx.net>
  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. # <http://mercurial.selenic.com/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. '''expand keywords in tracked files
  29. This extension expands RCS/CVS-like or self-customized $Keywords$ in
  30. tracked text files selected by your configuration.
  31. Keywords are only expanded in local repositories and not stored in the
  32. change history. The mechanism can be regarded as a convenience for the
  33. current user or for archive distribution.
  34. Keywords expand to the changeset data pertaining to the latest change
  35. relative to the working directory parent of each file.
  36. Configuration is done in the [keyword], [keywordset] and [keywordmaps]
  37. sections of hgrc files.
  38. Example::
  39. [keyword]
  40. # expand keywords in every python file except those matching "x*"
  41. **.py =
  42. x* = ignore
  43. [keywordset]
  44. # prefer svn- over cvs-like default keywordmaps
  45. svn = True
  46. .. note::
  47. The more specific you are in your filename patterns the less you
  48. lose speed in huge repositories.
  49. For [keywordmaps] template mapping and expansion demonstration and
  50. control run :hg:`kwdemo`. See :hg:`help templates` for a list of
  51. available templates and filters.
  52. Three additional date template filters are provided:
  53. :``utcdate``: "2006/09/18 15:13:13"
  54. :``svnutcdate``: "2006-09-18 15:13:13Z"
  55. :``svnisodate``: "2006-09-18 08:13:13 -700 (Mon, 18 Sep 2006)"
  56. The default template mappings (view with :hg:`kwdemo -d`) can be
  57. replaced with customized keywords and templates. Again, run
  58. :hg:`kwdemo` to control the results of your configuration changes.
  59. Before changing/disabling active keywords, you must run :hg:`kwshrink`
  60. to avoid storing expanded keywords in the change history.
  61. To force expansion after enabling it, or a configuration change, run
  62. :hg:`kwexpand`.
  63. Expansions spanning more than one line and incremental expansions,
  64. like CVS' $Log$, are not supported. A keyword template map "Log =
  65. {desc}" expands to the first line of the changeset description.
  66. '''
  67. from mercurial import commands, context, cmdutil, dispatch, filelog, extensions
  68. from mercurial import localrepo, match, patch, templatefilters, templater, util
  69. from mercurial import scmutil, pathutil
  70. from mercurial.hgweb import webcommands
  71. from mercurial.i18n import _
  72. import os, re, shutil, tempfile
  73. cmdtable = {}
  74. command = cmdutil.command(cmdtable)
  75. testedwith = 'internal'
  76. # hg commands that do not act on keywords
  77. nokwcommands = ('add addremove annotate bundle export grep incoming init log'
  78. ' outgoing push tip verify convert email glog')
  79. # hg commands that trigger expansion only when writing to working dir,
  80. # not when reading filelog, and unexpand when reading from working dir
  81. restricted = ('merge kwexpand kwshrink record qrecord resolve transplant'
  82. ' unshelve rebase graft backout histedit fetch')
  83. # names of extensions using dorecord
  84. recordextensions = 'record'
  85. colortable = {
  86. 'kwfiles.enabled': 'green bold',
  87. 'kwfiles.deleted': 'cyan bold underline',
  88. 'kwfiles.enabledunknown': 'green',
  89. 'kwfiles.ignored': 'bold',
  90. 'kwfiles.ignoredunknown': 'none'
  91. }
  92. # date like in cvs' $Date
  93. def utcdate(text):
  94. ''':utcdate: Date. Returns a UTC-date in this format: "2009/08/18 11:00:13".
  95. '''
  96. return util.datestr((util.parsedate(text)[0], 0), '%Y/%m/%d %H:%M:%S')
  97. # date like in svn's $Date
  98. def svnisodate(text):
  99. ''':svnisodate: Date. Returns a date in this format: "2009-08-18 13:00:13
  100. +0200 (Tue, 18 Aug 2009)".
  101. '''
  102. return util.datestr(text, '%Y-%m-%d %H:%M:%S %1%2 (%a, %d %b %Y)')
  103. # date like in svn's $Id
  104. def svnutcdate(text):
  105. ''':svnutcdate: Date. Returns a UTC-date in this format: "2009-08-18
  106. 11:00:13Z".
  107. '''
  108. return util.datestr((util.parsedate(text)[0], 0), '%Y-%m-%d %H:%M:%SZ')
  109. templatefilters.filters.update({'utcdate': utcdate,
  110. 'svnisodate': svnisodate,
  111. 'svnutcdate': svnutcdate})
  112. # make keyword tools accessible
  113. kwtools = {'templater': None, 'hgcmd': ''}
  114. def _defaultkwmaps(ui):
  115. '''Returns default keywordmaps according to keywordset configuration.'''
  116. templates = {
  117. 'Revision': '{node|short}',
  118. 'Author': '{author|user}',
  119. }
  120. kwsets = ({
  121. 'Date': '{date|utcdate}',
  122. 'RCSfile': '{file|basename},v',
  123. 'RCSFile': '{file|basename},v', # kept for backwards compatibility
  124. # with hg-keyword
  125. 'Source': '{root}/{file},v',
  126. 'Id': '{file|basename},v {node|short} {date|utcdate} {author|user}',
  127. 'Header': '{root}/{file},v {node|short} {date|utcdate} {author|user}',
  128. }, {
  129. 'Date': '{date|svnisodate}',
  130. 'Id': '{file|basename},v {node|short} {date|svnutcdate} {author|user}',
  131. 'LastChangedRevision': '{node|short}',
  132. 'LastChangedBy': '{author|user}',
  133. 'LastChangedDate': '{date|svnisodate}',
  134. })
  135. templates.update(kwsets[ui.configbool('keywordset', 'svn')])
  136. return templates
  137. def _shrinktext(text, subfunc):
  138. '''Helper for keyword expansion removal in text.
  139. Depending on subfunc also returns number of substitutions.'''
  140. return subfunc(r'$\1$', text)
  141. def _preselect(wstatus, changed):
  142. '''Retrieves modified and added files from a working directory state
  143. and returns the subset of each contained in given changed files
  144. retrieved from a change context.'''
  145. modified, added = wstatus[:2]
  146. modified = [f for f in modified if f in changed]
  147. added = [f for f in added if f in changed]
  148. return modified, added
  149. class kwtemplater(object):
  150. '''
  151. Sets up keyword templates, corresponding keyword regex, and
  152. provides keyword substitution functions.
  153. '''
  154. def __init__(self, ui, repo, inc, exc):
  155. self.ui = ui
  156. self.repo = repo
  157. self.match = match.match(repo.root, '', [], inc, exc)
  158. self.restrict = kwtools['hgcmd'] in restricted.split()
  159. self.postcommit = False
  160. kwmaps = self.ui.configitems('keywordmaps')
  161. if kwmaps: # override default templates
  162. self.templates = dict((k, templater.parsestring(v, False))
  163. for k, v in kwmaps)
  164. else:
  165. self.templates = _defaultkwmaps(self.ui)
  166. @util.propertycache
  167. def escape(self):
  168. '''Returns bar-separated and escaped keywords.'''
  169. return '|'.join(map(re.escape, self.templates.keys()))
  170. @util.propertycache
  171. def rekw(self):
  172. '''Returns regex for unexpanded keywords.'''
  173. return re.compile(r'\$(%s)\$' % self.escape)
  174. @util.propertycache
  175. def rekwexp(self):
  176. '''Returns regex for expanded keywords.'''
  177. return re.compile(r'\$(%s): [^$\n\r]*? \$' % self.escape)
  178. def substitute(self, data, path, ctx, subfunc):
  179. '''Replaces keywords in data with expanded template.'''
  180. def kwsub(mobj):
  181. kw = mobj.group(1)
  182. ct = cmdutil.changeset_templater(self.ui, self.repo, False, None,
  183. self.templates[kw], '', False)
  184. self.ui.pushbuffer()
  185. ct.show(ctx, root=self.repo.root, file=path)
  186. ekw = templatefilters.firstline(self.ui.popbuffer())
  187. return '$%s: %s $' % (kw, ekw)
  188. return subfunc(kwsub, data)
  189. def linkctx(self, path, fileid):
  190. '''Similar to filelog.linkrev, but returns a changectx.'''
  191. return self.repo.filectx(path, fileid=fileid).changectx()
  192. def expand(self, path, node, data):
  193. '''Returns data with keywords expanded.'''
  194. if not self.restrict and self.match(path) and not util.binary(data):
  195. ctx = self.linkctx(path, node)
  196. return self.substitute(data, path, ctx, self.rekw.sub)
  197. return data
  198. def iskwfile(self, cand, ctx):
  199. '''Returns subset of candidates which are configured for keyword
  200. expansion but are not symbolic links.'''
  201. return [f for f in cand if self.match(f) and 'l' not in ctx.flags(f)]
  202. def overwrite(self, ctx, candidates, lookup, expand, rekw=False):
  203. '''Overwrites selected files expanding/shrinking keywords.'''
  204. if self.restrict or lookup or self.postcommit: # exclude kw_copy
  205. candidates = self.iskwfile(candidates, ctx)
  206. if not candidates:
  207. return
  208. kwcmd = self.restrict and lookup # kwexpand/kwshrink
  209. if self.restrict or expand and lookup:
  210. mf = ctx.manifest()
  211. if self.restrict or rekw:
  212. re_kw = self.rekw
  213. else:
  214. re_kw = self.rekwexp
  215. if expand:
  216. msg = _('overwriting %s expanding keywords\n')
  217. else:
  218. msg = _('overwriting %s shrinking keywords\n')
  219. for f in candidates:
  220. if self.restrict:
  221. data = self.repo.file(f).read(mf[f])
  222. else:
  223. data = self.repo.wread(f)
  224. if util.binary(data):
  225. continue
  226. if expand:
  227. if lookup:
  228. ctx = self.linkctx(f, mf[f])
  229. data, found = self.substitute(data, f, ctx, re_kw.subn)
  230. elif self.restrict:
  231. found = re_kw.search(data)
  232. else:
  233. data, found = _shrinktext(data, re_kw.subn)
  234. if found:
  235. self.ui.note(msg % f)
  236. fp = self.repo.wopener(f, "wb", atomictemp=True)
  237. fp.write(data)
  238. fp.close()
  239. if kwcmd:
  240. self.repo.dirstate.normal(f)
  241. elif self.postcommit:
  242. self.repo.dirstate.normallookup(f)
  243. def shrink(self, fname, text):
  244. '''Returns text with all keyword substitutions removed.'''
  245. if self.match(fname) and not util.binary(text):
  246. return _shrinktext(text, self.rekwexp.sub)
  247. return text
  248. def shrinklines(self, fname, lines):
  249. '''Returns lines with keyword substitutions removed.'''
  250. if self.match(fname):
  251. text = ''.join(lines)
  252. if not util.binary(text):
  253. return _shrinktext(text, self.rekwexp.sub).splitlines(True)
  254. return lines
  255. def wread(self, fname, data):
  256. '''If in restricted mode returns data read from wdir with
  257. keyword substitutions removed.'''
  258. if self.restrict:
  259. return self.shrink(fname, data)
  260. return data
  261. class kwfilelog(filelog.filelog):
  262. '''
  263. Subclass of filelog to hook into its read, add, cmp methods.
  264. Keywords are "stored" unexpanded, and processed on reading.
  265. '''
  266. def __init__(self, opener, kwt, path):
  267. super(kwfilelog, self).__init__(opener, path)
  268. self.kwt = kwt
  269. self.path = path
  270. def read(self, node):
  271. '''Expands keywords when reading filelog.'''
  272. data = super(kwfilelog, self).read(node)
  273. if self.renamed(node):
  274. return data
  275. return self.kwt.expand(self.path, node, data)
  276. def add(self, text, meta, tr, link, p1=None, p2=None):
  277. '''Removes keyword substitutions when adding to filelog.'''
  278. text = self.kwt.shrink(self.path, text)
  279. return super(kwfilelog, self).add(text, meta, tr, link, p1, p2)
  280. def cmp(self, node, text):
  281. '''Removes keyword substitutions for comparison.'''
  282. text = self.kwt.shrink(self.path, text)
  283. return super(kwfilelog, self).cmp(node, text)
  284. def _status(ui, repo, wctx, kwt, *pats, **opts):
  285. '''Bails out if [keyword] configuration is not active.
  286. Returns status of working directory.'''
  287. if kwt:
  288. return repo.status(match=scmutil.match(wctx, pats, opts), clean=True,
  289. unknown=opts.get('unknown') or opts.get('all'))
  290. if ui.configitems('keyword'):
  291. raise util.Abort(_('[keyword] patterns cannot match'))
  292. raise util.Abort(_('no [keyword] patterns configured'))
  293. def _kwfwrite(ui, repo, expand, *pats, **opts):
  294. '''Selects files and passes them to kwtemplater.overwrite.'''
  295. wctx = repo[None]
  296. if len(wctx.parents()) > 1:
  297. raise util.Abort(_('outstanding uncommitted merge'))
  298. kwt = kwtools['templater']
  299. wlock = repo.wlock()
  300. try:
  301. status = _status(ui, repo, wctx, kwt, *pats, **opts)
  302. modified, added, removed, deleted, unknown, ignored, clean = status
  303. if modified or added or removed or deleted:
  304. raise util.Abort(_('outstanding uncommitted changes'))
  305. kwt.overwrite(wctx, clean, True, expand)
  306. finally:
  307. wlock.release()
  308. @command('kwdemo',
  309. [('d', 'default', None, _('show default keyword template maps')),
  310. ('f', 'rcfile', '',
  311. _('read maps from rcfile'), _('FILE'))],
  312. _('hg kwdemo [-d] [-f RCFILE] [TEMPLATEMAP]...'),
  313. optionalrepo=True)
  314. def demo(ui, repo, *args, **opts):
  315. '''print [keywordmaps] configuration and an expansion example
  316. Show current, custom, or default keyword template maps and their
  317. expansions.
  318. Extend the current configuration by specifying maps as arguments
  319. and using -f/--rcfile to source an external hgrc file.
  320. Use -d/--default to disable current configuration.
  321. See :hg:`help templates` for information on templates and filters.
  322. '''
  323. def demoitems(section, items):
  324. ui.write('[%s]\n' % section)
  325. for k, v in sorted(items):
  326. ui.write('%s = %s\n' % (k, v))
  327. fn = 'demo.txt'
  328. tmpdir = tempfile.mkdtemp('', 'kwdemo.')
  329. ui.note(_('creating temporary repository at %s\n') % tmpdir)
  330. repo = localrepo.localrepository(repo.baseui, tmpdir, True)
  331. ui.setconfig('keyword', fn, '', 'keyword')
  332. svn = ui.configbool('keywordset', 'svn')
  333. # explicitly set keywordset for demo output
  334. ui.setconfig('keywordset', 'svn', svn, 'keyword')
  335. uikwmaps = ui.configitems('keywordmaps')
  336. if args or opts.get('rcfile'):
  337. ui.status(_('\n\tconfiguration using custom keyword template maps\n'))
  338. if uikwmaps:
  339. ui.status(_('\textending current template maps\n'))
  340. if opts.get('default') or not uikwmaps:
  341. if svn:
  342. ui.status(_('\toverriding default svn keywordset\n'))
  343. else:
  344. ui.status(_('\toverriding default cvs keywordset\n'))
  345. if opts.get('rcfile'):
  346. ui.readconfig(opts.get('rcfile'))
  347. if args:
  348. # simulate hgrc parsing
  349. rcmaps = ['[keywordmaps]\n'] + [a + '\n' for a in args]
  350. fp = repo.opener('hgrc', 'w')
  351. fp.writelines(rcmaps)
  352. fp.close()
  353. ui.readconfig(repo.join('hgrc'))
  354. kwmaps = dict(ui.configitems('keywordmaps'))
  355. elif opts.get('default'):
  356. if svn:
  357. ui.status(_('\n\tconfiguration using default svn keywordset\n'))
  358. else:
  359. ui.status(_('\n\tconfiguration using default cvs keywordset\n'))
  360. kwmaps = _defaultkwmaps(ui)
  361. if uikwmaps:
  362. ui.status(_('\tdisabling current template maps\n'))
  363. for k, v in kwmaps.iteritems():
  364. ui.setconfig('keywordmaps', k, v, 'keyword')
  365. else:
  366. ui.status(_('\n\tconfiguration using current keyword template maps\n'))
  367. if uikwmaps:
  368. kwmaps = dict(uikwmaps)
  369. else:
  370. kwmaps = _defaultkwmaps(ui)
  371. uisetup(ui)
  372. reposetup(ui, repo)
  373. ui.write('[extensions]\nkeyword =\n')
  374. demoitems('keyword', ui.configitems('keyword'))
  375. demoitems('keywordset', ui.configitems('keywordset'))
  376. demoitems('keywordmaps', kwmaps.iteritems())
  377. keywords = '$' + '$\n$'.join(sorted(kwmaps.keys())) + '$\n'
  378. repo.wopener.write(fn, keywords)
  379. repo[None].add([fn])
  380. ui.note(_('\nkeywords written to %s:\n') % fn)
  381. ui.note(keywords)
  382. wlock = repo.wlock()
  383. try:
  384. repo.dirstate.setbranch('demobranch')
  385. finally:
  386. wlock.release()
  387. for name, cmd in ui.configitems('hooks'):
  388. if name.split('.', 1)[0].find('commit') > -1:
  389. repo.ui.setconfig('hooks', name, '', 'keyword')
  390. msg = _('hg keyword configuration and expansion example')
  391. ui.note(("hg ci -m '%s'\n" % msg))
  392. repo.commit(text=msg)
  393. ui.status(_('\n\tkeywords expanded\n'))
  394. ui.write(repo.wread(fn))
  395. shutil.rmtree(tmpdir, ignore_errors=True)
  396. @command('kwexpand',
  397. commands.walkopts,
  398. _('hg kwexpand [OPTION]... [FILE]...'),
  399. inferrepo=True)
  400. def expand(ui, repo, *pats, **opts):
  401. '''expand keywords in the working directory
  402. Run after (re)enabling keyword expansion.
  403. kwexpand refuses to run if given files contain local changes.
  404. '''
  405. # 3rd argument sets expansion to True
  406. _kwfwrite(ui, repo, True, *pats, **opts)
  407. @command('kwfiles',
  408. [('A', 'all', None, _('show keyword status flags of all files')),
  409. ('i', 'ignore', None, _('show files excluded from expansion')),
  410. ('u', 'unknown', None, _('only show unknown (not tracked) files')),
  411. ] + commands.walkopts,
  412. _('hg kwfiles [OPTION]... [FILE]...'),
  413. inferrepo=True)
  414. def files(ui, repo, *pats, **opts):
  415. '''show files configured for keyword expansion
  416. List which files in the working directory are matched by the
  417. [keyword] configuration patterns.
  418. Useful to prevent inadvertent keyword expansion and to speed up
  419. execution by including only files that are actual candidates for
  420. expansion.
  421. See :hg:`help keyword` on how to construct patterns both for
  422. inclusion and exclusion of files.
  423. With -A/--all and -v/--verbose the codes used to show the status
  424. of files are::
  425. K = keyword expansion candidate
  426. k = keyword expansion candidate (not tracked)
  427. I = ignored
  428. i = ignored (not tracked)
  429. '''
  430. kwt = kwtools['templater']
  431. wctx = repo[None]
  432. status = _status(ui, repo, wctx, kwt, *pats, **opts)
  433. cwd = pats and repo.getcwd() or ''
  434. modified, added, removed, deleted, unknown, ignored, clean = status
  435. files = []
  436. if not opts.get('unknown') or opts.get('all'):
  437. files = sorted(modified + added + clean)
  438. kwfiles = kwt.iskwfile(files, wctx)
  439. kwdeleted = kwt.iskwfile(deleted, wctx)
  440. kwunknown = kwt.iskwfile(unknown, wctx)
  441. if not opts.get('ignore') or opts.get('all'):
  442. showfiles = kwfiles, kwdeleted, kwunknown
  443. else:
  444. showfiles = [], [], []
  445. if opts.get('all') or opts.get('ignore'):
  446. showfiles += ([f for f in files if f not in kwfiles],
  447. [f for f in unknown if f not in kwunknown])
  448. kwlabels = 'enabled deleted enabledunknown ignored ignoredunknown'.split()
  449. kwstates = zip(kwlabels, 'K!kIi', showfiles)
  450. fm = ui.formatter('kwfiles', opts)
  451. fmt = '%.0s%s\n'
  452. if opts.get('all') or ui.verbose:
  453. fmt = '%s %s\n'
  454. for kwstate, char, filenames in kwstates:
  455. label = 'kwfiles.' + kwstate
  456. for f in filenames:
  457. fm.startitem()
  458. fm.write('kwstatus path', fmt, char,
  459. repo.pathto(f, cwd), label=label)
  460. fm.end()
  461. @command('kwshrink',
  462. commands.walkopts,
  463. _('hg kwshrink [OPTION]... [FILE]...'),
  464. inferrepo=True)
  465. def shrink(ui, repo, *pats, **opts):
  466. '''revert expanded keywords in the working directory
  467. Must be run before changing/disabling active keywords.
  468. kwshrink refuses to run if given files contain local changes.
  469. '''
  470. # 3rd argument sets expansion to False
  471. _kwfwrite(ui, repo, False, *pats, **opts)
  472. def uisetup(ui):
  473. ''' Monkeypatches dispatch._parse to retrieve user command.'''
  474. def kwdispatch_parse(orig, ui, args):
  475. '''Monkeypatch dispatch._parse to obtain running hg command.'''
  476. cmd, func, args, options, cmdoptions = orig(ui, args)
  477. kwtools['hgcmd'] = cmd
  478. return cmd, func, args, options, cmdoptions
  479. extensions.wrapfunction(dispatch, '_parse', kwdispatch_parse)
  480. def reposetup(ui, repo):
  481. '''Sets up repo as kwrepo for keyword substitution.
  482. Overrides file method to return kwfilelog instead of filelog
  483. if file matches user configuration.
  484. Wraps commit to overwrite configured files with updated
  485. keyword substitutions.
  486. Monkeypatches patch and webcommands.'''
  487. try:
  488. if (not repo.local() or kwtools['hgcmd'] in nokwcommands.split()
  489. or '.hg' in util.splitpath(repo.root)
  490. or repo._url.startswith('bundle:')):
  491. return
  492. except AttributeError:
  493. pass
  494. inc, exc = [], ['.hg*']
  495. for pat, opt in ui.configitems('keyword'):
  496. if opt != 'ignore':
  497. inc.append(pat)
  498. else:
  499. exc.append(pat)
  500. if not inc:
  501. return
  502. kwtools['templater'] = kwt = kwtemplater(ui, repo, inc, exc)
  503. class kwrepo(repo.__class__):
  504. def file(self, f):
  505. if f[0] == '/':
  506. f = f[1:]
  507. return kwfilelog(self.sopener, kwt, f)
  508. def wread(self, filename):
  509. data = super(kwrepo, self).wread(filename)
  510. return kwt.wread(filename, data)
  511. def commit(self, *args, **opts):
  512. # use custom commitctx for user commands
  513. # other extensions can still wrap repo.commitctx directly
  514. self.commitctx = self.kwcommitctx
  515. try:
  516. return super(kwrepo, self).commit(*args, **opts)
  517. finally:
  518. del self.commitctx
  519. def kwcommitctx(self, ctx, error=False):
  520. n = super(kwrepo, self).commitctx(ctx, error)
  521. # no lock needed, only called from repo.commit() which already locks
  522. if not kwt.postcommit:
  523. restrict = kwt.restrict
  524. kwt.restrict = True
  525. kwt.overwrite(self[n], sorted(ctx.added() + ctx.modified()),
  526. False, True)
  527. kwt.restrict = restrict
  528. return n
  529. def rollback(self, dryrun=False, force=False):
  530. wlock = self.wlock()
  531. try:
  532. if not dryrun:
  533. changed = self['.'].files()
  534. ret = super(kwrepo, self).rollback(dryrun, force)
  535. if not dryrun:
  536. ctx = self['.']
  537. modified, added = _preselect(self[None].status(), changed)
  538. kwt.overwrite(ctx, modified, True, True)
  539. kwt.overwrite(ctx, added, True, False)
  540. return ret
  541. finally:
  542. wlock.release()
  543. # monkeypatches
  544. def kwpatchfile_init(orig, self, ui, gp, backend, store, eolmode=None):
  545. '''Monkeypatch/wrap patch.patchfile.__init__ to avoid
  546. rejects or conflicts due to expanded keywords in working dir.'''
  547. orig(self, ui, gp, backend, store, eolmode)
  548. # shrink keywords read from working dir
  549. self.lines = kwt.shrinklines(self.fname, self.lines)
  550. def kw_diff(orig, repo, node1=None, node2=None, match=None, changes=None,
  551. opts=None, prefix=''):
  552. '''Monkeypatch patch.diff to avoid expansion.'''
  553. kwt.restrict = True
  554. return orig(repo, node1, node2, match, changes, opts, prefix)
  555. def kwweb_skip(orig, web, req, tmpl):
  556. '''Wraps webcommands.x turning off keyword expansion.'''
  557. kwt.match = util.never
  558. return orig(web, req, tmpl)
  559. def kw_amend(orig, ui, repo, commitfunc, old, extra, pats, opts):
  560. '''Wraps cmdutil.amend expanding keywords after amend.'''
  561. wlock = repo.wlock()
  562. try:
  563. kwt.postcommit = True
  564. newid = orig(ui, repo, commitfunc, old, extra, pats, opts)
  565. if newid != old.node():
  566. ctx = repo[newid]
  567. kwt.restrict = True
  568. kwt.overwrite(ctx, ctx.files(), False, True)
  569. kwt.restrict = False
  570. return newid
  571. finally:
  572. wlock.release()
  573. def kw_copy(orig, ui, repo, pats, opts, rename=False):
  574. '''Wraps cmdutil.copy so that copy/rename destinations do not
  575. contain expanded keywords.
  576. Note that the source of a regular file destination may also be a
  577. symlink:
  578. hg cp sym x -> x is symlink
  579. cp sym x; hg cp -A sym x -> x is file (maybe expanded keywords)
  580. For the latter we have to follow the symlink to find out whether its
  581. target is configured for expansion and we therefore must unexpand the
  582. keywords in the destination.'''
  583. wlock = repo.wlock()
  584. try:
  585. orig(ui, repo, pats, opts, rename)
  586. if opts.get('dry_run'):
  587. return
  588. wctx = repo[None]
  589. cwd = repo.getcwd()
  590. def haskwsource(dest):
  591. '''Returns true if dest is a regular file and configured for
  592. expansion or a symlink which points to a file configured for
  593. expansion. '''
  594. source = repo.dirstate.copied(dest)
  595. if 'l' in wctx.flags(source):
  596. source = pathutil.canonpath(repo.root, cwd,
  597. os.path.realpath(source))
  598. return kwt.match(source)
  599. candidates = [f for f in repo.dirstate.copies() if
  600. 'l' not in wctx.flags(f) and haskwsource(f)]
  601. kwt.overwrite(wctx, candidates, False, False)
  602. finally:
  603. wlock.release()
  604. def kw_dorecord(orig, ui, repo, commitfunc, *pats, **opts):
  605. '''Wraps record.dorecord expanding keywords after recording.'''
  606. wlock = repo.wlock()
  607. try:
  608. # record returns 0 even when nothing has changed
  609. # therefore compare nodes before and after
  610. kwt.postcommit = True
  611. ctx = repo['.']
  612. wstatus = repo[None].status()
  613. ret = orig(ui, repo, commitfunc, *pats, **opts)
  614. recctx = repo['.']
  615. if ctx != recctx:
  616. modified, added = _preselect(wstatus, recctx.files())
  617. kwt.restrict = False
  618. kwt.overwrite(recctx, modified, False, True)
  619. kwt.overwrite(recctx, added, False, True, True)
  620. kwt.restrict = True
  621. return ret
  622. finally:
  623. wlock.release()
  624. def kwfilectx_cmp(orig, self, fctx):
  625. # keyword affects data size, comparing wdir and filelog size does
  626. # not make sense
  627. if (fctx._filerev is None and
  628. (self._repo._encodefilterpats or
  629. kwt.match(fctx.path()) and 'l' not in fctx.flags() or
  630. self.size() - 4 == fctx.size()) or
  631. self.size() == fctx.size()):
  632. return self._filelog.cmp(self._filenode, fctx.data())
  633. return True
  634. extensions.wrapfunction(context.filectx, 'cmp', kwfilectx_cmp)
  635. extensions.wrapfunction(patch.patchfile, '__init__', kwpatchfile_init)
  636. extensions.wrapfunction(patch, 'diff', kw_diff)
  637. extensions.wrapfunction(cmdutil, 'amend', kw_amend)
  638. extensions.wrapfunction(cmdutil, 'copy', kw_copy)
  639. for c in 'annotate changeset rev filediff diff'.split():
  640. extensions.wrapfunction(webcommands, c, kwweb_skip)
  641. for name in recordextensions.split():
  642. try:
  643. record = extensions.find(name)
  644. extensions.wrapfunction(record, 'dorecord', kw_dorecord)
  645. except KeyError:
  646. pass
  647. repo.__class__ = kwrepo