Debian Codegraph @

hgext/fastannotate/formatter.py

raw
1 # Copyright 2016-present Facebook. All Rights Reserved.
2 #
3 # format: defines the format used to output annotate result
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 __future__ import annotations
8
9 from mercurial.node import (
10 hex,
11 short,
12 )
13 from mercurial import (
14 encoding,
15 pycompat,
16 templatefilters,
17 util,
18 )
19 from mercurial.utils import dateutil
20
21
22 # imitating mercurial.commands.annotate, not using the vanilla formatter since
23 # the data structures are a bit different, and we have some fast paths.
24 class defaultformatter:
25 """the default formatter that does leftpad and support some common flags"""
26
27 def __init__(self, ui, repo, opts):
28 self.ui = ui
29 self.opts = opts
30
31 if ui.quiet:
32 datefunc = dateutil.shortdate
33 else:
34 datefunc = dateutil.datestr
35 datefunc = util.cachefunc(datefunc)
36 getctx = util.cachefunc(lambda x: repo[x[0]])
37 hexfunc = self._hexfunc
38
39 # special handling working copy "changeset" and "rev" functions
40 if self.opts.get(b'rev') == b'wdir()':
41 orig = hexfunc
42 hexfunc = lambda x: None if x is None else orig(x)
43 wnode = hexfunc(repo[b'.'].node()) + b'+'
44 wrev = b'%d' % repo[b'.'].rev()
45 wrevpad = b''
46 if not opts.get(b'changeset'): # only show + if changeset is hidden
47 wrev += b'+'
48 wrevpad = b' '
49 revenc = lambda x: wrev if x is None else (b'%d' % x) + wrevpad
50
51 def csetenc(x):
52 if x is None:
53 return wnode
54 return pycompat.bytestr(x) + b' '
55
56 else:
57 revenc = csetenc = pycompat.bytestr
58
59 # opt name, separator, raw value (for json/plain), encoder (for plain)
60 opmap = [
61 (b'user', b' ', lambda x: getctx(x).user(), ui.shortuser),
62 (b'number', b' ', lambda x: getctx(x).rev(), revenc),
63 (b'changeset', b' ', lambda x: hexfunc(x[0]), csetenc),
64 (b'date', b' ', lambda x: getctx(x).date(), datefunc),
65 (b'file', b' ', lambda x: x[2], pycompat.bytestr),
66 (b'line_number', b':', lambda x: x[1] + 1, pycompat.bytestr),
67 ]
68 fieldnamemap = {b'number': b'rev', b'changeset': b'node'}
69 funcmap = [
70 (get, sep, fieldnamemap.get(op, op), enc)
71 for op, sep, get, enc in opmap
72 if opts.get(op)
73 ]
74 # no separator for first column
75 funcmap[0] = list(funcmap[0])
76 funcmap[0][1] = b''
77 self.funcmap = funcmap
78
79 def write(self, annotatedresult, lines=None, existinglines=None):
80 """(annotateresult, [str], set([rev, linenum])) -> None. write output.
81 annotateresult can be [(node, linenum, path)], or [(node, linenum)]
82 """
83 pieces = [] # [[str]]
84 maxwidths = [] # [int]
85
86 # calculate padding
87 for f, sep, name, enc in self.funcmap:
88 l = [enc(f(x)) for x in annotatedresult]
89 pieces.append(l)
90 if name in [b'node', b'date']: # node and date has fixed size
91 l = l[:1]
92 widths = pycompat.maplist(encoding.colwidth, set(l))
93 maxwidth = max(widths) if widths else 0
94 maxwidths.append(maxwidth)
95
96 # buffered output
97 result = b''
98 for i in range(len(annotatedresult)):
99 for j, p in enumerate(pieces):
100 sep = self.funcmap[j][1]
101 padding = b' ' * (maxwidths[j] - len(p[i]))
102 result += sep + padding + p[i]
103 if lines:
104 if existinglines is None:
105 result += b': ' + lines[i]
106 else: # extra formatting showing whether a line exists
107 key = (annotatedresult[i][0], annotatedresult[i][1])
108 if key in existinglines:
109 result += b': ' + lines[i]
110 else:
111 result += b': ' + self.ui.label(
112 b'-' + lines[i], b'diff.deleted'
113 )
114
115 if result[-1:] != b'\n':
116 result += b'\n'
117
118 self.ui.write(result)
119
120 @util.propertycache
121 def _hexfunc(self):
122 if self.ui.debugflag or self.opts.get(b'long_hash'):
123 return hex
124 else:
125 return short
126
127 def end(self):
128 pass
129
130
131 class jsonformatter(defaultformatter):
132 def __init__(self, ui, repo, opts):
133 super().__init__(ui, repo, opts)
134 self.ui.write(b'[')
135 self.needcomma = False
136
137 def write(self, annotatedresult, lines=None, existinglines=None):
138 if annotatedresult:
139 self._writecomma()
140
141 pieces = [
142 (name, pycompat.maplist(f, annotatedresult))
143 for f, sep, name, enc in self.funcmap
144 ]
145 if lines is not None:
146 pieces.append((b'line', lines))
147 pieces.sort()
148
149 seps = [b','] * len(pieces[:-1]) + [b'']
150
151 result = b''
152 lasti = len(annotatedresult) - 1
153 for i in range(len(annotatedresult)):
154 result += b'\n {\n'
155 for j, p in enumerate(pieces):
156 k, vs = p
157 result += b' "%s": %s%s\n' % (
158 k,
159 templatefilters.json(vs[i], paranoid=False),
160 seps[j],
161 )
162 result += b' }%s' % (b'' if i == lasti else b',')
163 if lasti >= 0:
164 self.needcomma = True
165
166 self.ui.write(result)
167
168 def _writecomma(self):
169 if self.needcomma:
170 self.ui.write(b',')
171 self.needcomma = False
172
173 @util.propertycache
174 def _hexfunc(self):
175 return hex
176
177 def end(self):
178 self.ui.write(b'\n]\n')