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