PageRenderTime 44ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/mercurial/templatekw.py

https://bitbucket.org/mirror/mercurial/
Python | 404 lines | 387 code | 5 blank | 12 comment | 7 complexity | 5c286abf0bb6435c7d03522e009ffd10 MD5 | raw file
Possible License(s): GPL-2.0
  1. # templatekw.py - common changeset template keywords
  2. #
  3. # Copyright 2005-2009 Matt Mackall <mpm@selenic.com>
  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. from node import hex
  8. import patch, util, error
  9. import hbisect
  10. # This helper class allows us to handle both:
  11. # "{files}" (legacy command-line-specific list hack) and
  12. # "{files % '{file}\n'}" (hgweb-style with inlining and function support)
  13. class _hybrid(object):
  14. def __init__(self, gen, values, joinfmt=None):
  15. self.gen = gen
  16. self.values = values
  17. if joinfmt:
  18. self.joinfmt = joinfmt
  19. else:
  20. self.joinfmt = lambda x: x.values()[0]
  21. def __iter__(self):
  22. return self.gen
  23. def __call__(self):
  24. for x in self.values:
  25. yield x
  26. def showlist(name, values, plural=None, element=None, **args):
  27. if not element:
  28. element = name
  29. f = _showlist(name, values, plural, **args)
  30. return _hybrid(f, [{element: x} for x in values])
  31. def _showlist(name, values, plural=None, **args):
  32. '''expand set of values.
  33. name is name of key in template map.
  34. values is list of strings or dicts.
  35. plural is plural of name, if not simply name + 's'.
  36. expansion works like this, given name 'foo'.
  37. if values is empty, expand 'no_foos'.
  38. if 'foo' not in template map, return values as a string,
  39. joined by space.
  40. expand 'start_foos'.
  41. for each value, expand 'foo'. if 'last_foo' in template
  42. map, expand it instead of 'foo' for last key.
  43. expand 'end_foos'.
  44. '''
  45. templ = args['templ']
  46. if plural:
  47. names = plural
  48. else: names = name + 's'
  49. if not values:
  50. noname = 'no_' + names
  51. if noname in templ:
  52. yield templ(noname, **args)
  53. return
  54. if name not in templ:
  55. if isinstance(values[0], str):
  56. yield ' '.join(values)
  57. else:
  58. for v in values:
  59. yield dict(v, **args)
  60. return
  61. startname = 'start_' + names
  62. if startname in templ:
  63. yield templ(startname, **args)
  64. vargs = args.copy()
  65. def one(v, tag=name):
  66. try:
  67. vargs.update(v)
  68. except (AttributeError, ValueError):
  69. try:
  70. for a, b in v:
  71. vargs[a] = b
  72. except ValueError:
  73. vargs[name] = v
  74. return templ(tag, **vargs)
  75. lastname = 'last_' + name
  76. if lastname in templ:
  77. last = values.pop()
  78. else:
  79. last = None
  80. for v in values:
  81. yield one(v)
  82. if last is not None:
  83. yield one(last, tag=lastname)
  84. endname = 'end_' + names
  85. if endname in templ:
  86. yield templ(endname, **args)
  87. def getfiles(repo, ctx, revcache):
  88. if 'files' not in revcache:
  89. revcache['files'] = repo.status(ctx.p1().node(), ctx.node())[:3]
  90. return revcache['files']
  91. def getlatesttags(repo, ctx, cache):
  92. '''return date, distance and name for the latest tag of rev'''
  93. if 'latesttags' not in cache:
  94. # Cache mapping from rev to a tuple with tag date, tag
  95. # distance and tag name
  96. cache['latesttags'] = {-1: (0, 0, 'null')}
  97. latesttags = cache['latesttags']
  98. rev = ctx.rev()
  99. todo = [rev]
  100. while todo:
  101. rev = todo.pop()
  102. if rev in latesttags:
  103. continue
  104. ctx = repo[rev]
  105. tags = [t for t in ctx.tags()
  106. if (repo.tagtype(t) and repo.tagtype(t) != 'local')]
  107. if tags:
  108. latesttags[rev] = ctx.date()[0], 0, ':'.join(sorted(tags))
  109. continue
  110. try:
  111. # The tuples are laid out so the right one can be found by
  112. # comparison.
  113. pdate, pdist, ptag = max(
  114. latesttags[p.rev()] for p in ctx.parents())
  115. except KeyError:
  116. # Cache miss - recurse
  117. todo.append(rev)
  118. todo.extend(p.rev() for p in ctx.parents())
  119. continue
  120. latesttags[rev] = pdate, pdist + 1, ptag
  121. return latesttags[rev]
  122. def getrenamedfn(repo, endrev=None):
  123. rcache = {}
  124. if endrev is None:
  125. endrev = len(repo)
  126. def getrenamed(fn, rev):
  127. '''looks up all renames for a file (up to endrev) the first
  128. time the file is given. It indexes on the changerev and only
  129. parses the manifest if linkrev != changerev.
  130. Returns rename info for fn at changerev rev.'''
  131. if fn not in rcache:
  132. rcache[fn] = {}
  133. fl = repo.file(fn)
  134. for i in fl:
  135. lr = fl.linkrev(i)
  136. renamed = fl.renamed(fl.node(i))
  137. rcache[fn][lr] = renamed
  138. if lr >= endrev:
  139. break
  140. if rev in rcache[fn]:
  141. return rcache[fn][rev]
  142. # If linkrev != rev (i.e. rev not found in rcache) fallback to
  143. # filectx logic.
  144. try:
  145. return repo[rev][fn].renamed()
  146. except error.LookupError:
  147. return None
  148. return getrenamed
  149. def showauthor(repo, ctx, templ, **args):
  150. """:author: String. The unmodified author of the changeset."""
  151. return ctx.user()
  152. def showbisect(repo, ctx, templ, **args):
  153. """:bisect: String. The changeset bisection status."""
  154. return hbisect.label(repo, ctx.node())
  155. def showbranch(**args):
  156. """:branch: String. The name of the branch on which the changeset was
  157. committed.
  158. """
  159. return args['ctx'].branch()
  160. def showbranches(**args):
  161. """:branches: List of strings. The name of the branch on which the
  162. changeset was committed. Will be empty if the branch name was
  163. default.
  164. """
  165. branch = args['ctx'].branch()
  166. if branch != 'default':
  167. return showlist('branch', [branch], plural='branches', **args)
  168. return showlist('branch', [], plural='branches', **args)
  169. def showbookmarks(**args):
  170. """:bookmarks: List of strings. Any bookmarks associated with the
  171. changeset.
  172. """
  173. repo = args['ctx']._repo
  174. bookmarks = args['ctx'].bookmarks()
  175. hybrid = showlist('bookmark', bookmarks, **args)
  176. for value in hybrid.values:
  177. value['current'] = repo._bookmarkcurrent
  178. return hybrid
  179. def showchildren(**args):
  180. """:children: List of strings. The children of the changeset."""
  181. ctx = args['ctx']
  182. childrevs = ['%d:%s' % (cctx, cctx) for cctx in ctx.children()]
  183. return showlist('children', childrevs, element='child', **args)
  184. def showdate(repo, ctx, templ, **args):
  185. """:date: Date information. The date when the changeset was committed."""
  186. return ctx.date()
  187. def showdescription(repo, ctx, templ, **args):
  188. """:desc: String. The text of the changeset description."""
  189. return ctx.description().strip()
  190. def showdiffstat(repo, ctx, templ, **args):
  191. """:diffstat: String. Statistics of changes with the following format:
  192. "modified files: +added/-removed lines"
  193. """
  194. stats = patch.diffstatdata(util.iterlines(ctx.diff()))
  195. maxname, maxtotal, adds, removes, binary = patch.diffstatsum(stats)
  196. return '%s: +%s/-%s' % (len(stats), adds, removes)
  197. def showextras(**args):
  198. """:extras: List of dicts with key, value entries of the 'extras'
  199. field of this changeset."""
  200. extras = args['ctx'].extra()
  201. c = [{'key': x[0], 'value': x[1]} for x in sorted(extras.items())]
  202. f = _showlist('extra', c, plural='extras', **args)
  203. return _hybrid(f, c, lambda x: '%s=%s' % (x['key'], x['value']))
  204. def showfileadds(**args):
  205. """:file_adds: List of strings. Files added by this changeset."""
  206. repo, ctx, revcache = args['repo'], args['ctx'], args['revcache']
  207. return showlist('file_add', getfiles(repo, ctx, revcache)[1],
  208. element='file', **args)
  209. def showfilecopies(**args):
  210. """:file_copies: List of strings. Files copied in this changeset with
  211. their sources.
  212. """
  213. cache, ctx = args['cache'], args['ctx']
  214. copies = args['revcache'].get('copies')
  215. if copies is None:
  216. if 'getrenamed' not in cache:
  217. cache['getrenamed'] = getrenamedfn(args['repo'])
  218. copies = []
  219. getrenamed = cache['getrenamed']
  220. for fn in ctx.files():
  221. rename = getrenamed(fn, ctx.rev())
  222. if rename:
  223. copies.append((fn, rename[0]))
  224. c = [{'name': x[0], 'source': x[1]} for x in copies]
  225. f = _showlist('file_copy', c, plural='file_copies', **args)
  226. return _hybrid(f, c, lambda x: '%s (%s)' % (x['name'], x['source']))
  227. # showfilecopiesswitch() displays file copies only if copy records are
  228. # provided before calling the templater, usually with a --copies
  229. # command line switch.
  230. def showfilecopiesswitch(**args):
  231. """:file_copies_switch: List of strings. Like "file_copies" but displayed
  232. only if the --copied switch is set.
  233. """
  234. copies = args['revcache'].get('copies') or []
  235. c = [{'name': x[0], 'source': x[1]} for x in copies]
  236. f = _showlist('file_copy', c, plural='file_copies', **args)
  237. return _hybrid(f, c, lambda x: '%s (%s)' % (x['name'], x['source']))
  238. def showfiledels(**args):
  239. """:file_dels: List of strings. Files removed by this changeset."""
  240. repo, ctx, revcache = args['repo'], args['ctx'], args['revcache']
  241. return showlist('file_del', getfiles(repo, ctx, revcache)[2],
  242. element='file', **args)
  243. def showfilemods(**args):
  244. """:file_mods: List of strings. Files modified by this changeset."""
  245. repo, ctx, revcache = args['repo'], args['ctx'], args['revcache']
  246. return showlist('file_mod', getfiles(repo, ctx, revcache)[0],
  247. element='file', **args)
  248. def showfiles(**args):
  249. """:files: List of strings. All files modified, added, or removed by this
  250. changeset.
  251. """
  252. return showlist('file', args['ctx'].files(), **args)
  253. def showlatesttag(repo, ctx, templ, cache, **args):
  254. """:latesttag: String. Most recent global tag in the ancestors of this
  255. changeset.
  256. """
  257. return getlatesttags(repo, ctx, cache)[2]
  258. def showlatesttagdistance(repo, ctx, templ, cache, **args):
  259. """:latesttagdistance: Integer. Longest path to the latest tag."""
  260. return getlatesttags(repo, ctx, cache)[1]
  261. def showmanifest(**args):
  262. repo, ctx, templ = args['repo'], args['ctx'], args['templ']
  263. args = args.copy()
  264. args.update({'rev': repo.manifest.rev(ctx.changeset()[0]),
  265. 'node': hex(ctx.changeset()[0])})
  266. return templ('manifest', **args)
  267. def shownode(repo, ctx, templ, **args):
  268. """:node: String. The changeset identification hash, as a 40 hexadecimal
  269. digit string.
  270. """
  271. return ctx.hex()
  272. def showp1rev(repo, ctx, templ, **args):
  273. """:p1rev: Integer. The repository-local revision number of the changeset's
  274. first parent, or -1 if the changeset has no parents."""
  275. return ctx.p1().rev()
  276. def showp2rev(repo, ctx, templ, **args):
  277. """:p2rev: Integer. The repository-local revision number of the changeset's
  278. second parent, or -1 if the changeset has no second parent."""
  279. return ctx.p2().rev()
  280. def showp1node(repo, ctx, templ, **args):
  281. """:p1node: String. The identification hash of the changeset's first parent,
  282. as a 40 digit hexadecimal string. If the changeset has no parents, all
  283. digits are 0."""
  284. return ctx.p1().hex()
  285. def showp2node(repo, ctx, templ, **args):
  286. """:p2node: String. The identification hash of the changeset's second
  287. parent, as a 40 digit hexadecimal string. If the changeset has no second
  288. parent, all digits are 0."""
  289. return ctx.p2().hex()
  290. def showphase(repo, ctx, templ, **args):
  291. """:phase: String. The changeset phase name."""
  292. return ctx.phasestr()
  293. def showphaseidx(repo, ctx, templ, **args):
  294. """:phaseidx: Integer. The changeset phase index."""
  295. return ctx.phase()
  296. def showrev(repo, ctx, templ, **args):
  297. """:rev: Integer. The repository-local changeset revision number."""
  298. return ctx.rev()
  299. def showtags(**args):
  300. """:tags: List of strings. Any tags associated with the changeset."""
  301. return showlist('tag', args['ctx'].tags(), **args)
  302. # keywords are callables like:
  303. # fn(repo, ctx, templ, cache, revcache, **args)
  304. # with:
  305. # repo - current repository instance
  306. # ctx - the changectx being displayed
  307. # templ - the templater instance
  308. # cache - a cache dictionary for the whole templater run
  309. # revcache - a cache dictionary for the current revision
  310. keywords = {
  311. 'author': showauthor,
  312. 'bisect': showbisect,
  313. 'branch': showbranch,
  314. 'branches': showbranches,
  315. 'bookmarks': showbookmarks,
  316. 'children': showchildren,
  317. 'date': showdate,
  318. 'desc': showdescription,
  319. 'diffstat': showdiffstat,
  320. 'extras': showextras,
  321. 'file_adds': showfileadds,
  322. 'file_copies': showfilecopies,
  323. 'file_copies_switch': showfilecopiesswitch,
  324. 'file_dels': showfiledels,
  325. 'file_mods': showfilemods,
  326. 'files': showfiles,
  327. 'latesttag': showlatesttag,
  328. 'latesttagdistance': showlatesttagdistance,
  329. 'manifest': showmanifest,
  330. 'node': shownode,
  331. 'p1rev': showp1rev,
  332. 'p1node': showp1node,
  333. 'p2rev': showp2rev,
  334. 'p2node': showp2node,
  335. 'phase': showphase,
  336. 'phaseidx': showphaseidx,
  337. 'rev': showrev,
  338. 'tags': showtags,
  339. }
  340. def _showparents(**args):
  341. """:parents: List of strings. The parents of the changeset in "rev:node"
  342. format. If the changeset has only one "natural" parent (the predecessor
  343. revision) nothing is shown."""
  344. pass
  345. dockeywords = {
  346. 'parents': _showparents,
  347. }
  348. dockeywords.update(keywords)
  349. del dockeywords['branches']
  350. # tell hggettext to extract docstrings from these functions:
  351. i18nfunctions = dockeywords.values()