##// END OF EJS Templates
log: duplicate _logrevs() dedicated for walkchangerevs()...
Yuya Nishihara -
r35700:8273c1a4 default
parent child Browse files
Show More
@@ -1,3937 +1,3952
1 # cmdutil.py - help for command processing in mercurial
1 # cmdutil.py - help for command processing in mercurial
2 #
2 #
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
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 from __future__ import absolute_import
8 from __future__ import absolute_import
9
9
10 import errno
10 import errno
11 import itertools
11 import itertools
12 import os
12 import os
13 import re
13 import re
14 import tempfile
14 import tempfile
15
15
16 from .i18n import _
16 from .i18n import _
17 from .node import (
17 from .node import (
18 hex,
18 hex,
19 nullid,
19 nullid,
20 nullrev,
20 nullrev,
21 short,
21 short,
22 )
22 )
23
23
24 from . import (
24 from . import (
25 bookmarks,
25 bookmarks,
26 changelog,
26 changelog,
27 copies,
27 copies,
28 crecord as crecordmod,
28 crecord as crecordmod,
29 dagop,
29 dagop,
30 dirstateguard,
30 dirstateguard,
31 encoding,
31 encoding,
32 error,
32 error,
33 formatter,
33 formatter,
34 graphmod,
34 graphmod,
35 match as matchmod,
35 match as matchmod,
36 mdiff,
36 mdiff,
37 obsolete,
37 obsolete,
38 patch,
38 patch,
39 pathutil,
39 pathutil,
40 pycompat,
40 pycompat,
41 registrar,
41 registrar,
42 revlog,
42 revlog,
43 revset,
43 revset,
44 revsetlang,
44 revsetlang,
45 scmutil,
45 scmutil,
46 smartset,
46 smartset,
47 templatekw,
47 templatekw,
48 templater,
48 templater,
49 util,
49 util,
50 vfs as vfsmod,
50 vfs as vfsmod,
51 )
51 )
52 stringio = util.stringio
52 stringio = util.stringio
53
53
54 # templates of common command options
54 # templates of common command options
55
55
56 dryrunopts = [
56 dryrunopts = [
57 ('n', 'dry-run', None,
57 ('n', 'dry-run', None,
58 _('do not perform actions, just print output')),
58 _('do not perform actions, just print output')),
59 ]
59 ]
60
60
61 remoteopts = [
61 remoteopts = [
62 ('e', 'ssh', '',
62 ('e', 'ssh', '',
63 _('specify ssh command to use'), _('CMD')),
63 _('specify ssh command to use'), _('CMD')),
64 ('', 'remotecmd', '',
64 ('', 'remotecmd', '',
65 _('specify hg command to run on the remote side'), _('CMD')),
65 _('specify hg command to run on the remote side'), _('CMD')),
66 ('', 'insecure', None,
66 ('', 'insecure', None,
67 _('do not verify server certificate (ignoring web.cacerts config)')),
67 _('do not verify server certificate (ignoring web.cacerts config)')),
68 ]
68 ]
69
69
70 walkopts = [
70 walkopts = [
71 ('I', 'include', [],
71 ('I', 'include', [],
72 _('include names matching the given patterns'), _('PATTERN')),
72 _('include names matching the given patterns'), _('PATTERN')),
73 ('X', 'exclude', [],
73 ('X', 'exclude', [],
74 _('exclude names matching the given patterns'), _('PATTERN')),
74 _('exclude names matching the given patterns'), _('PATTERN')),
75 ]
75 ]
76
76
77 commitopts = [
77 commitopts = [
78 ('m', 'message', '',
78 ('m', 'message', '',
79 _('use text as commit message'), _('TEXT')),
79 _('use text as commit message'), _('TEXT')),
80 ('l', 'logfile', '',
80 ('l', 'logfile', '',
81 _('read commit message from file'), _('FILE')),
81 _('read commit message from file'), _('FILE')),
82 ]
82 ]
83
83
84 commitopts2 = [
84 commitopts2 = [
85 ('d', 'date', '',
85 ('d', 'date', '',
86 _('record the specified date as commit date'), _('DATE')),
86 _('record the specified date as commit date'), _('DATE')),
87 ('u', 'user', '',
87 ('u', 'user', '',
88 _('record the specified user as committer'), _('USER')),
88 _('record the specified user as committer'), _('USER')),
89 ]
89 ]
90
90
91 # hidden for now
91 # hidden for now
92 formatteropts = [
92 formatteropts = [
93 ('T', 'template', '',
93 ('T', 'template', '',
94 _('display with template (EXPERIMENTAL)'), _('TEMPLATE')),
94 _('display with template (EXPERIMENTAL)'), _('TEMPLATE')),
95 ]
95 ]
96
96
97 templateopts = [
97 templateopts = [
98 ('', 'style', '',
98 ('', 'style', '',
99 _('display using template map file (DEPRECATED)'), _('STYLE')),
99 _('display using template map file (DEPRECATED)'), _('STYLE')),
100 ('T', 'template', '',
100 ('T', 'template', '',
101 _('display with template'), _('TEMPLATE')),
101 _('display with template'), _('TEMPLATE')),
102 ]
102 ]
103
103
104 logopts = [
104 logopts = [
105 ('p', 'patch', None, _('show patch')),
105 ('p', 'patch', None, _('show patch')),
106 ('g', 'git', None, _('use git extended diff format')),
106 ('g', 'git', None, _('use git extended diff format')),
107 ('l', 'limit', '',
107 ('l', 'limit', '',
108 _('limit number of changes displayed'), _('NUM')),
108 _('limit number of changes displayed'), _('NUM')),
109 ('M', 'no-merges', None, _('do not show merges')),
109 ('M', 'no-merges', None, _('do not show merges')),
110 ('', 'stat', None, _('output diffstat-style summary of changes')),
110 ('', 'stat', None, _('output diffstat-style summary of changes')),
111 ('G', 'graph', None, _("show the revision DAG")),
111 ('G', 'graph', None, _("show the revision DAG")),
112 ] + templateopts
112 ] + templateopts
113
113
114 diffopts = [
114 diffopts = [
115 ('a', 'text', None, _('treat all files as text')),
115 ('a', 'text', None, _('treat all files as text')),
116 ('g', 'git', None, _('use git extended diff format')),
116 ('g', 'git', None, _('use git extended diff format')),
117 ('', 'binary', None, _('generate binary diffs in git mode (default)')),
117 ('', 'binary', None, _('generate binary diffs in git mode (default)')),
118 ('', 'nodates', None, _('omit dates from diff headers'))
118 ('', 'nodates', None, _('omit dates from diff headers'))
119 ]
119 ]
120
120
121 diffwsopts = [
121 diffwsopts = [
122 ('w', 'ignore-all-space', None,
122 ('w', 'ignore-all-space', None,
123 _('ignore white space when comparing lines')),
123 _('ignore white space when comparing lines')),
124 ('b', 'ignore-space-change', None,
124 ('b', 'ignore-space-change', None,
125 _('ignore changes in the amount of white space')),
125 _('ignore changes in the amount of white space')),
126 ('B', 'ignore-blank-lines', None,
126 ('B', 'ignore-blank-lines', None,
127 _('ignore changes whose lines are all blank')),
127 _('ignore changes whose lines are all blank')),
128 ('Z', 'ignore-space-at-eol', None,
128 ('Z', 'ignore-space-at-eol', None,
129 _('ignore changes in whitespace at EOL')),
129 _('ignore changes in whitespace at EOL')),
130 ]
130 ]
131
131
132 diffopts2 = [
132 diffopts2 = [
133 ('', 'noprefix', None, _('omit a/ and b/ prefixes from filenames')),
133 ('', 'noprefix', None, _('omit a/ and b/ prefixes from filenames')),
134 ('p', 'show-function', None, _('show which function each change is in')),
134 ('p', 'show-function', None, _('show which function each change is in')),
135 ('', 'reverse', None, _('produce a diff that undoes the changes')),
135 ('', 'reverse', None, _('produce a diff that undoes the changes')),
136 ] + diffwsopts + [
136 ] + diffwsopts + [
137 ('U', 'unified', '',
137 ('U', 'unified', '',
138 _('number of lines of context to show'), _('NUM')),
138 _('number of lines of context to show'), _('NUM')),
139 ('', 'stat', None, _('output diffstat-style summary of changes')),
139 ('', 'stat', None, _('output diffstat-style summary of changes')),
140 ('', 'root', '', _('produce diffs relative to subdirectory'), _('DIR')),
140 ('', 'root', '', _('produce diffs relative to subdirectory'), _('DIR')),
141 ]
141 ]
142
142
143 mergetoolopts = [
143 mergetoolopts = [
144 ('t', 'tool', '', _('specify merge tool')),
144 ('t', 'tool', '', _('specify merge tool')),
145 ]
145 ]
146
146
147 similarityopts = [
147 similarityopts = [
148 ('s', 'similarity', '',
148 ('s', 'similarity', '',
149 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
149 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
150 ]
150 ]
151
151
152 subrepoopts = [
152 subrepoopts = [
153 ('S', 'subrepos', None,
153 ('S', 'subrepos', None,
154 _('recurse into subrepositories'))
154 _('recurse into subrepositories'))
155 ]
155 ]
156
156
157 debugrevlogopts = [
157 debugrevlogopts = [
158 ('c', 'changelog', False, _('open changelog')),
158 ('c', 'changelog', False, _('open changelog')),
159 ('m', 'manifest', False, _('open manifest')),
159 ('m', 'manifest', False, _('open manifest')),
160 ('', 'dir', '', _('open directory manifest')),
160 ('', 'dir', '', _('open directory manifest')),
161 ]
161 ]
162
162
163 # special string such that everything below this line will be ingored in the
163 # special string such that everything below this line will be ingored in the
164 # editor text
164 # editor text
165 _linebelow = "^HG: ------------------------ >8 ------------------------$"
165 _linebelow = "^HG: ------------------------ >8 ------------------------$"
166
166
167 def ishunk(x):
167 def ishunk(x):
168 hunkclasses = (crecordmod.uihunk, patch.recordhunk)
168 hunkclasses = (crecordmod.uihunk, patch.recordhunk)
169 return isinstance(x, hunkclasses)
169 return isinstance(x, hunkclasses)
170
170
171 def newandmodified(chunks, originalchunks):
171 def newandmodified(chunks, originalchunks):
172 newlyaddedandmodifiedfiles = set()
172 newlyaddedandmodifiedfiles = set()
173 for chunk in chunks:
173 for chunk in chunks:
174 if ishunk(chunk) and chunk.header.isnewfile() and chunk not in \
174 if ishunk(chunk) and chunk.header.isnewfile() and chunk not in \
175 originalchunks:
175 originalchunks:
176 newlyaddedandmodifiedfiles.add(chunk.header.filename())
176 newlyaddedandmodifiedfiles.add(chunk.header.filename())
177 return newlyaddedandmodifiedfiles
177 return newlyaddedandmodifiedfiles
178
178
179 def parsealiases(cmd):
179 def parsealiases(cmd):
180 return cmd.lstrip("^").split("|")
180 return cmd.lstrip("^").split("|")
181
181
182 def setupwrapcolorwrite(ui):
182 def setupwrapcolorwrite(ui):
183 # wrap ui.write so diff output can be labeled/colorized
183 # wrap ui.write so diff output can be labeled/colorized
184 def wrapwrite(orig, *args, **kw):
184 def wrapwrite(orig, *args, **kw):
185 label = kw.pop(r'label', '')
185 label = kw.pop(r'label', '')
186 for chunk, l in patch.difflabel(lambda: args):
186 for chunk, l in patch.difflabel(lambda: args):
187 orig(chunk, label=label + l)
187 orig(chunk, label=label + l)
188
188
189 oldwrite = ui.write
189 oldwrite = ui.write
190 def wrap(*args, **kwargs):
190 def wrap(*args, **kwargs):
191 return wrapwrite(oldwrite, *args, **kwargs)
191 return wrapwrite(oldwrite, *args, **kwargs)
192 setattr(ui, 'write', wrap)
192 setattr(ui, 'write', wrap)
193 return oldwrite
193 return oldwrite
194
194
195 def filterchunks(ui, originalhunks, usecurses, testfile, operation=None):
195 def filterchunks(ui, originalhunks, usecurses, testfile, operation=None):
196 if usecurses:
196 if usecurses:
197 if testfile:
197 if testfile:
198 recordfn = crecordmod.testdecorator(testfile,
198 recordfn = crecordmod.testdecorator(testfile,
199 crecordmod.testchunkselector)
199 crecordmod.testchunkselector)
200 else:
200 else:
201 recordfn = crecordmod.chunkselector
201 recordfn = crecordmod.chunkselector
202
202
203 return crecordmod.filterpatch(ui, originalhunks, recordfn, operation)
203 return crecordmod.filterpatch(ui, originalhunks, recordfn, operation)
204
204
205 else:
205 else:
206 return patch.filterpatch(ui, originalhunks, operation)
206 return patch.filterpatch(ui, originalhunks, operation)
207
207
208 def recordfilter(ui, originalhunks, operation=None):
208 def recordfilter(ui, originalhunks, operation=None):
209 """ Prompts the user to filter the originalhunks and return a list of
209 """ Prompts the user to filter the originalhunks and return a list of
210 selected hunks.
210 selected hunks.
211 *operation* is used for to build ui messages to indicate the user what
211 *operation* is used for to build ui messages to indicate the user what
212 kind of filtering they are doing: reverting, committing, shelving, etc.
212 kind of filtering they are doing: reverting, committing, shelving, etc.
213 (see patch.filterpatch).
213 (see patch.filterpatch).
214 """
214 """
215 usecurses = crecordmod.checkcurses(ui)
215 usecurses = crecordmod.checkcurses(ui)
216 testfile = ui.config('experimental', 'crecordtest')
216 testfile = ui.config('experimental', 'crecordtest')
217 oldwrite = setupwrapcolorwrite(ui)
217 oldwrite = setupwrapcolorwrite(ui)
218 try:
218 try:
219 newchunks, newopts = filterchunks(ui, originalhunks, usecurses,
219 newchunks, newopts = filterchunks(ui, originalhunks, usecurses,
220 testfile, operation)
220 testfile, operation)
221 finally:
221 finally:
222 ui.write = oldwrite
222 ui.write = oldwrite
223 return newchunks, newopts
223 return newchunks, newopts
224
224
225 def dorecord(ui, repo, commitfunc, cmdsuggest, backupall,
225 def dorecord(ui, repo, commitfunc, cmdsuggest, backupall,
226 filterfn, *pats, **opts):
226 filterfn, *pats, **opts):
227 from . import merge as mergemod
227 from . import merge as mergemod
228 opts = pycompat.byteskwargs(opts)
228 opts = pycompat.byteskwargs(opts)
229 if not ui.interactive():
229 if not ui.interactive():
230 if cmdsuggest:
230 if cmdsuggest:
231 msg = _('running non-interactively, use %s instead') % cmdsuggest
231 msg = _('running non-interactively, use %s instead') % cmdsuggest
232 else:
232 else:
233 msg = _('running non-interactively')
233 msg = _('running non-interactively')
234 raise error.Abort(msg)
234 raise error.Abort(msg)
235
235
236 # make sure username is set before going interactive
236 # make sure username is set before going interactive
237 if not opts.get('user'):
237 if not opts.get('user'):
238 ui.username() # raise exception, username not provided
238 ui.username() # raise exception, username not provided
239
239
240 def recordfunc(ui, repo, message, match, opts):
240 def recordfunc(ui, repo, message, match, opts):
241 """This is generic record driver.
241 """This is generic record driver.
242
242
243 Its job is to interactively filter local changes, and
243 Its job is to interactively filter local changes, and
244 accordingly prepare working directory into a state in which the
244 accordingly prepare working directory into a state in which the
245 job can be delegated to a non-interactive commit command such as
245 job can be delegated to a non-interactive commit command such as
246 'commit' or 'qrefresh'.
246 'commit' or 'qrefresh'.
247
247
248 After the actual job is done by non-interactive command, the
248 After the actual job is done by non-interactive command, the
249 working directory is restored to its original state.
249 working directory is restored to its original state.
250
250
251 In the end we'll record interesting changes, and everything else
251 In the end we'll record interesting changes, and everything else
252 will be left in place, so the user can continue working.
252 will be left in place, so the user can continue working.
253 """
253 """
254
254
255 checkunfinished(repo, commit=True)
255 checkunfinished(repo, commit=True)
256 wctx = repo[None]
256 wctx = repo[None]
257 merge = len(wctx.parents()) > 1
257 merge = len(wctx.parents()) > 1
258 if merge:
258 if merge:
259 raise error.Abort(_('cannot partially commit a merge '
259 raise error.Abort(_('cannot partially commit a merge '
260 '(use "hg commit" instead)'))
260 '(use "hg commit" instead)'))
261
261
262 def fail(f, msg):
262 def fail(f, msg):
263 raise error.Abort('%s: %s' % (f, msg))
263 raise error.Abort('%s: %s' % (f, msg))
264
264
265 force = opts.get('force')
265 force = opts.get('force')
266 if not force:
266 if not force:
267 vdirs = []
267 vdirs = []
268 match.explicitdir = vdirs.append
268 match.explicitdir = vdirs.append
269 match.bad = fail
269 match.bad = fail
270
270
271 status = repo.status(match=match)
271 status = repo.status(match=match)
272 if not force:
272 if not force:
273 repo.checkcommitpatterns(wctx, vdirs, match, status, fail)
273 repo.checkcommitpatterns(wctx, vdirs, match, status, fail)
274 diffopts = patch.difffeatureopts(ui, opts=opts, whitespace=True)
274 diffopts = patch.difffeatureopts(ui, opts=opts, whitespace=True)
275 diffopts.nodates = True
275 diffopts.nodates = True
276 diffopts.git = True
276 diffopts.git = True
277 diffopts.showfunc = True
277 diffopts.showfunc = True
278 originaldiff = patch.diff(repo, changes=status, opts=diffopts)
278 originaldiff = patch.diff(repo, changes=status, opts=diffopts)
279 originalchunks = patch.parsepatch(originaldiff)
279 originalchunks = patch.parsepatch(originaldiff)
280
280
281 # 1. filter patch, since we are intending to apply subset of it
281 # 1. filter patch, since we are intending to apply subset of it
282 try:
282 try:
283 chunks, newopts = filterfn(ui, originalchunks)
283 chunks, newopts = filterfn(ui, originalchunks)
284 except error.PatchError as err:
284 except error.PatchError as err:
285 raise error.Abort(_('error parsing patch: %s') % err)
285 raise error.Abort(_('error parsing patch: %s') % err)
286 opts.update(newopts)
286 opts.update(newopts)
287
287
288 # We need to keep a backup of files that have been newly added and
288 # We need to keep a backup of files that have been newly added and
289 # modified during the recording process because there is a previous
289 # modified during the recording process because there is a previous
290 # version without the edit in the workdir
290 # version without the edit in the workdir
291 newlyaddedandmodifiedfiles = newandmodified(chunks, originalchunks)
291 newlyaddedandmodifiedfiles = newandmodified(chunks, originalchunks)
292 contenders = set()
292 contenders = set()
293 for h in chunks:
293 for h in chunks:
294 try:
294 try:
295 contenders.update(set(h.files()))
295 contenders.update(set(h.files()))
296 except AttributeError:
296 except AttributeError:
297 pass
297 pass
298
298
299 changed = status.modified + status.added + status.removed
299 changed = status.modified + status.added + status.removed
300 newfiles = [f for f in changed if f in contenders]
300 newfiles = [f for f in changed if f in contenders]
301 if not newfiles:
301 if not newfiles:
302 ui.status(_('no changes to record\n'))
302 ui.status(_('no changes to record\n'))
303 return 0
303 return 0
304
304
305 modified = set(status.modified)
305 modified = set(status.modified)
306
306
307 # 2. backup changed files, so we can restore them in the end
307 # 2. backup changed files, so we can restore them in the end
308
308
309 if backupall:
309 if backupall:
310 tobackup = changed
310 tobackup = changed
311 else:
311 else:
312 tobackup = [f for f in newfiles if f in modified or f in \
312 tobackup = [f for f in newfiles if f in modified or f in \
313 newlyaddedandmodifiedfiles]
313 newlyaddedandmodifiedfiles]
314 backups = {}
314 backups = {}
315 if tobackup:
315 if tobackup:
316 backupdir = repo.vfs.join('record-backups')
316 backupdir = repo.vfs.join('record-backups')
317 try:
317 try:
318 os.mkdir(backupdir)
318 os.mkdir(backupdir)
319 except OSError as err:
319 except OSError as err:
320 if err.errno != errno.EEXIST:
320 if err.errno != errno.EEXIST:
321 raise
321 raise
322 try:
322 try:
323 # backup continues
323 # backup continues
324 for f in tobackup:
324 for f in tobackup:
325 fd, tmpname = tempfile.mkstemp(prefix=f.replace('/', '_')+'.',
325 fd, tmpname = tempfile.mkstemp(prefix=f.replace('/', '_')+'.',
326 dir=backupdir)
326 dir=backupdir)
327 os.close(fd)
327 os.close(fd)
328 ui.debug('backup %r as %r\n' % (f, tmpname))
328 ui.debug('backup %r as %r\n' % (f, tmpname))
329 util.copyfile(repo.wjoin(f), tmpname, copystat=True)
329 util.copyfile(repo.wjoin(f), tmpname, copystat=True)
330 backups[f] = tmpname
330 backups[f] = tmpname
331
331
332 fp = stringio()
332 fp = stringio()
333 for c in chunks:
333 for c in chunks:
334 fname = c.filename()
334 fname = c.filename()
335 if fname in backups:
335 if fname in backups:
336 c.write(fp)
336 c.write(fp)
337 dopatch = fp.tell()
337 dopatch = fp.tell()
338 fp.seek(0)
338 fp.seek(0)
339
339
340 # 2.5 optionally review / modify patch in text editor
340 # 2.5 optionally review / modify patch in text editor
341 if opts.get('review', False):
341 if opts.get('review', False):
342 patchtext = (crecordmod.diffhelptext
342 patchtext = (crecordmod.diffhelptext
343 + crecordmod.patchhelptext
343 + crecordmod.patchhelptext
344 + fp.read())
344 + fp.read())
345 reviewedpatch = ui.edit(patchtext, "",
345 reviewedpatch = ui.edit(patchtext, "",
346 action="diff",
346 action="diff",
347 repopath=repo.path)
347 repopath=repo.path)
348 fp.truncate(0)
348 fp.truncate(0)
349 fp.write(reviewedpatch)
349 fp.write(reviewedpatch)
350 fp.seek(0)
350 fp.seek(0)
351
351
352 [os.unlink(repo.wjoin(c)) for c in newlyaddedandmodifiedfiles]
352 [os.unlink(repo.wjoin(c)) for c in newlyaddedandmodifiedfiles]
353 # 3a. apply filtered patch to clean repo (clean)
353 # 3a. apply filtered patch to clean repo (clean)
354 if backups:
354 if backups:
355 # Equivalent to hg.revert
355 # Equivalent to hg.revert
356 m = scmutil.matchfiles(repo, backups.keys())
356 m = scmutil.matchfiles(repo, backups.keys())
357 mergemod.update(repo, repo.dirstate.p1(),
357 mergemod.update(repo, repo.dirstate.p1(),
358 False, True, matcher=m)
358 False, True, matcher=m)
359
359
360 # 3b. (apply)
360 # 3b. (apply)
361 if dopatch:
361 if dopatch:
362 try:
362 try:
363 ui.debug('applying patch\n')
363 ui.debug('applying patch\n')
364 ui.debug(fp.getvalue())
364 ui.debug(fp.getvalue())
365 patch.internalpatch(ui, repo, fp, 1, eolmode=None)
365 patch.internalpatch(ui, repo, fp, 1, eolmode=None)
366 except error.PatchError as err:
366 except error.PatchError as err:
367 raise error.Abort(str(err))
367 raise error.Abort(str(err))
368 del fp
368 del fp
369
369
370 # 4. We prepared working directory according to filtered
370 # 4. We prepared working directory according to filtered
371 # patch. Now is the time to delegate the job to
371 # patch. Now is the time to delegate the job to
372 # commit/qrefresh or the like!
372 # commit/qrefresh or the like!
373
373
374 # Make all of the pathnames absolute.
374 # Make all of the pathnames absolute.
375 newfiles = [repo.wjoin(nf) for nf in newfiles]
375 newfiles = [repo.wjoin(nf) for nf in newfiles]
376 return commitfunc(ui, repo, *newfiles, **pycompat.strkwargs(opts))
376 return commitfunc(ui, repo, *newfiles, **pycompat.strkwargs(opts))
377 finally:
377 finally:
378 # 5. finally restore backed-up files
378 # 5. finally restore backed-up files
379 try:
379 try:
380 dirstate = repo.dirstate
380 dirstate = repo.dirstate
381 for realname, tmpname in backups.iteritems():
381 for realname, tmpname in backups.iteritems():
382 ui.debug('restoring %r to %r\n' % (tmpname, realname))
382 ui.debug('restoring %r to %r\n' % (tmpname, realname))
383
383
384 if dirstate[realname] == 'n':
384 if dirstate[realname] == 'n':
385 # without normallookup, restoring timestamp
385 # without normallookup, restoring timestamp
386 # may cause partially committed files
386 # may cause partially committed files
387 # to be treated as unmodified
387 # to be treated as unmodified
388 dirstate.normallookup(realname)
388 dirstate.normallookup(realname)
389
389
390 # copystat=True here and above are a hack to trick any
390 # copystat=True here and above are a hack to trick any
391 # editors that have f open that we haven't modified them.
391 # editors that have f open that we haven't modified them.
392 #
392 #
393 # Also note that this racy as an editor could notice the
393 # Also note that this racy as an editor could notice the
394 # file's mtime before we've finished writing it.
394 # file's mtime before we've finished writing it.
395 util.copyfile(tmpname, repo.wjoin(realname), copystat=True)
395 util.copyfile(tmpname, repo.wjoin(realname), copystat=True)
396 os.unlink(tmpname)
396 os.unlink(tmpname)
397 if tobackup:
397 if tobackup:
398 os.rmdir(backupdir)
398 os.rmdir(backupdir)
399 except OSError:
399 except OSError:
400 pass
400 pass
401
401
402 def recordinwlock(ui, repo, message, match, opts):
402 def recordinwlock(ui, repo, message, match, opts):
403 with repo.wlock():
403 with repo.wlock():
404 return recordfunc(ui, repo, message, match, opts)
404 return recordfunc(ui, repo, message, match, opts)
405
405
406 return commit(ui, repo, recordinwlock, pats, opts)
406 return commit(ui, repo, recordinwlock, pats, opts)
407
407
408 class dirnode(object):
408 class dirnode(object):
409 """
409 """
410 Represent a directory in user working copy with information required for
410 Represent a directory in user working copy with information required for
411 the purpose of tersing its status.
411 the purpose of tersing its status.
412
412
413 path is the path to the directory
413 path is the path to the directory
414
414
415 statuses is a set of statuses of all files in this directory (this includes
415 statuses is a set of statuses of all files in this directory (this includes
416 all the files in all the subdirectories too)
416 all the files in all the subdirectories too)
417
417
418 files is a list of files which are direct child of this directory
418 files is a list of files which are direct child of this directory
419
419
420 subdirs is a dictionary of sub-directory name as the key and it's own
420 subdirs is a dictionary of sub-directory name as the key and it's own
421 dirnode object as the value
421 dirnode object as the value
422 """
422 """
423
423
424 def __init__(self, dirpath):
424 def __init__(self, dirpath):
425 self.path = dirpath
425 self.path = dirpath
426 self.statuses = set([])
426 self.statuses = set([])
427 self.files = []
427 self.files = []
428 self.subdirs = {}
428 self.subdirs = {}
429
429
430 def _addfileindir(self, filename, status):
430 def _addfileindir(self, filename, status):
431 """Add a file in this directory as a direct child."""
431 """Add a file in this directory as a direct child."""
432 self.files.append((filename, status))
432 self.files.append((filename, status))
433
433
434 def addfile(self, filename, status):
434 def addfile(self, filename, status):
435 """
435 """
436 Add a file to this directory or to its direct parent directory.
436 Add a file to this directory or to its direct parent directory.
437
437
438 If the file is not direct child of this directory, we traverse to the
438 If the file is not direct child of this directory, we traverse to the
439 directory of which this file is a direct child of and add the file
439 directory of which this file is a direct child of and add the file
440 there.
440 there.
441 """
441 """
442
442
443 # the filename contains a path separator, it means it's not the direct
443 # the filename contains a path separator, it means it's not the direct
444 # child of this directory
444 # child of this directory
445 if '/' in filename:
445 if '/' in filename:
446 subdir, filep = filename.split('/', 1)
446 subdir, filep = filename.split('/', 1)
447
447
448 # does the dirnode object for subdir exists
448 # does the dirnode object for subdir exists
449 if subdir not in self.subdirs:
449 if subdir not in self.subdirs:
450 subdirpath = os.path.join(self.path, subdir)
450 subdirpath = os.path.join(self.path, subdir)
451 self.subdirs[subdir] = dirnode(subdirpath)
451 self.subdirs[subdir] = dirnode(subdirpath)
452
452
453 # try adding the file in subdir
453 # try adding the file in subdir
454 self.subdirs[subdir].addfile(filep, status)
454 self.subdirs[subdir].addfile(filep, status)
455
455
456 else:
456 else:
457 self._addfileindir(filename, status)
457 self._addfileindir(filename, status)
458
458
459 if status not in self.statuses:
459 if status not in self.statuses:
460 self.statuses.add(status)
460 self.statuses.add(status)
461
461
462 def iterfilepaths(self):
462 def iterfilepaths(self):
463 """Yield (status, path) for files directly under this directory."""
463 """Yield (status, path) for files directly under this directory."""
464 for f, st in self.files:
464 for f, st in self.files:
465 yield st, os.path.join(self.path, f)
465 yield st, os.path.join(self.path, f)
466
466
467 def tersewalk(self, terseargs):
467 def tersewalk(self, terseargs):
468 """
468 """
469 Yield (status, path) obtained by processing the status of this
469 Yield (status, path) obtained by processing the status of this
470 dirnode.
470 dirnode.
471
471
472 terseargs is the string of arguments passed by the user with `--terse`
472 terseargs is the string of arguments passed by the user with `--terse`
473 flag.
473 flag.
474
474
475 Following are the cases which can happen:
475 Following are the cases which can happen:
476
476
477 1) All the files in the directory (including all the files in its
477 1) All the files in the directory (including all the files in its
478 subdirectories) share the same status and the user has asked us to terse
478 subdirectories) share the same status and the user has asked us to terse
479 that status. -> yield (status, dirpath)
479 that status. -> yield (status, dirpath)
480
480
481 2) Otherwise, we do following:
481 2) Otherwise, we do following:
482
482
483 a) Yield (status, filepath) for all the files which are in this
483 a) Yield (status, filepath) for all the files which are in this
484 directory (only the ones in this directory, not the subdirs)
484 directory (only the ones in this directory, not the subdirs)
485
485
486 b) Recurse the function on all the subdirectories of this
486 b) Recurse the function on all the subdirectories of this
487 directory
487 directory
488 """
488 """
489
489
490 if len(self.statuses) == 1:
490 if len(self.statuses) == 1:
491 onlyst = self.statuses.pop()
491 onlyst = self.statuses.pop()
492
492
493 # Making sure we terse only when the status abbreviation is
493 # Making sure we terse only when the status abbreviation is
494 # passed as terse argument
494 # passed as terse argument
495 if onlyst in terseargs:
495 if onlyst in terseargs:
496 yield onlyst, self.path + pycompat.ossep
496 yield onlyst, self.path + pycompat.ossep
497 return
497 return
498
498
499 # add the files to status list
499 # add the files to status list
500 for st, fpath in self.iterfilepaths():
500 for st, fpath in self.iterfilepaths():
501 yield st, fpath
501 yield st, fpath
502
502
503 #recurse on the subdirs
503 #recurse on the subdirs
504 for dirobj in self.subdirs.values():
504 for dirobj in self.subdirs.values():
505 for st, fpath in dirobj.tersewalk(terseargs):
505 for st, fpath in dirobj.tersewalk(terseargs):
506 yield st, fpath
506 yield st, fpath
507
507
508 def tersedir(statuslist, terseargs):
508 def tersedir(statuslist, terseargs):
509 """
509 """
510 Terse the status if all the files in a directory shares the same status.
510 Terse the status if all the files in a directory shares the same status.
511
511
512 statuslist is scmutil.status() object which contains a list of files for
512 statuslist is scmutil.status() object which contains a list of files for
513 each status.
513 each status.
514 terseargs is string which is passed by the user as the argument to `--terse`
514 terseargs is string which is passed by the user as the argument to `--terse`
515 flag.
515 flag.
516
516
517 The function makes a tree of objects of dirnode class, and at each node it
517 The function makes a tree of objects of dirnode class, and at each node it
518 stores the information required to know whether we can terse a certain
518 stores the information required to know whether we can terse a certain
519 directory or not.
519 directory or not.
520 """
520 """
521 # the order matters here as that is used to produce final list
521 # the order matters here as that is used to produce final list
522 allst = ('m', 'a', 'r', 'd', 'u', 'i', 'c')
522 allst = ('m', 'a', 'r', 'd', 'u', 'i', 'c')
523
523
524 # checking the argument validity
524 # checking the argument validity
525 for s in pycompat.bytestr(terseargs):
525 for s in pycompat.bytestr(terseargs):
526 if s not in allst:
526 if s not in allst:
527 raise error.Abort(_("'%s' not recognized") % s)
527 raise error.Abort(_("'%s' not recognized") % s)
528
528
529 # creating a dirnode object for the root of the repo
529 # creating a dirnode object for the root of the repo
530 rootobj = dirnode('')
530 rootobj = dirnode('')
531 pstatus = ('modified', 'added', 'deleted', 'clean', 'unknown',
531 pstatus = ('modified', 'added', 'deleted', 'clean', 'unknown',
532 'ignored', 'removed')
532 'ignored', 'removed')
533
533
534 tersedict = {}
534 tersedict = {}
535 for attrname in pstatus:
535 for attrname in pstatus:
536 statuschar = attrname[0:1]
536 statuschar = attrname[0:1]
537 for f in getattr(statuslist, attrname):
537 for f in getattr(statuslist, attrname):
538 rootobj.addfile(f, statuschar)
538 rootobj.addfile(f, statuschar)
539 tersedict[statuschar] = []
539 tersedict[statuschar] = []
540
540
541 # we won't be tersing the root dir, so add files in it
541 # we won't be tersing the root dir, so add files in it
542 for st, fpath in rootobj.iterfilepaths():
542 for st, fpath in rootobj.iterfilepaths():
543 tersedict[st].append(fpath)
543 tersedict[st].append(fpath)
544
544
545 # process each sub-directory and build tersedict
545 # process each sub-directory and build tersedict
546 for subdir in rootobj.subdirs.values():
546 for subdir in rootobj.subdirs.values():
547 for st, f in subdir.tersewalk(terseargs):
547 for st, f in subdir.tersewalk(terseargs):
548 tersedict[st].append(f)
548 tersedict[st].append(f)
549
549
550 tersedlist = []
550 tersedlist = []
551 for st in allst:
551 for st in allst:
552 tersedict[st].sort()
552 tersedict[st].sort()
553 tersedlist.append(tersedict[st])
553 tersedlist.append(tersedict[st])
554
554
555 return tersedlist
555 return tersedlist
556
556
557 def _commentlines(raw):
557 def _commentlines(raw):
558 '''Surround lineswith a comment char and a new line'''
558 '''Surround lineswith a comment char and a new line'''
559 lines = raw.splitlines()
559 lines = raw.splitlines()
560 commentedlines = ['# %s' % line for line in lines]
560 commentedlines = ['# %s' % line for line in lines]
561 return '\n'.join(commentedlines) + '\n'
561 return '\n'.join(commentedlines) + '\n'
562
562
563 def _conflictsmsg(repo):
563 def _conflictsmsg(repo):
564 # avoid merge cycle
564 # avoid merge cycle
565 from . import merge as mergemod
565 from . import merge as mergemod
566 mergestate = mergemod.mergestate.read(repo)
566 mergestate = mergemod.mergestate.read(repo)
567 if not mergestate.active():
567 if not mergestate.active():
568 return
568 return
569
569
570 m = scmutil.match(repo[None])
570 m = scmutil.match(repo[None])
571 unresolvedlist = [f for f in mergestate.unresolved() if m(f)]
571 unresolvedlist = [f for f in mergestate.unresolved() if m(f)]
572 if unresolvedlist:
572 if unresolvedlist:
573 mergeliststr = '\n'.join(
573 mergeliststr = '\n'.join(
574 [' %s' % util.pathto(repo.root, pycompat.getcwd(), path)
574 [' %s' % util.pathto(repo.root, pycompat.getcwd(), path)
575 for path in unresolvedlist])
575 for path in unresolvedlist])
576 msg = _('''Unresolved merge conflicts:
576 msg = _('''Unresolved merge conflicts:
577
577
578 %s
578 %s
579
579
580 To mark files as resolved: hg resolve --mark FILE''') % mergeliststr
580 To mark files as resolved: hg resolve --mark FILE''') % mergeliststr
581 else:
581 else:
582 msg = _('No unresolved merge conflicts.')
582 msg = _('No unresolved merge conflicts.')
583
583
584 return _commentlines(msg)
584 return _commentlines(msg)
585
585
586 def _helpmessage(continuecmd, abortcmd):
586 def _helpmessage(continuecmd, abortcmd):
587 msg = _('To continue: %s\n'
587 msg = _('To continue: %s\n'
588 'To abort: %s') % (continuecmd, abortcmd)
588 'To abort: %s') % (continuecmd, abortcmd)
589 return _commentlines(msg)
589 return _commentlines(msg)
590
590
591 def _rebasemsg():
591 def _rebasemsg():
592 return _helpmessage('hg rebase --continue', 'hg rebase --abort')
592 return _helpmessage('hg rebase --continue', 'hg rebase --abort')
593
593
594 def _histeditmsg():
594 def _histeditmsg():
595 return _helpmessage('hg histedit --continue', 'hg histedit --abort')
595 return _helpmessage('hg histedit --continue', 'hg histedit --abort')
596
596
597 def _unshelvemsg():
597 def _unshelvemsg():
598 return _helpmessage('hg unshelve --continue', 'hg unshelve --abort')
598 return _helpmessage('hg unshelve --continue', 'hg unshelve --abort')
599
599
600 def _updatecleanmsg(dest=None):
600 def _updatecleanmsg(dest=None):
601 warning = _('warning: this will discard uncommitted changes')
601 warning = _('warning: this will discard uncommitted changes')
602 return 'hg update --clean %s (%s)' % (dest or '.', warning)
602 return 'hg update --clean %s (%s)' % (dest or '.', warning)
603
603
604 def _graftmsg():
604 def _graftmsg():
605 # tweakdefaults requires `update` to have a rev hence the `.`
605 # tweakdefaults requires `update` to have a rev hence the `.`
606 return _helpmessage('hg graft --continue', _updatecleanmsg())
606 return _helpmessage('hg graft --continue', _updatecleanmsg())
607
607
608 def _mergemsg():
608 def _mergemsg():
609 # tweakdefaults requires `update` to have a rev hence the `.`
609 # tweakdefaults requires `update` to have a rev hence the `.`
610 return _helpmessage('hg commit', _updatecleanmsg())
610 return _helpmessage('hg commit', _updatecleanmsg())
611
611
612 def _bisectmsg():
612 def _bisectmsg():
613 msg = _('To mark the changeset good: hg bisect --good\n'
613 msg = _('To mark the changeset good: hg bisect --good\n'
614 'To mark the changeset bad: hg bisect --bad\n'
614 'To mark the changeset bad: hg bisect --bad\n'
615 'To abort: hg bisect --reset\n')
615 'To abort: hg bisect --reset\n')
616 return _commentlines(msg)
616 return _commentlines(msg)
617
617
618 def fileexistspredicate(filename):
618 def fileexistspredicate(filename):
619 return lambda repo: repo.vfs.exists(filename)
619 return lambda repo: repo.vfs.exists(filename)
620
620
621 def _mergepredicate(repo):
621 def _mergepredicate(repo):
622 return len(repo[None].parents()) > 1
622 return len(repo[None].parents()) > 1
623
623
624 STATES = (
624 STATES = (
625 # (state, predicate to detect states, helpful message function)
625 # (state, predicate to detect states, helpful message function)
626 ('histedit', fileexistspredicate('histedit-state'), _histeditmsg),
626 ('histedit', fileexistspredicate('histedit-state'), _histeditmsg),
627 ('bisect', fileexistspredicate('bisect.state'), _bisectmsg),
627 ('bisect', fileexistspredicate('bisect.state'), _bisectmsg),
628 ('graft', fileexistspredicate('graftstate'), _graftmsg),
628 ('graft', fileexistspredicate('graftstate'), _graftmsg),
629 ('unshelve', fileexistspredicate('unshelverebasestate'), _unshelvemsg),
629 ('unshelve', fileexistspredicate('unshelverebasestate'), _unshelvemsg),
630 ('rebase', fileexistspredicate('rebasestate'), _rebasemsg),
630 ('rebase', fileexistspredicate('rebasestate'), _rebasemsg),
631 # The merge state is part of a list that will be iterated over.
631 # The merge state is part of a list that will be iterated over.
632 # They need to be last because some of the other unfinished states may also
632 # They need to be last because some of the other unfinished states may also
633 # be in a merge or update state (eg. rebase, histedit, graft, etc).
633 # be in a merge or update state (eg. rebase, histedit, graft, etc).
634 # We want those to have priority.
634 # We want those to have priority.
635 ('merge', _mergepredicate, _mergemsg),
635 ('merge', _mergepredicate, _mergemsg),
636 )
636 )
637
637
638 def _getrepostate(repo):
638 def _getrepostate(repo):
639 # experimental config: commands.status.skipstates
639 # experimental config: commands.status.skipstates
640 skip = set(repo.ui.configlist('commands', 'status.skipstates'))
640 skip = set(repo.ui.configlist('commands', 'status.skipstates'))
641 for state, statedetectionpredicate, msgfn in STATES:
641 for state, statedetectionpredicate, msgfn in STATES:
642 if state in skip:
642 if state in skip:
643 continue
643 continue
644 if statedetectionpredicate(repo):
644 if statedetectionpredicate(repo):
645 return (state, statedetectionpredicate, msgfn)
645 return (state, statedetectionpredicate, msgfn)
646
646
647 def morestatus(repo, fm):
647 def morestatus(repo, fm):
648 statetuple = _getrepostate(repo)
648 statetuple = _getrepostate(repo)
649 label = 'status.morestatus'
649 label = 'status.morestatus'
650 if statetuple:
650 if statetuple:
651 fm.startitem()
651 fm.startitem()
652 state, statedetectionpredicate, helpfulmsg = statetuple
652 state, statedetectionpredicate, helpfulmsg = statetuple
653 statemsg = _('The repository is in an unfinished *%s* state.') % state
653 statemsg = _('The repository is in an unfinished *%s* state.') % state
654 fm.write('statemsg', '%s\n', _commentlines(statemsg), label=label)
654 fm.write('statemsg', '%s\n', _commentlines(statemsg), label=label)
655 conmsg = _conflictsmsg(repo)
655 conmsg = _conflictsmsg(repo)
656 if conmsg:
656 if conmsg:
657 fm.write('conflictsmsg', '%s\n', conmsg, label=label)
657 fm.write('conflictsmsg', '%s\n', conmsg, label=label)
658 if helpfulmsg:
658 if helpfulmsg:
659 helpmsg = helpfulmsg()
659 helpmsg = helpfulmsg()
660 fm.write('helpmsg', '%s\n', helpmsg, label=label)
660 fm.write('helpmsg', '%s\n', helpmsg, label=label)
661
661
662 def findpossible(cmd, table, strict=False):
662 def findpossible(cmd, table, strict=False):
663 """
663 """
664 Return cmd -> (aliases, command table entry)
664 Return cmd -> (aliases, command table entry)
665 for each matching command.
665 for each matching command.
666 Return debug commands (or their aliases) only if no normal command matches.
666 Return debug commands (or their aliases) only if no normal command matches.
667 """
667 """
668 choice = {}
668 choice = {}
669 debugchoice = {}
669 debugchoice = {}
670
670
671 if cmd in table:
671 if cmd in table:
672 # short-circuit exact matches, "log" alias beats "^log|history"
672 # short-circuit exact matches, "log" alias beats "^log|history"
673 keys = [cmd]
673 keys = [cmd]
674 else:
674 else:
675 keys = table.keys()
675 keys = table.keys()
676
676
677 allcmds = []
677 allcmds = []
678 for e in keys:
678 for e in keys:
679 aliases = parsealiases(e)
679 aliases = parsealiases(e)
680 allcmds.extend(aliases)
680 allcmds.extend(aliases)
681 found = None
681 found = None
682 if cmd in aliases:
682 if cmd in aliases:
683 found = cmd
683 found = cmd
684 elif not strict:
684 elif not strict:
685 for a in aliases:
685 for a in aliases:
686 if a.startswith(cmd):
686 if a.startswith(cmd):
687 found = a
687 found = a
688 break
688 break
689 if found is not None:
689 if found is not None:
690 if aliases[0].startswith("debug") or found.startswith("debug"):
690 if aliases[0].startswith("debug") or found.startswith("debug"):
691 debugchoice[found] = (aliases, table[e])
691 debugchoice[found] = (aliases, table[e])
692 else:
692 else:
693 choice[found] = (aliases, table[e])
693 choice[found] = (aliases, table[e])
694
694
695 if not choice and debugchoice:
695 if not choice and debugchoice:
696 choice = debugchoice
696 choice = debugchoice
697
697
698 return choice, allcmds
698 return choice, allcmds
699
699
700 def findcmd(cmd, table, strict=True):
700 def findcmd(cmd, table, strict=True):
701 """Return (aliases, command table entry) for command string."""
701 """Return (aliases, command table entry) for command string."""
702 choice, allcmds = findpossible(cmd, table, strict)
702 choice, allcmds = findpossible(cmd, table, strict)
703
703
704 if cmd in choice:
704 if cmd in choice:
705 return choice[cmd]
705 return choice[cmd]
706
706
707 if len(choice) > 1:
707 if len(choice) > 1:
708 clist = sorted(choice)
708 clist = sorted(choice)
709 raise error.AmbiguousCommand(cmd, clist)
709 raise error.AmbiguousCommand(cmd, clist)
710
710
711 if choice:
711 if choice:
712 return list(choice.values())[0]
712 return list(choice.values())[0]
713
713
714 raise error.UnknownCommand(cmd, allcmds)
714 raise error.UnknownCommand(cmd, allcmds)
715
715
716 def findrepo(p):
716 def findrepo(p):
717 while not os.path.isdir(os.path.join(p, ".hg")):
717 while not os.path.isdir(os.path.join(p, ".hg")):
718 oldp, p = p, os.path.dirname(p)
718 oldp, p = p, os.path.dirname(p)
719 if p == oldp:
719 if p == oldp:
720 return None
720 return None
721
721
722 return p
722 return p
723
723
724 def bailifchanged(repo, merge=True, hint=None):
724 def bailifchanged(repo, merge=True, hint=None):
725 """ enforce the precondition that working directory must be clean.
725 """ enforce the precondition that working directory must be clean.
726
726
727 'merge' can be set to false if a pending uncommitted merge should be
727 'merge' can be set to false if a pending uncommitted merge should be
728 ignored (such as when 'update --check' runs).
728 ignored (such as when 'update --check' runs).
729
729
730 'hint' is the usual hint given to Abort exception.
730 'hint' is the usual hint given to Abort exception.
731 """
731 """
732
732
733 if merge and repo.dirstate.p2() != nullid:
733 if merge and repo.dirstate.p2() != nullid:
734 raise error.Abort(_('outstanding uncommitted merge'), hint=hint)
734 raise error.Abort(_('outstanding uncommitted merge'), hint=hint)
735 modified, added, removed, deleted = repo.status()[:4]
735 modified, added, removed, deleted = repo.status()[:4]
736 if modified or added or removed or deleted:
736 if modified or added or removed or deleted:
737 raise error.Abort(_('uncommitted changes'), hint=hint)
737 raise error.Abort(_('uncommitted changes'), hint=hint)
738 ctx = repo[None]
738 ctx = repo[None]
739 for s in sorted(ctx.substate):
739 for s in sorted(ctx.substate):
740 ctx.sub(s).bailifchanged(hint=hint)
740 ctx.sub(s).bailifchanged(hint=hint)
741
741
742 def logmessage(ui, opts):
742 def logmessage(ui, opts):
743 """ get the log message according to -m and -l option """
743 """ get the log message according to -m and -l option """
744 message = opts.get('message')
744 message = opts.get('message')
745 logfile = opts.get('logfile')
745 logfile = opts.get('logfile')
746
746
747 if message and logfile:
747 if message and logfile:
748 raise error.Abort(_('options --message and --logfile are mutually '
748 raise error.Abort(_('options --message and --logfile are mutually '
749 'exclusive'))
749 'exclusive'))
750 if not message and logfile:
750 if not message and logfile:
751 try:
751 try:
752 if isstdiofilename(logfile):
752 if isstdiofilename(logfile):
753 message = ui.fin.read()
753 message = ui.fin.read()
754 else:
754 else:
755 message = '\n'.join(util.readfile(logfile).splitlines())
755 message = '\n'.join(util.readfile(logfile).splitlines())
756 except IOError as inst:
756 except IOError as inst:
757 raise error.Abort(_("can't read commit message '%s': %s") %
757 raise error.Abort(_("can't read commit message '%s': %s") %
758 (logfile, encoding.strtolocal(inst.strerror)))
758 (logfile, encoding.strtolocal(inst.strerror)))
759 return message
759 return message
760
760
761 def mergeeditform(ctxorbool, baseformname):
761 def mergeeditform(ctxorbool, baseformname):
762 """return appropriate editform name (referencing a committemplate)
762 """return appropriate editform name (referencing a committemplate)
763
763
764 'ctxorbool' is either a ctx to be committed, or a bool indicating whether
764 'ctxorbool' is either a ctx to be committed, or a bool indicating whether
765 merging is committed.
765 merging is committed.
766
766
767 This returns baseformname with '.merge' appended if it is a merge,
767 This returns baseformname with '.merge' appended if it is a merge,
768 otherwise '.normal' is appended.
768 otherwise '.normal' is appended.
769 """
769 """
770 if isinstance(ctxorbool, bool):
770 if isinstance(ctxorbool, bool):
771 if ctxorbool:
771 if ctxorbool:
772 return baseformname + ".merge"
772 return baseformname + ".merge"
773 elif 1 < len(ctxorbool.parents()):
773 elif 1 < len(ctxorbool.parents()):
774 return baseformname + ".merge"
774 return baseformname + ".merge"
775
775
776 return baseformname + ".normal"
776 return baseformname + ".normal"
777
777
778 def getcommiteditor(edit=False, finishdesc=None, extramsg=None,
778 def getcommiteditor(edit=False, finishdesc=None, extramsg=None,
779 editform='', **opts):
779 editform='', **opts):
780 """get appropriate commit message editor according to '--edit' option
780 """get appropriate commit message editor according to '--edit' option
781
781
782 'finishdesc' is a function to be called with edited commit message
782 'finishdesc' is a function to be called with edited commit message
783 (= 'description' of the new changeset) just after editing, but
783 (= 'description' of the new changeset) just after editing, but
784 before checking empty-ness. It should return actual text to be
784 before checking empty-ness. It should return actual text to be
785 stored into history. This allows to change description before
785 stored into history. This allows to change description before
786 storing.
786 storing.
787
787
788 'extramsg' is a extra message to be shown in the editor instead of
788 'extramsg' is a extra message to be shown in the editor instead of
789 'Leave message empty to abort commit' line. 'HG: ' prefix and EOL
789 'Leave message empty to abort commit' line. 'HG: ' prefix and EOL
790 is automatically added.
790 is automatically added.
791
791
792 'editform' is a dot-separated list of names, to distinguish
792 'editform' is a dot-separated list of names, to distinguish
793 the purpose of commit text editing.
793 the purpose of commit text editing.
794
794
795 'getcommiteditor' returns 'commitforceeditor' regardless of
795 'getcommiteditor' returns 'commitforceeditor' regardless of
796 'edit', if one of 'finishdesc' or 'extramsg' is specified, because
796 'edit', if one of 'finishdesc' or 'extramsg' is specified, because
797 they are specific for usage in MQ.
797 they are specific for usage in MQ.
798 """
798 """
799 if edit or finishdesc or extramsg:
799 if edit or finishdesc or extramsg:
800 return lambda r, c, s: commitforceeditor(r, c, s,
800 return lambda r, c, s: commitforceeditor(r, c, s,
801 finishdesc=finishdesc,
801 finishdesc=finishdesc,
802 extramsg=extramsg,
802 extramsg=extramsg,
803 editform=editform)
803 editform=editform)
804 elif editform:
804 elif editform:
805 return lambda r, c, s: commiteditor(r, c, s, editform=editform)
805 return lambda r, c, s: commiteditor(r, c, s, editform=editform)
806 else:
806 else:
807 return commiteditor
807 return commiteditor
808
808
809 def loglimit(opts):
809 def loglimit(opts):
810 """get the log limit according to option -l/--limit"""
810 """get the log limit according to option -l/--limit"""
811 limit = opts.get('limit')
811 limit = opts.get('limit')
812 if limit:
812 if limit:
813 try:
813 try:
814 limit = int(limit)
814 limit = int(limit)
815 except ValueError:
815 except ValueError:
816 raise error.Abort(_('limit must be a positive integer'))
816 raise error.Abort(_('limit must be a positive integer'))
817 if limit <= 0:
817 if limit <= 0:
818 raise error.Abort(_('limit must be positive'))
818 raise error.Abort(_('limit must be positive'))
819 else:
819 else:
820 limit = None
820 limit = None
821 return limit
821 return limit
822
822
823 def makefilename(repo, pat, node, desc=None,
823 def makefilename(repo, pat, node, desc=None,
824 total=None, seqno=None, revwidth=None, pathname=None):
824 total=None, seqno=None, revwidth=None, pathname=None):
825 node_expander = {
825 node_expander = {
826 'H': lambda: hex(node),
826 'H': lambda: hex(node),
827 'R': lambda: '%d' % repo.changelog.rev(node),
827 'R': lambda: '%d' % repo.changelog.rev(node),
828 'h': lambda: short(node),
828 'h': lambda: short(node),
829 'm': lambda: re.sub('[^\w]', '_', desc or '')
829 'm': lambda: re.sub('[^\w]', '_', desc or '')
830 }
830 }
831 expander = {
831 expander = {
832 '%': lambda: '%',
832 '%': lambda: '%',
833 'b': lambda: os.path.basename(repo.root),
833 'b': lambda: os.path.basename(repo.root),
834 }
834 }
835
835
836 try:
836 try:
837 if node:
837 if node:
838 expander.update(node_expander)
838 expander.update(node_expander)
839 if node:
839 if node:
840 expander['r'] = (lambda:
840 expander['r'] = (lambda:
841 ('%d' % repo.changelog.rev(node)).zfill(revwidth or 0))
841 ('%d' % repo.changelog.rev(node)).zfill(revwidth or 0))
842 if total is not None:
842 if total is not None:
843 expander['N'] = lambda: '%d' % total
843 expander['N'] = lambda: '%d' % total
844 if seqno is not None:
844 if seqno is not None:
845 expander['n'] = lambda: '%d' % seqno
845 expander['n'] = lambda: '%d' % seqno
846 if total is not None and seqno is not None:
846 if total is not None and seqno is not None:
847 expander['n'] = (lambda: ('%d' % seqno).zfill(len('%d' % total)))
847 expander['n'] = (lambda: ('%d' % seqno).zfill(len('%d' % total)))
848 if pathname is not None:
848 if pathname is not None:
849 expander['s'] = lambda: os.path.basename(pathname)
849 expander['s'] = lambda: os.path.basename(pathname)
850 expander['d'] = lambda: os.path.dirname(pathname) or '.'
850 expander['d'] = lambda: os.path.dirname(pathname) or '.'
851 expander['p'] = lambda: pathname
851 expander['p'] = lambda: pathname
852
852
853 newname = []
853 newname = []
854 patlen = len(pat)
854 patlen = len(pat)
855 i = 0
855 i = 0
856 while i < patlen:
856 while i < patlen:
857 c = pat[i:i + 1]
857 c = pat[i:i + 1]
858 if c == '%':
858 if c == '%':
859 i += 1
859 i += 1
860 c = pat[i:i + 1]
860 c = pat[i:i + 1]
861 c = expander[c]()
861 c = expander[c]()
862 newname.append(c)
862 newname.append(c)
863 i += 1
863 i += 1
864 return ''.join(newname)
864 return ''.join(newname)
865 except KeyError as inst:
865 except KeyError as inst:
866 raise error.Abort(_("invalid format spec '%%%s' in output filename") %
866 raise error.Abort(_("invalid format spec '%%%s' in output filename") %
867 inst.args[0])
867 inst.args[0])
868
868
869 def isstdiofilename(pat):
869 def isstdiofilename(pat):
870 """True if the given pat looks like a filename denoting stdin/stdout"""
870 """True if the given pat looks like a filename denoting stdin/stdout"""
871 return not pat or pat == '-'
871 return not pat or pat == '-'
872
872
873 class _unclosablefile(object):
873 class _unclosablefile(object):
874 def __init__(self, fp):
874 def __init__(self, fp):
875 self._fp = fp
875 self._fp = fp
876
876
877 def close(self):
877 def close(self):
878 pass
878 pass
879
879
880 def __iter__(self):
880 def __iter__(self):
881 return iter(self._fp)
881 return iter(self._fp)
882
882
883 def __getattr__(self, attr):
883 def __getattr__(self, attr):
884 return getattr(self._fp, attr)
884 return getattr(self._fp, attr)
885
885
886 def __enter__(self):
886 def __enter__(self):
887 return self
887 return self
888
888
889 def __exit__(self, exc_type, exc_value, exc_tb):
889 def __exit__(self, exc_type, exc_value, exc_tb):
890 pass
890 pass
891
891
892 def makefileobj(repo, pat, node=None, desc=None, total=None,
892 def makefileobj(repo, pat, node=None, desc=None, total=None,
893 seqno=None, revwidth=None, mode='wb', modemap=None,
893 seqno=None, revwidth=None, mode='wb', modemap=None,
894 pathname=None):
894 pathname=None):
895
895
896 writable = mode not in ('r', 'rb')
896 writable = mode not in ('r', 'rb')
897
897
898 if isstdiofilename(pat):
898 if isstdiofilename(pat):
899 if writable:
899 if writable:
900 fp = repo.ui.fout
900 fp = repo.ui.fout
901 else:
901 else:
902 fp = repo.ui.fin
902 fp = repo.ui.fin
903 return _unclosablefile(fp)
903 return _unclosablefile(fp)
904 fn = makefilename(repo, pat, node, desc, total, seqno, revwidth, pathname)
904 fn = makefilename(repo, pat, node, desc, total, seqno, revwidth, pathname)
905 if modemap is not None:
905 if modemap is not None:
906 mode = modemap.get(fn, mode)
906 mode = modemap.get(fn, mode)
907 if mode == 'wb':
907 if mode == 'wb':
908 modemap[fn] = 'ab'
908 modemap[fn] = 'ab'
909 return open(fn, mode)
909 return open(fn, mode)
910
910
911 def openrevlog(repo, cmd, file_, opts):
911 def openrevlog(repo, cmd, file_, opts):
912 """opens the changelog, manifest, a filelog or a given revlog"""
912 """opens the changelog, manifest, a filelog or a given revlog"""
913 cl = opts['changelog']
913 cl = opts['changelog']
914 mf = opts['manifest']
914 mf = opts['manifest']
915 dir = opts['dir']
915 dir = opts['dir']
916 msg = None
916 msg = None
917 if cl and mf:
917 if cl and mf:
918 msg = _('cannot specify --changelog and --manifest at the same time')
918 msg = _('cannot specify --changelog and --manifest at the same time')
919 elif cl and dir:
919 elif cl and dir:
920 msg = _('cannot specify --changelog and --dir at the same time')
920 msg = _('cannot specify --changelog and --dir at the same time')
921 elif cl or mf or dir:
921 elif cl or mf or dir:
922 if file_:
922 if file_:
923 msg = _('cannot specify filename with --changelog or --manifest')
923 msg = _('cannot specify filename with --changelog or --manifest')
924 elif not repo:
924 elif not repo:
925 msg = _('cannot specify --changelog or --manifest or --dir '
925 msg = _('cannot specify --changelog or --manifest or --dir '
926 'without a repository')
926 'without a repository')
927 if msg:
927 if msg:
928 raise error.Abort(msg)
928 raise error.Abort(msg)
929
929
930 r = None
930 r = None
931 if repo:
931 if repo:
932 if cl:
932 if cl:
933 r = repo.unfiltered().changelog
933 r = repo.unfiltered().changelog
934 elif dir:
934 elif dir:
935 if 'treemanifest' not in repo.requirements:
935 if 'treemanifest' not in repo.requirements:
936 raise error.Abort(_("--dir can only be used on repos with "
936 raise error.Abort(_("--dir can only be used on repos with "
937 "treemanifest enabled"))
937 "treemanifest enabled"))
938 dirlog = repo.manifestlog._revlog.dirlog(dir)
938 dirlog = repo.manifestlog._revlog.dirlog(dir)
939 if len(dirlog):
939 if len(dirlog):
940 r = dirlog
940 r = dirlog
941 elif mf:
941 elif mf:
942 r = repo.manifestlog._revlog
942 r = repo.manifestlog._revlog
943 elif file_:
943 elif file_:
944 filelog = repo.file(file_)
944 filelog = repo.file(file_)
945 if len(filelog):
945 if len(filelog):
946 r = filelog
946 r = filelog
947 if not r:
947 if not r:
948 if not file_:
948 if not file_:
949 raise error.CommandError(cmd, _('invalid arguments'))
949 raise error.CommandError(cmd, _('invalid arguments'))
950 if not os.path.isfile(file_):
950 if not os.path.isfile(file_):
951 raise error.Abort(_("revlog '%s' not found") % file_)
951 raise error.Abort(_("revlog '%s' not found") % file_)
952 r = revlog.revlog(vfsmod.vfs(pycompat.getcwd(), audit=False),
952 r = revlog.revlog(vfsmod.vfs(pycompat.getcwd(), audit=False),
953 file_[:-2] + ".i")
953 file_[:-2] + ".i")
954 return r
954 return r
955
955
956 def copy(ui, repo, pats, opts, rename=False):
956 def copy(ui, repo, pats, opts, rename=False):
957 # called with the repo lock held
957 # called with the repo lock held
958 #
958 #
959 # hgsep => pathname that uses "/" to separate directories
959 # hgsep => pathname that uses "/" to separate directories
960 # ossep => pathname that uses os.sep to separate directories
960 # ossep => pathname that uses os.sep to separate directories
961 cwd = repo.getcwd()
961 cwd = repo.getcwd()
962 targets = {}
962 targets = {}
963 after = opts.get("after")
963 after = opts.get("after")
964 dryrun = opts.get("dry_run")
964 dryrun = opts.get("dry_run")
965 wctx = repo[None]
965 wctx = repo[None]
966
966
967 def walkpat(pat):
967 def walkpat(pat):
968 srcs = []
968 srcs = []
969 if after:
969 if after:
970 badstates = '?'
970 badstates = '?'
971 else:
971 else:
972 badstates = '?r'
972 badstates = '?r'
973 m = scmutil.match(wctx, [pat], opts, globbed=True)
973 m = scmutil.match(wctx, [pat], opts, globbed=True)
974 for abs in wctx.walk(m):
974 for abs in wctx.walk(m):
975 state = repo.dirstate[abs]
975 state = repo.dirstate[abs]
976 rel = m.rel(abs)
976 rel = m.rel(abs)
977 exact = m.exact(abs)
977 exact = m.exact(abs)
978 if state in badstates:
978 if state in badstates:
979 if exact and state == '?':
979 if exact and state == '?':
980 ui.warn(_('%s: not copying - file is not managed\n') % rel)
980 ui.warn(_('%s: not copying - file is not managed\n') % rel)
981 if exact and state == 'r':
981 if exact and state == 'r':
982 ui.warn(_('%s: not copying - file has been marked for'
982 ui.warn(_('%s: not copying - file has been marked for'
983 ' remove\n') % rel)
983 ' remove\n') % rel)
984 continue
984 continue
985 # abs: hgsep
985 # abs: hgsep
986 # rel: ossep
986 # rel: ossep
987 srcs.append((abs, rel, exact))
987 srcs.append((abs, rel, exact))
988 return srcs
988 return srcs
989
989
990 # abssrc: hgsep
990 # abssrc: hgsep
991 # relsrc: ossep
991 # relsrc: ossep
992 # otarget: ossep
992 # otarget: ossep
993 def copyfile(abssrc, relsrc, otarget, exact):
993 def copyfile(abssrc, relsrc, otarget, exact):
994 abstarget = pathutil.canonpath(repo.root, cwd, otarget)
994 abstarget = pathutil.canonpath(repo.root, cwd, otarget)
995 if '/' in abstarget:
995 if '/' in abstarget:
996 # We cannot normalize abstarget itself, this would prevent
996 # We cannot normalize abstarget itself, this would prevent
997 # case only renames, like a => A.
997 # case only renames, like a => A.
998 abspath, absname = abstarget.rsplit('/', 1)
998 abspath, absname = abstarget.rsplit('/', 1)
999 abstarget = repo.dirstate.normalize(abspath) + '/' + absname
999 abstarget = repo.dirstate.normalize(abspath) + '/' + absname
1000 reltarget = repo.pathto(abstarget, cwd)
1000 reltarget = repo.pathto(abstarget, cwd)
1001 target = repo.wjoin(abstarget)
1001 target = repo.wjoin(abstarget)
1002 src = repo.wjoin(abssrc)
1002 src = repo.wjoin(abssrc)
1003 state = repo.dirstate[abstarget]
1003 state = repo.dirstate[abstarget]
1004
1004
1005 scmutil.checkportable(ui, abstarget)
1005 scmutil.checkportable(ui, abstarget)
1006
1006
1007 # check for collisions
1007 # check for collisions
1008 prevsrc = targets.get(abstarget)
1008 prevsrc = targets.get(abstarget)
1009 if prevsrc is not None:
1009 if prevsrc is not None:
1010 ui.warn(_('%s: not overwriting - %s collides with %s\n') %
1010 ui.warn(_('%s: not overwriting - %s collides with %s\n') %
1011 (reltarget, repo.pathto(abssrc, cwd),
1011 (reltarget, repo.pathto(abssrc, cwd),
1012 repo.pathto(prevsrc, cwd)))
1012 repo.pathto(prevsrc, cwd)))
1013 return
1013 return
1014
1014
1015 # check for overwrites
1015 # check for overwrites
1016 exists = os.path.lexists(target)
1016 exists = os.path.lexists(target)
1017 samefile = False
1017 samefile = False
1018 if exists and abssrc != abstarget:
1018 if exists and abssrc != abstarget:
1019 if (repo.dirstate.normalize(abssrc) ==
1019 if (repo.dirstate.normalize(abssrc) ==
1020 repo.dirstate.normalize(abstarget)):
1020 repo.dirstate.normalize(abstarget)):
1021 if not rename:
1021 if not rename:
1022 ui.warn(_("%s: can't copy - same file\n") % reltarget)
1022 ui.warn(_("%s: can't copy - same file\n") % reltarget)
1023 return
1023 return
1024 exists = False
1024 exists = False
1025 samefile = True
1025 samefile = True
1026
1026
1027 if not after and exists or after and state in 'mn':
1027 if not after and exists or after and state in 'mn':
1028 if not opts['force']:
1028 if not opts['force']:
1029 if state in 'mn':
1029 if state in 'mn':
1030 msg = _('%s: not overwriting - file already committed\n')
1030 msg = _('%s: not overwriting - file already committed\n')
1031 if after:
1031 if after:
1032 flags = '--after --force'
1032 flags = '--after --force'
1033 else:
1033 else:
1034 flags = '--force'
1034 flags = '--force'
1035 if rename:
1035 if rename:
1036 hint = _('(hg rename %s to replace the file by '
1036 hint = _('(hg rename %s to replace the file by '
1037 'recording a rename)\n') % flags
1037 'recording a rename)\n') % flags
1038 else:
1038 else:
1039 hint = _('(hg copy %s to replace the file by '
1039 hint = _('(hg copy %s to replace the file by '
1040 'recording a copy)\n') % flags
1040 'recording a copy)\n') % flags
1041 else:
1041 else:
1042 msg = _('%s: not overwriting - file exists\n')
1042 msg = _('%s: not overwriting - file exists\n')
1043 if rename:
1043 if rename:
1044 hint = _('(hg rename --after to record the rename)\n')
1044 hint = _('(hg rename --after to record the rename)\n')
1045 else:
1045 else:
1046 hint = _('(hg copy --after to record the copy)\n')
1046 hint = _('(hg copy --after to record the copy)\n')
1047 ui.warn(msg % reltarget)
1047 ui.warn(msg % reltarget)
1048 ui.warn(hint)
1048 ui.warn(hint)
1049 return
1049 return
1050
1050
1051 if after:
1051 if after:
1052 if not exists:
1052 if not exists:
1053 if rename:
1053 if rename:
1054 ui.warn(_('%s: not recording move - %s does not exist\n') %
1054 ui.warn(_('%s: not recording move - %s does not exist\n') %
1055 (relsrc, reltarget))
1055 (relsrc, reltarget))
1056 else:
1056 else:
1057 ui.warn(_('%s: not recording copy - %s does not exist\n') %
1057 ui.warn(_('%s: not recording copy - %s does not exist\n') %
1058 (relsrc, reltarget))
1058 (relsrc, reltarget))
1059 return
1059 return
1060 elif not dryrun:
1060 elif not dryrun:
1061 try:
1061 try:
1062 if exists:
1062 if exists:
1063 os.unlink(target)
1063 os.unlink(target)
1064 targetdir = os.path.dirname(target) or '.'
1064 targetdir = os.path.dirname(target) or '.'
1065 if not os.path.isdir(targetdir):
1065 if not os.path.isdir(targetdir):
1066 os.makedirs(targetdir)
1066 os.makedirs(targetdir)
1067 if samefile:
1067 if samefile:
1068 tmp = target + "~hgrename"
1068 tmp = target + "~hgrename"
1069 os.rename(src, tmp)
1069 os.rename(src, tmp)
1070 os.rename(tmp, target)
1070 os.rename(tmp, target)
1071 else:
1071 else:
1072 util.copyfile(src, target)
1072 util.copyfile(src, target)
1073 srcexists = True
1073 srcexists = True
1074 except IOError as inst:
1074 except IOError as inst:
1075 if inst.errno == errno.ENOENT:
1075 if inst.errno == errno.ENOENT:
1076 ui.warn(_('%s: deleted in working directory\n') % relsrc)
1076 ui.warn(_('%s: deleted in working directory\n') % relsrc)
1077 srcexists = False
1077 srcexists = False
1078 else:
1078 else:
1079 ui.warn(_('%s: cannot copy - %s\n') %
1079 ui.warn(_('%s: cannot copy - %s\n') %
1080 (relsrc, encoding.strtolocal(inst.strerror)))
1080 (relsrc, encoding.strtolocal(inst.strerror)))
1081 return True # report a failure
1081 return True # report a failure
1082
1082
1083 if ui.verbose or not exact:
1083 if ui.verbose or not exact:
1084 if rename:
1084 if rename:
1085 ui.status(_('moving %s to %s\n') % (relsrc, reltarget))
1085 ui.status(_('moving %s to %s\n') % (relsrc, reltarget))
1086 else:
1086 else:
1087 ui.status(_('copying %s to %s\n') % (relsrc, reltarget))
1087 ui.status(_('copying %s to %s\n') % (relsrc, reltarget))
1088
1088
1089 targets[abstarget] = abssrc
1089 targets[abstarget] = abssrc
1090
1090
1091 # fix up dirstate
1091 # fix up dirstate
1092 scmutil.dirstatecopy(ui, repo, wctx, abssrc, abstarget,
1092 scmutil.dirstatecopy(ui, repo, wctx, abssrc, abstarget,
1093 dryrun=dryrun, cwd=cwd)
1093 dryrun=dryrun, cwd=cwd)
1094 if rename and not dryrun:
1094 if rename and not dryrun:
1095 if not after and srcexists and not samefile:
1095 if not after and srcexists and not samefile:
1096 repo.wvfs.unlinkpath(abssrc)
1096 repo.wvfs.unlinkpath(abssrc)
1097 wctx.forget([abssrc])
1097 wctx.forget([abssrc])
1098
1098
1099 # pat: ossep
1099 # pat: ossep
1100 # dest ossep
1100 # dest ossep
1101 # srcs: list of (hgsep, hgsep, ossep, bool)
1101 # srcs: list of (hgsep, hgsep, ossep, bool)
1102 # return: function that takes hgsep and returns ossep
1102 # return: function that takes hgsep and returns ossep
1103 def targetpathfn(pat, dest, srcs):
1103 def targetpathfn(pat, dest, srcs):
1104 if os.path.isdir(pat):
1104 if os.path.isdir(pat):
1105 abspfx = pathutil.canonpath(repo.root, cwd, pat)
1105 abspfx = pathutil.canonpath(repo.root, cwd, pat)
1106 abspfx = util.localpath(abspfx)
1106 abspfx = util.localpath(abspfx)
1107 if destdirexists:
1107 if destdirexists:
1108 striplen = len(os.path.split(abspfx)[0])
1108 striplen = len(os.path.split(abspfx)[0])
1109 else:
1109 else:
1110 striplen = len(abspfx)
1110 striplen = len(abspfx)
1111 if striplen:
1111 if striplen:
1112 striplen += len(pycompat.ossep)
1112 striplen += len(pycompat.ossep)
1113 res = lambda p: os.path.join(dest, util.localpath(p)[striplen:])
1113 res = lambda p: os.path.join(dest, util.localpath(p)[striplen:])
1114 elif destdirexists:
1114 elif destdirexists:
1115 res = lambda p: os.path.join(dest,
1115 res = lambda p: os.path.join(dest,
1116 os.path.basename(util.localpath(p)))
1116 os.path.basename(util.localpath(p)))
1117 else:
1117 else:
1118 res = lambda p: dest
1118 res = lambda p: dest
1119 return res
1119 return res
1120
1120
1121 # pat: ossep
1121 # pat: ossep
1122 # dest ossep
1122 # dest ossep
1123 # srcs: list of (hgsep, hgsep, ossep, bool)
1123 # srcs: list of (hgsep, hgsep, ossep, bool)
1124 # return: function that takes hgsep and returns ossep
1124 # return: function that takes hgsep and returns ossep
1125 def targetpathafterfn(pat, dest, srcs):
1125 def targetpathafterfn(pat, dest, srcs):
1126 if matchmod.patkind(pat):
1126 if matchmod.patkind(pat):
1127 # a mercurial pattern
1127 # a mercurial pattern
1128 res = lambda p: os.path.join(dest,
1128 res = lambda p: os.path.join(dest,
1129 os.path.basename(util.localpath(p)))
1129 os.path.basename(util.localpath(p)))
1130 else:
1130 else:
1131 abspfx = pathutil.canonpath(repo.root, cwd, pat)
1131 abspfx = pathutil.canonpath(repo.root, cwd, pat)
1132 if len(abspfx) < len(srcs[0][0]):
1132 if len(abspfx) < len(srcs[0][0]):
1133 # A directory. Either the target path contains the last
1133 # A directory. Either the target path contains the last
1134 # component of the source path or it does not.
1134 # component of the source path or it does not.
1135 def evalpath(striplen):
1135 def evalpath(striplen):
1136 score = 0
1136 score = 0
1137 for s in srcs:
1137 for s in srcs:
1138 t = os.path.join(dest, util.localpath(s[0])[striplen:])
1138 t = os.path.join(dest, util.localpath(s[0])[striplen:])
1139 if os.path.lexists(t):
1139 if os.path.lexists(t):
1140 score += 1
1140 score += 1
1141 return score
1141 return score
1142
1142
1143 abspfx = util.localpath(abspfx)
1143 abspfx = util.localpath(abspfx)
1144 striplen = len(abspfx)
1144 striplen = len(abspfx)
1145 if striplen:
1145 if striplen:
1146 striplen += len(pycompat.ossep)
1146 striplen += len(pycompat.ossep)
1147 if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])):
1147 if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])):
1148 score = evalpath(striplen)
1148 score = evalpath(striplen)
1149 striplen1 = len(os.path.split(abspfx)[0])
1149 striplen1 = len(os.path.split(abspfx)[0])
1150 if striplen1:
1150 if striplen1:
1151 striplen1 += len(pycompat.ossep)
1151 striplen1 += len(pycompat.ossep)
1152 if evalpath(striplen1) > score:
1152 if evalpath(striplen1) > score:
1153 striplen = striplen1
1153 striplen = striplen1
1154 res = lambda p: os.path.join(dest,
1154 res = lambda p: os.path.join(dest,
1155 util.localpath(p)[striplen:])
1155 util.localpath(p)[striplen:])
1156 else:
1156 else:
1157 # a file
1157 # a file
1158 if destdirexists:
1158 if destdirexists:
1159 res = lambda p: os.path.join(dest,
1159 res = lambda p: os.path.join(dest,
1160 os.path.basename(util.localpath(p)))
1160 os.path.basename(util.localpath(p)))
1161 else:
1161 else:
1162 res = lambda p: dest
1162 res = lambda p: dest
1163 return res
1163 return res
1164
1164
1165 pats = scmutil.expandpats(pats)
1165 pats = scmutil.expandpats(pats)
1166 if not pats:
1166 if not pats:
1167 raise error.Abort(_('no source or destination specified'))
1167 raise error.Abort(_('no source or destination specified'))
1168 if len(pats) == 1:
1168 if len(pats) == 1:
1169 raise error.Abort(_('no destination specified'))
1169 raise error.Abort(_('no destination specified'))
1170 dest = pats.pop()
1170 dest = pats.pop()
1171 destdirexists = os.path.isdir(dest) and not os.path.islink(dest)
1171 destdirexists = os.path.isdir(dest) and not os.path.islink(dest)
1172 if not destdirexists:
1172 if not destdirexists:
1173 if len(pats) > 1 or matchmod.patkind(pats[0]):
1173 if len(pats) > 1 or matchmod.patkind(pats[0]):
1174 raise error.Abort(_('with multiple sources, destination must be an '
1174 raise error.Abort(_('with multiple sources, destination must be an '
1175 'existing directory'))
1175 'existing directory'))
1176 if util.endswithsep(dest):
1176 if util.endswithsep(dest):
1177 raise error.Abort(_('destination %s is not a directory') % dest)
1177 raise error.Abort(_('destination %s is not a directory') % dest)
1178
1178
1179 tfn = targetpathfn
1179 tfn = targetpathfn
1180 if after:
1180 if after:
1181 tfn = targetpathafterfn
1181 tfn = targetpathafterfn
1182 copylist = []
1182 copylist = []
1183 for pat in pats:
1183 for pat in pats:
1184 srcs = walkpat(pat)
1184 srcs = walkpat(pat)
1185 if not srcs:
1185 if not srcs:
1186 continue
1186 continue
1187 copylist.append((tfn(pat, dest, srcs), srcs))
1187 copylist.append((tfn(pat, dest, srcs), srcs))
1188 if not copylist:
1188 if not copylist:
1189 raise error.Abort(_('no files to copy'))
1189 raise error.Abort(_('no files to copy'))
1190
1190
1191 errors = 0
1191 errors = 0
1192 for targetpath, srcs in copylist:
1192 for targetpath, srcs in copylist:
1193 for abssrc, relsrc, exact in srcs:
1193 for abssrc, relsrc, exact in srcs:
1194 if copyfile(abssrc, relsrc, targetpath(abssrc), exact):
1194 if copyfile(abssrc, relsrc, targetpath(abssrc), exact):
1195 errors += 1
1195 errors += 1
1196
1196
1197 if errors:
1197 if errors:
1198 ui.warn(_('(consider using --after)\n'))
1198 ui.warn(_('(consider using --after)\n'))
1199
1199
1200 return errors != 0
1200 return errors != 0
1201
1201
1202 ## facility to let extension process additional data into an import patch
1202 ## facility to let extension process additional data into an import patch
1203 # list of identifier to be executed in order
1203 # list of identifier to be executed in order
1204 extrapreimport = [] # run before commit
1204 extrapreimport = [] # run before commit
1205 extrapostimport = [] # run after commit
1205 extrapostimport = [] # run after commit
1206 # mapping from identifier to actual import function
1206 # mapping from identifier to actual import function
1207 #
1207 #
1208 # 'preimport' are run before the commit is made and are provided the following
1208 # 'preimport' are run before the commit is made and are provided the following
1209 # arguments:
1209 # arguments:
1210 # - repo: the localrepository instance,
1210 # - repo: the localrepository instance,
1211 # - patchdata: data extracted from patch header (cf m.patch.patchheadermap),
1211 # - patchdata: data extracted from patch header (cf m.patch.patchheadermap),
1212 # - extra: the future extra dictionary of the changeset, please mutate it,
1212 # - extra: the future extra dictionary of the changeset, please mutate it,
1213 # - opts: the import options.
1213 # - opts: the import options.
1214 # XXX ideally, we would just pass an ctx ready to be computed, that would allow
1214 # XXX ideally, we would just pass an ctx ready to be computed, that would allow
1215 # mutation of in memory commit and more. Feel free to rework the code to get
1215 # mutation of in memory commit and more. Feel free to rework the code to get
1216 # there.
1216 # there.
1217 extrapreimportmap = {}
1217 extrapreimportmap = {}
1218 # 'postimport' are run after the commit is made and are provided the following
1218 # 'postimport' are run after the commit is made and are provided the following
1219 # argument:
1219 # argument:
1220 # - ctx: the changectx created by import.
1220 # - ctx: the changectx created by import.
1221 extrapostimportmap = {}
1221 extrapostimportmap = {}
1222
1222
1223 def tryimportone(ui, repo, hunk, parents, opts, msgs, updatefunc):
1223 def tryimportone(ui, repo, hunk, parents, opts, msgs, updatefunc):
1224 """Utility function used by commands.import to import a single patch
1224 """Utility function used by commands.import to import a single patch
1225
1225
1226 This function is explicitly defined here to help the evolve extension to
1226 This function is explicitly defined here to help the evolve extension to
1227 wrap this part of the import logic.
1227 wrap this part of the import logic.
1228
1228
1229 The API is currently a bit ugly because it a simple code translation from
1229 The API is currently a bit ugly because it a simple code translation from
1230 the import command. Feel free to make it better.
1230 the import command. Feel free to make it better.
1231
1231
1232 :hunk: a patch (as a binary string)
1232 :hunk: a patch (as a binary string)
1233 :parents: nodes that will be parent of the created commit
1233 :parents: nodes that will be parent of the created commit
1234 :opts: the full dict of option passed to the import command
1234 :opts: the full dict of option passed to the import command
1235 :msgs: list to save commit message to.
1235 :msgs: list to save commit message to.
1236 (used in case we need to save it when failing)
1236 (used in case we need to save it when failing)
1237 :updatefunc: a function that update a repo to a given node
1237 :updatefunc: a function that update a repo to a given node
1238 updatefunc(<repo>, <node>)
1238 updatefunc(<repo>, <node>)
1239 """
1239 """
1240 # avoid cycle context -> subrepo -> cmdutil
1240 # avoid cycle context -> subrepo -> cmdutil
1241 from . import context
1241 from . import context
1242 extractdata = patch.extract(ui, hunk)
1242 extractdata = patch.extract(ui, hunk)
1243 tmpname = extractdata.get('filename')
1243 tmpname = extractdata.get('filename')
1244 message = extractdata.get('message')
1244 message = extractdata.get('message')
1245 user = opts.get('user') or extractdata.get('user')
1245 user = opts.get('user') or extractdata.get('user')
1246 date = opts.get('date') or extractdata.get('date')
1246 date = opts.get('date') or extractdata.get('date')
1247 branch = extractdata.get('branch')
1247 branch = extractdata.get('branch')
1248 nodeid = extractdata.get('nodeid')
1248 nodeid = extractdata.get('nodeid')
1249 p1 = extractdata.get('p1')
1249 p1 = extractdata.get('p1')
1250 p2 = extractdata.get('p2')
1250 p2 = extractdata.get('p2')
1251
1251
1252 nocommit = opts.get('no_commit')
1252 nocommit = opts.get('no_commit')
1253 importbranch = opts.get('import_branch')
1253 importbranch = opts.get('import_branch')
1254 update = not opts.get('bypass')
1254 update = not opts.get('bypass')
1255 strip = opts["strip"]
1255 strip = opts["strip"]
1256 prefix = opts["prefix"]
1256 prefix = opts["prefix"]
1257 sim = float(opts.get('similarity') or 0)
1257 sim = float(opts.get('similarity') or 0)
1258 if not tmpname:
1258 if not tmpname:
1259 return (None, None, False)
1259 return (None, None, False)
1260
1260
1261 rejects = False
1261 rejects = False
1262
1262
1263 try:
1263 try:
1264 cmdline_message = logmessage(ui, opts)
1264 cmdline_message = logmessage(ui, opts)
1265 if cmdline_message:
1265 if cmdline_message:
1266 # pickup the cmdline msg
1266 # pickup the cmdline msg
1267 message = cmdline_message
1267 message = cmdline_message
1268 elif message:
1268 elif message:
1269 # pickup the patch msg
1269 # pickup the patch msg
1270 message = message.strip()
1270 message = message.strip()
1271 else:
1271 else:
1272 # launch the editor
1272 # launch the editor
1273 message = None
1273 message = None
1274 ui.debug('message:\n%s\n' % message)
1274 ui.debug('message:\n%s\n' % message)
1275
1275
1276 if len(parents) == 1:
1276 if len(parents) == 1:
1277 parents.append(repo[nullid])
1277 parents.append(repo[nullid])
1278 if opts.get('exact'):
1278 if opts.get('exact'):
1279 if not nodeid or not p1:
1279 if not nodeid or not p1:
1280 raise error.Abort(_('not a Mercurial patch'))
1280 raise error.Abort(_('not a Mercurial patch'))
1281 p1 = repo[p1]
1281 p1 = repo[p1]
1282 p2 = repo[p2 or nullid]
1282 p2 = repo[p2 or nullid]
1283 elif p2:
1283 elif p2:
1284 try:
1284 try:
1285 p1 = repo[p1]
1285 p1 = repo[p1]
1286 p2 = repo[p2]
1286 p2 = repo[p2]
1287 # Without any options, consider p2 only if the
1287 # Without any options, consider p2 only if the
1288 # patch is being applied on top of the recorded
1288 # patch is being applied on top of the recorded
1289 # first parent.
1289 # first parent.
1290 if p1 != parents[0]:
1290 if p1 != parents[0]:
1291 p1 = parents[0]
1291 p1 = parents[0]
1292 p2 = repo[nullid]
1292 p2 = repo[nullid]
1293 except error.RepoError:
1293 except error.RepoError:
1294 p1, p2 = parents
1294 p1, p2 = parents
1295 if p2.node() == nullid:
1295 if p2.node() == nullid:
1296 ui.warn(_("warning: import the patch as a normal revision\n"
1296 ui.warn(_("warning: import the patch as a normal revision\n"
1297 "(use --exact to import the patch as a merge)\n"))
1297 "(use --exact to import the patch as a merge)\n"))
1298 else:
1298 else:
1299 p1, p2 = parents
1299 p1, p2 = parents
1300
1300
1301 n = None
1301 n = None
1302 if update:
1302 if update:
1303 if p1 != parents[0]:
1303 if p1 != parents[0]:
1304 updatefunc(repo, p1.node())
1304 updatefunc(repo, p1.node())
1305 if p2 != parents[1]:
1305 if p2 != parents[1]:
1306 repo.setparents(p1.node(), p2.node())
1306 repo.setparents(p1.node(), p2.node())
1307
1307
1308 if opts.get('exact') or importbranch:
1308 if opts.get('exact') or importbranch:
1309 repo.dirstate.setbranch(branch or 'default')
1309 repo.dirstate.setbranch(branch or 'default')
1310
1310
1311 partial = opts.get('partial', False)
1311 partial = opts.get('partial', False)
1312 files = set()
1312 files = set()
1313 try:
1313 try:
1314 patch.patch(ui, repo, tmpname, strip=strip, prefix=prefix,
1314 patch.patch(ui, repo, tmpname, strip=strip, prefix=prefix,
1315 files=files, eolmode=None, similarity=sim / 100.0)
1315 files=files, eolmode=None, similarity=sim / 100.0)
1316 except error.PatchError as e:
1316 except error.PatchError as e:
1317 if not partial:
1317 if not partial:
1318 raise error.Abort(str(e))
1318 raise error.Abort(str(e))
1319 if partial:
1319 if partial:
1320 rejects = True
1320 rejects = True
1321
1321
1322 files = list(files)
1322 files = list(files)
1323 if nocommit:
1323 if nocommit:
1324 if message:
1324 if message:
1325 msgs.append(message)
1325 msgs.append(message)
1326 else:
1326 else:
1327 if opts.get('exact') or p2:
1327 if opts.get('exact') or p2:
1328 # If you got here, you either use --force and know what
1328 # If you got here, you either use --force and know what
1329 # you are doing or used --exact or a merge patch while
1329 # you are doing or used --exact or a merge patch while
1330 # being updated to its first parent.
1330 # being updated to its first parent.
1331 m = None
1331 m = None
1332 else:
1332 else:
1333 m = scmutil.matchfiles(repo, files or [])
1333 m = scmutil.matchfiles(repo, files or [])
1334 editform = mergeeditform(repo[None], 'import.normal')
1334 editform = mergeeditform(repo[None], 'import.normal')
1335 if opts.get('exact'):
1335 if opts.get('exact'):
1336 editor = None
1336 editor = None
1337 else:
1337 else:
1338 editor = getcommiteditor(editform=editform,
1338 editor = getcommiteditor(editform=editform,
1339 **pycompat.strkwargs(opts))
1339 **pycompat.strkwargs(opts))
1340 extra = {}
1340 extra = {}
1341 for idfunc in extrapreimport:
1341 for idfunc in extrapreimport:
1342 extrapreimportmap[idfunc](repo, extractdata, extra, opts)
1342 extrapreimportmap[idfunc](repo, extractdata, extra, opts)
1343 overrides = {}
1343 overrides = {}
1344 if partial:
1344 if partial:
1345 overrides[('ui', 'allowemptycommit')] = True
1345 overrides[('ui', 'allowemptycommit')] = True
1346 with repo.ui.configoverride(overrides, 'import'):
1346 with repo.ui.configoverride(overrides, 'import'):
1347 n = repo.commit(message, user,
1347 n = repo.commit(message, user,
1348 date, match=m,
1348 date, match=m,
1349 editor=editor, extra=extra)
1349 editor=editor, extra=extra)
1350 for idfunc in extrapostimport:
1350 for idfunc in extrapostimport:
1351 extrapostimportmap[idfunc](repo[n])
1351 extrapostimportmap[idfunc](repo[n])
1352 else:
1352 else:
1353 if opts.get('exact') or importbranch:
1353 if opts.get('exact') or importbranch:
1354 branch = branch or 'default'
1354 branch = branch or 'default'
1355 else:
1355 else:
1356 branch = p1.branch()
1356 branch = p1.branch()
1357 store = patch.filestore()
1357 store = patch.filestore()
1358 try:
1358 try:
1359 files = set()
1359 files = set()
1360 try:
1360 try:
1361 patch.patchrepo(ui, repo, p1, store, tmpname, strip, prefix,
1361 patch.patchrepo(ui, repo, p1, store, tmpname, strip, prefix,
1362 files, eolmode=None)
1362 files, eolmode=None)
1363 except error.PatchError as e:
1363 except error.PatchError as e:
1364 raise error.Abort(str(e))
1364 raise error.Abort(str(e))
1365 if opts.get('exact'):
1365 if opts.get('exact'):
1366 editor = None
1366 editor = None
1367 else:
1367 else:
1368 editor = getcommiteditor(editform='import.bypass')
1368 editor = getcommiteditor(editform='import.bypass')
1369 memctx = context.memctx(repo, (p1.node(), p2.node()),
1369 memctx = context.memctx(repo, (p1.node(), p2.node()),
1370 message,
1370 message,
1371 files=files,
1371 files=files,
1372 filectxfn=store,
1372 filectxfn=store,
1373 user=user,
1373 user=user,
1374 date=date,
1374 date=date,
1375 branch=branch,
1375 branch=branch,
1376 editor=editor)
1376 editor=editor)
1377 n = memctx.commit()
1377 n = memctx.commit()
1378 finally:
1378 finally:
1379 store.close()
1379 store.close()
1380 if opts.get('exact') and nocommit:
1380 if opts.get('exact') and nocommit:
1381 # --exact with --no-commit is still useful in that it does merge
1381 # --exact with --no-commit is still useful in that it does merge
1382 # and branch bits
1382 # and branch bits
1383 ui.warn(_("warning: can't check exact import with --no-commit\n"))
1383 ui.warn(_("warning: can't check exact import with --no-commit\n"))
1384 elif opts.get('exact') and hex(n) != nodeid:
1384 elif opts.get('exact') and hex(n) != nodeid:
1385 raise error.Abort(_('patch is damaged or loses information'))
1385 raise error.Abort(_('patch is damaged or loses information'))
1386 msg = _('applied to working directory')
1386 msg = _('applied to working directory')
1387 if n:
1387 if n:
1388 # i18n: refers to a short changeset id
1388 # i18n: refers to a short changeset id
1389 msg = _('created %s') % short(n)
1389 msg = _('created %s') % short(n)
1390 return (msg, n, rejects)
1390 return (msg, n, rejects)
1391 finally:
1391 finally:
1392 os.unlink(tmpname)
1392 os.unlink(tmpname)
1393
1393
1394 # facility to let extensions include additional data in an exported patch
1394 # facility to let extensions include additional data in an exported patch
1395 # list of identifiers to be executed in order
1395 # list of identifiers to be executed in order
1396 extraexport = []
1396 extraexport = []
1397 # mapping from identifier to actual export function
1397 # mapping from identifier to actual export function
1398 # function as to return a string to be added to the header or None
1398 # function as to return a string to be added to the header or None
1399 # it is given two arguments (sequencenumber, changectx)
1399 # it is given two arguments (sequencenumber, changectx)
1400 extraexportmap = {}
1400 extraexportmap = {}
1401
1401
1402 def _exportsingle(repo, ctx, match, switch_parent, rev, seqno, write, diffopts):
1402 def _exportsingle(repo, ctx, match, switch_parent, rev, seqno, write, diffopts):
1403 node = scmutil.binnode(ctx)
1403 node = scmutil.binnode(ctx)
1404 parents = [p.node() for p in ctx.parents() if p]
1404 parents = [p.node() for p in ctx.parents() if p]
1405 branch = ctx.branch()
1405 branch = ctx.branch()
1406 if switch_parent:
1406 if switch_parent:
1407 parents.reverse()
1407 parents.reverse()
1408
1408
1409 if parents:
1409 if parents:
1410 prev = parents[0]
1410 prev = parents[0]
1411 else:
1411 else:
1412 prev = nullid
1412 prev = nullid
1413
1413
1414 write("# HG changeset patch\n")
1414 write("# HG changeset patch\n")
1415 write("# User %s\n" % ctx.user())
1415 write("# User %s\n" % ctx.user())
1416 write("# Date %d %d\n" % ctx.date())
1416 write("# Date %d %d\n" % ctx.date())
1417 write("# %s\n" % util.datestr(ctx.date()))
1417 write("# %s\n" % util.datestr(ctx.date()))
1418 if branch and branch != 'default':
1418 if branch and branch != 'default':
1419 write("# Branch %s\n" % branch)
1419 write("# Branch %s\n" % branch)
1420 write("# Node ID %s\n" % hex(node))
1420 write("# Node ID %s\n" % hex(node))
1421 write("# Parent %s\n" % hex(prev))
1421 write("# Parent %s\n" % hex(prev))
1422 if len(parents) > 1:
1422 if len(parents) > 1:
1423 write("# Parent %s\n" % hex(parents[1]))
1423 write("# Parent %s\n" % hex(parents[1]))
1424
1424
1425 for headerid in extraexport:
1425 for headerid in extraexport:
1426 header = extraexportmap[headerid](seqno, ctx)
1426 header = extraexportmap[headerid](seqno, ctx)
1427 if header is not None:
1427 if header is not None:
1428 write('# %s\n' % header)
1428 write('# %s\n' % header)
1429 write(ctx.description().rstrip())
1429 write(ctx.description().rstrip())
1430 write("\n\n")
1430 write("\n\n")
1431
1431
1432 for chunk, label in patch.diffui(repo, prev, node, match, opts=diffopts):
1432 for chunk, label in patch.diffui(repo, prev, node, match, opts=diffopts):
1433 write(chunk, label=label)
1433 write(chunk, label=label)
1434
1434
1435 def export(repo, revs, fntemplate='hg-%h.patch', fp=None, switch_parent=False,
1435 def export(repo, revs, fntemplate='hg-%h.patch', fp=None, switch_parent=False,
1436 opts=None, match=None):
1436 opts=None, match=None):
1437 '''export changesets as hg patches
1437 '''export changesets as hg patches
1438
1438
1439 Args:
1439 Args:
1440 repo: The repository from which we're exporting revisions.
1440 repo: The repository from which we're exporting revisions.
1441 revs: A list of revisions to export as revision numbers.
1441 revs: A list of revisions to export as revision numbers.
1442 fntemplate: An optional string to use for generating patch file names.
1442 fntemplate: An optional string to use for generating patch file names.
1443 fp: An optional file-like object to which patches should be written.
1443 fp: An optional file-like object to which patches should be written.
1444 switch_parent: If True, show diffs against second parent when not nullid.
1444 switch_parent: If True, show diffs against second parent when not nullid.
1445 Default is false, which always shows diff against p1.
1445 Default is false, which always shows diff against p1.
1446 opts: diff options to use for generating the patch.
1446 opts: diff options to use for generating the patch.
1447 match: If specified, only export changes to files matching this matcher.
1447 match: If specified, only export changes to files matching this matcher.
1448
1448
1449 Returns:
1449 Returns:
1450 Nothing.
1450 Nothing.
1451
1451
1452 Side Effect:
1452 Side Effect:
1453 "HG Changeset Patch" data is emitted to one of the following
1453 "HG Changeset Patch" data is emitted to one of the following
1454 destinations:
1454 destinations:
1455 fp is specified: All revs are written to the specified
1455 fp is specified: All revs are written to the specified
1456 file-like object.
1456 file-like object.
1457 fntemplate specified: Each rev is written to a unique file named using
1457 fntemplate specified: Each rev is written to a unique file named using
1458 the given template.
1458 the given template.
1459 Neither fp nor template specified: All revs written to repo.ui.write()
1459 Neither fp nor template specified: All revs written to repo.ui.write()
1460 '''
1460 '''
1461
1461
1462 total = len(revs)
1462 total = len(revs)
1463 revwidth = max(len(str(rev)) for rev in revs)
1463 revwidth = max(len(str(rev)) for rev in revs)
1464 filemode = {}
1464 filemode = {}
1465
1465
1466 write = None
1466 write = None
1467 dest = '<unnamed>'
1467 dest = '<unnamed>'
1468 if fp:
1468 if fp:
1469 dest = getattr(fp, 'name', dest)
1469 dest = getattr(fp, 'name', dest)
1470 def write(s, **kw):
1470 def write(s, **kw):
1471 fp.write(s)
1471 fp.write(s)
1472 elif not fntemplate:
1472 elif not fntemplate:
1473 write = repo.ui.write
1473 write = repo.ui.write
1474
1474
1475 for seqno, rev in enumerate(revs, 1):
1475 for seqno, rev in enumerate(revs, 1):
1476 ctx = repo[rev]
1476 ctx = repo[rev]
1477 fo = None
1477 fo = None
1478 if not fp and fntemplate:
1478 if not fp and fntemplate:
1479 desc_lines = ctx.description().rstrip().split('\n')
1479 desc_lines = ctx.description().rstrip().split('\n')
1480 desc = desc_lines[0] #Commit always has a first line.
1480 desc = desc_lines[0] #Commit always has a first line.
1481 fo = makefileobj(repo, fntemplate, ctx.node(), desc=desc,
1481 fo = makefileobj(repo, fntemplate, ctx.node(), desc=desc,
1482 total=total, seqno=seqno, revwidth=revwidth,
1482 total=total, seqno=seqno, revwidth=revwidth,
1483 mode='wb', modemap=filemode)
1483 mode='wb', modemap=filemode)
1484 dest = fo.name
1484 dest = fo.name
1485 def write(s, **kw):
1485 def write(s, **kw):
1486 fo.write(s)
1486 fo.write(s)
1487 if not dest.startswith('<'):
1487 if not dest.startswith('<'):
1488 repo.ui.note("%s\n" % dest)
1488 repo.ui.note("%s\n" % dest)
1489 _exportsingle(
1489 _exportsingle(
1490 repo, ctx, match, switch_parent, rev, seqno, write, opts)
1490 repo, ctx, match, switch_parent, rev, seqno, write, opts)
1491 if fo is not None:
1491 if fo is not None:
1492 fo.close()
1492 fo.close()
1493
1493
1494 def diffordiffstat(ui, repo, diffopts, node1, node2, match,
1494 def diffordiffstat(ui, repo, diffopts, node1, node2, match,
1495 changes=None, stat=False, fp=None, prefix='',
1495 changes=None, stat=False, fp=None, prefix='',
1496 root='', listsubrepos=False, hunksfilterfn=None):
1496 root='', listsubrepos=False, hunksfilterfn=None):
1497 '''show diff or diffstat.'''
1497 '''show diff or diffstat.'''
1498 if fp is None:
1498 if fp is None:
1499 write = ui.write
1499 write = ui.write
1500 else:
1500 else:
1501 def write(s, **kw):
1501 def write(s, **kw):
1502 fp.write(s)
1502 fp.write(s)
1503
1503
1504 if root:
1504 if root:
1505 relroot = pathutil.canonpath(repo.root, repo.getcwd(), root)
1505 relroot = pathutil.canonpath(repo.root, repo.getcwd(), root)
1506 else:
1506 else:
1507 relroot = ''
1507 relroot = ''
1508 if relroot != '':
1508 if relroot != '':
1509 # XXX relative roots currently don't work if the root is within a
1509 # XXX relative roots currently don't work if the root is within a
1510 # subrepo
1510 # subrepo
1511 uirelroot = match.uipath(relroot)
1511 uirelroot = match.uipath(relroot)
1512 relroot += '/'
1512 relroot += '/'
1513 for matchroot in match.files():
1513 for matchroot in match.files():
1514 if not matchroot.startswith(relroot):
1514 if not matchroot.startswith(relroot):
1515 ui.warn(_('warning: %s not inside relative root %s\n') % (
1515 ui.warn(_('warning: %s not inside relative root %s\n') % (
1516 match.uipath(matchroot), uirelroot))
1516 match.uipath(matchroot), uirelroot))
1517
1517
1518 if stat:
1518 if stat:
1519 diffopts = diffopts.copy(context=0, noprefix=False)
1519 diffopts = diffopts.copy(context=0, noprefix=False)
1520 width = 80
1520 width = 80
1521 if not ui.plain():
1521 if not ui.plain():
1522 width = ui.termwidth()
1522 width = ui.termwidth()
1523 chunks = patch.diff(repo, node1, node2, match, changes, opts=diffopts,
1523 chunks = patch.diff(repo, node1, node2, match, changes, opts=diffopts,
1524 prefix=prefix, relroot=relroot,
1524 prefix=prefix, relroot=relroot,
1525 hunksfilterfn=hunksfilterfn)
1525 hunksfilterfn=hunksfilterfn)
1526 for chunk, label in patch.diffstatui(util.iterlines(chunks),
1526 for chunk, label in patch.diffstatui(util.iterlines(chunks),
1527 width=width):
1527 width=width):
1528 write(chunk, label=label)
1528 write(chunk, label=label)
1529 else:
1529 else:
1530 for chunk, label in patch.diffui(repo, node1, node2, match,
1530 for chunk, label in patch.diffui(repo, node1, node2, match,
1531 changes, opts=diffopts, prefix=prefix,
1531 changes, opts=diffopts, prefix=prefix,
1532 relroot=relroot,
1532 relroot=relroot,
1533 hunksfilterfn=hunksfilterfn):
1533 hunksfilterfn=hunksfilterfn):
1534 write(chunk, label=label)
1534 write(chunk, label=label)
1535
1535
1536 if listsubrepos:
1536 if listsubrepos:
1537 ctx1 = repo[node1]
1537 ctx1 = repo[node1]
1538 ctx2 = repo[node2]
1538 ctx2 = repo[node2]
1539 for subpath, sub in scmutil.itersubrepos(ctx1, ctx2):
1539 for subpath, sub in scmutil.itersubrepos(ctx1, ctx2):
1540 tempnode2 = node2
1540 tempnode2 = node2
1541 try:
1541 try:
1542 if node2 is not None:
1542 if node2 is not None:
1543 tempnode2 = ctx2.substate[subpath][1]
1543 tempnode2 = ctx2.substate[subpath][1]
1544 except KeyError:
1544 except KeyError:
1545 # A subrepo that existed in node1 was deleted between node1 and
1545 # A subrepo that existed in node1 was deleted between node1 and
1546 # node2 (inclusive). Thus, ctx2's substate won't contain that
1546 # node2 (inclusive). Thus, ctx2's substate won't contain that
1547 # subpath. The best we can do is to ignore it.
1547 # subpath. The best we can do is to ignore it.
1548 tempnode2 = None
1548 tempnode2 = None
1549 submatch = matchmod.subdirmatcher(subpath, match)
1549 submatch = matchmod.subdirmatcher(subpath, match)
1550 sub.diff(ui, diffopts, tempnode2, submatch, changes=changes,
1550 sub.diff(ui, diffopts, tempnode2, submatch, changes=changes,
1551 stat=stat, fp=fp, prefix=prefix)
1551 stat=stat, fp=fp, prefix=prefix)
1552
1552
1553 def _changesetlabels(ctx):
1553 def _changesetlabels(ctx):
1554 labels = ['log.changeset', 'changeset.%s' % ctx.phasestr()]
1554 labels = ['log.changeset', 'changeset.%s' % ctx.phasestr()]
1555 if ctx.obsolete():
1555 if ctx.obsolete():
1556 labels.append('changeset.obsolete')
1556 labels.append('changeset.obsolete')
1557 if ctx.isunstable():
1557 if ctx.isunstable():
1558 labels.append('changeset.unstable')
1558 labels.append('changeset.unstable')
1559 for instability in ctx.instabilities():
1559 for instability in ctx.instabilities():
1560 labels.append('instability.%s' % instability)
1560 labels.append('instability.%s' % instability)
1561 return ' '.join(labels)
1561 return ' '.join(labels)
1562
1562
1563 class changeset_printer(object):
1563 class changeset_printer(object):
1564 '''show changeset information when templating not requested.'''
1564 '''show changeset information when templating not requested.'''
1565
1565
1566 def __init__(self, ui, repo, matchfn, diffopts, buffered):
1566 def __init__(self, ui, repo, matchfn, diffopts, buffered):
1567 self.ui = ui
1567 self.ui = ui
1568 self.repo = repo
1568 self.repo = repo
1569 self.buffered = buffered
1569 self.buffered = buffered
1570 self.matchfn = matchfn
1570 self.matchfn = matchfn
1571 self.diffopts = diffopts
1571 self.diffopts = diffopts
1572 self.header = {}
1572 self.header = {}
1573 self.hunk = {}
1573 self.hunk = {}
1574 self.lastheader = None
1574 self.lastheader = None
1575 self.footer = None
1575 self.footer = None
1576 self._columns = templatekw.getlogcolumns()
1576 self._columns = templatekw.getlogcolumns()
1577
1577
1578 def flush(self, ctx):
1578 def flush(self, ctx):
1579 rev = ctx.rev()
1579 rev = ctx.rev()
1580 if rev in self.header:
1580 if rev in self.header:
1581 h = self.header[rev]
1581 h = self.header[rev]
1582 if h != self.lastheader:
1582 if h != self.lastheader:
1583 self.lastheader = h
1583 self.lastheader = h
1584 self.ui.write(h)
1584 self.ui.write(h)
1585 del self.header[rev]
1585 del self.header[rev]
1586 if rev in self.hunk:
1586 if rev in self.hunk:
1587 self.ui.write(self.hunk[rev])
1587 self.ui.write(self.hunk[rev])
1588 del self.hunk[rev]
1588 del self.hunk[rev]
1589
1589
1590 def close(self):
1590 def close(self):
1591 if self.footer:
1591 if self.footer:
1592 self.ui.write(self.footer)
1592 self.ui.write(self.footer)
1593
1593
1594 def show(self, ctx, copies=None, matchfn=None, hunksfilterfn=None,
1594 def show(self, ctx, copies=None, matchfn=None, hunksfilterfn=None,
1595 **props):
1595 **props):
1596 props = pycompat.byteskwargs(props)
1596 props = pycompat.byteskwargs(props)
1597 if self.buffered:
1597 if self.buffered:
1598 self.ui.pushbuffer(labeled=True)
1598 self.ui.pushbuffer(labeled=True)
1599 self._show(ctx, copies, matchfn, hunksfilterfn, props)
1599 self._show(ctx, copies, matchfn, hunksfilterfn, props)
1600 self.hunk[ctx.rev()] = self.ui.popbuffer()
1600 self.hunk[ctx.rev()] = self.ui.popbuffer()
1601 else:
1601 else:
1602 self._show(ctx, copies, matchfn, hunksfilterfn, props)
1602 self._show(ctx, copies, matchfn, hunksfilterfn, props)
1603
1603
1604 def _show(self, ctx, copies, matchfn, hunksfilterfn, props):
1604 def _show(self, ctx, copies, matchfn, hunksfilterfn, props):
1605 '''show a single changeset or file revision'''
1605 '''show a single changeset or file revision'''
1606 changenode = ctx.node()
1606 changenode = ctx.node()
1607 rev = ctx.rev()
1607 rev = ctx.rev()
1608
1608
1609 if self.ui.quiet:
1609 if self.ui.quiet:
1610 self.ui.write("%s\n" % scmutil.formatchangeid(ctx),
1610 self.ui.write("%s\n" % scmutil.formatchangeid(ctx),
1611 label='log.node')
1611 label='log.node')
1612 return
1612 return
1613
1613
1614 columns = self._columns
1614 columns = self._columns
1615 self.ui.write(columns['changeset'] % scmutil.formatchangeid(ctx),
1615 self.ui.write(columns['changeset'] % scmutil.formatchangeid(ctx),
1616 label=_changesetlabels(ctx))
1616 label=_changesetlabels(ctx))
1617
1617
1618 # branches are shown first before any other names due to backwards
1618 # branches are shown first before any other names due to backwards
1619 # compatibility
1619 # compatibility
1620 branch = ctx.branch()
1620 branch = ctx.branch()
1621 # don't show the default branch name
1621 # don't show the default branch name
1622 if branch != 'default':
1622 if branch != 'default':
1623 self.ui.write(columns['branch'] % branch, label='log.branch')
1623 self.ui.write(columns['branch'] % branch, label='log.branch')
1624
1624
1625 for nsname, ns in self.repo.names.iteritems():
1625 for nsname, ns in self.repo.names.iteritems():
1626 # branches has special logic already handled above, so here we just
1626 # branches has special logic already handled above, so here we just
1627 # skip it
1627 # skip it
1628 if nsname == 'branches':
1628 if nsname == 'branches':
1629 continue
1629 continue
1630 # we will use the templatename as the color name since those two
1630 # we will use the templatename as the color name since those two
1631 # should be the same
1631 # should be the same
1632 for name in ns.names(self.repo, changenode):
1632 for name in ns.names(self.repo, changenode):
1633 self.ui.write(ns.logfmt % name,
1633 self.ui.write(ns.logfmt % name,
1634 label='log.%s' % ns.colorname)
1634 label='log.%s' % ns.colorname)
1635 if self.ui.debugflag:
1635 if self.ui.debugflag:
1636 self.ui.write(columns['phase'] % ctx.phasestr(), label='log.phase')
1636 self.ui.write(columns['phase'] % ctx.phasestr(), label='log.phase')
1637 for pctx in scmutil.meaningfulparents(self.repo, ctx):
1637 for pctx in scmutil.meaningfulparents(self.repo, ctx):
1638 label = 'log.parent changeset.%s' % pctx.phasestr()
1638 label = 'log.parent changeset.%s' % pctx.phasestr()
1639 self.ui.write(columns['parent'] % scmutil.formatchangeid(pctx),
1639 self.ui.write(columns['parent'] % scmutil.formatchangeid(pctx),
1640 label=label)
1640 label=label)
1641
1641
1642 if self.ui.debugflag and rev is not None:
1642 if self.ui.debugflag and rev is not None:
1643 mnode = ctx.manifestnode()
1643 mnode = ctx.manifestnode()
1644 mrev = self.repo.manifestlog._revlog.rev(mnode)
1644 mrev = self.repo.manifestlog._revlog.rev(mnode)
1645 self.ui.write(columns['manifest']
1645 self.ui.write(columns['manifest']
1646 % scmutil.formatrevnode(self.ui, mrev, mnode),
1646 % scmutil.formatrevnode(self.ui, mrev, mnode),
1647 label='ui.debug log.manifest')
1647 label='ui.debug log.manifest')
1648 self.ui.write(columns['user'] % ctx.user(), label='log.user')
1648 self.ui.write(columns['user'] % ctx.user(), label='log.user')
1649 self.ui.write(columns['date'] % util.datestr(ctx.date()),
1649 self.ui.write(columns['date'] % util.datestr(ctx.date()),
1650 label='log.date')
1650 label='log.date')
1651
1651
1652 if ctx.isunstable():
1652 if ctx.isunstable():
1653 instabilities = ctx.instabilities()
1653 instabilities = ctx.instabilities()
1654 self.ui.write(columns['instability'] % ', '.join(instabilities),
1654 self.ui.write(columns['instability'] % ', '.join(instabilities),
1655 label='log.instability')
1655 label='log.instability')
1656
1656
1657 elif ctx.obsolete():
1657 elif ctx.obsolete():
1658 self._showobsfate(ctx)
1658 self._showobsfate(ctx)
1659
1659
1660 self._exthook(ctx)
1660 self._exthook(ctx)
1661
1661
1662 if self.ui.debugflag:
1662 if self.ui.debugflag:
1663 files = ctx.p1().status(ctx)[:3]
1663 files = ctx.p1().status(ctx)[:3]
1664 for key, value in zip(['files', 'files+', 'files-'], files):
1664 for key, value in zip(['files', 'files+', 'files-'], files):
1665 if value:
1665 if value:
1666 self.ui.write(columns[key] % " ".join(value),
1666 self.ui.write(columns[key] % " ".join(value),
1667 label='ui.debug log.files')
1667 label='ui.debug log.files')
1668 elif ctx.files() and self.ui.verbose:
1668 elif ctx.files() and self.ui.verbose:
1669 self.ui.write(columns['files'] % " ".join(ctx.files()),
1669 self.ui.write(columns['files'] % " ".join(ctx.files()),
1670 label='ui.note log.files')
1670 label='ui.note log.files')
1671 if copies and self.ui.verbose:
1671 if copies and self.ui.verbose:
1672 copies = ['%s (%s)' % c for c in copies]
1672 copies = ['%s (%s)' % c for c in copies]
1673 self.ui.write(columns['copies'] % ' '.join(copies),
1673 self.ui.write(columns['copies'] % ' '.join(copies),
1674 label='ui.note log.copies')
1674 label='ui.note log.copies')
1675
1675
1676 extra = ctx.extra()
1676 extra = ctx.extra()
1677 if extra and self.ui.debugflag:
1677 if extra and self.ui.debugflag:
1678 for key, value in sorted(extra.items()):
1678 for key, value in sorted(extra.items()):
1679 self.ui.write(columns['extra'] % (key, util.escapestr(value)),
1679 self.ui.write(columns['extra'] % (key, util.escapestr(value)),
1680 label='ui.debug log.extra')
1680 label='ui.debug log.extra')
1681
1681
1682 description = ctx.description().strip()
1682 description = ctx.description().strip()
1683 if description:
1683 if description:
1684 if self.ui.verbose:
1684 if self.ui.verbose:
1685 self.ui.write(_("description:\n"),
1685 self.ui.write(_("description:\n"),
1686 label='ui.note log.description')
1686 label='ui.note log.description')
1687 self.ui.write(description,
1687 self.ui.write(description,
1688 label='ui.note log.description')
1688 label='ui.note log.description')
1689 self.ui.write("\n\n")
1689 self.ui.write("\n\n")
1690 else:
1690 else:
1691 self.ui.write(columns['summary'] % description.splitlines()[0],
1691 self.ui.write(columns['summary'] % description.splitlines()[0],
1692 label='log.summary')
1692 label='log.summary')
1693 self.ui.write("\n")
1693 self.ui.write("\n")
1694
1694
1695 self.showpatch(ctx, matchfn, hunksfilterfn=hunksfilterfn)
1695 self.showpatch(ctx, matchfn, hunksfilterfn=hunksfilterfn)
1696
1696
1697 def _showobsfate(self, ctx):
1697 def _showobsfate(self, ctx):
1698 obsfate = templatekw.showobsfate(repo=self.repo, ctx=ctx, ui=self.ui)
1698 obsfate = templatekw.showobsfate(repo=self.repo, ctx=ctx, ui=self.ui)
1699
1699
1700 if obsfate:
1700 if obsfate:
1701 for obsfateline in obsfate:
1701 for obsfateline in obsfate:
1702 self.ui.write(self._columns['obsolete'] % obsfateline,
1702 self.ui.write(self._columns['obsolete'] % obsfateline,
1703 label='log.obsfate')
1703 label='log.obsfate')
1704
1704
1705 def _exthook(self, ctx):
1705 def _exthook(self, ctx):
1706 '''empty method used by extension as a hook point
1706 '''empty method used by extension as a hook point
1707 '''
1707 '''
1708
1708
1709 def showpatch(self, ctx, matchfn, hunksfilterfn=None):
1709 def showpatch(self, ctx, matchfn, hunksfilterfn=None):
1710 if not matchfn:
1710 if not matchfn:
1711 matchfn = self.matchfn
1711 matchfn = self.matchfn
1712 if matchfn:
1712 if matchfn:
1713 stat = self.diffopts.get('stat')
1713 stat = self.diffopts.get('stat')
1714 diff = self.diffopts.get('patch')
1714 diff = self.diffopts.get('patch')
1715 diffopts = patch.diffallopts(self.ui, self.diffopts)
1715 diffopts = patch.diffallopts(self.ui, self.diffopts)
1716 node = ctx.node()
1716 node = ctx.node()
1717 prev = ctx.p1().node()
1717 prev = ctx.p1().node()
1718 if stat:
1718 if stat:
1719 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1719 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1720 match=matchfn, stat=True,
1720 match=matchfn, stat=True,
1721 hunksfilterfn=hunksfilterfn)
1721 hunksfilterfn=hunksfilterfn)
1722 if diff:
1722 if diff:
1723 if stat:
1723 if stat:
1724 self.ui.write("\n")
1724 self.ui.write("\n")
1725 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1725 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1726 match=matchfn, stat=False,
1726 match=matchfn, stat=False,
1727 hunksfilterfn=hunksfilterfn)
1727 hunksfilterfn=hunksfilterfn)
1728 self.ui.write("\n")
1728 self.ui.write("\n")
1729
1729
1730 class jsonchangeset(changeset_printer):
1730 class jsonchangeset(changeset_printer):
1731 '''format changeset information.'''
1731 '''format changeset information.'''
1732
1732
1733 def __init__(self, ui, repo, matchfn, diffopts, buffered):
1733 def __init__(self, ui, repo, matchfn, diffopts, buffered):
1734 changeset_printer.__init__(self, ui, repo, matchfn, diffopts, buffered)
1734 changeset_printer.__init__(self, ui, repo, matchfn, diffopts, buffered)
1735 self.cache = {}
1735 self.cache = {}
1736 self._first = True
1736 self._first = True
1737
1737
1738 def close(self):
1738 def close(self):
1739 if not self._first:
1739 if not self._first:
1740 self.ui.write("\n]\n")
1740 self.ui.write("\n]\n")
1741 else:
1741 else:
1742 self.ui.write("[]\n")
1742 self.ui.write("[]\n")
1743
1743
1744 def _show(self, ctx, copies, matchfn, hunksfilterfn, props):
1744 def _show(self, ctx, copies, matchfn, hunksfilterfn, props):
1745 '''show a single changeset or file revision'''
1745 '''show a single changeset or file revision'''
1746 rev = ctx.rev()
1746 rev = ctx.rev()
1747 if rev is None:
1747 if rev is None:
1748 jrev = jnode = 'null'
1748 jrev = jnode = 'null'
1749 else:
1749 else:
1750 jrev = '%d' % rev
1750 jrev = '%d' % rev
1751 jnode = '"%s"' % hex(ctx.node())
1751 jnode = '"%s"' % hex(ctx.node())
1752 j = encoding.jsonescape
1752 j = encoding.jsonescape
1753
1753
1754 if self._first:
1754 if self._first:
1755 self.ui.write("[\n {")
1755 self.ui.write("[\n {")
1756 self._first = False
1756 self._first = False
1757 else:
1757 else:
1758 self.ui.write(",\n {")
1758 self.ui.write(",\n {")
1759
1759
1760 if self.ui.quiet:
1760 if self.ui.quiet:
1761 self.ui.write(('\n "rev": %s') % jrev)
1761 self.ui.write(('\n "rev": %s') % jrev)
1762 self.ui.write((',\n "node": %s') % jnode)
1762 self.ui.write((',\n "node": %s') % jnode)
1763 self.ui.write('\n }')
1763 self.ui.write('\n }')
1764 return
1764 return
1765
1765
1766 self.ui.write(('\n "rev": %s') % jrev)
1766 self.ui.write(('\n "rev": %s') % jrev)
1767 self.ui.write((',\n "node": %s') % jnode)
1767 self.ui.write((',\n "node": %s') % jnode)
1768 self.ui.write((',\n "branch": "%s"') % j(ctx.branch()))
1768 self.ui.write((',\n "branch": "%s"') % j(ctx.branch()))
1769 self.ui.write((',\n "phase": "%s"') % ctx.phasestr())
1769 self.ui.write((',\n "phase": "%s"') % ctx.phasestr())
1770 self.ui.write((',\n "user": "%s"') % j(ctx.user()))
1770 self.ui.write((',\n "user": "%s"') % j(ctx.user()))
1771 self.ui.write((',\n "date": [%d, %d]') % ctx.date())
1771 self.ui.write((',\n "date": [%d, %d]') % ctx.date())
1772 self.ui.write((',\n "desc": "%s"') % j(ctx.description()))
1772 self.ui.write((',\n "desc": "%s"') % j(ctx.description()))
1773
1773
1774 self.ui.write((',\n "bookmarks": [%s]') %
1774 self.ui.write((',\n "bookmarks": [%s]') %
1775 ", ".join('"%s"' % j(b) for b in ctx.bookmarks()))
1775 ", ".join('"%s"' % j(b) for b in ctx.bookmarks()))
1776 self.ui.write((',\n "tags": [%s]') %
1776 self.ui.write((',\n "tags": [%s]') %
1777 ", ".join('"%s"' % j(t) for t in ctx.tags()))
1777 ", ".join('"%s"' % j(t) for t in ctx.tags()))
1778 self.ui.write((',\n "parents": [%s]') %
1778 self.ui.write((',\n "parents": [%s]') %
1779 ", ".join('"%s"' % c.hex() for c in ctx.parents()))
1779 ", ".join('"%s"' % c.hex() for c in ctx.parents()))
1780
1780
1781 if self.ui.debugflag:
1781 if self.ui.debugflag:
1782 if rev is None:
1782 if rev is None:
1783 jmanifestnode = 'null'
1783 jmanifestnode = 'null'
1784 else:
1784 else:
1785 jmanifestnode = '"%s"' % hex(ctx.manifestnode())
1785 jmanifestnode = '"%s"' % hex(ctx.manifestnode())
1786 self.ui.write((',\n "manifest": %s') % jmanifestnode)
1786 self.ui.write((',\n "manifest": %s') % jmanifestnode)
1787
1787
1788 self.ui.write((',\n "extra": {%s}') %
1788 self.ui.write((',\n "extra": {%s}') %
1789 ", ".join('"%s": "%s"' % (j(k), j(v))
1789 ", ".join('"%s": "%s"' % (j(k), j(v))
1790 for k, v in ctx.extra().items()))
1790 for k, v in ctx.extra().items()))
1791
1791
1792 files = ctx.p1().status(ctx)
1792 files = ctx.p1().status(ctx)
1793 self.ui.write((',\n "modified": [%s]') %
1793 self.ui.write((',\n "modified": [%s]') %
1794 ", ".join('"%s"' % j(f) for f in files[0]))
1794 ", ".join('"%s"' % j(f) for f in files[0]))
1795 self.ui.write((',\n "added": [%s]') %
1795 self.ui.write((',\n "added": [%s]') %
1796 ", ".join('"%s"' % j(f) for f in files[1]))
1796 ", ".join('"%s"' % j(f) for f in files[1]))
1797 self.ui.write((',\n "removed": [%s]') %
1797 self.ui.write((',\n "removed": [%s]') %
1798 ", ".join('"%s"' % j(f) for f in files[2]))
1798 ", ".join('"%s"' % j(f) for f in files[2]))
1799
1799
1800 elif self.ui.verbose:
1800 elif self.ui.verbose:
1801 self.ui.write((',\n "files": [%s]') %
1801 self.ui.write((',\n "files": [%s]') %
1802 ", ".join('"%s"' % j(f) for f in ctx.files()))
1802 ", ".join('"%s"' % j(f) for f in ctx.files()))
1803
1803
1804 if copies:
1804 if copies:
1805 self.ui.write((',\n "copies": {%s}') %
1805 self.ui.write((',\n "copies": {%s}') %
1806 ", ".join('"%s": "%s"' % (j(k), j(v))
1806 ", ".join('"%s": "%s"' % (j(k), j(v))
1807 for k, v in copies))
1807 for k, v in copies))
1808
1808
1809 matchfn = self.matchfn
1809 matchfn = self.matchfn
1810 if matchfn:
1810 if matchfn:
1811 stat = self.diffopts.get('stat')
1811 stat = self.diffopts.get('stat')
1812 diff = self.diffopts.get('patch')
1812 diff = self.diffopts.get('patch')
1813 diffopts = patch.difffeatureopts(self.ui, self.diffopts, git=True)
1813 diffopts = patch.difffeatureopts(self.ui, self.diffopts, git=True)
1814 node, prev = ctx.node(), ctx.p1().node()
1814 node, prev = ctx.node(), ctx.p1().node()
1815 if stat:
1815 if stat:
1816 self.ui.pushbuffer()
1816 self.ui.pushbuffer()
1817 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1817 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1818 match=matchfn, stat=True)
1818 match=matchfn, stat=True)
1819 self.ui.write((',\n "diffstat": "%s"')
1819 self.ui.write((',\n "diffstat": "%s"')
1820 % j(self.ui.popbuffer()))
1820 % j(self.ui.popbuffer()))
1821 if diff:
1821 if diff:
1822 self.ui.pushbuffer()
1822 self.ui.pushbuffer()
1823 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1823 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1824 match=matchfn, stat=False)
1824 match=matchfn, stat=False)
1825 self.ui.write((',\n "diff": "%s"') % j(self.ui.popbuffer()))
1825 self.ui.write((',\n "diff": "%s"') % j(self.ui.popbuffer()))
1826
1826
1827 self.ui.write("\n }")
1827 self.ui.write("\n }")
1828
1828
1829 class changeset_templater(changeset_printer):
1829 class changeset_templater(changeset_printer):
1830 '''format changeset information.
1830 '''format changeset information.
1831
1831
1832 Note: there are a variety of convenience functions to build a
1832 Note: there are a variety of convenience functions to build a
1833 changeset_templater for common cases. See functions such as:
1833 changeset_templater for common cases. See functions such as:
1834 makelogtemplater, show_changeset, buildcommittemplate, or other
1834 makelogtemplater, show_changeset, buildcommittemplate, or other
1835 functions that use changesest_templater.
1835 functions that use changesest_templater.
1836 '''
1836 '''
1837
1837
1838 # Arguments before "buffered" used to be positional. Consider not
1838 # Arguments before "buffered" used to be positional. Consider not
1839 # adding/removing arguments before "buffered" to not break callers.
1839 # adding/removing arguments before "buffered" to not break callers.
1840 def __init__(self, ui, repo, tmplspec, matchfn=None, diffopts=None,
1840 def __init__(self, ui, repo, tmplspec, matchfn=None, diffopts=None,
1841 buffered=False):
1841 buffered=False):
1842 diffopts = diffopts or {}
1842 diffopts = diffopts or {}
1843
1843
1844 changeset_printer.__init__(self, ui, repo, matchfn, diffopts, buffered)
1844 changeset_printer.__init__(self, ui, repo, matchfn, diffopts, buffered)
1845 tres = formatter.templateresources(ui, repo)
1845 tres = formatter.templateresources(ui, repo)
1846 self.t = formatter.loadtemplater(ui, tmplspec,
1846 self.t = formatter.loadtemplater(ui, tmplspec,
1847 defaults=templatekw.keywords,
1847 defaults=templatekw.keywords,
1848 resources=tres,
1848 resources=tres,
1849 cache=templatekw.defaulttempl)
1849 cache=templatekw.defaulttempl)
1850 self._counter = itertools.count()
1850 self._counter = itertools.count()
1851 self.cache = tres['cache'] # shared with _graphnodeformatter()
1851 self.cache = tres['cache'] # shared with _graphnodeformatter()
1852
1852
1853 self._tref = tmplspec.ref
1853 self._tref = tmplspec.ref
1854 self._parts = {'header': '', 'footer': '',
1854 self._parts = {'header': '', 'footer': '',
1855 tmplspec.ref: tmplspec.ref,
1855 tmplspec.ref: tmplspec.ref,
1856 'docheader': '', 'docfooter': '',
1856 'docheader': '', 'docfooter': '',
1857 'separator': ''}
1857 'separator': ''}
1858 if tmplspec.mapfile:
1858 if tmplspec.mapfile:
1859 # find correct templates for current mode, for backward
1859 # find correct templates for current mode, for backward
1860 # compatibility with 'log -v/-q/--debug' using a mapfile
1860 # compatibility with 'log -v/-q/--debug' using a mapfile
1861 tmplmodes = [
1861 tmplmodes = [
1862 (True, ''),
1862 (True, ''),
1863 (self.ui.verbose, '_verbose'),
1863 (self.ui.verbose, '_verbose'),
1864 (self.ui.quiet, '_quiet'),
1864 (self.ui.quiet, '_quiet'),
1865 (self.ui.debugflag, '_debug'),
1865 (self.ui.debugflag, '_debug'),
1866 ]
1866 ]
1867 for mode, postfix in tmplmodes:
1867 for mode, postfix in tmplmodes:
1868 for t in self._parts:
1868 for t in self._parts:
1869 cur = t + postfix
1869 cur = t + postfix
1870 if mode and cur in self.t:
1870 if mode and cur in self.t:
1871 self._parts[t] = cur
1871 self._parts[t] = cur
1872 else:
1872 else:
1873 partnames = [p for p in self._parts.keys() if p != tmplspec.ref]
1873 partnames = [p for p in self._parts.keys() if p != tmplspec.ref]
1874 m = formatter.templatepartsmap(tmplspec, self.t, partnames)
1874 m = formatter.templatepartsmap(tmplspec, self.t, partnames)
1875 self._parts.update(m)
1875 self._parts.update(m)
1876
1876
1877 if self._parts['docheader']:
1877 if self._parts['docheader']:
1878 self.ui.write(templater.stringify(self.t(self._parts['docheader'])))
1878 self.ui.write(templater.stringify(self.t(self._parts['docheader'])))
1879
1879
1880 def close(self):
1880 def close(self):
1881 if self._parts['docfooter']:
1881 if self._parts['docfooter']:
1882 if not self.footer:
1882 if not self.footer:
1883 self.footer = ""
1883 self.footer = ""
1884 self.footer += templater.stringify(self.t(self._parts['docfooter']))
1884 self.footer += templater.stringify(self.t(self._parts['docfooter']))
1885 return super(changeset_templater, self).close()
1885 return super(changeset_templater, self).close()
1886
1886
1887 def _show(self, ctx, copies, matchfn, hunksfilterfn, props):
1887 def _show(self, ctx, copies, matchfn, hunksfilterfn, props):
1888 '''show a single changeset or file revision'''
1888 '''show a single changeset or file revision'''
1889 props = props.copy()
1889 props = props.copy()
1890 props['ctx'] = ctx
1890 props['ctx'] = ctx
1891 props['index'] = index = next(self._counter)
1891 props['index'] = index = next(self._counter)
1892 props['revcache'] = {'copies': copies}
1892 props['revcache'] = {'copies': copies}
1893 props = pycompat.strkwargs(props)
1893 props = pycompat.strkwargs(props)
1894
1894
1895 # write separator, which wouldn't work well with the header part below
1895 # write separator, which wouldn't work well with the header part below
1896 # since there's inherently a conflict between header (across items) and
1896 # since there's inherently a conflict between header (across items) and
1897 # separator (per item)
1897 # separator (per item)
1898 if self._parts['separator'] and index > 0:
1898 if self._parts['separator'] and index > 0:
1899 self.ui.write(templater.stringify(self.t(self._parts['separator'])))
1899 self.ui.write(templater.stringify(self.t(self._parts['separator'])))
1900
1900
1901 # write header
1901 # write header
1902 if self._parts['header']:
1902 if self._parts['header']:
1903 h = templater.stringify(self.t(self._parts['header'], **props))
1903 h = templater.stringify(self.t(self._parts['header'], **props))
1904 if self.buffered:
1904 if self.buffered:
1905 self.header[ctx.rev()] = h
1905 self.header[ctx.rev()] = h
1906 else:
1906 else:
1907 if self.lastheader != h:
1907 if self.lastheader != h:
1908 self.lastheader = h
1908 self.lastheader = h
1909 self.ui.write(h)
1909 self.ui.write(h)
1910
1910
1911 # write changeset metadata, then patch if requested
1911 # write changeset metadata, then patch if requested
1912 key = self._parts[self._tref]
1912 key = self._parts[self._tref]
1913 self.ui.write(templater.stringify(self.t(key, **props)))
1913 self.ui.write(templater.stringify(self.t(key, **props)))
1914 self.showpatch(ctx, matchfn, hunksfilterfn=hunksfilterfn)
1914 self.showpatch(ctx, matchfn, hunksfilterfn=hunksfilterfn)
1915
1915
1916 if self._parts['footer']:
1916 if self._parts['footer']:
1917 if not self.footer:
1917 if not self.footer:
1918 self.footer = templater.stringify(
1918 self.footer = templater.stringify(
1919 self.t(self._parts['footer'], **props))
1919 self.t(self._parts['footer'], **props))
1920
1920
1921 def logtemplatespec(tmpl, mapfile):
1921 def logtemplatespec(tmpl, mapfile):
1922 if mapfile:
1922 if mapfile:
1923 return formatter.templatespec('changeset', tmpl, mapfile)
1923 return formatter.templatespec('changeset', tmpl, mapfile)
1924 else:
1924 else:
1925 return formatter.templatespec('', tmpl, None)
1925 return formatter.templatespec('', tmpl, None)
1926
1926
1927 def _lookuplogtemplate(ui, tmpl, style):
1927 def _lookuplogtemplate(ui, tmpl, style):
1928 """Find the template matching the given template spec or style
1928 """Find the template matching the given template spec or style
1929
1929
1930 See formatter.lookuptemplate() for details.
1930 See formatter.lookuptemplate() for details.
1931 """
1931 """
1932
1932
1933 # ui settings
1933 # ui settings
1934 if not tmpl and not style: # template are stronger than style
1934 if not tmpl and not style: # template are stronger than style
1935 tmpl = ui.config('ui', 'logtemplate')
1935 tmpl = ui.config('ui', 'logtemplate')
1936 if tmpl:
1936 if tmpl:
1937 return logtemplatespec(templater.unquotestring(tmpl), None)
1937 return logtemplatespec(templater.unquotestring(tmpl), None)
1938 else:
1938 else:
1939 style = util.expandpath(ui.config('ui', 'style'))
1939 style = util.expandpath(ui.config('ui', 'style'))
1940
1940
1941 if not tmpl and style:
1941 if not tmpl and style:
1942 mapfile = style
1942 mapfile = style
1943 if not os.path.split(mapfile)[0]:
1943 if not os.path.split(mapfile)[0]:
1944 mapname = (templater.templatepath('map-cmdline.' + mapfile)
1944 mapname = (templater.templatepath('map-cmdline.' + mapfile)
1945 or templater.templatepath(mapfile))
1945 or templater.templatepath(mapfile))
1946 if mapname:
1946 if mapname:
1947 mapfile = mapname
1947 mapfile = mapname
1948 return logtemplatespec(None, mapfile)
1948 return logtemplatespec(None, mapfile)
1949
1949
1950 if not tmpl:
1950 if not tmpl:
1951 return logtemplatespec(None, None)
1951 return logtemplatespec(None, None)
1952
1952
1953 return formatter.lookuptemplate(ui, 'changeset', tmpl)
1953 return formatter.lookuptemplate(ui, 'changeset', tmpl)
1954
1954
1955 def makelogtemplater(ui, repo, tmpl, buffered=False):
1955 def makelogtemplater(ui, repo, tmpl, buffered=False):
1956 """Create a changeset_templater from a literal template 'tmpl'
1956 """Create a changeset_templater from a literal template 'tmpl'
1957 byte-string."""
1957 byte-string."""
1958 spec = logtemplatespec(tmpl, None)
1958 spec = logtemplatespec(tmpl, None)
1959 return changeset_templater(ui, repo, spec, buffered=buffered)
1959 return changeset_templater(ui, repo, spec, buffered=buffered)
1960
1960
1961 def show_changeset(ui, repo, opts, buffered=False):
1961 def show_changeset(ui, repo, opts, buffered=False):
1962 """show one changeset using template or regular display.
1962 """show one changeset using template or regular display.
1963
1963
1964 Display format will be the first non-empty hit of:
1964 Display format will be the first non-empty hit of:
1965 1. option 'template'
1965 1. option 'template'
1966 2. option 'style'
1966 2. option 'style'
1967 3. [ui] setting 'logtemplate'
1967 3. [ui] setting 'logtemplate'
1968 4. [ui] setting 'style'
1968 4. [ui] setting 'style'
1969 If all of these values are either the unset or the empty string,
1969 If all of these values are either the unset or the empty string,
1970 regular display via changeset_printer() is done.
1970 regular display via changeset_printer() is done.
1971 """
1971 """
1972 # options
1972 # options
1973 match = None
1973 match = None
1974 if opts.get('patch') or opts.get('stat'):
1974 if opts.get('patch') or opts.get('stat'):
1975 match = scmutil.matchall(repo)
1975 match = scmutil.matchall(repo)
1976
1976
1977 if opts.get('template') == 'json':
1977 if opts.get('template') == 'json':
1978 return jsonchangeset(ui, repo, match, opts, buffered)
1978 return jsonchangeset(ui, repo, match, opts, buffered)
1979
1979
1980 spec = _lookuplogtemplate(ui, opts.get('template'), opts.get('style'))
1980 spec = _lookuplogtemplate(ui, opts.get('template'), opts.get('style'))
1981
1981
1982 if not spec.ref and not spec.tmpl and not spec.mapfile:
1982 if not spec.ref and not spec.tmpl and not spec.mapfile:
1983 return changeset_printer(ui, repo, match, opts, buffered)
1983 return changeset_printer(ui, repo, match, opts, buffered)
1984
1984
1985 return changeset_templater(ui, repo, spec, match, opts, buffered)
1985 return changeset_templater(ui, repo, spec, match, opts, buffered)
1986
1986
1987 def showmarker(fm, marker, index=None):
1987 def showmarker(fm, marker, index=None):
1988 """utility function to display obsolescence marker in a readable way
1988 """utility function to display obsolescence marker in a readable way
1989
1989
1990 To be used by debug function."""
1990 To be used by debug function."""
1991 if index is not None:
1991 if index is not None:
1992 fm.write('index', '%i ', index)
1992 fm.write('index', '%i ', index)
1993 fm.write('prednode', '%s ', hex(marker.prednode()))
1993 fm.write('prednode', '%s ', hex(marker.prednode()))
1994 succs = marker.succnodes()
1994 succs = marker.succnodes()
1995 fm.condwrite(succs, 'succnodes', '%s ',
1995 fm.condwrite(succs, 'succnodes', '%s ',
1996 fm.formatlist(map(hex, succs), name='node'))
1996 fm.formatlist(map(hex, succs), name='node'))
1997 fm.write('flag', '%X ', marker.flags())
1997 fm.write('flag', '%X ', marker.flags())
1998 parents = marker.parentnodes()
1998 parents = marker.parentnodes()
1999 if parents is not None:
1999 if parents is not None:
2000 fm.write('parentnodes', '{%s} ',
2000 fm.write('parentnodes', '{%s} ',
2001 fm.formatlist(map(hex, parents), name='node', sep=', '))
2001 fm.formatlist(map(hex, parents), name='node', sep=', '))
2002 fm.write('date', '(%s) ', fm.formatdate(marker.date()))
2002 fm.write('date', '(%s) ', fm.formatdate(marker.date()))
2003 meta = marker.metadata().copy()
2003 meta = marker.metadata().copy()
2004 meta.pop('date', None)
2004 meta.pop('date', None)
2005 fm.write('metadata', '{%s}', fm.formatdict(meta, fmt='%r: %r', sep=', '))
2005 fm.write('metadata', '{%s}', fm.formatdict(meta, fmt='%r: %r', sep=', '))
2006 fm.plain('\n')
2006 fm.plain('\n')
2007
2007
2008 def finddate(ui, repo, date):
2008 def finddate(ui, repo, date):
2009 """Find the tipmost changeset that matches the given date spec"""
2009 """Find the tipmost changeset that matches the given date spec"""
2010
2010
2011 df = util.matchdate(date)
2011 df = util.matchdate(date)
2012 m = scmutil.matchall(repo)
2012 m = scmutil.matchall(repo)
2013 results = {}
2013 results = {}
2014
2014
2015 def prep(ctx, fns):
2015 def prep(ctx, fns):
2016 d = ctx.date()
2016 d = ctx.date()
2017 if df(d[0]):
2017 if df(d[0]):
2018 results[ctx.rev()] = d
2018 results[ctx.rev()] = d
2019
2019
2020 for ctx in walkchangerevs(repo, m, {'rev': None}, prep):
2020 for ctx in walkchangerevs(repo, m, {'rev': None}, prep):
2021 rev = ctx.rev()
2021 rev = ctx.rev()
2022 if rev in results:
2022 if rev in results:
2023 ui.status(_("found revision %s from %s\n") %
2023 ui.status(_("found revision %s from %s\n") %
2024 (rev, util.datestr(results[rev])))
2024 (rev, util.datestr(results[rev])))
2025 return '%d' % rev
2025 return '%d' % rev
2026
2026
2027 raise error.Abort(_("revision matching date not found"))
2027 raise error.Abort(_("revision matching date not found"))
2028
2028
2029 def increasingwindows(windowsize=8, sizelimit=512):
2029 def increasingwindows(windowsize=8, sizelimit=512):
2030 while True:
2030 while True:
2031 yield windowsize
2031 yield windowsize
2032 if windowsize < sizelimit:
2032 if windowsize < sizelimit:
2033 windowsize *= 2
2033 windowsize *= 2
2034
2034
2035 def _walkrevs(repo, opts):
2036 # Default --rev value depends on --follow but --follow behavior
2037 # depends on revisions resolved from --rev...
2038 follow = opts.get('follow') or opts.get('follow_first')
2039 if opts.get('rev'):
2040 revs = scmutil.revrange(repo, opts['rev'])
2041 elif follow and repo.dirstate.p1() == nullid:
2042 revs = smartset.baseset()
2043 elif follow:
2044 revs = repo.revs('reverse(:.)')
2045 else:
2046 revs = smartset.spanset(repo)
2047 revs.reverse()
2048 return revs
2049
2035 class FileWalkError(Exception):
2050 class FileWalkError(Exception):
2036 pass
2051 pass
2037
2052
2038 def walkfilerevs(repo, match, follow, revs, fncache):
2053 def walkfilerevs(repo, match, follow, revs, fncache):
2039 '''Walks the file history for the matched files.
2054 '''Walks the file history for the matched files.
2040
2055
2041 Returns the changeset revs that are involved in the file history.
2056 Returns the changeset revs that are involved in the file history.
2042
2057
2043 Throws FileWalkError if the file history can't be walked using
2058 Throws FileWalkError if the file history can't be walked using
2044 filelogs alone.
2059 filelogs alone.
2045 '''
2060 '''
2046 wanted = set()
2061 wanted = set()
2047 copies = []
2062 copies = []
2048 minrev, maxrev = min(revs), max(revs)
2063 minrev, maxrev = min(revs), max(revs)
2049 def filerevgen(filelog, last):
2064 def filerevgen(filelog, last):
2050 """
2065 """
2051 Only files, no patterns. Check the history of each file.
2066 Only files, no patterns. Check the history of each file.
2052
2067
2053 Examines filelog entries within minrev, maxrev linkrev range
2068 Examines filelog entries within minrev, maxrev linkrev range
2054 Returns an iterator yielding (linkrev, parentlinkrevs, copied)
2069 Returns an iterator yielding (linkrev, parentlinkrevs, copied)
2055 tuples in backwards order
2070 tuples in backwards order
2056 """
2071 """
2057 cl_count = len(repo)
2072 cl_count = len(repo)
2058 revs = []
2073 revs = []
2059 for j in xrange(0, last + 1):
2074 for j in xrange(0, last + 1):
2060 linkrev = filelog.linkrev(j)
2075 linkrev = filelog.linkrev(j)
2061 if linkrev < minrev:
2076 if linkrev < minrev:
2062 continue
2077 continue
2063 # only yield rev for which we have the changelog, it can
2078 # only yield rev for which we have the changelog, it can
2064 # happen while doing "hg log" during a pull or commit
2079 # happen while doing "hg log" during a pull or commit
2065 if linkrev >= cl_count:
2080 if linkrev >= cl_count:
2066 break
2081 break
2067
2082
2068 parentlinkrevs = []
2083 parentlinkrevs = []
2069 for p in filelog.parentrevs(j):
2084 for p in filelog.parentrevs(j):
2070 if p != nullrev:
2085 if p != nullrev:
2071 parentlinkrevs.append(filelog.linkrev(p))
2086 parentlinkrevs.append(filelog.linkrev(p))
2072 n = filelog.node(j)
2087 n = filelog.node(j)
2073 revs.append((linkrev, parentlinkrevs,
2088 revs.append((linkrev, parentlinkrevs,
2074 follow and filelog.renamed(n)))
2089 follow and filelog.renamed(n)))
2075
2090
2076 return reversed(revs)
2091 return reversed(revs)
2077 def iterfiles():
2092 def iterfiles():
2078 pctx = repo['.']
2093 pctx = repo['.']
2079 for filename in match.files():
2094 for filename in match.files():
2080 if follow:
2095 if follow:
2081 if filename not in pctx:
2096 if filename not in pctx:
2082 raise error.Abort(_('cannot follow file not in parent '
2097 raise error.Abort(_('cannot follow file not in parent '
2083 'revision: "%s"') % filename)
2098 'revision: "%s"') % filename)
2084 yield filename, pctx[filename].filenode()
2099 yield filename, pctx[filename].filenode()
2085 else:
2100 else:
2086 yield filename, None
2101 yield filename, None
2087 for filename_node in copies:
2102 for filename_node in copies:
2088 yield filename_node
2103 yield filename_node
2089
2104
2090 for file_, node in iterfiles():
2105 for file_, node in iterfiles():
2091 filelog = repo.file(file_)
2106 filelog = repo.file(file_)
2092 if not len(filelog):
2107 if not len(filelog):
2093 if node is None:
2108 if node is None:
2094 # A zero count may be a directory or deleted file, so
2109 # A zero count may be a directory or deleted file, so
2095 # try to find matching entries on the slow path.
2110 # try to find matching entries on the slow path.
2096 if follow:
2111 if follow:
2097 raise error.Abort(
2112 raise error.Abort(
2098 _('cannot follow nonexistent file: "%s"') % file_)
2113 _('cannot follow nonexistent file: "%s"') % file_)
2099 raise FileWalkError("Cannot walk via filelog")
2114 raise FileWalkError("Cannot walk via filelog")
2100 else:
2115 else:
2101 continue
2116 continue
2102
2117
2103 if node is None:
2118 if node is None:
2104 last = len(filelog) - 1
2119 last = len(filelog) - 1
2105 else:
2120 else:
2106 last = filelog.rev(node)
2121 last = filelog.rev(node)
2107
2122
2108 # keep track of all ancestors of the file
2123 # keep track of all ancestors of the file
2109 ancestors = {filelog.linkrev(last)}
2124 ancestors = {filelog.linkrev(last)}
2110
2125
2111 # iterate from latest to oldest revision
2126 # iterate from latest to oldest revision
2112 for rev, flparentlinkrevs, copied in filerevgen(filelog, last):
2127 for rev, flparentlinkrevs, copied in filerevgen(filelog, last):
2113 if not follow:
2128 if not follow:
2114 if rev > maxrev:
2129 if rev > maxrev:
2115 continue
2130 continue
2116 else:
2131 else:
2117 # Note that last might not be the first interesting
2132 # Note that last might not be the first interesting
2118 # rev to us:
2133 # rev to us:
2119 # if the file has been changed after maxrev, we'll
2134 # if the file has been changed after maxrev, we'll
2120 # have linkrev(last) > maxrev, and we still need
2135 # have linkrev(last) > maxrev, and we still need
2121 # to explore the file graph
2136 # to explore the file graph
2122 if rev not in ancestors:
2137 if rev not in ancestors:
2123 continue
2138 continue
2124 # XXX insert 1327 fix here
2139 # XXX insert 1327 fix here
2125 if flparentlinkrevs:
2140 if flparentlinkrevs:
2126 ancestors.update(flparentlinkrevs)
2141 ancestors.update(flparentlinkrevs)
2127
2142
2128 fncache.setdefault(rev, []).append(file_)
2143 fncache.setdefault(rev, []).append(file_)
2129 wanted.add(rev)
2144 wanted.add(rev)
2130 if copied:
2145 if copied:
2131 copies.append(copied)
2146 copies.append(copied)
2132
2147
2133 return wanted
2148 return wanted
2134
2149
2135 class _followfilter(object):
2150 class _followfilter(object):
2136 def __init__(self, repo, onlyfirst=False):
2151 def __init__(self, repo, onlyfirst=False):
2137 self.repo = repo
2152 self.repo = repo
2138 self.startrev = nullrev
2153 self.startrev = nullrev
2139 self.roots = set()
2154 self.roots = set()
2140 self.onlyfirst = onlyfirst
2155 self.onlyfirst = onlyfirst
2141
2156
2142 def match(self, rev):
2157 def match(self, rev):
2143 def realparents(rev):
2158 def realparents(rev):
2144 if self.onlyfirst:
2159 if self.onlyfirst:
2145 return self.repo.changelog.parentrevs(rev)[0:1]
2160 return self.repo.changelog.parentrevs(rev)[0:1]
2146 else:
2161 else:
2147 return filter(lambda x: x != nullrev,
2162 return filter(lambda x: x != nullrev,
2148 self.repo.changelog.parentrevs(rev))
2163 self.repo.changelog.parentrevs(rev))
2149
2164
2150 if self.startrev == nullrev:
2165 if self.startrev == nullrev:
2151 self.startrev = rev
2166 self.startrev = rev
2152 return True
2167 return True
2153
2168
2154 if rev > self.startrev:
2169 if rev > self.startrev:
2155 # forward: all descendants
2170 # forward: all descendants
2156 if not self.roots:
2171 if not self.roots:
2157 self.roots.add(self.startrev)
2172 self.roots.add(self.startrev)
2158 for parent in realparents(rev):
2173 for parent in realparents(rev):
2159 if parent in self.roots:
2174 if parent in self.roots:
2160 self.roots.add(rev)
2175 self.roots.add(rev)
2161 return True
2176 return True
2162 else:
2177 else:
2163 # backwards: all parents
2178 # backwards: all parents
2164 if not self.roots:
2179 if not self.roots:
2165 self.roots.update(realparents(self.startrev))
2180 self.roots.update(realparents(self.startrev))
2166 if rev in self.roots:
2181 if rev in self.roots:
2167 self.roots.remove(rev)
2182 self.roots.remove(rev)
2168 self.roots.update(realparents(rev))
2183 self.roots.update(realparents(rev))
2169 return True
2184 return True
2170
2185
2171 return False
2186 return False
2172
2187
2173 def walkchangerevs(repo, match, opts, prepare):
2188 def walkchangerevs(repo, match, opts, prepare):
2174 '''Iterate over files and the revs in which they changed.
2189 '''Iterate over files and the revs in which they changed.
2175
2190
2176 Callers most commonly need to iterate backwards over the history
2191 Callers most commonly need to iterate backwards over the history
2177 in which they are interested. Doing so has awful (quadratic-looking)
2192 in which they are interested. Doing so has awful (quadratic-looking)
2178 performance, so we use iterators in a "windowed" way.
2193 performance, so we use iterators in a "windowed" way.
2179
2194
2180 We walk a window of revisions in the desired order. Within the
2195 We walk a window of revisions in the desired order. Within the
2181 window, we first walk forwards to gather data, then in the desired
2196 window, we first walk forwards to gather data, then in the desired
2182 order (usually backwards) to display it.
2197 order (usually backwards) to display it.
2183
2198
2184 This function returns an iterator yielding contexts. Before
2199 This function returns an iterator yielding contexts. Before
2185 yielding each context, the iterator will first call the prepare
2200 yielding each context, the iterator will first call the prepare
2186 function on each context in the window in forward order.'''
2201 function on each context in the window in forward order.'''
2187
2202
2188 follow = opts.get('follow') or opts.get('follow_first')
2203 follow = opts.get('follow') or opts.get('follow_first')
2189 revs = _logrevs(repo, opts)
2204 revs = _walkrevs(repo, opts)
2190 if not revs:
2205 if not revs:
2191 return []
2206 return []
2192 wanted = set()
2207 wanted = set()
2193 slowpath = match.anypats() or (not match.always() and opts.get('removed'))
2208 slowpath = match.anypats() or (not match.always() and opts.get('removed'))
2194 fncache = {}
2209 fncache = {}
2195 change = repo.changectx
2210 change = repo.changectx
2196
2211
2197 # First step is to fill wanted, the set of revisions that we want to yield.
2212 # First step is to fill wanted, the set of revisions that we want to yield.
2198 # When it does not induce extra cost, we also fill fncache for revisions in
2213 # When it does not induce extra cost, we also fill fncache for revisions in
2199 # wanted: a cache of filenames that were changed (ctx.files()) and that
2214 # wanted: a cache of filenames that were changed (ctx.files()) and that
2200 # match the file filtering conditions.
2215 # match the file filtering conditions.
2201
2216
2202 if match.always():
2217 if match.always():
2203 # No files, no patterns. Display all revs.
2218 # No files, no patterns. Display all revs.
2204 wanted = revs
2219 wanted = revs
2205 elif not slowpath:
2220 elif not slowpath:
2206 # We only have to read through the filelog to find wanted revisions
2221 # We only have to read through the filelog to find wanted revisions
2207
2222
2208 try:
2223 try:
2209 wanted = walkfilerevs(repo, match, follow, revs, fncache)
2224 wanted = walkfilerevs(repo, match, follow, revs, fncache)
2210 except FileWalkError:
2225 except FileWalkError:
2211 slowpath = True
2226 slowpath = True
2212
2227
2213 # We decided to fall back to the slowpath because at least one
2228 # We decided to fall back to the slowpath because at least one
2214 # of the paths was not a file. Check to see if at least one of them
2229 # of the paths was not a file. Check to see if at least one of them
2215 # existed in history, otherwise simply return
2230 # existed in history, otherwise simply return
2216 for path in match.files():
2231 for path in match.files():
2217 if path == '.' or path in repo.store:
2232 if path == '.' or path in repo.store:
2218 break
2233 break
2219 else:
2234 else:
2220 return []
2235 return []
2221
2236
2222 if slowpath:
2237 if slowpath:
2223 # We have to read the changelog to match filenames against
2238 # We have to read the changelog to match filenames against
2224 # changed files
2239 # changed files
2225
2240
2226 if follow:
2241 if follow:
2227 raise error.Abort(_('can only follow copies/renames for explicit '
2242 raise error.Abort(_('can only follow copies/renames for explicit '
2228 'filenames'))
2243 'filenames'))
2229
2244
2230 # The slow path checks files modified in every changeset.
2245 # The slow path checks files modified in every changeset.
2231 # This is really slow on large repos, so compute the set lazily.
2246 # This is really slow on large repos, so compute the set lazily.
2232 class lazywantedset(object):
2247 class lazywantedset(object):
2233 def __init__(self):
2248 def __init__(self):
2234 self.set = set()
2249 self.set = set()
2235 self.revs = set(revs)
2250 self.revs = set(revs)
2236
2251
2237 # No need to worry about locality here because it will be accessed
2252 # No need to worry about locality here because it will be accessed
2238 # in the same order as the increasing window below.
2253 # in the same order as the increasing window below.
2239 def __contains__(self, value):
2254 def __contains__(self, value):
2240 if value in self.set:
2255 if value in self.set:
2241 return True
2256 return True
2242 elif not value in self.revs:
2257 elif not value in self.revs:
2243 return False
2258 return False
2244 else:
2259 else:
2245 self.revs.discard(value)
2260 self.revs.discard(value)
2246 ctx = change(value)
2261 ctx = change(value)
2247 matches = filter(match, ctx.files())
2262 matches = filter(match, ctx.files())
2248 if matches:
2263 if matches:
2249 fncache[value] = matches
2264 fncache[value] = matches
2250 self.set.add(value)
2265 self.set.add(value)
2251 return True
2266 return True
2252 return False
2267 return False
2253
2268
2254 def discard(self, value):
2269 def discard(self, value):
2255 self.revs.discard(value)
2270 self.revs.discard(value)
2256 self.set.discard(value)
2271 self.set.discard(value)
2257
2272
2258 wanted = lazywantedset()
2273 wanted = lazywantedset()
2259
2274
2260 # it might be worthwhile to do this in the iterator if the rev range
2275 # it might be worthwhile to do this in the iterator if the rev range
2261 # is descending and the prune args are all within that range
2276 # is descending and the prune args are all within that range
2262 for rev in opts.get('prune', ()):
2277 for rev in opts.get('prune', ()):
2263 rev = repo[rev].rev()
2278 rev = repo[rev].rev()
2264 ff = _followfilter(repo)
2279 ff = _followfilter(repo)
2265 stop = min(revs[0], revs[-1])
2280 stop = min(revs[0], revs[-1])
2266 for x in xrange(rev, stop - 1, -1):
2281 for x in xrange(rev, stop - 1, -1):
2267 if ff.match(x):
2282 if ff.match(x):
2268 wanted = wanted - [x]
2283 wanted = wanted - [x]
2269
2284
2270 # Now that wanted is correctly initialized, we can iterate over the
2285 # Now that wanted is correctly initialized, we can iterate over the
2271 # revision range, yielding only revisions in wanted.
2286 # revision range, yielding only revisions in wanted.
2272 def iterate():
2287 def iterate():
2273 if follow and match.always():
2288 if follow and match.always():
2274 ff = _followfilter(repo, onlyfirst=opts.get('follow_first'))
2289 ff = _followfilter(repo, onlyfirst=opts.get('follow_first'))
2275 def want(rev):
2290 def want(rev):
2276 return ff.match(rev) and rev in wanted
2291 return ff.match(rev) and rev in wanted
2277 else:
2292 else:
2278 def want(rev):
2293 def want(rev):
2279 return rev in wanted
2294 return rev in wanted
2280
2295
2281 it = iter(revs)
2296 it = iter(revs)
2282 stopiteration = False
2297 stopiteration = False
2283 for windowsize in increasingwindows():
2298 for windowsize in increasingwindows():
2284 nrevs = []
2299 nrevs = []
2285 for i in xrange(windowsize):
2300 for i in xrange(windowsize):
2286 rev = next(it, None)
2301 rev = next(it, None)
2287 if rev is None:
2302 if rev is None:
2288 stopiteration = True
2303 stopiteration = True
2289 break
2304 break
2290 elif want(rev):
2305 elif want(rev):
2291 nrevs.append(rev)
2306 nrevs.append(rev)
2292 for rev in sorted(nrevs):
2307 for rev in sorted(nrevs):
2293 fns = fncache.get(rev)
2308 fns = fncache.get(rev)
2294 ctx = change(rev)
2309 ctx = change(rev)
2295 if not fns:
2310 if not fns:
2296 def fns_generator():
2311 def fns_generator():
2297 for f in ctx.files():
2312 for f in ctx.files():
2298 if match(f):
2313 if match(f):
2299 yield f
2314 yield f
2300 fns = fns_generator()
2315 fns = fns_generator()
2301 prepare(ctx, fns)
2316 prepare(ctx, fns)
2302 for rev in nrevs:
2317 for rev in nrevs:
2303 yield change(rev)
2318 yield change(rev)
2304
2319
2305 if stopiteration:
2320 if stopiteration:
2306 break
2321 break
2307
2322
2308 return iterate()
2323 return iterate()
2309
2324
2310 def _makefollowlogfilematcher(repo, files, followfirst):
2325 def _makefollowlogfilematcher(repo, files, followfirst):
2311 # When displaying a revision with --patch --follow FILE, we have
2326 # When displaying a revision with --patch --follow FILE, we have
2312 # to know which file of the revision must be diffed. With
2327 # to know which file of the revision must be diffed. With
2313 # --follow, we want the names of the ancestors of FILE in the
2328 # --follow, we want the names of the ancestors of FILE in the
2314 # revision, stored in "fcache". "fcache" is populated by
2329 # revision, stored in "fcache". "fcache" is populated by
2315 # reproducing the graph traversal already done by --follow revset
2330 # reproducing the graph traversal already done by --follow revset
2316 # and relating revs to file names (which is not "correct" but
2331 # and relating revs to file names (which is not "correct" but
2317 # good enough).
2332 # good enough).
2318 fcache = {}
2333 fcache = {}
2319 fcacheready = [False]
2334 fcacheready = [False]
2320 pctx = repo['.']
2335 pctx = repo['.']
2321
2336
2322 def populate():
2337 def populate():
2323 for fn in files:
2338 for fn in files:
2324 fctx = pctx[fn]
2339 fctx = pctx[fn]
2325 fcache.setdefault(fctx.introrev(), set()).add(fctx.path())
2340 fcache.setdefault(fctx.introrev(), set()).add(fctx.path())
2326 for c in fctx.ancestors(followfirst=followfirst):
2341 for c in fctx.ancestors(followfirst=followfirst):
2327 fcache.setdefault(c.rev(), set()).add(c.path())
2342 fcache.setdefault(c.rev(), set()).add(c.path())
2328
2343
2329 def filematcher(rev):
2344 def filematcher(rev):
2330 if not fcacheready[0]:
2345 if not fcacheready[0]:
2331 # Lazy initialization
2346 # Lazy initialization
2332 fcacheready[0] = True
2347 fcacheready[0] = True
2333 populate()
2348 populate()
2334 return scmutil.matchfiles(repo, fcache.get(rev, []))
2349 return scmutil.matchfiles(repo, fcache.get(rev, []))
2335
2350
2336 return filematcher
2351 return filematcher
2337
2352
2338 def _makenofollowlogfilematcher(repo, pats, opts):
2353 def _makenofollowlogfilematcher(repo, pats, opts):
2339 '''hook for extensions to override the filematcher for non-follow cases'''
2354 '''hook for extensions to override the filematcher for non-follow cases'''
2340 return None
2355 return None
2341
2356
2342 _opt2logrevset = {
2357 _opt2logrevset = {
2343 'no_merges': ('not merge()', None),
2358 'no_merges': ('not merge()', None),
2344 'only_merges': ('merge()', None),
2359 'only_merges': ('merge()', None),
2345 '_ancestors': ('ancestors(%r)', None),
2360 '_ancestors': ('ancestors(%r)', None),
2346 '_fancestors': ('_firstancestors(%r)', None),
2361 '_fancestors': ('_firstancestors(%r)', None),
2347 '_descendants': ('descendants(%r)', None),
2362 '_descendants': ('descendants(%r)', None),
2348 '_fdescendants': ('_firstdescendants(%r)', None),
2363 '_fdescendants': ('_firstdescendants(%r)', None),
2349 '_matchfiles': (None, '_matchfiles(%ps)'),
2364 '_matchfiles': (None, '_matchfiles(%ps)'),
2350 'date': ('date(%s)', None),
2365 'date': ('date(%s)', None),
2351 'branch': ('branch(%s)', '%lr'),
2366 'branch': ('branch(%s)', '%lr'),
2352 '_patslog': ('filelog(%s)', '%lr'),
2367 '_patslog': ('filelog(%s)', '%lr'),
2353 '_patsfollow': ('follow(%s)', '%lr'),
2368 '_patsfollow': ('follow(%s)', '%lr'),
2354 '_patsfollowfirst': ('_followfirst(%s)', '%lr'),
2369 '_patsfollowfirst': ('_followfirst(%s)', '%lr'),
2355 'keyword': ('keyword(%s)', '%lr'),
2370 'keyword': ('keyword(%s)', '%lr'),
2356 'prune': ('ancestors(%s)', 'not %lr'),
2371 'prune': ('ancestors(%s)', 'not %lr'),
2357 'user': ('user(%s)', '%lr'),
2372 'user': ('user(%s)', '%lr'),
2358 }
2373 }
2359
2374
2360 def _makelogrevset(repo, pats, opts, revs):
2375 def _makelogrevset(repo, pats, opts, revs):
2361 """Return (expr, filematcher) where expr is a revset string built
2376 """Return (expr, filematcher) where expr is a revset string built
2362 from log options and file patterns or None. If --stat or --patch
2377 from log options and file patterns or None. If --stat or --patch
2363 are not passed filematcher is None. Otherwise it is a callable
2378 are not passed filematcher is None. Otherwise it is a callable
2364 taking a revision number and returning a match objects filtering
2379 taking a revision number and returning a match objects filtering
2365 the files to be detailed when displaying the revision.
2380 the files to be detailed when displaying the revision.
2366 """
2381 """
2367 opts = dict(opts)
2382 opts = dict(opts)
2368 # follow or not follow?
2383 # follow or not follow?
2369 follow = opts.get('follow') or opts.get('follow_first')
2384 follow = opts.get('follow') or opts.get('follow_first')
2370 if opts.get('follow_first'):
2385 if opts.get('follow_first'):
2371 followfirst = 1
2386 followfirst = 1
2372 else:
2387 else:
2373 followfirst = 0
2388 followfirst = 0
2374 # --follow with FILE behavior depends on revs...
2389 # --follow with FILE behavior depends on revs...
2375 it = iter(revs)
2390 it = iter(revs)
2376 startrev = next(it)
2391 startrev = next(it)
2377 followdescendants = startrev < next(it, startrev)
2392 followdescendants = startrev < next(it, startrev)
2378
2393
2379 # branch and only_branch are really aliases and must be handled at
2394 # branch and only_branch are really aliases and must be handled at
2380 # the same time
2395 # the same time
2381 opts['branch'] = opts.get('branch', []) + opts.get('only_branch', [])
2396 opts['branch'] = opts.get('branch', []) + opts.get('only_branch', [])
2382 opts['branch'] = [repo.lookupbranch(b) for b in opts['branch']]
2397 opts['branch'] = [repo.lookupbranch(b) for b in opts['branch']]
2383 # pats/include/exclude are passed to match.match() directly in
2398 # pats/include/exclude are passed to match.match() directly in
2384 # _matchfiles() revset but walkchangerevs() builds its matcher with
2399 # _matchfiles() revset but walkchangerevs() builds its matcher with
2385 # scmutil.match(). The difference is input pats are globbed on
2400 # scmutil.match(). The difference is input pats are globbed on
2386 # platforms without shell expansion (windows).
2401 # platforms without shell expansion (windows).
2387 wctx = repo[None]
2402 wctx = repo[None]
2388 match, pats = scmutil.matchandpats(wctx, pats, opts)
2403 match, pats = scmutil.matchandpats(wctx, pats, opts)
2389 slowpath = match.anypats() or (not match.always() and opts.get('removed'))
2404 slowpath = match.anypats() or (not match.always() and opts.get('removed'))
2390 if not slowpath:
2405 if not slowpath:
2391 for f in match.files():
2406 for f in match.files():
2392 if follow and f not in wctx:
2407 if follow and f not in wctx:
2393 # If the file exists, it may be a directory, so let it
2408 # If the file exists, it may be a directory, so let it
2394 # take the slow path.
2409 # take the slow path.
2395 if os.path.exists(repo.wjoin(f)):
2410 if os.path.exists(repo.wjoin(f)):
2396 slowpath = True
2411 slowpath = True
2397 continue
2412 continue
2398 else:
2413 else:
2399 raise error.Abort(_('cannot follow file not in parent '
2414 raise error.Abort(_('cannot follow file not in parent '
2400 'revision: "%s"') % f)
2415 'revision: "%s"') % f)
2401 filelog = repo.file(f)
2416 filelog = repo.file(f)
2402 if not filelog:
2417 if not filelog:
2403 # A zero count may be a directory or deleted file, so
2418 # A zero count may be a directory or deleted file, so
2404 # try to find matching entries on the slow path.
2419 # try to find matching entries on the slow path.
2405 if follow:
2420 if follow:
2406 raise error.Abort(
2421 raise error.Abort(
2407 _('cannot follow nonexistent file: "%s"') % f)
2422 _('cannot follow nonexistent file: "%s"') % f)
2408 slowpath = True
2423 slowpath = True
2409
2424
2410 # We decided to fall back to the slowpath because at least one
2425 # We decided to fall back to the slowpath because at least one
2411 # of the paths was not a file. Check to see if at least one of them
2426 # of the paths was not a file. Check to see if at least one of them
2412 # existed in history - in that case, we'll continue down the
2427 # existed in history - in that case, we'll continue down the
2413 # slowpath; otherwise, we can turn off the slowpath
2428 # slowpath; otherwise, we can turn off the slowpath
2414 if slowpath:
2429 if slowpath:
2415 for path in match.files():
2430 for path in match.files():
2416 if path == '.' or path in repo.store:
2431 if path == '.' or path in repo.store:
2417 break
2432 break
2418 else:
2433 else:
2419 slowpath = False
2434 slowpath = False
2420
2435
2421 fpats = ('_patsfollow', '_patsfollowfirst')
2436 fpats = ('_patsfollow', '_patsfollowfirst')
2422 fnopats = (('_ancestors', '_fancestors'),
2437 fnopats = (('_ancestors', '_fancestors'),
2423 ('_descendants', '_fdescendants'))
2438 ('_descendants', '_fdescendants'))
2424 if slowpath:
2439 if slowpath:
2425 # See walkchangerevs() slow path.
2440 # See walkchangerevs() slow path.
2426 #
2441 #
2427 # pats/include/exclude cannot be represented as separate
2442 # pats/include/exclude cannot be represented as separate
2428 # revset expressions as their filtering logic applies at file
2443 # revset expressions as their filtering logic applies at file
2429 # level. For instance "-I a -X a" matches a revision touching
2444 # level. For instance "-I a -X a" matches a revision touching
2430 # "a" and "b" while "file(a) and not file(b)" does
2445 # "a" and "b" while "file(a) and not file(b)" does
2431 # not. Besides, filesets are evaluated against the working
2446 # not. Besides, filesets are evaluated against the working
2432 # directory.
2447 # directory.
2433 matchargs = ['r:', 'd:relpath']
2448 matchargs = ['r:', 'd:relpath']
2434 for p in pats:
2449 for p in pats:
2435 matchargs.append('p:' + p)
2450 matchargs.append('p:' + p)
2436 for p in opts.get('include', []):
2451 for p in opts.get('include', []):
2437 matchargs.append('i:' + p)
2452 matchargs.append('i:' + p)
2438 for p in opts.get('exclude', []):
2453 for p in opts.get('exclude', []):
2439 matchargs.append('x:' + p)
2454 matchargs.append('x:' + p)
2440 opts['_matchfiles'] = matchargs
2455 opts['_matchfiles'] = matchargs
2441 if follow:
2456 if follow:
2442 opts[fnopats[0][followfirst]] = '.'
2457 opts[fnopats[0][followfirst]] = '.'
2443 else:
2458 else:
2444 if follow:
2459 if follow:
2445 if pats:
2460 if pats:
2446 # follow() revset interprets its file argument as a
2461 # follow() revset interprets its file argument as a
2447 # manifest entry, so use match.files(), not pats.
2462 # manifest entry, so use match.files(), not pats.
2448 opts[fpats[followfirst]] = list(match.files())
2463 opts[fpats[followfirst]] = list(match.files())
2449 else:
2464 else:
2450 op = fnopats[followdescendants][followfirst]
2465 op = fnopats[followdescendants][followfirst]
2451 opts[op] = 'rev(%d)' % startrev
2466 opts[op] = 'rev(%d)' % startrev
2452 else:
2467 else:
2453 opts['_patslog'] = list(pats)
2468 opts['_patslog'] = list(pats)
2454
2469
2455 filematcher = None
2470 filematcher = None
2456 if opts.get('patch') or opts.get('stat'):
2471 if opts.get('patch') or opts.get('stat'):
2457 # When following files, track renames via a special matcher.
2472 # When following files, track renames via a special matcher.
2458 # If we're forced to take the slowpath it means we're following
2473 # If we're forced to take the slowpath it means we're following
2459 # at least one pattern/directory, so don't bother with rename tracking.
2474 # at least one pattern/directory, so don't bother with rename tracking.
2460 if follow and not match.always() and not slowpath:
2475 if follow and not match.always() and not slowpath:
2461 # _makefollowlogfilematcher expects its files argument to be
2476 # _makefollowlogfilematcher expects its files argument to be
2462 # relative to the repo root, so use match.files(), not pats.
2477 # relative to the repo root, so use match.files(), not pats.
2463 filematcher = _makefollowlogfilematcher(repo, match.files(),
2478 filematcher = _makefollowlogfilematcher(repo, match.files(),
2464 followfirst)
2479 followfirst)
2465 else:
2480 else:
2466 filematcher = _makenofollowlogfilematcher(repo, pats, opts)
2481 filematcher = _makenofollowlogfilematcher(repo, pats, opts)
2467 if filematcher is None:
2482 if filematcher is None:
2468 filematcher = lambda rev: match
2483 filematcher = lambda rev: match
2469
2484
2470 expr = []
2485 expr = []
2471 for op, val in sorted(opts.iteritems()):
2486 for op, val in sorted(opts.iteritems()):
2472 if not val:
2487 if not val:
2473 continue
2488 continue
2474 if op not in _opt2logrevset:
2489 if op not in _opt2logrevset:
2475 continue
2490 continue
2476 revop, listop = _opt2logrevset[op]
2491 revop, listop = _opt2logrevset[op]
2477 if revop and '%' not in revop:
2492 if revop and '%' not in revop:
2478 expr.append(revop)
2493 expr.append(revop)
2479 elif not listop:
2494 elif not listop:
2480 expr.append(revsetlang.formatspec(revop, val))
2495 expr.append(revsetlang.formatspec(revop, val))
2481 else:
2496 else:
2482 if revop:
2497 if revop:
2483 val = [revsetlang.formatspec(revop, v) for v in val]
2498 val = [revsetlang.formatspec(revop, v) for v in val]
2484 expr.append(revsetlang.formatspec(listop, val))
2499 expr.append(revsetlang.formatspec(listop, val))
2485
2500
2486 if expr:
2501 if expr:
2487 expr = '(' + ' and '.join(expr) + ')'
2502 expr = '(' + ' and '.join(expr) + ')'
2488 else:
2503 else:
2489 expr = None
2504 expr = None
2490 return expr, filematcher
2505 return expr, filematcher
2491
2506
2492 def _logrevs(repo, opts):
2507 def _logrevs(repo, opts):
2493 # Default --rev value depends on --follow but --follow behavior
2508 # Default --rev value depends on --follow but --follow behavior
2494 # depends on revisions resolved from --rev...
2509 # depends on revisions resolved from --rev...
2495 follow = opts.get('follow') or opts.get('follow_first')
2510 follow = opts.get('follow') or opts.get('follow_first')
2496 if opts.get('rev'):
2511 if opts.get('rev'):
2497 revs = scmutil.revrange(repo, opts['rev'])
2512 revs = scmutil.revrange(repo, opts['rev'])
2498 elif follow and repo.dirstate.p1() == nullid:
2513 elif follow and repo.dirstate.p1() == nullid:
2499 revs = smartset.baseset()
2514 revs = smartset.baseset()
2500 elif follow:
2515 elif follow:
2501 revs = repo.revs('reverse(:.)')
2516 revs = repo.revs('reverse(:.)')
2502 else:
2517 else:
2503 revs = smartset.spanset(repo)
2518 revs = smartset.spanset(repo)
2504 revs.reverse()
2519 revs.reverse()
2505 return revs
2520 return revs
2506
2521
2507 def getlogrevs(repo, pats, opts):
2522 def getlogrevs(repo, pats, opts):
2508 """Return (revs, filematcher) where revs is a smartset
2523 """Return (revs, filematcher) where revs is a smartset
2509
2524
2510 If --stat or --patch is not passed, filematcher is None. Otherwise it
2525 If --stat or --patch is not passed, filematcher is None. Otherwise it
2511 is a callable taking a revision number and returning a match objects
2526 is a callable taking a revision number and returning a match objects
2512 filtering the files to be detailed when displaying the revision.
2527 filtering the files to be detailed when displaying the revision.
2513 """
2528 """
2514 limit = loglimit(opts)
2529 limit = loglimit(opts)
2515 revs = _logrevs(repo, opts)
2530 revs = _logrevs(repo, opts)
2516 if not revs:
2531 if not revs:
2517 return smartset.baseset(), None
2532 return smartset.baseset(), None
2518 expr, filematcher = _makelogrevset(repo, pats, opts, revs)
2533 expr, filematcher = _makelogrevset(repo, pats, opts, revs)
2519 if opts.get('graph') and opts.get('rev'):
2534 if opts.get('graph') and opts.get('rev'):
2520 # User-specified revs might be unsorted, but don't sort before
2535 # User-specified revs might be unsorted, but don't sort before
2521 # _makelogrevset because it might depend on the order of revs
2536 # _makelogrevset because it might depend on the order of revs
2522 if not (revs.isdescending() or revs.istopo()):
2537 if not (revs.isdescending() or revs.istopo()):
2523 revs.sort(reverse=True)
2538 revs.sort(reverse=True)
2524 if expr:
2539 if expr:
2525 matcher = revset.match(None, expr)
2540 matcher = revset.match(None, expr)
2526 revs = matcher(repo, revs)
2541 revs = matcher(repo, revs)
2527 if limit is not None:
2542 if limit is not None:
2528 revs = revs.slice(0, limit)
2543 revs = revs.slice(0, limit)
2529 return revs, filematcher
2544 return revs, filematcher
2530
2545
2531 def _parselinerangelogopt(repo, opts):
2546 def _parselinerangelogopt(repo, opts):
2532 """Parse --line-range log option and return a list of tuples (filename,
2547 """Parse --line-range log option and return a list of tuples (filename,
2533 (fromline, toline)).
2548 (fromline, toline)).
2534 """
2549 """
2535 linerangebyfname = []
2550 linerangebyfname = []
2536 for pat in opts.get('line_range', []):
2551 for pat in opts.get('line_range', []):
2537 try:
2552 try:
2538 pat, linerange = pat.rsplit(',', 1)
2553 pat, linerange = pat.rsplit(',', 1)
2539 except ValueError:
2554 except ValueError:
2540 raise error.Abort(_('malformatted line-range pattern %s') % pat)
2555 raise error.Abort(_('malformatted line-range pattern %s') % pat)
2541 try:
2556 try:
2542 fromline, toline = map(int, linerange.split(':'))
2557 fromline, toline = map(int, linerange.split(':'))
2543 except ValueError:
2558 except ValueError:
2544 raise error.Abort(_("invalid line range for %s") % pat)
2559 raise error.Abort(_("invalid line range for %s") % pat)
2545 msg = _("line range pattern '%s' must match exactly one file") % pat
2560 msg = _("line range pattern '%s' must match exactly one file") % pat
2546 fname = scmutil.parsefollowlinespattern(repo, None, pat, msg)
2561 fname = scmutil.parsefollowlinespattern(repo, None, pat, msg)
2547 linerangebyfname.append(
2562 linerangebyfname.append(
2548 (fname, util.processlinerange(fromline, toline)))
2563 (fname, util.processlinerange(fromline, toline)))
2549 return linerangebyfname
2564 return linerangebyfname
2550
2565
2551 def getloglinerangerevs(repo, userrevs, opts):
2566 def getloglinerangerevs(repo, userrevs, opts):
2552 """Return (revs, filematcher, hunksfilter).
2567 """Return (revs, filematcher, hunksfilter).
2553
2568
2554 "revs" are revisions obtained by processing "line-range" log options and
2569 "revs" are revisions obtained by processing "line-range" log options and
2555 walking block ancestors of each specified file/line-range.
2570 walking block ancestors of each specified file/line-range.
2556
2571
2557 "filematcher(rev) -> match" is a factory function returning a match object
2572 "filematcher(rev) -> match" is a factory function returning a match object
2558 for a given revision for file patterns specified in --line-range option.
2573 for a given revision for file patterns specified in --line-range option.
2559 If neither --stat nor --patch options are passed, "filematcher" is None.
2574 If neither --stat nor --patch options are passed, "filematcher" is None.
2560
2575
2561 "hunksfilter(rev) -> filterfn(fctx, hunks)" is a factory function
2576 "hunksfilter(rev) -> filterfn(fctx, hunks)" is a factory function
2562 returning a hunks filtering function.
2577 returning a hunks filtering function.
2563 If neither --stat nor --patch options are passed, "filterhunks" is None.
2578 If neither --stat nor --patch options are passed, "filterhunks" is None.
2564 """
2579 """
2565 wctx = repo[None]
2580 wctx = repo[None]
2566
2581
2567 # Two-levels map of "rev -> file ctx -> [line range]".
2582 # Two-levels map of "rev -> file ctx -> [line range]".
2568 linerangesbyrev = {}
2583 linerangesbyrev = {}
2569 for fname, (fromline, toline) in _parselinerangelogopt(repo, opts):
2584 for fname, (fromline, toline) in _parselinerangelogopt(repo, opts):
2570 if fname not in wctx:
2585 if fname not in wctx:
2571 raise error.Abort(_('cannot follow file not in parent '
2586 raise error.Abort(_('cannot follow file not in parent '
2572 'revision: "%s"') % fname)
2587 'revision: "%s"') % fname)
2573 fctx = wctx.filectx(fname)
2588 fctx = wctx.filectx(fname)
2574 for fctx, linerange in dagop.blockancestors(fctx, fromline, toline):
2589 for fctx, linerange in dagop.blockancestors(fctx, fromline, toline):
2575 rev = fctx.introrev()
2590 rev = fctx.introrev()
2576 if rev not in userrevs:
2591 if rev not in userrevs:
2577 continue
2592 continue
2578 linerangesbyrev.setdefault(
2593 linerangesbyrev.setdefault(
2579 rev, {}).setdefault(
2594 rev, {}).setdefault(
2580 fctx.path(), []).append(linerange)
2595 fctx.path(), []).append(linerange)
2581
2596
2582 filematcher = None
2597 filematcher = None
2583 hunksfilter = None
2598 hunksfilter = None
2584 if opts.get('patch') or opts.get('stat'):
2599 if opts.get('patch') or opts.get('stat'):
2585
2600
2586 def nofilterhunksfn(fctx, hunks):
2601 def nofilterhunksfn(fctx, hunks):
2587 return hunks
2602 return hunks
2588
2603
2589 def hunksfilter(rev):
2604 def hunksfilter(rev):
2590 fctxlineranges = linerangesbyrev.get(rev)
2605 fctxlineranges = linerangesbyrev.get(rev)
2591 if fctxlineranges is None:
2606 if fctxlineranges is None:
2592 return nofilterhunksfn
2607 return nofilterhunksfn
2593
2608
2594 def filterfn(fctx, hunks):
2609 def filterfn(fctx, hunks):
2595 lineranges = fctxlineranges.get(fctx.path())
2610 lineranges = fctxlineranges.get(fctx.path())
2596 if lineranges is not None:
2611 if lineranges is not None:
2597 for hr, lines in hunks:
2612 for hr, lines in hunks:
2598 if hr is None: # binary
2613 if hr is None: # binary
2599 yield hr, lines
2614 yield hr, lines
2600 continue
2615 continue
2601 if any(mdiff.hunkinrange(hr[2:], lr)
2616 if any(mdiff.hunkinrange(hr[2:], lr)
2602 for lr in lineranges):
2617 for lr in lineranges):
2603 yield hr, lines
2618 yield hr, lines
2604 else:
2619 else:
2605 for hunk in hunks:
2620 for hunk in hunks:
2606 yield hunk
2621 yield hunk
2607
2622
2608 return filterfn
2623 return filterfn
2609
2624
2610 def filematcher(rev):
2625 def filematcher(rev):
2611 files = list(linerangesbyrev.get(rev, []))
2626 files = list(linerangesbyrev.get(rev, []))
2612 return scmutil.matchfiles(repo, files)
2627 return scmutil.matchfiles(repo, files)
2613
2628
2614 revs = sorted(linerangesbyrev, reverse=True)
2629 revs = sorted(linerangesbyrev, reverse=True)
2615
2630
2616 return revs, filematcher, hunksfilter
2631 return revs, filematcher, hunksfilter
2617
2632
2618 def _graphnodeformatter(ui, displayer):
2633 def _graphnodeformatter(ui, displayer):
2619 spec = ui.config('ui', 'graphnodetemplate')
2634 spec = ui.config('ui', 'graphnodetemplate')
2620 if not spec:
2635 if not spec:
2621 return templatekw.showgraphnode # fast path for "{graphnode}"
2636 return templatekw.showgraphnode # fast path for "{graphnode}"
2622
2637
2623 spec = templater.unquotestring(spec)
2638 spec = templater.unquotestring(spec)
2624 tres = formatter.templateresources(ui)
2639 tres = formatter.templateresources(ui)
2625 if isinstance(displayer, changeset_templater):
2640 if isinstance(displayer, changeset_templater):
2626 tres['cache'] = displayer.cache # reuse cache of slow templates
2641 tres['cache'] = displayer.cache # reuse cache of slow templates
2627 templ = formatter.maketemplater(ui, spec, defaults=templatekw.keywords,
2642 templ = formatter.maketemplater(ui, spec, defaults=templatekw.keywords,
2628 resources=tres)
2643 resources=tres)
2629 def formatnode(repo, ctx):
2644 def formatnode(repo, ctx):
2630 props = {'ctx': ctx, 'repo': repo, 'revcache': {}}
2645 props = {'ctx': ctx, 'repo': repo, 'revcache': {}}
2631 return templ.render(props)
2646 return templ.render(props)
2632 return formatnode
2647 return formatnode
2633
2648
2634 def displaygraph(ui, repo, dag, displayer, edgefn, getrenamed=None,
2649 def displaygraph(ui, repo, dag, displayer, edgefn, getrenamed=None,
2635 filematcher=None, props=None):
2650 filematcher=None, props=None):
2636 props = props or {}
2651 props = props or {}
2637 formatnode = _graphnodeformatter(ui, displayer)
2652 formatnode = _graphnodeformatter(ui, displayer)
2638 state = graphmod.asciistate()
2653 state = graphmod.asciistate()
2639 styles = state['styles']
2654 styles = state['styles']
2640
2655
2641 # only set graph styling if HGPLAIN is not set.
2656 # only set graph styling if HGPLAIN is not set.
2642 if ui.plain('graph'):
2657 if ui.plain('graph'):
2643 # set all edge styles to |, the default pre-3.8 behaviour
2658 # set all edge styles to |, the default pre-3.8 behaviour
2644 styles.update(dict.fromkeys(styles, '|'))
2659 styles.update(dict.fromkeys(styles, '|'))
2645 else:
2660 else:
2646 edgetypes = {
2661 edgetypes = {
2647 'parent': graphmod.PARENT,
2662 'parent': graphmod.PARENT,
2648 'grandparent': graphmod.GRANDPARENT,
2663 'grandparent': graphmod.GRANDPARENT,
2649 'missing': graphmod.MISSINGPARENT
2664 'missing': graphmod.MISSINGPARENT
2650 }
2665 }
2651 for name, key in edgetypes.items():
2666 for name, key in edgetypes.items():
2652 # experimental config: experimental.graphstyle.*
2667 # experimental config: experimental.graphstyle.*
2653 styles[key] = ui.config('experimental', 'graphstyle.%s' % name,
2668 styles[key] = ui.config('experimental', 'graphstyle.%s' % name,
2654 styles[key])
2669 styles[key])
2655 if not styles[key]:
2670 if not styles[key]:
2656 styles[key] = None
2671 styles[key] = None
2657
2672
2658 # experimental config: experimental.graphshorten
2673 # experimental config: experimental.graphshorten
2659 state['graphshorten'] = ui.configbool('experimental', 'graphshorten')
2674 state['graphshorten'] = ui.configbool('experimental', 'graphshorten')
2660
2675
2661 for rev, type, ctx, parents in dag:
2676 for rev, type, ctx, parents in dag:
2662 char = formatnode(repo, ctx)
2677 char = formatnode(repo, ctx)
2663 copies = None
2678 copies = None
2664 if getrenamed and ctx.rev():
2679 if getrenamed and ctx.rev():
2665 copies = []
2680 copies = []
2666 for fn in ctx.files():
2681 for fn in ctx.files():
2667 rename = getrenamed(fn, ctx.rev())
2682 rename = getrenamed(fn, ctx.rev())
2668 if rename:
2683 if rename:
2669 copies.append((fn, rename[0]))
2684 copies.append((fn, rename[0]))
2670 revmatchfn = None
2685 revmatchfn = None
2671 if filematcher is not None:
2686 if filematcher is not None:
2672 revmatchfn = filematcher(ctx.rev())
2687 revmatchfn = filematcher(ctx.rev())
2673 edges = edgefn(type, char, state, rev, parents)
2688 edges = edgefn(type, char, state, rev, parents)
2674 firstedge = next(edges)
2689 firstedge = next(edges)
2675 width = firstedge[2]
2690 width = firstedge[2]
2676 displayer.show(ctx, copies=copies, matchfn=revmatchfn,
2691 displayer.show(ctx, copies=copies, matchfn=revmatchfn,
2677 _graphwidth=width, **pycompat.strkwargs(props))
2692 _graphwidth=width, **pycompat.strkwargs(props))
2678 lines = displayer.hunk.pop(rev).split('\n')
2693 lines = displayer.hunk.pop(rev).split('\n')
2679 if not lines[-1]:
2694 if not lines[-1]:
2680 del lines[-1]
2695 del lines[-1]
2681 displayer.flush(ctx)
2696 displayer.flush(ctx)
2682 for type, char, width, coldata in itertools.chain([firstedge], edges):
2697 for type, char, width, coldata in itertools.chain([firstedge], edges):
2683 graphmod.ascii(ui, state, type, char, lines, coldata)
2698 graphmod.ascii(ui, state, type, char, lines, coldata)
2684 lines = []
2699 lines = []
2685 displayer.close()
2700 displayer.close()
2686
2701
2687 def graphlog(ui, repo, revs, filematcher, opts):
2702 def graphlog(ui, repo, revs, filematcher, opts):
2688 # Parameters are identical to log command ones
2703 # Parameters are identical to log command ones
2689 revdag = graphmod.dagwalker(repo, revs)
2704 revdag = graphmod.dagwalker(repo, revs)
2690
2705
2691 getrenamed = None
2706 getrenamed = None
2692 if opts.get('copies'):
2707 if opts.get('copies'):
2693 endrev = None
2708 endrev = None
2694 if opts.get('rev'):
2709 if opts.get('rev'):
2695 endrev = scmutil.revrange(repo, opts.get('rev')).max() + 1
2710 endrev = scmutil.revrange(repo, opts.get('rev')).max() + 1
2696 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
2711 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
2697
2712
2698 ui.pager('log')
2713 ui.pager('log')
2699 displayer = show_changeset(ui, repo, opts, buffered=True)
2714 displayer = show_changeset(ui, repo, opts, buffered=True)
2700 displaygraph(ui, repo, revdag, displayer, graphmod.asciiedges, getrenamed,
2715 displaygraph(ui, repo, revdag, displayer, graphmod.asciiedges, getrenamed,
2701 filematcher)
2716 filematcher)
2702
2717
2703 def checkunsupportedgraphflags(pats, opts):
2718 def checkunsupportedgraphflags(pats, opts):
2704 for op in ["newest_first"]:
2719 for op in ["newest_first"]:
2705 if op in opts and opts[op]:
2720 if op in opts and opts[op]:
2706 raise error.Abort(_("-G/--graph option is incompatible with --%s")
2721 raise error.Abort(_("-G/--graph option is incompatible with --%s")
2707 % op.replace("_", "-"))
2722 % op.replace("_", "-"))
2708
2723
2709 def graphrevs(repo, nodes, opts):
2724 def graphrevs(repo, nodes, opts):
2710 limit = loglimit(opts)
2725 limit = loglimit(opts)
2711 nodes.reverse()
2726 nodes.reverse()
2712 if limit is not None:
2727 if limit is not None:
2713 nodes = nodes[:limit]
2728 nodes = nodes[:limit]
2714 return graphmod.nodes(repo, nodes)
2729 return graphmod.nodes(repo, nodes)
2715
2730
2716 def add(ui, repo, match, prefix, explicitonly, **opts):
2731 def add(ui, repo, match, prefix, explicitonly, **opts):
2717 join = lambda f: os.path.join(prefix, f)
2732 join = lambda f: os.path.join(prefix, f)
2718 bad = []
2733 bad = []
2719
2734
2720 badfn = lambda x, y: bad.append(x) or match.bad(x, y)
2735 badfn = lambda x, y: bad.append(x) or match.bad(x, y)
2721 names = []
2736 names = []
2722 wctx = repo[None]
2737 wctx = repo[None]
2723 cca = None
2738 cca = None
2724 abort, warn = scmutil.checkportabilityalert(ui)
2739 abort, warn = scmutil.checkportabilityalert(ui)
2725 if abort or warn:
2740 if abort or warn:
2726 cca = scmutil.casecollisionauditor(ui, abort, repo.dirstate)
2741 cca = scmutil.casecollisionauditor(ui, abort, repo.dirstate)
2727
2742
2728 badmatch = matchmod.badmatch(match, badfn)
2743 badmatch = matchmod.badmatch(match, badfn)
2729 dirstate = repo.dirstate
2744 dirstate = repo.dirstate
2730 # We don't want to just call wctx.walk here, since it would return a lot of
2745 # We don't want to just call wctx.walk here, since it would return a lot of
2731 # clean files, which we aren't interested in and takes time.
2746 # clean files, which we aren't interested in and takes time.
2732 for f in sorted(dirstate.walk(badmatch, subrepos=sorted(wctx.substate),
2747 for f in sorted(dirstate.walk(badmatch, subrepos=sorted(wctx.substate),
2733 unknown=True, ignored=False, full=False)):
2748 unknown=True, ignored=False, full=False)):
2734 exact = match.exact(f)
2749 exact = match.exact(f)
2735 if exact or not explicitonly and f not in wctx and repo.wvfs.lexists(f):
2750 if exact or not explicitonly and f not in wctx and repo.wvfs.lexists(f):
2736 if cca:
2751 if cca:
2737 cca(f)
2752 cca(f)
2738 names.append(f)
2753 names.append(f)
2739 if ui.verbose or not exact:
2754 if ui.verbose or not exact:
2740 ui.status(_('adding %s\n') % match.rel(f))
2755 ui.status(_('adding %s\n') % match.rel(f))
2741
2756
2742 for subpath in sorted(wctx.substate):
2757 for subpath in sorted(wctx.substate):
2743 sub = wctx.sub(subpath)
2758 sub = wctx.sub(subpath)
2744 try:
2759 try:
2745 submatch = matchmod.subdirmatcher(subpath, match)
2760 submatch = matchmod.subdirmatcher(subpath, match)
2746 if opts.get(r'subrepos'):
2761 if opts.get(r'subrepos'):
2747 bad.extend(sub.add(ui, submatch, prefix, False, **opts))
2762 bad.extend(sub.add(ui, submatch, prefix, False, **opts))
2748 else:
2763 else:
2749 bad.extend(sub.add(ui, submatch, prefix, True, **opts))
2764 bad.extend(sub.add(ui, submatch, prefix, True, **opts))
2750 except error.LookupError:
2765 except error.LookupError:
2751 ui.status(_("skipping missing subrepository: %s\n")
2766 ui.status(_("skipping missing subrepository: %s\n")
2752 % join(subpath))
2767 % join(subpath))
2753
2768
2754 if not opts.get(r'dry_run'):
2769 if not opts.get(r'dry_run'):
2755 rejected = wctx.add(names, prefix)
2770 rejected = wctx.add(names, prefix)
2756 bad.extend(f for f in rejected if f in match.files())
2771 bad.extend(f for f in rejected if f in match.files())
2757 return bad
2772 return bad
2758
2773
2759 def addwebdirpath(repo, serverpath, webconf):
2774 def addwebdirpath(repo, serverpath, webconf):
2760 webconf[serverpath] = repo.root
2775 webconf[serverpath] = repo.root
2761 repo.ui.debug('adding %s = %s\n' % (serverpath, repo.root))
2776 repo.ui.debug('adding %s = %s\n' % (serverpath, repo.root))
2762
2777
2763 for r in repo.revs('filelog("path:.hgsub")'):
2778 for r in repo.revs('filelog("path:.hgsub")'):
2764 ctx = repo[r]
2779 ctx = repo[r]
2765 for subpath in ctx.substate:
2780 for subpath in ctx.substate:
2766 ctx.sub(subpath).addwebdirpath(serverpath, webconf)
2781 ctx.sub(subpath).addwebdirpath(serverpath, webconf)
2767
2782
2768 def forget(ui, repo, match, prefix, explicitonly):
2783 def forget(ui, repo, match, prefix, explicitonly):
2769 join = lambda f: os.path.join(prefix, f)
2784 join = lambda f: os.path.join(prefix, f)
2770 bad = []
2785 bad = []
2771 badfn = lambda x, y: bad.append(x) or match.bad(x, y)
2786 badfn = lambda x, y: bad.append(x) or match.bad(x, y)
2772 wctx = repo[None]
2787 wctx = repo[None]
2773 forgot = []
2788 forgot = []
2774
2789
2775 s = repo.status(match=matchmod.badmatch(match, badfn), clean=True)
2790 s = repo.status(match=matchmod.badmatch(match, badfn), clean=True)
2776 forget = sorted(s.modified + s.added + s.deleted + s.clean)
2791 forget = sorted(s.modified + s.added + s.deleted + s.clean)
2777 if explicitonly:
2792 if explicitonly:
2778 forget = [f for f in forget if match.exact(f)]
2793 forget = [f for f in forget if match.exact(f)]
2779
2794
2780 for subpath in sorted(wctx.substate):
2795 for subpath in sorted(wctx.substate):
2781 sub = wctx.sub(subpath)
2796 sub = wctx.sub(subpath)
2782 try:
2797 try:
2783 submatch = matchmod.subdirmatcher(subpath, match)
2798 submatch = matchmod.subdirmatcher(subpath, match)
2784 subbad, subforgot = sub.forget(submatch, prefix)
2799 subbad, subforgot = sub.forget(submatch, prefix)
2785 bad.extend([subpath + '/' + f for f in subbad])
2800 bad.extend([subpath + '/' + f for f in subbad])
2786 forgot.extend([subpath + '/' + f for f in subforgot])
2801 forgot.extend([subpath + '/' + f for f in subforgot])
2787 except error.LookupError:
2802 except error.LookupError:
2788 ui.status(_("skipping missing subrepository: %s\n")
2803 ui.status(_("skipping missing subrepository: %s\n")
2789 % join(subpath))
2804 % join(subpath))
2790
2805
2791 if not explicitonly:
2806 if not explicitonly:
2792 for f in match.files():
2807 for f in match.files():
2793 if f not in repo.dirstate and not repo.wvfs.isdir(f):
2808 if f not in repo.dirstate and not repo.wvfs.isdir(f):
2794 if f not in forgot:
2809 if f not in forgot:
2795 if repo.wvfs.exists(f):
2810 if repo.wvfs.exists(f):
2796 # Don't complain if the exact case match wasn't given.
2811 # Don't complain if the exact case match wasn't given.
2797 # But don't do this until after checking 'forgot', so
2812 # But don't do this until after checking 'forgot', so
2798 # that subrepo files aren't normalized, and this op is
2813 # that subrepo files aren't normalized, and this op is
2799 # purely from data cached by the status walk above.
2814 # purely from data cached by the status walk above.
2800 if repo.dirstate.normalize(f) in repo.dirstate:
2815 if repo.dirstate.normalize(f) in repo.dirstate:
2801 continue
2816 continue
2802 ui.warn(_('not removing %s: '
2817 ui.warn(_('not removing %s: '
2803 'file is already untracked\n')
2818 'file is already untracked\n')
2804 % match.rel(f))
2819 % match.rel(f))
2805 bad.append(f)
2820 bad.append(f)
2806
2821
2807 for f in forget:
2822 for f in forget:
2808 if ui.verbose or not match.exact(f):
2823 if ui.verbose or not match.exact(f):
2809 ui.status(_('removing %s\n') % match.rel(f))
2824 ui.status(_('removing %s\n') % match.rel(f))
2810
2825
2811 rejected = wctx.forget(forget, prefix)
2826 rejected = wctx.forget(forget, prefix)
2812 bad.extend(f for f in rejected if f in match.files())
2827 bad.extend(f for f in rejected if f in match.files())
2813 forgot.extend(f for f in forget if f not in rejected)
2828 forgot.extend(f for f in forget if f not in rejected)
2814 return bad, forgot
2829 return bad, forgot
2815
2830
2816 def files(ui, ctx, m, fm, fmt, subrepos):
2831 def files(ui, ctx, m, fm, fmt, subrepos):
2817 rev = ctx.rev()
2832 rev = ctx.rev()
2818 ret = 1
2833 ret = 1
2819 ds = ctx.repo().dirstate
2834 ds = ctx.repo().dirstate
2820
2835
2821 for f in ctx.matches(m):
2836 for f in ctx.matches(m):
2822 if rev is None and ds[f] == 'r':
2837 if rev is None and ds[f] == 'r':
2823 continue
2838 continue
2824 fm.startitem()
2839 fm.startitem()
2825 if ui.verbose:
2840 if ui.verbose:
2826 fc = ctx[f]
2841 fc = ctx[f]
2827 fm.write('size flags', '% 10d % 1s ', fc.size(), fc.flags())
2842 fm.write('size flags', '% 10d % 1s ', fc.size(), fc.flags())
2828 fm.data(abspath=f)
2843 fm.data(abspath=f)
2829 fm.write('path', fmt, m.rel(f))
2844 fm.write('path', fmt, m.rel(f))
2830 ret = 0
2845 ret = 0
2831
2846
2832 for subpath in sorted(ctx.substate):
2847 for subpath in sorted(ctx.substate):
2833 submatch = matchmod.subdirmatcher(subpath, m)
2848 submatch = matchmod.subdirmatcher(subpath, m)
2834 if (subrepos or m.exact(subpath) or any(submatch.files())):
2849 if (subrepos or m.exact(subpath) or any(submatch.files())):
2835 sub = ctx.sub(subpath)
2850 sub = ctx.sub(subpath)
2836 try:
2851 try:
2837 recurse = m.exact(subpath) or subrepos
2852 recurse = m.exact(subpath) or subrepos
2838 if sub.printfiles(ui, submatch, fm, fmt, recurse) == 0:
2853 if sub.printfiles(ui, submatch, fm, fmt, recurse) == 0:
2839 ret = 0
2854 ret = 0
2840 except error.LookupError:
2855 except error.LookupError:
2841 ui.status(_("skipping missing subrepository: %s\n")
2856 ui.status(_("skipping missing subrepository: %s\n")
2842 % m.abs(subpath))
2857 % m.abs(subpath))
2843
2858
2844 return ret
2859 return ret
2845
2860
2846 def remove(ui, repo, m, prefix, after, force, subrepos, warnings=None):
2861 def remove(ui, repo, m, prefix, after, force, subrepos, warnings=None):
2847 join = lambda f: os.path.join(prefix, f)
2862 join = lambda f: os.path.join(prefix, f)
2848 ret = 0
2863 ret = 0
2849 s = repo.status(match=m, clean=True)
2864 s = repo.status(match=m, clean=True)
2850 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
2865 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
2851
2866
2852 wctx = repo[None]
2867 wctx = repo[None]
2853
2868
2854 if warnings is None:
2869 if warnings is None:
2855 warnings = []
2870 warnings = []
2856 warn = True
2871 warn = True
2857 else:
2872 else:
2858 warn = False
2873 warn = False
2859
2874
2860 subs = sorted(wctx.substate)
2875 subs = sorted(wctx.substate)
2861 total = len(subs)
2876 total = len(subs)
2862 count = 0
2877 count = 0
2863 for subpath in subs:
2878 for subpath in subs:
2864 count += 1
2879 count += 1
2865 submatch = matchmod.subdirmatcher(subpath, m)
2880 submatch = matchmod.subdirmatcher(subpath, m)
2866 if subrepos or m.exact(subpath) or any(submatch.files()):
2881 if subrepos or m.exact(subpath) or any(submatch.files()):
2867 ui.progress(_('searching'), count, total=total, unit=_('subrepos'))
2882 ui.progress(_('searching'), count, total=total, unit=_('subrepos'))
2868 sub = wctx.sub(subpath)
2883 sub = wctx.sub(subpath)
2869 try:
2884 try:
2870 if sub.removefiles(submatch, prefix, after, force, subrepos,
2885 if sub.removefiles(submatch, prefix, after, force, subrepos,
2871 warnings):
2886 warnings):
2872 ret = 1
2887 ret = 1
2873 except error.LookupError:
2888 except error.LookupError:
2874 warnings.append(_("skipping missing subrepository: %s\n")
2889 warnings.append(_("skipping missing subrepository: %s\n")
2875 % join(subpath))
2890 % join(subpath))
2876 ui.progress(_('searching'), None)
2891 ui.progress(_('searching'), None)
2877
2892
2878 # warn about failure to delete explicit files/dirs
2893 # warn about failure to delete explicit files/dirs
2879 deleteddirs = util.dirs(deleted)
2894 deleteddirs = util.dirs(deleted)
2880 files = m.files()
2895 files = m.files()
2881 total = len(files)
2896 total = len(files)
2882 count = 0
2897 count = 0
2883 for f in files:
2898 for f in files:
2884 def insubrepo():
2899 def insubrepo():
2885 for subpath in wctx.substate:
2900 for subpath in wctx.substate:
2886 if f.startswith(subpath + '/'):
2901 if f.startswith(subpath + '/'):
2887 return True
2902 return True
2888 return False
2903 return False
2889
2904
2890 count += 1
2905 count += 1
2891 ui.progress(_('deleting'), count, total=total, unit=_('files'))
2906 ui.progress(_('deleting'), count, total=total, unit=_('files'))
2892 isdir = f in deleteddirs or wctx.hasdir(f)
2907 isdir = f in deleteddirs or wctx.hasdir(f)
2893 if (f in repo.dirstate or isdir or f == '.'
2908 if (f in repo.dirstate or isdir or f == '.'
2894 or insubrepo() or f in subs):
2909 or insubrepo() or f in subs):
2895 continue
2910 continue
2896
2911
2897 if repo.wvfs.exists(f):
2912 if repo.wvfs.exists(f):
2898 if repo.wvfs.isdir(f):
2913 if repo.wvfs.isdir(f):
2899 warnings.append(_('not removing %s: no tracked files\n')
2914 warnings.append(_('not removing %s: no tracked files\n')
2900 % m.rel(f))
2915 % m.rel(f))
2901 else:
2916 else:
2902 warnings.append(_('not removing %s: file is untracked\n')
2917 warnings.append(_('not removing %s: file is untracked\n')
2903 % m.rel(f))
2918 % m.rel(f))
2904 # missing files will generate a warning elsewhere
2919 # missing files will generate a warning elsewhere
2905 ret = 1
2920 ret = 1
2906 ui.progress(_('deleting'), None)
2921 ui.progress(_('deleting'), None)
2907
2922
2908 if force:
2923 if force:
2909 list = modified + deleted + clean + added
2924 list = modified + deleted + clean + added
2910 elif after:
2925 elif after:
2911 list = deleted
2926 list = deleted
2912 remaining = modified + added + clean
2927 remaining = modified + added + clean
2913 total = len(remaining)
2928 total = len(remaining)
2914 count = 0
2929 count = 0
2915 for f in remaining:
2930 for f in remaining:
2916 count += 1
2931 count += 1
2917 ui.progress(_('skipping'), count, total=total, unit=_('files'))
2932 ui.progress(_('skipping'), count, total=total, unit=_('files'))
2918 if ui.verbose or (f in files):
2933 if ui.verbose or (f in files):
2919 warnings.append(_('not removing %s: file still exists\n')
2934 warnings.append(_('not removing %s: file still exists\n')
2920 % m.rel(f))
2935 % m.rel(f))
2921 ret = 1
2936 ret = 1
2922 ui.progress(_('skipping'), None)
2937 ui.progress(_('skipping'), None)
2923 else:
2938 else:
2924 list = deleted + clean
2939 list = deleted + clean
2925 total = len(modified) + len(added)
2940 total = len(modified) + len(added)
2926 count = 0
2941 count = 0
2927 for f in modified:
2942 for f in modified:
2928 count += 1
2943 count += 1
2929 ui.progress(_('skipping'), count, total=total, unit=_('files'))
2944 ui.progress(_('skipping'), count, total=total, unit=_('files'))
2930 warnings.append(_('not removing %s: file is modified (use -f'
2945 warnings.append(_('not removing %s: file is modified (use -f'
2931 ' to force removal)\n') % m.rel(f))
2946 ' to force removal)\n') % m.rel(f))
2932 ret = 1
2947 ret = 1
2933 for f in added:
2948 for f in added:
2934 count += 1
2949 count += 1
2935 ui.progress(_('skipping'), count, total=total, unit=_('files'))
2950 ui.progress(_('skipping'), count, total=total, unit=_('files'))
2936 warnings.append(_("not removing %s: file has been marked for add"
2951 warnings.append(_("not removing %s: file has been marked for add"
2937 " (use 'hg forget' to undo add)\n") % m.rel(f))
2952 " (use 'hg forget' to undo add)\n") % m.rel(f))
2938 ret = 1
2953 ret = 1
2939 ui.progress(_('skipping'), None)
2954 ui.progress(_('skipping'), None)
2940
2955
2941 list = sorted(list)
2956 list = sorted(list)
2942 total = len(list)
2957 total = len(list)
2943 count = 0
2958 count = 0
2944 for f in list:
2959 for f in list:
2945 count += 1
2960 count += 1
2946 if ui.verbose or not m.exact(f):
2961 if ui.verbose or not m.exact(f):
2947 ui.progress(_('deleting'), count, total=total, unit=_('files'))
2962 ui.progress(_('deleting'), count, total=total, unit=_('files'))
2948 ui.status(_('removing %s\n') % m.rel(f))
2963 ui.status(_('removing %s\n') % m.rel(f))
2949 ui.progress(_('deleting'), None)
2964 ui.progress(_('deleting'), None)
2950
2965
2951 with repo.wlock():
2966 with repo.wlock():
2952 if not after:
2967 if not after:
2953 for f in list:
2968 for f in list:
2954 if f in added:
2969 if f in added:
2955 continue # we never unlink added files on remove
2970 continue # we never unlink added files on remove
2956 repo.wvfs.unlinkpath(f, ignoremissing=True)
2971 repo.wvfs.unlinkpath(f, ignoremissing=True)
2957 repo[None].forget(list)
2972 repo[None].forget(list)
2958
2973
2959 if warn:
2974 if warn:
2960 for warning in warnings:
2975 for warning in warnings:
2961 ui.warn(warning)
2976 ui.warn(warning)
2962
2977
2963 return ret
2978 return ret
2964
2979
2965 def _updatecatformatter(fm, ctx, matcher, path, decode):
2980 def _updatecatformatter(fm, ctx, matcher, path, decode):
2966 """Hook for adding data to the formatter used by ``hg cat``.
2981 """Hook for adding data to the formatter used by ``hg cat``.
2967
2982
2968 Extensions (e.g., lfs) can wrap this to inject keywords/data, but must call
2983 Extensions (e.g., lfs) can wrap this to inject keywords/data, but must call
2969 this method first."""
2984 this method first."""
2970 data = ctx[path].data()
2985 data = ctx[path].data()
2971 if decode:
2986 if decode:
2972 data = ctx.repo().wwritedata(path, data)
2987 data = ctx.repo().wwritedata(path, data)
2973 fm.startitem()
2988 fm.startitem()
2974 fm.write('data', '%s', data)
2989 fm.write('data', '%s', data)
2975 fm.data(abspath=path, path=matcher.rel(path))
2990 fm.data(abspath=path, path=matcher.rel(path))
2976
2991
2977 def cat(ui, repo, ctx, matcher, basefm, fntemplate, prefix, **opts):
2992 def cat(ui, repo, ctx, matcher, basefm, fntemplate, prefix, **opts):
2978 err = 1
2993 err = 1
2979 opts = pycompat.byteskwargs(opts)
2994 opts = pycompat.byteskwargs(opts)
2980
2995
2981 def write(path):
2996 def write(path):
2982 filename = None
2997 filename = None
2983 if fntemplate:
2998 if fntemplate:
2984 filename = makefilename(repo, fntemplate, ctx.node(),
2999 filename = makefilename(repo, fntemplate, ctx.node(),
2985 pathname=os.path.join(prefix, path))
3000 pathname=os.path.join(prefix, path))
2986 # attempt to create the directory if it does not already exist
3001 # attempt to create the directory if it does not already exist
2987 try:
3002 try:
2988 os.makedirs(os.path.dirname(filename))
3003 os.makedirs(os.path.dirname(filename))
2989 except OSError:
3004 except OSError:
2990 pass
3005 pass
2991 with formatter.maybereopen(basefm, filename, opts) as fm:
3006 with formatter.maybereopen(basefm, filename, opts) as fm:
2992 _updatecatformatter(fm, ctx, matcher, path, opts.get('decode'))
3007 _updatecatformatter(fm, ctx, matcher, path, opts.get('decode'))
2993
3008
2994 # Automation often uses hg cat on single files, so special case it
3009 # Automation often uses hg cat on single files, so special case it
2995 # for performance to avoid the cost of parsing the manifest.
3010 # for performance to avoid the cost of parsing the manifest.
2996 if len(matcher.files()) == 1 and not matcher.anypats():
3011 if len(matcher.files()) == 1 and not matcher.anypats():
2997 file = matcher.files()[0]
3012 file = matcher.files()[0]
2998 mfl = repo.manifestlog
3013 mfl = repo.manifestlog
2999 mfnode = ctx.manifestnode()
3014 mfnode = ctx.manifestnode()
3000 try:
3015 try:
3001 if mfnode and mfl[mfnode].find(file)[0]:
3016 if mfnode and mfl[mfnode].find(file)[0]:
3002 write(file)
3017 write(file)
3003 return 0
3018 return 0
3004 except KeyError:
3019 except KeyError:
3005 pass
3020 pass
3006
3021
3007 for abs in ctx.walk(matcher):
3022 for abs in ctx.walk(matcher):
3008 write(abs)
3023 write(abs)
3009 err = 0
3024 err = 0
3010
3025
3011 for subpath in sorted(ctx.substate):
3026 for subpath in sorted(ctx.substate):
3012 sub = ctx.sub(subpath)
3027 sub = ctx.sub(subpath)
3013 try:
3028 try:
3014 submatch = matchmod.subdirmatcher(subpath, matcher)
3029 submatch = matchmod.subdirmatcher(subpath, matcher)
3015
3030
3016 if not sub.cat(submatch, basefm, fntemplate,
3031 if not sub.cat(submatch, basefm, fntemplate,
3017 os.path.join(prefix, sub._path),
3032 os.path.join(prefix, sub._path),
3018 **pycompat.strkwargs(opts)):
3033 **pycompat.strkwargs(opts)):
3019 err = 0
3034 err = 0
3020 except error.RepoLookupError:
3035 except error.RepoLookupError:
3021 ui.status(_("skipping missing subrepository: %s\n")
3036 ui.status(_("skipping missing subrepository: %s\n")
3022 % os.path.join(prefix, subpath))
3037 % os.path.join(prefix, subpath))
3023
3038
3024 return err
3039 return err
3025
3040
3026 def commit(ui, repo, commitfunc, pats, opts):
3041 def commit(ui, repo, commitfunc, pats, opts):
3027 '''commit the specified files or all outstanding changes'''
3042 '''commit the specified files or all outstanding changes'''
3028 date = opts.get('date')
3043 date = opts.get('date')
3029 if date:
3044 if date:
3030 opts['date'] = util.parsedate(date)
3045 opts['date'] = util.parsedate(date)
3031 message = logmessage(ui, opts)
3046 message = logmessage(ui, opts)
3032 matcher = scmutil.match(repo[None], pats, opts)
3047 matcher = scmutil.match(repo[None], pats, opts)
3033
3048
3034 dsguard = None
3049 dsguard = None
3035 # extract addremove carefully -- this function can be called from a command
3050 # extract addremove carefully -- this function can be called from a command
3036 # that doesn't support addremove
3051 # that doesn't support addremove
3037 if opts.get('addremove'):
3052 if opts.get('addremove'):
3038 dsguard = dirstateguard.dirstateguard(repo, 'commit')
3053 dsguard = dirstateguard.dirstateguard(repo, 'commit')
3039 with dsguard or util.nullcontextmanager():
3054 with dsguard or util.nullcontextmanager():
3040 if dsguard:
3055 if dsguard:
3041 if scmutil.addremove(repo, matcher, "", opts) != 0:
3056 if scmutil.addremove(repo, matcher, "", opts) != 0:
3042 raise error.Abort(
3057 raise error.Abort(
3043 _("failed to mark all new/missing files as added/removed"))
3058 _("failed to mark all new/missing files as added/removed"))
3044
3059
3045 return commitfunc(ui, repo, message, matcher, opts)
3060 return commitfunc(ui, repo, message, matcher, opts)
3046
3061
3047 def samefile(f, ctx1, ctx2):
3062 def samefile(f, ctx1, ctx2):
3048 if f in ctx1.manifest():
3063 if f in ctx1.manifest():
3049 a = ctx1.filectx(f)
3064 a = ctx1.filectx(f)
3050 if f in ctx2.manifest():
3065 if f in ctx2.manifest():
3051 b = ctx2.filectx(f)
3066 b = ctx2.filectx(f)
3052 return (not a.cmp(b)
3067 return (not a.cmp(b)
3053 and a.flags() == b.flags())
3068 and a.flags() == b.flags())
3054 else:
3069 else:
3055 return False
3070 return False
3056 else:
3071 else:
3057 return f not in ctx2.manifest()
3072 return f not in ctx2.manifest()
3058
3073
3059 def amend(ui, repo, old, extra, pats, opts):
3074 def amend(ui, repo, old, extra, pats, opts):
3060 # avoid cycle context -> subrepo -> cmdutil
3075 # avoid cycle context -> subrepo -> cmdutil
3061 from . import context
3076 from . import context
3062
3077
3063 # amend will reuse the existing user if not specified, but the obsolete
3078 # amend will reuse the existing user if not specified, but the obsolete
3064 # marker creation requires that the current user's name is specified.
3079 # marker creation requires that the current user's name is specified.
3065 if obsolete.isenabled(repo, obsolete.createmarkersopt):
3080 if obsolete.isenabled(repo, obsolete.createmarkersopt):
3066 ui.username() # raise exception if username not set
3081 ui.username() # raise exception if username not set
3067
3082
3068 ui.note(_('amending changeset %s\n') % old)
3083 ui.note(_('amending changeset %s\n') % old)
3069 base = old.p1()
3084 base = old.p1()
3070
3085
3071 with repo.wlock(), repo.lock(), repo.transaction('amend'):
3086 with repo.wlock(), repo.lock(), repo.transaction('amend'):
3072 # Participating changesets:
3087 # Participating changesets:
3073 #
3088 #
3074 # wctx o - workingctx that contains changes from working copy
3089 # wctx o - workingctx that contains changes from working copy
3075 # | to go into amending commit
3090 # | to go into amending commit
3076 # |
3091 # |
3077 # old o - changeset to amend
3092 # old o - changeset to amend
3078 # |
3093 # |
3079 # base o - first parent of the changeset to amend
3094 # base o - first parent of the changeset to amend
3080 wctx = repo[None]
3095 wctx = repo[None]
3081
3096
3082 # Copy to avoid mutating input
3097 # Copy to avoid mutating input
3083 extra = extra.copy()
3098 extra = extra.copy()
3084 # Update extra dict from amended commit (e.g. to preserve graft
3099 # Update extra dict from amended commit (e.g. to preserve graft
3085 # source)
3100 # source)
3086 extra.update(old.extra())
3101 extra.update(old.extra())
3087
3102
3088 # Also update it from the from the wctx
3103 # Also update it from the from the wctx
3089 extra.update(wctx.extra())
3104 extra.update(wctx.extra())
3090
3105
3091 user = opts.get('user') or old.user()
3106 user = opts.get('user') or old.user()
3092 date = opts.get('date') or old.date()
3107 date = opts.get('date') or old.date()
3093
3108
3094 # Parse the date to allow comparison between date and old.date()
3109 # Parse the date to allow comparison between date and old.date()
3095 date = util.parsedate(date)
3110 date = util.parsedate(date)
3096
3111
3097 if len(old.parents()) > 1:
3112 if len(old.parents()) > 1:
3098 # ctx.files() isn't reliable for merges, so fall back to the
3113 # ctx.files() isn't reliable for merges, so fall back to the
3099 # slower repo.status() method
3114 # slower repo.status() method
3100 files = set([fn for st in repo.status(base, old)[:3]
3115 files = set([fn for st in repo.status(base, old)[:3]
3101 for fn in st])
3116 for fn in st])
3102 else:
3117 else:
3103 files = set(old.files())
3118 files = set(old.files())
3104
3119
3105 # add/remove the files to the working copy if the "addremove" option
3120 # add/remove the files to the working copy if the "addremove" option
3106 # was specified.
3121 # was specified.
3107 matcher = scmutil.match(wctx, pats, opts)
3122 matcher = scmutil.match(wctx, pats, opts)
3108 if (opts.get('addremove')
3123 if (opts.get('addremove')
3109 and scmutil.addremove(repo, matcher, "", opts)):
3124 and scmutil.addremove(repo, matcher, "", opts)):
3110 raise error.Abort(
3125 raise error.Abort(
3111 _("failed to mark all new/missing files as added/removed"))
3126 _("failed to mark all new/missing files as added/removed"))
3112
3127
3113 # Check subrepos. This depends on in-place wctx._status update in
3128 # Check subrepos. This depends on in-place wctx._status update in
3114 # subrepo.precommit(). To minimize the risk of this hack, we do
3129 # subrepo.precommit(). To minimize the risk of this hack, we do
3115 # nothing if .hgsub does not exist.
3130 # nothing if .hgsub does not exist.
3116 if '.hgsub' in wctx or '.hgsub' in old:
3131 if '.hgsub' in wctx or '.hgsub' in old:
3117 from . import subrepo # avoid cycle: cmdutil -> subrepo -> cmdutil
3132 from . import subrepo # avoid cycle: cmdutil -> subrepo -> cmdutil
3118 subs, commitsubs, newsubstate = subrepo.precommit(
3133 subs, commitsubs, newsubstate = subrepo.precommit(
3119 ui, wctx, wctx._status, matcher)
3134 ui, wctx, wctx._status, matcher)
3120 # amend should abort if commitsubrepos is enabled
3135 # amend should abort if commitsubrepos is enabled
3121 assert not commitsubs
3136 assert not commitsubs
3122 if subs:
3137 if subs:
3123 subrepo.writestate(repo, newsubstate)
3138 subrepo.writestate(repo, newsubstate)
3124
3139
3125 filestoamend = set(f for f in wctx.files() if matcher(f))
3140 filestoamend = set(f for f in wctx.files() if matcher(f))
3126
3141
3127 changes = (len(filestoamend) > 0)
3142 changes = (len(filestoamend) > 0)
3128 if changes:
3143 if changes:
3129 # Recompute copies (avoid recording a -> b -> a)
3144 # Recompute copies (avoid recording a -> b -> a)
3130 copied = copies.pathcopies(base, wctx, matcher)
3145 copied = copies.pathcopies(base, wctx, matcher)
3131 if old.p2:
3146 if old.p2:
3132 copied.update(copies.pathcopies(old.p2(), wctx, matcher))
3147 copied.update(copies.pathcopies(old.p2(), wctx, matcher))
3133
3148
3134 # Prune files which were reverted by the updates: if old
3149 # Prune files which were reverted by the updates: if old
3135 # introduced file X and the file was renamed in the working
3150 # introduced file X and the file was renamed in the working
3136 # copy, then those two files are the same and
3151 # copy, then those two files are the same and
3137 # we can discard X from our list of files. Likewise if X
3152 # we can discard X from our list of files. Likewise if X
3138 # was removed, it's no longer relevant. If X is missing (aka
3153 # was removed, it's no longer relevant. If X is missing (aka
3139 # deleted), old X must be preserved.
3154 # deleted), old X must be preserved.
3140 files.update(filestoamend)
3155 files.update(filestoamend)
3141 files = [f for f in files if (not samefile(f, wctx, base)
3156 files = [f for f in files if (not samefile(f, wctx, base)
3142 or f in wctx.deleted())]
3157 or f in wctx.deleted())]
3143
3158
3144 def filectxfn(repo, ctx_, path):
3159 def filectxfn(repo, ctx_, path):
3145 try:
3160 try:
3146 # If the file being considered is not amongst the files
3161 # If the file being considered is not amongst the files
3147 # to be amended, we should return the file context from the
3162 # to be amended, we should return the file context from the
3148 # old changeset. This avoids issues when only some files in
3163 # old changeset. This avoids issues when only some files in
3149 # the working copy are being amended but there are also
3164 # the working copy are being amended but there are also
3150 # changes to other files from the old changeset.
3165 # changes to other files from the old changeset.
3151 if path not in filestoamend:
3166 if path not in filestoamend:
3152 return old.filectx(path)
3167 return old.filectx(path)
3153
3168
3154 # Return None for removed files.
3169 # Return None for removed files.
3155 if path in wctx.removed():
3170 if path in wctx.removed():
3156 return None
3171 return None
3157
3172
3158 fctx = wctx[path]
3173 fctx = wctx[path]
3159 flags = fctx.flags()
3174 flags = fctx.flags()
3160 mctx = context.memfilectx(repo, ctx_,
3175 mctx = context.memfilectx(repo, ctx_,
3161 fctx.path(), fctx.data(),
3176 fctx.path(), fctx.data(),
3162 islink='l' in flags,
3177 islink='l' in flags,
3163 isexec='x' in flags,
3178 isexec='x' in flags,
3164 copied=copied.get(path))
3179 copied=copied.get(path))
3165 return mctx
3180 return mctx
3166 except KeyError:
3181 except KeyError:
3167 return None
3182 return None
3168 else:
3183 else:
3169 ui.note(_('copying changeset %s to %s\n') % (old, base))
3184 ui.note(_('copying changeset %s to %s\n') % (old, base))
3170
3185
3171 # Use version of files as in the old cset
3186 # Use version of files as in the old cset
3172 def filectxfn(repo, ctx_, path):
3187 def filectxfn(repo, ctx_, path):
3173 try:
3188 try:
3174 return old.filectx(path)
3189 return old.filectx(path)
3175 except KeyError:
3190 except KeyError:
3176 return None
3191 return None
3177
3192
3178 # See if we got a message from -m or -l, if not, open the editor with
3193 # See if we got a message from -m or -l, if not, open the editor with
3179 # the message of the changeset to amend.
3194 # the message of the changeset to amend.
3180 message = logmessage(ui, opts)
3195 message = logmessage(ui, opts)
3181
3196
3182 editform = mergeeditform(old, 'commit.amend')
3197 editform = mergeeditform(old, 'commit.amend')
3183 editor = getcommiteditor(editform=editform,
3198 editor = getcommiteditor(editform=editform,
3184 **pycompat.strkwargs(opts))
3199 **pycompat.strkwargs(opts))
3185
3200
3186 if not message:
3201 if not message:
3187 editor = getcommiteditor(edit=True, editform=editform)
3202 editor = getcommiteditor(edit=True, editform=editform)
3188 message = old.description()
3203 message = old.description()
3189
3204
3190 pureextra = extra.copy()
3205 pureextra = extra.copy()
3191 extra['amend_source'] = old.hex()
3206 extra['amend_source'] = old.hex()
3192
3207
3193 new = context.memctx(repo,
3208 new = context.memctx(repo,
3194 parents=[base.node(), old.p2().node()],
3209 parents=[base.node(), old.p2().node()],
3195 text=message,
3210 text=message,
3196 files=files,
3211 files=files,
3197 filectxfn=filectxfn,
3212 filectxfn=filectxfn,
3198 user=user,
3213 user=user,
3199 date=date,
3214 date=date,
3200 extra=extra,
3215 extra=extra,
3201 editor=editor)
3216 editor=editor)
3202
3217
3203 newdesc = changelog.stripdesc(new.description())
3218 newdesc = changelog.stripdesc(new.description())
3204 if ((not changes)
3219 if ((not changes)
3205 and newdesc == old.description()
3220 and newdesc == old.description()
3206 and user == old.user()
3221 and user == old.user()
3207 and date == old.date()
3222 and date == old.date()
3208 and pureextra == old.extra()):
3223 and pureextra == old.extra()):
3209 # nothing changed. continuing here would create a new node
3224 # nothing changed. continuing here would create a new node
3210 # anyway because of the amend_source noise.
3225 # anyway because of the amend_source noise.
3211 #
3226 #
3212 # This not what we expect from amend.
3227 # This not what we expect from amend.
3213 return old.node()
3228 return old.node()
3214
3229
3215 if opts.get('secret'):
3230 if opts.get('secret'):
3216 commitphase = 'secret'
3231 commitphase = 'secret'
3217 else:
3232 else:
3218 commitphase = old.phase()
3233 commitphase = old.phase()
3219 overrides = {('phases', 'new-commit'): commitphase}
3234 overrides = {('phases', 'new-commit'): commitphase}
3220 with ui.configoverride(overrides, 'amend'):
3235 with ui.configoverride(overrides, 'amend'):
3221 newid = repo.commitctx(new)
3236 newid = repo.commitctx(new)
3222
3237
3223 # Reroute the working copy parent to the new changeset
3238 # Reroute the working copy parent to the new changeset
3224 repo.setparents(newid, nullid)
3239 repo.setparents(newid, nullid)
3225 mapping = {old.node(): (newid,)}
3240 mapping = {old.node(): (newid,)}
3226 obsmetadata = None
3241 obsmetadata = None
3227 if opts.get('note'):
3242 if opts.get('note'):
3228 obsmetadata = {'note': opts['note']}
3243 obsmetadata = {'note': opts['note']}
3229 scmutil.cleanupnodes(repo, mapping, 'amend', metadata=obsmetadata)
3244 scmutil.cleanupnodes(repo, mapping, 'amend', metadata=obsmetadata)
3230
3245
3231 # Fixing the dirstate because localrepo.commitctx does not update
3246 # Fixing the dirstate because localrepo.commitctx does not update
3232 # it. This is rather convenient because we did not need to update
3247 # it. This is rather convenient because we did not need to update
3233 # the dirstate for all the files in the new commit which commitctx
3248 # the dirstate for all the files in the new commit which commitctx
3234 # could have done if it updated the dirstate. Now, we can
3249 # could have done if it updated the dirstate. Now, we can
3235 # selectively update the dirstate only for the amended files.
3250 # selectively update the dirstate only for the amended files.
3236 dirstate = repo.dirstate
3251 dirstate = repo.dirstate
3237
3252
3238 # Update the state of the files which were added and
3253 # Update the state of the files which were added and
3239 # and modified in the amend to "normal" in the dirstate.
3254 # and modified in the amend to "normal" in the dirstate.
3240 normalfiles = set(wctx.modified() + wctx.added()) & filestoamend
3255 normalfiles = set(wctx.modified() + wctx.added()) & filestoamend
3241 for f in normalfiles:
3256 for f in normalfiles:
3242 dirstate.normal(f)
3257 dirstate.normal(f)
3243
3258
3244 # Update the state of files which were removed in the amend
3259 # Update the state of files which were removed in the amend
3245 # to "removed" in the dirstate.
3260 # to "removed" in the dirstate.
3246 removedfiles = set(wctx.removed()) & filestoamend
3261 removedfiles = set(wctx.removed()) & filestoamend
3247 for f in removedfiles:
3262 for f in removedfiles:
3248 dirstate.drop(f)
3263 dirstate.drop(f)
3249
3264
3250 return newid
3265 return newid
3251
3266
3252 def commiteditor(repo, ctx, subs, editform=''):
3267 def commiteditor(repo, ctx, subs, editform=''):
3253 if ctx.description():
3268 if ctx.description():
3254 return ctx.description()
3269 return ctx.description()
3255 return commitforceeditor(repo, ctx, subs, editform=editform,
3270 return commitforceeditor(repo, ctx, subs, editform=editform,
3256 unchangedmessagedetection=True)
3271 unchangedmessagedetection=True)
3257
3272
3258 def commitforceeditor(repo, ctx, subs, finishdesc=None, extramsg=None,
3273 def commitforceeditor(repo, ctx, subs, finishdesc=None, extramsg=None,
3259 editform='', unchangedmessagedetection=False):
3274 editform='', unchangedmessagedetection=False):
3260 if not extramsg:
3275 if not extramsg:
3261 extramsg = _("Leave message empty to abort commit.")
3276 extramsg = _("Leave message empty to abort commit.")
3262
3277
3263 forms = [e for e in editform.split('.') if e]
3278 forms = [e for e in editform.split('.') if e]
3264 forms.insert(0, 'changeset')
3279 forms.insert(0, 'changeset')
3265 templatetext = None
3280 templatetext = None
3266 while forms:
3281 while forms:
3267 ref = '.'.join(forms)
3282 ref = '.'.join(forms)
3268 if repo.ui.config('committemplate', ref):
3283 if repo.ui.config('committemplate', ref):
3269 templatetext = committext = buildcommittemplate(
3284 templatetext = committext = buildcommittemplate(
3270 repo, ctx, subs, extramsg, ref)
3285 repo, ctx, subs, extramsg, ref)
3271 break
3286 break
3272 forms.pop()
3287 forms.pop()
3273 else:
3288 else:
3274 committext = buildcommittext(repo, ctx, subs, extramsg)
3289 committext = buildcommittext(repo, ctx, subs, extramsg)
3275
3290
3276 # run editor in the repository root
3291 # run editor in the repository root
3277 olddir = pycompat.getcwd()
3292 olddir = pycompat.getcwd()
3278 os.chdir(repo.root)
3293 os.chdir(repo.root)
3279
3294
3280 # make in-memory changes visible to external process
3295 # make in-memory changes visible to external process
3281 tr = repo.currenttransaction()
3296 tr = repo.currenttransaction()
3282 repo.dirstate.write(tr)
3297 repo.dirstate.write(tr)
3283 pending = tr and tr.writepending() and repo.root
3298 pending = tr and tr.writepending() and repo.root
3284
3299
3285 editortext = repo.ui.edit(committext, ctx.user(), ctx.extra(),
3300 editortext = repo.ui.edit(committext, ctx.user(), ctx.extra(),
3286 editform=editform, pending=pending,
3301 editform=editform, pending=pending,
3287 repopath=repo.path, action='commit')
3302 repopath=repo.path, action='commit')
3288 text = editortext
3303 text = editortext
3289
3304
3290 # strip away anything below this special string (used for editors that want
3305 # strip away anything below this special string (used for editors that want
3291 # to display the diff)
3306 # to display the diff)
3292 stripbelow = re.search(_linebelow, text, flags=re.MULTILINE)
3307 stripbelow = re.search(_linebelow, text, flags=re.MULTILINE)
3293 if stripbelow:
3308 if stripbelow:
3294 text = text[:stripbelow.start()]
3309 text = text[:stripbelow.start()]
3295
3310
3296 text = re.sub("(?m)^HG:.*(\n|$)", "", text)
3311 text = re.sub("(?m)^HG:.*(\n|$)", "", text)
3297 os.chdir(olddir)
3312 os.chdir(olddir)
3298
3313
3299 if finishdesc:
3314 if finishdesc:
3300 text = finishdesc(text)
3315 text = finishdesc(text)
3301 if not text.strip():
3316 if not text.strip():
3302 raise error.Abort(_("empty commit message"))
3317 raise error.Abort(_("empty commit message"))
3303 if unchangedmessagedetection and editortext == templatetext:
3318 if unchangedmessagedetection and editortext == templatetext:
3304 raise error.Abort(_("commit message unchanged"))
3319 raise error.Abort(_("commit message unchanged"))
3305
3320
3306 return text
3321 return text
3307
3322
3308 def buildcommittemplate(repo, ctx, subs, extramsg, ref):
3323 def buildcommittemplate(repo, ctx, subs, extramsg, ref):
3309 ui = repo.ui
3324 ui = repo.ui
3310 spec = formatter.templatespec(ref, None, None)
3325 spec = formatter.templatespec(ref, None, None)
3311 t = changeset_templater(ui, repo, spec, None, {}, False)
3326 t = changeset_templater(ui, repo, spec, None, {}, False)
3312 t.t.cache.update((k, templater.unquotestring(v))
3327 t.t.cache.update((k, templater.unquotestring(v))
3313 for k, v in repo.ui.configitems('committemplate'))
3328 for k, v in repo.ui.configitems('committemplate'))
3314
3329
3315 if not extramsg:
3330 if not extramsg:
3316 extramsg = '' # ensure that extramsg is string
3331 extramsg = '' # ensure that extramsg is string
3317
3332
3318 ui.pushbuffer()
3333 ui.pushbuffer()
3319 t.show(ctx, extramsg=extramsg)
3334 t.show(ctx, extramsg=extramsg)
3320 return ui.popbuffer()
3335 return ui.popbuffer()
3321
3336
3322 def hgprefix(msg):
3337 def hgprefix(msg):
3323 return "\n".join(["HG: %s" % a for a in msg.split("\n") if a])
3338 return "\n".join(["HG: %s" % a for a in msg.split("\n") if a])
3324
3339
3325 def buildcommittext(repo, ctx, subs, extramsg):
3340 def buildcommittext(repo, ctx, subs, extramsg):
3326 edittext = []
3341 edittext = []
3327 modified, added, removed = ctx.modified(), ctx.added(), ctx.removed()
3342 modified, added, removed = ctx.modified(), ctx.added(), ctx.removed()
3328 if ctx.description():
3343 if ctx.description():
3329 edittext.append(ctx.description())
3344 edittext.append(ctx.description())
3330 edittext.append("")
3345 edittext.append("")
3331 edittext.append("") # Empty line between message and comments.
3346 edittext.append("") # Empty line between message and comments.
3332 edittext.append(hgprefix(_("Enter commit message."
3347 edittext.append(hgprefix(_("Enter commit message."
3333 " Lines beginning with 'HG:' are removed.")))
3348 " Lines beginning with 'HG:' are removed.")))
3334 edittext.append(hgprefix(extramsg))
3349 edittext.append(hgprefix(extramsg))
3335 edittext.append("HG: --")
3350 edittext.append("HG: --")
3336 edittext.append(hgprefix(_("user: %s") % ctx.user()))
3351 edittext.append(hgprefix(_("user: %s") % ctx.user()))
3337 if ctx.p2():
3352 if ctx.p2():
3338 edittext.append(hgprefix(_("branch merge")))
3353 edittext.append(hgprefix(_("branch merge")))
3339 if ctx.branch():
3354 if ctx.branch():
3340 edittext.append(hgprefix(_("branch '%s'") % ctx.branch()))
3355 edittext.append(hgprefix(_("branch '%s'") % ctx.branch()))
3341 if bookmarks.isactivewdirparent(repo):
3356 if bookmarks.isactivewdirparent(repo):
3342 edittext.append(hgprefix(_("bookmark '%s'") % repo._activebookmark))
3357 edittext.append(hgprefix(_("bookmark '%s'") % repo._activebookmark))
3343 edittext.extend([hgprefix(_("subrepo %s") % s) for s in subs])
3358 edittext.extend([hgprefix(_("subrepo %s") % s) for s in subs])
3344 edittext.extend([hgprefix(_("added %s") % f) for f in added])
3359 edittext.extend([hgprefix(_("added %s") % f) for f in added])
3345 edittext.extend([hgprefix(_("changed %s") % f) for f in modified])
3360 edittext.extend([hgprefix(_("changed %s") % f) for f in modified])
3346 edittext.extend([hgprefix(_("removed %s") % f) for f in removed])
3361 edittext.extend([hgprefix(_("removed %s") % f) for f in removed])
3347 if not added and not modified and not removed:
3362 if not added and not modified and not removed:
3348 edittext.append(hgprefix(_("no files changed")))
3363 edittext.append(hgprefix(_("no files changed")))
3349 edittext.append("")
3364 edittext.append("")
3350
3365
3351 return "\n".join(edittext)
3366 return "\n".join(edittext)
3352
3367
3353 def commitstatus(repo, node, branch, bheads=None, opts=None):
3368 def commitstatus(repo, node, branch, bheads=None, opts=None):
3354 if opts is None:
3369 if opts is None:
3355 opts = {}
3370 opts = {}
3356 ctx = repo[node]
3371 ctx = repo[node]
3357 parents = ctx.parents()
3372 parents = ctx.parents()
3358
3373
3359 if (not opts.get('amend') and bheads and node not in bheads and not
3374 if (not opts.get('amend') and bheads and node not in bheads and not
3360 [x for x in parents if x.node() in bheads and x.branch() == branch]):
3375 [x for x in parents if x.node() in bheads and x.branch() == branch]):
3361 repo.ui.status(_('created new head\n'))
3376 repo.ui.status(_('created new head\n'))
3362 # The message is not printed for initial roots. For the other
3377 # The message is not printed for initial roots. For the other
3363 # changesets, it is printed in the following situations:
3378 # changesets, it is printed in the following situations:
3364 #
3379 #
3365 # Par column: for the 2 parents with ...
3380 # Par column: for the 2 parents with ...
3366 # N: null or no parent
3381 # N: null or no parent
3367 # B: parent is on another named branch
3382 # B: parent is on another named branch
3368 # C: parent is a regular non head changeset
3383 # C: parent is a regular non head changeset
3369 # H: parent was a branch head of the current branch
3384 # H: parent was a branch head of the current branch
3370 # Msg column: whether we print "created new head" message
3385 # Msg column: whether we print "created new head" message
3371 # In the following, it is assumed that there already exists some
3386 # In the following, it is assumed that there already exists some
3372 # initial branch heads of the current branch, otherwise nothing is
3387 # initial branch heads of the current branch, otherwise nothing is
3373 # printed anyway.
3388 # printed anyway.
3374 #
3389 #
3375 # Par Msg Comment
3390 # Par Msg Comment
3376 # N N y additional topo root
3391 # N N y additional topo root
3377 #
3392 #
3378 # B N y additional branch root
3393 # B N y additional branch root
3379 # C N y additional topo head
3394 # C N y additional topo head
3380 # H N n usual case
3395 # H N n usual case
3381 #
3396 #
3382 # B B y weird additional branch root
3397 # B B y weird additional branch root
3383 # C B y branch merge
3398 # C B y branch merge
3384 # H B n merge with named branch
3399 # H B n merge with named branch
3385 #
3400 #
3386 # C C y additional head from merge
3401 # C C y additional head from merge
3387 # C H n merge with a head
3402 # C H n merge with a head
3388 #
3403 #
3389 # H H n head merge: head count decreases
3404 # H H n head merge: head count decreases
3390
3405
3391 if not opts.get('close_branch'):
3406 if not opts.get('close_branch'):
3392 for r in parents:
3407 for r in parents:
3393 if r.closesbranch() and r.branch() == branch:
3408 if r.closesbranch() and r.branch() == branch:
3394 repo.ui.status(_('reopening closed branch head %d\n') % r)
3409 repo.ui.status(_('reopening closed branch head %d\n') % r)
3395
3410
3396 if repo.ui.debugflag:
3411 if repo.ui.debugflag:
3397 repo.ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
3412 repo.ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
3398 elif repo.ui.verbose:
3413 elif repo.ui.verbose:
3399 repo.ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
3414 repo.ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
3400
3415
3401 def postcommitstatus(repo, pats, opts):
3416 def postcommitstatus(repo, pats, opts):
3402 return repo.status(match=scmutil.match(repo[None], pats, opts))
3417 return repo.status(match=scmutil.match(repo[None], pats, opts))
3403
3418
3404 def revert(ui, repo, ctx, parents, *pats, **opts):
3419 def revert(ui, repo, ctx, parents, *pats, **opts):
3405 opts = pycompat.byteskwargs(opts)
3420 opts = pycompat.byteskwargs(opts)
3406 parent, p2 = parents
3421 parent, p2 = parents
3407 node = ctx.node()
3422 node = ctx.node()
3408
3423
3409 mf = ctx.manifest()
3424 mf = ctx.manifest()
3410 if node == p2:
3425 if node == p2:
3411 parent = p2
3426 parent = p2
3412
3427
3413 # need all matching names in dirstate and manifest of target rev,
3428 # need all matching names in dirstate and manifest of target rev,
3414 # so have to walk both. do not print errors if files exist in one
3429 # so have to walk both. do not print errors if files exist in one
3415 # but not other. in both cases, filesets should be evaluated against
3430 # but not other. in both cases, filesets should be evaluated against
3416 # workingctx to get consistent result (issue4497). this means 'set:**'
3431 # workingctx to get consistent result (issue4497). this means 'set:**'
3417 # cannot be used to select missing files from target rev.
3432 # cannot be used to select missing files from target rev.
3418
3433
3419 # `names` is a mapping for all elements in working copy and target revision
3434 # `names` is a mapping for all elements in working copy and target revision
3420 # The mapping is in the form:
3435 # The mapping is in the form:
3421 # <asb path in repo> -> (<path from CWD>, <exactly specified by matcher?>)
3436 # <asb path in repo> -> (<path from CWD>, <exactly specified by matcher?>)
3422 names = {}
3437 names = {}
3423
3438
3424 with repo.wlock():
3439 with repo.wlock():
3425 ## filling of the `names` mapping
3440 ## filling of the `names` mapping
3426 # walk dirstate to fill `names`
3441 # walk dirstate to fill `names`
3427
3442
3428 interactive = opts.get('interactive', False)
3443 interactive = opts.get('interactive', False)
3429 wctx = repo[None]
3444 wctx = repo[None]
3430 m = scmutil.match(wctx, pats, opts)
3445 m = scmutil.match(wctx, pats, opts)
3431
3446
3432 # we'll need this later
3447 # we'll need this later
3433 targetsubs = sorted(s for s in wctx.substate if m(s))
3448 targetsubs = sorted(s for s in wctx.substate if m(s))
3434
3449
3435 if not m.always():
3450 if not m.always():
3436 matcher = matchmod.badmatch(m, lambda x, y: False)
3451 matcher = matchmod.badmatch(m, lambda x, y: False)
3437 for abs in wctx.walk(matcher):
3452 for abs in wctx.walk(matcher):
3438 names[abs] = m.rel(abs), m.exact(abs)
3453 names[abs] = m.rel(abs), m.exact(abs)
3439
3454
3440 # walk target manifest to fill `names`
3455 # walk target manifest to fill `names`
3441
3456
3442 def badfn(path, msg):
3457 def badfn(path, msg):
3443 if path in names:
3458 if path in names:
3444 return
3459 return
3445 if path in ctx.substate:
3460 if path in ctx.substate:
3446 return
3461 return
3447 path_ = path + '/'
3462 path_ = path + '/'
3448 for f in names:
3463 for f in names:
3449 if f.startswith(path_):
3464 if f.startswith(path_):
3450 return
3465 return
3451 ui.warn("%s: %s\n" % (m.rel(path), msg))
3466 ui.warn("%s: %s\n" % (m.rel(path), msg))
3452
3467
3453 for abs in ctx.walk(matchmod.badmatch(m, badfn)):
3468 for abs in ctx.walk(matchmod.badmatch(m, badfn)):
3454 if abs not in names:
3469 if abs not in names:
3455 names[abs] = m.rel(abs), m.exact(abs)
3470 names[abs] = m.rel(abs), m.exact(abs)
3456
3471
3457 # Find status of all file in `names`.
3472 # Find status of all file in `names`.
3458 m = scmutil.matchfiles(repo, names)
3473 m = scmutil.matchfiles(repo, names)
3459
3474
3460 changes = repo.status(node1=node, match=m,
3475 changes = repo.status(node1=node, match=m,
3461 unknown=True, ignored=True, clean=True)
3476 unknown=True, ignored=True, clean=True)
3462 else:
3477 else:
3463 changes = repo.status(node1=node, match=m)
3478 changes = repo.status(node1=node, match=m)
3464 for kind in changes:
3479 for kind in changes:
3465 for abs in kind:
3480 for abs in kind:
3466 names[abs] = m.rel(abs), m.exact(abs)
3481 names[abs] = m.rel(abs), m.exact(abs)
3467
3482
3468 m = scmutil.matchfiles(repo, names)
3483 m = scmutil.matchfiles(repo, names)
3469
3484
3470 modified = set(changes.modified)
3485 modified = set(changes.modified)
3471 added = set(changes.added)
3486 added = set(changes.added)
3472 removed = set(changes.removed)
3487 removed = set(changes.removed)
3473 _deleted = set(changes.deleted)
3488 _deleted = set(changes.deleted)
3474 unknown = set(changes.unknown)
3489 unknown = set(changes.unknown)
3475 unknown.update(changes.ignored)
3490 unknown.update(changes.ignored)
3476 clean = set(changes.clean)
3491 clean = set(changes.clean)
3477 modadded = set()
3492 modadded = set()
3478
3493
3479 # We need to account for the state of the file in the dirstate,
3494 # We need to account for the state of the file in the dirstate,
3480 # even when we revert against something else than parent. This will
3495 # even when we revert against something else than parent. This will
3481 # slightly alter the behavior of revert (doing back up or not, delete
3496 # slightly alter the behavior of revert (doing back up or not, delete
3482 # or just forget etc).
3497 # or just forget etc).
3483 if parent == node:
3498 if parent == node:
3484 dsmodified = modified
3499 dsmodified = modified
3485 dsadded = added
3500 dsadded = added
3486 dsremoved = removed
3501 dsremoved = removed
3487 # store all local modifications, useful later for rename detection
3502 # store all local modifications, useful later for rename detection
3488 localchanges = dsmodified | dsadded
3503 localchanges = dsmodified | dsadded
3489 modified, added, removed = set(), set(), set()
3504 modified, added, removed = set(), set(), set()
3490 else:
3505 else:
3491 changes = repo.status(node1=parent, match=m)
3506 changes = repo.status(node1=parent, match=m)
3492 dsmodified = set(changes.modified)
3507 dsmodified = set(changes.modified)
3493 dsadded = set(changes.added)
3508 dsadded = set(changes.added)
3494 dsremoved = set(changes.removed)
3509 dsremoved = set(changes.removed)
3495 # store all local modifications, useful later for rename detection
3510 # store all local modifications, useful later for rename detection
3496 localchanges = dsmodified | dsadded
3511 localchanges = dsmodified | dsadded
3497
3512
3498 # only take into account for removes between wc and target
3513 # only take into account for removes between wc and target
3499 clean |= dsremoved - removed
3514 clean |= dsremoved - removed
3500 dsremoved &= removed
3515 dsremoved &= removed
3501 # distinct between dirstate remove and other
3516 # distinct between dirstate remove and other
3502 removed -= dsremoved
3517 removed -= dsremoved
3503
3518
3504 modadded = added & dsmodified
3519 modadded = added & dsmodified
3505 added -= modadded
3520 added -= modadded
3506
3521
3507 # tell newly modified apart.
3522 # tell newly modified apart.
3508 dsmodified &= modified
3523 dsmodified &= modified
3509 dsmodified |= modified & dsadded # dirstate added may need backup
3524 dsmodified |= modified & dsadded # dirstate added may need backup
3510 modified -= dsmodified
3525 modified -= dsmodified
3511
3526
3512 # We need to wait for some post-processing to update this set
3527 # We need to wait for some post-processing to update this set
3513 # before making the distinction. The dirstate will be used for
3528 # before making the distinction. The dirstate will be used for
3514 # that purpose.
3529 # that purpose.
3515 dsadded = added
3530 dsadded = added
3516
3531
3517 # in case of merge, files that are actually added can be reported as
3532 # in case of merge, files that are actually added can be reported as
3518 # modified, we need to post process the result
3533 # modified, we need to post process the result
3519 if p2 != nullid:
3534 if p2 != nullid:
3520 mergeadd = set(dsmodified)
3535 mergeadd = set(dsmodified)
3521 for path in dsmodified:
3536 for path in dsmodified:
3522 if path in mf:
3537 if path in mf:
3523 mergeadd.remove(path)
3538 mergeadd.remove(path)
3524 dsadded |= mergeadd
3539 dsadded |= mergeadd
3525 dsmodified -= mergeadd
3540 dsmodified -= mergeadd
3526
3541
3527 # if f is a rename, update `names` to also revert the source
3542 # if f is a rename, update `names` to also revert the source
3528 cwd = repo.getcwd()
3543 cwd = repo.getcwd()
3529 for f in localchanges:
3544 for f in localchanges:
3530 src = repo.dirstate.copied(f)
3545 src = repo.dirstate.copied(f)
3531 # XXX should we check for rename down to target node?
3546 # XXX should we check for rename down to target node?
3532 if src and src not in names and repo.dirstate[src] == 'r':
3547 if src and src not in names and repo.dirstate[src] == 'r':
3533 dsremoved.add(src)
3548 dsremoved.add(src)
3534 names[src] = (repo.pathto(src, cwd), True)
3549 names[src] = (repo.pathto(src, cwd), True)
3535
3550
3536 # determine the exact nature of the deleted changesets
3551 # determine the exact nature of the deleted changesets
3537 deladded = set(_deleted)
3552 deladded = set(_deleted)
3538 for path in _deleted:
3553 for path in _deleted:
3539 if path in mf:
3554 if path in mf:
3540 deladded.remove(path)
3555 deladded.remove(path)
3541 deleted = _deleted - deladded
3556 deleted = _deleted - deladded
3542
3557
3543 # distinguish between file to forget and the other
3558 # distinguish between file to forget and the other
3544 added = set()
3559 added = set()
3545 for abs in dsadded:
3560 for abs in dsadded:
3546 if repo.dirstate[abs] != 'a':
3561 if repo.dirstate[abs] != 'a':
3547 added.add(abs)
3562 added.add(abs)
3548 dsadded -= added
3563 dsadded -= added
3549
3564
3550 for abs in deladded:
3565 for abs in deladded:
3551 if repo.dirstate[abs] == 'a':
3566 if repo.dirstate[abs] == 'a':
3552 dsadded.add(abs)
3567 dsadded.add(abs)
3553 deladded -= dsadded
3568 deladded -= dsadded
3554
3569
3555 # For files marked as removed, we check if an unknown file is present at
3570 # For files marked as removed, we check if an unknown file is present at
3556 # the same path. If a such file exists it may need to be backed up.
3571 # the same path. If a such file exists it may need to be backed up.
3557 # Making the distinction at this stage helps have simpler backup
3572 # Making the distinction at this stage helps have simpler backup
3558 # logic.
3573 # logic.
3559 removunk = set()
3574 removunk = set()
3560 for abs in removed:
3575 for abs in removed:
3561 target = repo.wjoin(abs)
3576 target = repo.wjoin(abs)
3562 if os.path.lexists(target):
3577 if os.path.lexists(target):
3563 removunk.add(abs)
3578 removunk.add(abs)
3564 removed -= removunk
3579 removed -= removunk
3565
3580
3566 dsremovunk = set()
3581 dsremovunk = set()
3567 for abs in dsremoved:
3582 for abs in dsremoved:
3568 target = repo.wjoin(abs)
3583 target = repo.wjoin(abs)
3569 if os.path.lexists(target):
3584 if os.path.lexists(target):
3570 dsremovunk.add(abs)
3585 dsremovunk.add(abs)
3571 dsremoved -= dsremovunk
3586 dsremoved -= dsremovunk
3572
3587
3573 # action to be actually performed by revert
3588 # action to be actually performed by revert
3574 # (<list of file>, message>) tuple
3589 # (<list of file>, message>) tuple
3575 actions = {'revert': ([], _('reverting %s\n')),
3590 actions = {'revert': ([], _('reverting %s\n')),
3576 'add': ([], _('adding %s\n')),
3591 'add': ([], _('adding %s\n')),
3577 'remove': ([], _('removing %s\n')),
3592 'remove': ([], _('removing %s\n')),
3578 'drop': ([], _('removing %s\n')),
3593 'drop': ([], _('removing %s\n')),
3579 'forget': ([], _('forgetting %s\n')),
3594 'forget': ([], _('forgetting %s\n')),
3580 'undelete': ([], _('undeleting %s\n')),
3595 'undelete': ([], _('undeleting %s\n')),
3581 'noop': (None, _('no changes needed to %s\n')),
3596 'noop': (None, _('no changes needed to %s\n')),
3582 'unknown': (None, _('file not managed: %s\n')),
3597 'unknown': (None, _('file not managed: %s\n')),
3583 }
3598 }
3584
3599
3585 # "constant" that convey the backup strategy.
3600 # "constant" that convey the backup strategy.
3586 # All set to `discard` if `no-backup` is set do avoid checking
3601 # All set to `discard` if `no-backup` is set do avoid checking
3587 # no_backup lower in the code.
3602 # no_backup lower in the code.
3588 # These values are ordered for comparison purposes
3603 # These values are ordered for comparison purposes
3589 backupinteractive = 3 # do backup if interactively modified
3604 backupinteractive = 3 # do backup if interactively modified
3590 backup = 2 # unconditionally do backup
3605 backup = 2 # unconditionally do backup
3591 check = 1 # check if the existing file differs from target
3606 check = 1 # check if the existing file differs from target
3592 discard = 0 # never do backup
3607 discard = 0 # never do backup
3593 if opts.get('no_backup'):
3608 if opts.get('no_backup'):
3594 backupinteractive = backup = check = discard
3609 backupinteractive = backup = check = discard
3595 if interactive:
3610 if interactive:
3596 dsmodifiedbackup = backupinteractive
3611 dsmodifiedbackup = backupinteractive
3597 else:
3612 else:
3598 dsmodifiedbackup = backup
3613 dsmodifiedbackup = backup
3599 tobackup = set()
3614 tobackup = set()
3600
3615
3601 backupanddel = actions['remove']
3616 backupanddel = actions['remove']
3602 if not opts.get('no_backup'):
3617 if not opts.get('no_backup'):
3603 backupanddel = actions['drop']
3618 backupanddel = actions['drop']
3604
3619
3605 disptable = (
3620 disptable = (
3606 # dispatch table:
3621 # dispatch table:
3607 # file state
3622 # file state
3608 # action
3623 # action
3609 # make backup
3624 # make backup
3610
3625
3611 ## Sets that results that will change file on disk
3626 ## Sets that results that will change file on disk
3612 # Modified compared to target, no local change
3627 # Modified compared to target, no local change
3613 (modified, actions['revert'], discard),
3628 (modified, actions['revert'], discard),
3614 # Modified compared to target, but local file is deleted
3629 # Modified compared to target, but local file is deleted
3615 (deleted, actions['revert'], discard),
3630 (deleted, actions['revert'], discard),
3616 # Modified compared to target, local change
3631 # Modified compared to target, local change
3617 (dsmodified, actions['revert'], dsmodifiedbackup),
3632 (dsmodified, actions['revert'], dsmodifiedbackup),
3618 # Added since target
3633 # Added since target
3619 (added, actions['remove'], discard),
3634 (added, actions['remove'], discard),
3620 # Added in working directory
3635 # Added in working directory
3621 (dsadded, actions['forget'], discard),
3636 (dsadded, actions['forget'], discard),
3622 # Added since target, have local modification
3637 # Added since target, have local modification
3623 (modadded, backupanddel, backup),
3638 (modadded, backupanddel, backup),
3624 # Added since target but file is missing in working directory
3639 # Added since target but file is missing in working directory
3625 (deladded, actions['drop'], discard),
3640 (deladded, actions['drop'], discard),
3626 # Removed since target, before working copy parent
3641 # Removed since target, before working copy parent
3627 (removed, actions['add'], discard),
3642 (removed, actions['add'], discard),
3628 # Same as `removed` but an unknown file exists at the same path
3643 # Same as `removed` but an unknown file exists at the same path
3629 (removunk, actions['add'], check),
3644 (removunk, actions['add'], check),
3630 # Removed since targe, marked as such in working copy parent
3645 # Removed since targe, marked as such in working copy parent
3631 (dsremoved, actions['undelete'], discard),
3646 (dsremoved, actions['undelete'], discard),
3632 # Same as `dsremoved` but an unknown file exists at the same path
3647 # Same as `dsremoved` but an unknown file exists at the same path
3633 (dsremovunk, actions['undelete'], check),
3648 (dsremovunk, actions['undelete'], check),
3634 ## the following sets does not result in any file changes
3649 ## the following sets does not result in any file changes
3635 # File with no modification
3650 # File with no modification
3636 (clean, actions['noop'], discard),
3651 (clean, actions['noop'], discard),
3637 # Existing file, not tracked anywhere
3652 # Existing file, not tracked anywhere
3638 (unknown, actions['unknown'], discard),
3653 (unknown, actions['unknown'], discard),
3639 )
3654 )
3640
3655
3641 for abs, (rel, exact) in sorted(names.items()):
3656 for abs, (rel, exact) in sorted(names.items()):
3642 # target file to be touch on disk (relative to cwd)
3657 # target file to be touch on disk (relative to cwd)
3643 target = repo.wjoin(abs)
3658 target = repo.wjoin(abs)
3644 # search the entry in the dispatch table.
3659 # search the entry in the dispatch table.
3645 # if the file is in any of these sets, it was touched in the working
3660 # if the file is in any of these sets, it was touched in the working
3646 # directory parent and we are sure it needs to be reverted.
3661 # directory parent and we are sure it needs to be reverted.
3647 for table, (xlist, msg), dobackup in disptable:
3662 for table, (xlist, msg), dobackup in disptable:
3648 if abs not in table:
3663 if abs not in table:
3649 continue
3664 continue
3650 if xlist is not None:
3665 if xlist is not None:
3651 xlist.append(abs)
3666 xlist.append(abs)
3652 if dobackup:
3667 if dobackup:
3653 # If in interactive mode, don't automatically create
3668 # If in interactive mode, don't automatically create
3654 # .orig files (issue4793)
3669 # .orig files (issue4793)
3655 if dobackup == backupinteractive:
3670 if dobackup == backupinteractive:
3656 tobackup.add(abs)
3671 tobackup.add(abs)
3657 elif (backup <= dobackup or wctx[abs].cmp(ctx[abs])):
3672 elif (backup <= dobackup or wctx[abs].cmp(ctx[abs])):
3658 bakname = scmutil.origpath(ui, repo, rel)
3673 bakname = scmutil.origpath(ui, repo, rel)
3659 ui.note(_('saving current version of %s as %s\n') %
3674 ui.note(_('saving current version of %s as %s\n') %
3660 (rel, bakname))
3675 (rel, bakname))
3661 if not opts.get('dry_run'):
3676 if not opts.get('dry_run'):
3662 if interactive:
3677 if interactive:
3663 util.copyfile(target, bakname)
3678 util.copyfile(target, bakname)
3664 else:
3679 else:
3665 util.rename(target, bakname)
3680 util.rename(target, bakname)
3666 if ui.verbose or not exact:
3681 if ui.verbose or not exact:
3667 if not isinstance(msg, bytes):
3682 if not isinstance(msg, bytes):
3668 msg = msg(abs)
3683 msg = msg(abs)
3669 ui.status(msg % rel)
3684 ui.status(msg % rel)
3670 elif exact:
3685 elif exact:
3671 ui.warn(msg % rel)
3686 ui.warn(msg % rel)
3672 break
3687 break
3673
3688
3674 if not opts.get('dry_run'):
3689 if not opts.get('dry_run'):
3675 needdata = ('revert', 'add', 'undelete')
3690 needdata = ('revert', 'add', 'undelete')
3676 _revertprefetch(repo, ctx, *[actions[name][0] for name in needdata])
3691 _revertprefetch(repo, ctx, *[actions[name][0] for name in needdata])
3677 _performrevert(repo, parents, ctx, actions, interactive, tobackup)
3692 _performrevert(repo, parents, ctx, actions, interactive, tobackup)
3678
3693
3679 if targetsubs:
3694 if targetsubs:
3680 # Revert the subrepos on the revert list
3695 # Revert the subrepos on the revert list
3681 for sub in targetsubs:
3696 for sub in targetsubs:
3682 try:
3697 try:
3683 wctx.sub(sub).revert(ctx.substate[sub], *pats,
3698 wctx.sub(sub).revert(ctx.substate[sub], *pats,
3684 **pycompat.strkwargs(opts))
3699 **pycompat.strkwargs(opts))
3685 except KeyError:
3700 except KeyError:
3686 raise error.Abort("subrepository '%s' does not exist in %s!"
3701 raise error.Abort("subrepository '%s' does not exist in %s!"
3687 % (sub, short(ctx.node())))
3702 % (sub, short(ctx.node())))
3688
3703
3689 def _revertprefetch(repo, ctx, *files):
3704 def _revertprefetch(repo, ctx, *files):
3690 """Let extension changing the storage layer prefetch content"""
3705 """Let extension changing the storage layer prefetch content"""
3691
3706
3692 def _performrevert(repo, parents, ctx, actions, interactive=False,
3707 def _performrevert(repo, parents, ctx, actions, interactive=False,
3693 tobackup=None):
3708 tobackup=None):
3694 """function that actually perform all the actions computed for revert
3709 """function that actually perform all the actions computed for revert
3695
3710
3696 This is an independent function to let extension to plug in and react to
3711 This is an independent function to let extension to plug in and react to
3697 the imminent revert.
3712 the imminent revert.
3698
3713
3699 Make sure you have the working directory locked when calling this function.
3714 Make sure you have the working directory locked when calling this function.
3700 """
3715 """
3701 parent, p2 = parents
3716 parent, p2 = parents
3702 node = ctx.node()
3717 node = ctx.node()
3703 excluded_files = []
3718 excluded_files = []
3704 matcher_opts = {"exclude": excluded_files}
3719 matcher_opts = {"exclude": excluded_files}
3705
3720
3706 def checkout(f):
3721 def checkout(f):
3707 fc = ctx[f]
3722 fc = ctx[f]
3708 repo.wwrite(f, fc.data(), fc.flags())
3723 repo.wwrite(f, fc.data(), fc.flags())
3709
3724
3710 def doremove(f):
3725 def doremove(f):
3711 try:
3726 try:
3712 repo.wvfs.unlinkpath(f)
3727 repo.wvfs.unlinkpath(f)
3713 except OSError:
3728 except OSError:
3714 pass
3729 pass
3715 repo.dirstate.remove(f)
3730 repo.dirstate.remove(f)
3716
3731
3717 audit_path = pathutil.pathauditor(repo.root, cached=True)
3732 audit_path = pathutil.pathauditor(repo.root, cached=True)
3718 for f in actions['forget'][0]:
3733 for f in actions['forget'][0]:
3719 if interactive:
3734 if interactive:
3720 choice = repo.ui.promptchoice(
3735 choice = repo.ui.promptchoice(
3721 _("forget added file %s (Yn)?$$ &Yes $$ &No") % f)
3736 _("forget added file %s (Yn)?$$ &Yes $$ &No") % f)
3722 if choice == 0:
3737 if choice == 0:
3723 repo.dirstate.drop(f)
3738 repo.dirstate.drop(f)
3724 else:
3739 else:
3725 excluded_files.append(repo.wjoin(f))
3740 excluded_files.append(repo.wjoin(f))
3726 else:
3741 else:
3727 repo.dirstate.drop(f)
3742 repo.dirstate.drop(f)
3728 for f in actions['remove'][0]:
3743 for f in actions['remove'][0]:
3729 audit_path(f)
3744 audit_path(f)
3730 if interactive:
3745 if interactive:
3731 choice = repo.ui.promptchoice(
3746 choice = repo.ui.promptchoice(
3732 _("remove added file %s (Yn)?$$ &Yes $$ &No") % f)
3747 _("remove added file %s (Yn)?$$ &Yes $$ &No") % f)
3733 if choice == 0:
3748 if choice == 0:
3734 doremove(f)
3749 doremove(f)
3735 else:
3750 else:
3736 excluded_files.append(repo.wjoin(f))
3751 excluded_files.append(repo.wjoin(f))
3737 else:
3752 else:
3738 doremove(f)
3753 doremove(f)
3739 for f in actions['drop'][0]:
3754 for f in actions['drop'][0]:
3740 audit_path(f)
3755 audit_path(f)
3741 repo.dirstate.remove(f)
3756 repo.dirstate.remove(f)
3742
3757
3743 normal = None
3758 normal = None
3744 if node == parent:
3759 if node == parent:
3745 # We're reverting to our parent. If possible, we'd like status
3760 # We're reverting to our parent. If possible, we'd like status
3746 # to report the file as clean. We have to use normallookup for
3761 # to report the file as clean. We have to use normallookup for
3747 # merges to avoid losing information about merged/dirty files.
3762 # merges to avoid losing information about merged/dirty files.
3748 if p2 != nullid:
3763 if p2 != nullid:
3749 normal = repo.dirstate.normallookup
3764 normal = repo.dirstate.normallookup
3750 else:
3765 else:
3751 normal = repo.dirstate.normal
3766 normal = repo.dirstate.normal
3752
3767
3753 newlyaddedandmodifiedfiles = set()
3768 newlyaddedandmodifiedfiles = set()
3754 if interactive:
3769 if interactive:
3755 # Prompt the user for changes to revert
3770 # Prompt the user for changes to revert
3756 torevert = [repo.wjoin(f) for f in actions['revert'][0]]
3771 torevert = [repo.wjoin(f) for f in actions['revert'][0]]
3757 m = scmutil.match(ctx, torevert, matcher_opts)
3772 m = scmutil.match(ctx, torevert, matcher_opts)
3758 diffopts = patch.difffeatureopts(repo.ui, whitespace=True)
3773 diffopts = patch.difffeatureopts(repo.ui, whitespace=True)
3759 diffopts.nodates = True
3774 diffopts.nodates = True
3760 diffopts.git = True
3775 diffopts.git = True
3761 operation = 'discard'
3776 operation = 'discard'
3762 reversehunks = True
3777 reversehunks = True
3763 if node != parent:
3778 if node != parent:
3764 operation = 'apply'
3779 operation = 'apply'
3765 reversehunks = False
3780 reversehunks = False
3766 if reversehunks:
3781 if reversehunks:
3767 diff = patch.diff(repo, ctx.node(), None, m, opts=diffopts)
3782 diff = patch.diff(repo, ctx.node(), None, m, opts=diffopts)
3768 else:
3783 else:
3769 diff = patch.diff(repo, None, ctx.node(), m, opts=diffopts)
3784 diff = patch.diff(repo, None, ctx.node(), m, opts=diffopts)
3770 originalchunks = patch.parsepatch(diff)
3785 originalchunks = patch.parsepatch(diff)
3771
3786
3772 try:
3787 try:
3773
3788
3774 chunks, opts = recordfilter(repo.ui, originalchunks,
3789 chunks, opts = recordfilter(repo.ui, originalchunks,
3775 operation=operation)
3790 operation=operation)
3776 if reversehunks:
3791 if reversehunks:
3777 chunks = patch.reversehunks(chunks)
3792 chunks = patch.reversehunks(chunks)
3778
3793
3779 except error.PatchError as err:
3794 except error.PatchError as err:
3780 raise error.Abort(_('error parsing patch: %s') % err)
3795 raise error.Abort(_('error parsing patch: %s') % err)
3781
3796
3782 newlyaddedandmodifiedfiles = newandmodified(chunks, originalchunks)
3797 newlyaddedandmodifiedfiles = newandmodified(chunks, originalchunks)
3783 if tobackup is None:
3798 if tobackup is None:
3784 tobackup = set()
3799 tobackup = set()
3785 # Apply changes
3800 # Apply changes
3786 fp = stringio()
3801 fp = stringio()
3787 for c in chunks:
3802 for c in chunks:
3788 # Create a backup file only if this hunk should be backed up
3803 # Create a backup file only if this hunk should be backed up
3789 if ishunk(c) and c.header.filename() in tobackup:
3804 if ishunk(c) and c.header.filename() in tobackup:
3790 abs = c.header.filename()
3805 abs = c.header.filename()
3791 target = repo.wjoin(abs)
3806 target = repo.wjoin(abs)
3792 bakname = scmutil.origpath(repo.ui, repo, m.rel(abs))
3807 bakname = scmutil.origpath(repo.ui, repo, m.rel(abs))
3793 util.copyfile(target, bakname)
3808 util.copyfile(target, bakname)
3794 tobackup.remove(abs)
3809 tobackup.remove(abs)
3795 c.write(fp)
3810 c.write(fp)
3796 dopatch = fp.tell()
3811 dopatch = fp.tell()
3797 fp.seek(0)
3812 fp.seek(0)
3798 if dopatch:
3813 if dopatch:
3799 try:
3814 try:
3800 patch.internalpatch(repo.ui, repo, fp, 1, eolmode=None)
3815 patch.internalpatch(repo.ui, repo, fp, 1, eolmode=None)
3801 except error.PatchError as err:
3816 except error.PatchError as err:
3802 raise error.Abort(str(err))
3817 raise error.Abort(str(err))
3803 del fp
3818 del fp
3804 else:
3819 else:
3805 for f in actions['revert'][0]:
3820 for f in actions['revert'][0]:
3806 checkout(f)
3821 checkout(f)
3807 if normal:
3822 if normal:
3808 normal(f)
3823 normal(f)
3809
3824
3810 for f in actions['add'][0]:
3825 for f in actions['add'][0]:
3811 # Don't checkout modified files, they are already created by the diff
3826 # Don't checkout modified files, they are already created by the diff
3812 if f not in newlyaddedandmodifiedfiles:
3827 if f not in newlyaddedandmodifiedfiles:
3813 checkout(f)
3828 checkout(f)
3814 repo.dirstate.add(f)
3829 repo.dirstate.add(f)
3815
3830
3816 normal = repo.dirstate.normallookup
3831 normal = repo.dirstate.normallookup
3817 if node == parent and p2 == nullid:
3832 if node == parent and p2 == nullid:
3818 normal = repo.dirstate.normal
3833 normal = repo.dirstate.normal
3819 for f in actions['undelete'][0]:
3834 for f in actions['undelete'][0]:
3820 checkout(f)
3835 checkout(f)
3821 normal(f)
3836 normal(f)
3822
3837
3823 copied = copies.pathcopies(repo[parent], ctx)
3838 copied = copies.pathcopies(repo[parent], ctx)
3824
3839
3825 for f in actions['add'][0] + actions['undelete'][0] + actions['revert'][0]:
3840 for f in actions['add'][0] + actions['undelete'][0] + actions['revert'][0]:
3826 if f in copied:
3841 if f in copied:
3827 repo.dirstate.copy(copied[f], f)
3842 repo.dirstate.copy(copied[f], f)
3828
3843
3829 class command(registrar.command):
3844 class command(registrar.command):
3830 """deprecated: used registrar.command instead"""
3845 """deprecated: used registrar.command instead"""
3831 def _doregister(self, func, name, *args, **kwargs):
3846 def _doregister(self, func, name, *args, **kwargs):
3832 func._deprecatedregistrar = True # flag for deprecwarn in extensions.py
3847 func._deprecatedregistrar = True # flag for deprecwarn in extensions.py
3833 return super(command, self)._doregister(func, name, *args, **kwargs)
3848 return super(command, self)._doregister(func, name, *args, **kwargs)
3834
3849
3835 # a list of (ui, repo, otherpeer, opts, missing) functions called by
3850 # a list of (ui, repo, otherpeer, opts, missing) functions called by
3836 # commands.outgoing. "missing" is "missing" of the result of
3851 # commands.outgoing. "missing" is "missing" of the result of
3837 # "findcommonoutgoing()"
3852 # "findcommonoutgoing()"
3838 outgoinghooks = util.hooks()
3853 outgoinghooks = util.hooks()
3839
3854
3840 # a list of (ui, repo) functions called by commands.summary
3855 # a list of (ui, repo) functions called by commands.summary
3841 summaryhooks = util.hooks()
3856 summaryhooks = util.hooks()
3842
3857
3843 # a list of (ui, repo, opts, changes) functions called by commands.summary.
3858 # a list of (ui, repo, opts, changes) functions called by commands.summary.
3844 #
3859 #
3845 # functions should return tuple of booleans below, if 'changes' is None:
3860 # functions should return tuple of booleans below, if 'changes' is None:
3846 # (whether-incomings-are-needed, whether-outgoings-are-needed)
3861 # (whether-incomings-are-needed, whether-outgoings-are-needed)
3847 #
3862 #
3848 # otherwise, 'changes' is a tuple of tuples below:
3863 # otherwise, 'changes' is a tuple of tuples below:
3849 # - (sourceurl, sourcebranch, sourcepeer, incoming)
3864 # - (sourceurl, sourcebranch, sourcepeer, incoming)
3850 # - (desturl, destbranch, destpeer, outgoing)
3865 # - (desturl, destbranch, destpeer, outgoing)
3851 summaryremotehooks = util.hooks()
3866 summaryremotehooks = util.hooks()
3852
3867
3853 # A list of state files kept by multistep operations like graft.
3868 # A list of state files kept by multistep operations like graft.
3854 # Since graft cannot be aborted, it is considered 'clearable' by update.
3869 # Since graft cannot be aborted, it is considered 'clearable' by update.
3855 # note: bisect is intentionally excluded
3870 # note: bisect is intentionally excluded
3856 # (state file, clearable, allowcommit, error, hint)
3871 # (state file, clearable, allowcommit, error, hint)
3857 unfinishedstates = [
3872 unfinishedstates = [
3858 ('graftstate', True, False, _('graft in progress'),
3873 ('graftstate', True, False, _('graft in progress'),
3859 _("use 'hg graft --continue' or 'hg update' to abort")),
3874 _("use 'hg graft --continue' or 'hg update' to abort")),
3860 ('updatestate', True, False, _('last update was interrupted'),
3875 ('updatestate', True, False, _('last update was interrupted'),
3861 _("use 'hg update' to get a consistent checkout"))
3876 _("use 'hg update' to get a consistent checkout"))
3862 ]
3877 ]
3863
3878
3864 def checkunfinished(repo, commit=False):
3879 def checkunfinished(repo, commit=False):
3865 '''Look for an unfinished multistep operation, like graft, and abort
3880 '''Look for an unfinished multistep operation, like graft, and abort
3866 if found. It's probably good to check this right before
3881 if found. It's probably good to check this right before
3867 bailifchanged().
3882 bailifchanged().
3868 '''
3883 '''
3869 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3884 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3870 if commit and allowcommit:
3885 if commit and allowcommit:
3871 continue
3886 continue
3872 if repo.vfs.exists(f):
3887 if repo.vfs.exists(f):
3873 raise error.Abort(msg, hint=hint)
3888 raise error.Abort(msg, hint=hint)
3874
3889
3875 def clearunfinished(repo):
3890 def clearunfinished(repo):
3876 '''Check for unfinished operations (as above), and clear the ones
3891 '''Check for unfinished operations (as above), and clear the ones
3877 that are clearable.
3892 that are clearable.
3878 '''
3893 '''
3879 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3894 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3880 if not clearable and repo.vfs.exists(f):
3895 if not clearable and repo.vfs.exists(f):
3881 raise error.Abort(msg, hint=hint)
3896 raise error.Abort(msg, hint=hint)
3882 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3897 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3883 if clearable and repo.vfs.exists(f):
3898 if clearable and repo.vfs.exists(f):
3884 util.unlink(repo.vfs.join(f))
3899 util.unlink(repo.vfs.join(f))
3885
3900
3886 afterresolvedstates = [
3901 afterresolvedstates = [
3887 ('graftstate',
3902 ('graftstate',
3888 _('hg graft --continue')),
3903 _('hg graft --continue')),
3889 ]
3904 ]
3890
3905
3891 def howtocontinue(repo):
3906 def howtocontinue(repo):
3892 '''Check for an unfinished operation and return the command to finish
3907 '''Check for an unfinished operation and return the command to finish
3893 it.
3908 it.
3894
3909
3895 afterresolvedstates tuples define a .hg/{file} and the corresponding
3910 afterresolvedstates tuples define a .hg/{file} and the corresponding
3896 command needed to finish it.
3911 command needed to finish it.
3897
3912
3898 Returns a (msg, warning) tuple. 'msg' is a string and 'warning' is
3913 Returns a (msg, warning) tuple. 'msg' is a string and 'warning' is
3899 a boolean.
3914 a boolean.
3900 '''
3915 '''
3901 contmsg = _("continue: %s")
3916 contmsg = _("continue: %s")
3902 for f, msg in afterresolvedstates:
3917 for f, msg in afterresolvedstates:
3903 if repo.vfs.exists(f):
3918 if repo.vfs.exists(f):
3904 return contmsg % msg, True
3919 return contmsg % msg, True
3905 if repo[None].dirty(missing=True, merge=False, branch=False):
3920 if repo[None].dirty(missing=True, merge=False, branch=False):
3906 return contmsg % _("hg commit"), False
3921 return contmsg % _("hg commit"), False
3907 return None, None
3922 return None, None
3908
3923
3909 def checkafterresolved(repo):
3924 def checkafterresolved(repo):
3910 '''Inform the user about the next action after completing hg resolve
3925 '''Inform the user about the next action after completing hg resolve
3911
3926
3912 If there's a matching afterresolvedstates, howtocontinue will yield
3927 If there's a matching afterresolvedstates, howtocontinue will yield
3913 repo.ui.warn as the reporter.
3928 repo.ui.warn as the reporter.
3914
3929
3915 Otherwise, it will yield repo.ui.note.
3930 Otherwise, it will yield repo.ui.note.
3916 '''
3931 '''
3917 msg, warning = howtocontinue(repo)
3932 msg, warning = howtocontinue(repo)
3918 if msg is not None:
3933 if msg is not None:
3919 if warning:
3934 if warning:
3920 repo.ui.warn("%s\n" % msg)
3935 repo.ui.warn("%s\n" % msg)
3921 else:
3936 else:
3922 repo.ui.note("%s\n" % msg)
3937 repo.ui.note("%s\n" % msg)
3923
3938
3924 def wrongtooltocontinue(repo, task):
3939 def wrongtooltocontinue(repo, task):
3925 '''Raise an abort suggesting how to properly continue if there is an
3940 '''Raise an abort suggesting how to properly continue if there is an
3926 active task.
3941 active task.
3927
3942
3928 Uses howtocontinue() to find the active task.
3943 Uses howtocontinue() to find the active task.
3929
3944
3930 If there's no task (repo.ui.note for 'hg commit'), it does not offer
3945 If there's no task (repo.ui.note for 'hg commit'), it does not offer
3931 a hint.
3946 a hint.
3932 '''
3947 '''
3933 after = howtocontinue(repo)
3948 after = howtocontinue(repo)
3934 hint = None
3949 hint = None
3935 if after[1]:
3950 if after[1]:
3936 hint = after[0]
3951 hint = after[0]
3937 raise error.Abort(_('no %s in progress') % task, hint=hint)
3952 raise error.Abort(_('no %s in progress') % task, hint=hint)
General Comments 0
You need to be logged in to leave comments. Login now