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