##// END OF EJS Templates
py3: handle keyword arguments correctly in cmdutil.py...
Pulkit Goyal -
r35351:82ee4011 default
parent child Browse files
Show More
@@ -1,3972 +1,3975 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(r'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, **pycompat.strkwargs(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: '%d' % repo.changelog.rev(node),
826 'R': lambda: '%d' % repo.changelog.rev(node),
827 'h': lambda: short(node),
827 'h': lambda: short(node),
828 'm': lambda: re.sub('[^\w]', '_', desc or '')
828 'm': lambda: re.sub('[^\w]', '_', desc or '')
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 ('%d' % repo.changelog.rev(node)).zfill(revwidth or 0))
840 ('%d' % repo.changelog.rev(node)).zfill(revwidth or 0))
841 if total is not None:
841 if total is not None:
842 expander['N'] = lambda: '%d' % total
842 expander['N'] = lambda: '%d' % total
843 if seqno is not None:
843 if seqno is not None:
844 expander['n'] = lambda: '%d' % seqno
844 expander['n'] = lambda: '%d' % 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: ('%d' % seqno).zfill(len('%d' % total)))
846 expander['n'] = (lambda: ('%d' % seqno).zfill(len('%d' % 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,
1338 **pycompat.strkwargs(opts))
1338 extra = {}
1339 extra = {}
1339 for idfunc in extrapreimport:
1340 for idfunc in extrapreimport:
1340 extrapreimportmap[idfunc](repo, extractdata, extra, opts)
1341 extrapreimportmap[idfunc](repo, extractdata, extra, opts)
1341 overrides = {}
1342 overrides = {}
1342 if partial:
1343 if partial:
1343 overrides[('ui', 'allowemptycommit')] = True
1344 overrides[('ui', 'allowemptycommit')] = True
1344 with repo.ui.configoverride(overrides, 'import'):
1345 with repo.ui.configoverride(overrides, 'import'):
1345 n = repo.commit(message, user,
1346 n = repo.commit(message, user,
1346 date, match=m,
1347 date, match=m,
1347 editor=editor, extra=extra)
1348 editor=editor, extra=extra)
1348 for idfunc in extrapostimport:
1349 for idfunc in extrapostimport:
1349 extrapostimportmap[idfunc](repo[n])
1350 extrapostimportmap[idfunc](repo[n])
1350 else:
1351 else:
1351 if opts.get('exact') or importbranch:
1352 if opts.get('exact') or importbranch:
1352 branch = branch or 'default'
1353 branch = branch or 'default'
1353 else:
1354 else:
1354 branch = p1.branch()
1355 branch = p1.branch()
1355 store = patch.filestore()
1356 store = patch.filestore()
1356 try:
1357 try:
1357 files = set()
1358 files = set()
1358 try:
1359 try:
1359 patch.patchrepo(ui, repo, p1, store, tmpname, strip, prefix,
1360 patch.patchrepo(ui, repo, p1, store, tmpname, strip, prefix,
1360 files, eolmode=None)
1361 files, eolmode=None)
1361 except error.PatchError as e:
1362 except error.PatchError as e:
1362 raise error.Abort(str(e))
1363 raise error.Abort(str(e))
1363 if opts.get('exact'):
1364 if opts.get('exact'):
1364 editor = None
1365 editor = None
1365 else:
1366 else:
1366 editor = getcommiteditor(editform='import.bypass')
1367 editor = getcommiteditor(editform='import.bypass')
1367 memctx = context.memctx(repo, (p1.node(), p2.node()),
1368 memctx = context.memctx(repo, (p1.node(), p2.node()),
1368 message,
1369 message,
1369 files=files,
1370 files=files,
1370 filectxfn=store,
1371 filectxfn=store,
1371 user=user,
1372 user=user,
1372 date=date,
1373 date=date,
1373 branch=branch,
1374 branch=branch,
1374 editor=editor)
1375 editor=editor)
1375 n = memctx.commit()
1376 n = memctx.commit()
1376 finally:
1377 finally:
1377 store.close()
1378 store.close()
1378 if opts.get('exact') and nocommit:
1379 if opts.get('exact') and nocommit:
1379 # --exact with --no-commit is still useful in that it does merge
1380 # --exact with --no-commit is still useful in that it does merge
1380 # and branch bits
1381 # and branch bits
1381 ui.warn(_("warning: can't check exact import with --no-commit\n"))
1382 ui.warn(_("warning: can't check exact import with --no-commit\n"))
1382 elif opts.get('exact') and hex(n) != nodeid:
1383 elif opts.get('exact') and hex(n) != nodeid:
1383 raise error.Abort(_('patch is damaged or loses information'))
1384 raise error.Abort(_('patch is damaged or loses information'))
1384 msg = _('applied to working directory')
1385 msg = _('applied to working directory')
1385 if n:
1386 if n:
1386 # i18n: refers to a short changeset id
1387 # i18n: refers to a short changeset id
1387 msg = _('created %s') % short(n)
1388 msg = _('created %s') % short(n)
1388 return (msg, n, rejects)
1389 return (msg, n, rejects)
1389 finally:
1390 finally:
1390 os.unlink(tmpname)
1391 os.unlink(tmpname)
1391
1392
1392 # facility to let extensions include additional data in an exported patch
1393 # facility to let extensions include additional data in an exported patch
1393 # list of identifiers to be executed in order
1394 # list of identifiers to be executed in order
1394 extraexport = []
1395 extraexport = []
1395 # mapping from identifier to actual export function
1396 # mapping from identifier to actual export function
1396 # function as to return a string to be added to the header or None
1397 # function as to return a string to be added to the header or None
1397 # it is given two arguments (sequencenumber, changectx)
1398 # it is given two arguments (sequencenumber, changectx)
1398 extraexportmap = {}
1399 extraexportmap = {}
1399
1400
1400 def _exportsingle(repo, ctx, match, switch_parent, rev, seqno, write, diffopts):
1401 def _exportsingle(repo, ctx, match, switch_parent, rev, seqno, write, diffopts):
1401 node = scmutil.binnode(ctx)
1402 node = scmutil.binnode(ctx)
1402 parents = [p.node() for p in ctx.parents() if p]
1403 parents = [p.node() for p in ctx.parents() if p]
1403 branch = ctx.branch()
1404 branch = ctx.branch()
1404 if switch_parent:
1405 if switch_parent:
1405 parents.reverse()
1406 parents.reverse()
1406
1407
1407 if parents:
1408 if parents:
1408 prev = parents[0]
1409 prev = parents[0]
1409 else:
1410 else:
1410 prev = nullid
1411 prev = nullid
1411
1412
1412 write("# HG changeset patch\n")
1413 write("# HG changeset patch\n")
1413 write("# User %s\n" % ctx.user())
1414 write("# User %s\n" % ctx.user())
1414 write("# Date %d %d\n" % ctx.date())
1415 write("# Date %d %d\n" % ctx.date())
1415 write("# %s\n" % util.datestr(ctx.date()))
1416 write("# %s\n" % util.datestr(ctx.date()))
1416 if branch and branch != 'default':
1417 if branch and branch != 'default':
1417 write("# Branch %s\n" % branch)
1418 write("# Branch %s\n" % branch)
1418 write("# Node ID %s\n" % hex(node))
1419 write("# Node ID %s\n" % hex(node))
1419 write("# Parent %s\n" % hex(prev))
1420 write("# Parent %s\n" % hex(prev))
1420 if len(parents) > 1:
1421 if len(parents) > 1:
1421 write("# Parent %s\n" % hex(parents[1]))
1422 write("# Parent %s\n" % hex(parents[1]))
1422
1423
1423 for headerid in extraexport:
1424 for headerid in extraexport:
1424 header = extraexportmap[headerid](seqno, ctx)
1425 header = extraexportmap[headerid](seqno, ctx)
1425 if header is not None:
1426 if header is not None:
1426 write('# %s\n' % header)
1427 write('# %s\n' % header)
1427 write(ctx.description().rstrip())
1428 write(ctx.description().rstrip())
1428 write("\n\n")
1429 write("\n\n")
1429
1430
1430 for chunk, label in patch.diffui(repo, prev, node, match, opts=diffopts):
1431 for chunk, label in patch.diffui(repo, prev, node, match, opts=diffopts):
1431 write(chunk, label=label)
1432 write(chunk, label=label)
1432
1433
1433 def export(repo, revs, fntemplate='hg-%h.patch', fp=None, switch_parent=False,
1434 def export(repo, revs, fntemplate='hg-%h.patch', fp=None, switch_parent=False,
1434 opts=None, match=None):
1435 opts=None, match=None):
1435 '''export changesets as hg patches
1436 '''export changesets as hg patches
1436
1437
1437 Args:
1438 Args:
1438 repo: The repository from which we're exporting revisions.
1439 repo: The repository from which we're exporting revisions.
1439 revs: A list of revisions to export as revision numbers.
1440 revs: A list of revisions to export as revision numbers.
1440 fntemplate: An optional string to use for generating patch file names.
1441 fntemplate: An optional string to use for generating patch file names.
1441 fp: An optional file-like object to which patches should be written.
1442 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.
1443 switch_parent: If True, show diffs against second parent when not nullid.
1443 Default is false, which always shows diff against p1.
1444 Default is false, which always shows diff against p1.
1444 opts: diff options to use for generating the patch.
1445 opts: diff options to use for generating the patch.
1445 match: If specified, only export changes to files matching this matcher.
1446 match: If specified, only export changes to files matching this matcher.
1446
1447
1447 Returns:
1448 Returns:
1448 Nothing.
1449 Nothing.
1449
1450
1450 Side Effect:
1451 Side Effect:
1451 "HG Changeset Patch" data is emitted to one of the following
1452 "HG Changeset Patch" data is emitted to one of the following
1452 destinations:
1453 destinations:
1453 fp is specified: All revs are written to the specified
1454 fp is specified: All revs are written to the specified
1454 file-like object.
1455 file-like object.
1455 fntemplate specified: Each rev is written to a unique file named using
1456 fntemplate specified: Each rev is written to a unique file named using
1456 the given template.
1457 the given template.
1457 Neither fp nor template specified: All revs written to repo.ui.write()
1458 Neither fp nor template specified: All revs written to repo.ui.write()
1458 '''
1459 '''
1459
1460
1460 total = len(revs)
1461 total = len(revs)
1461 revwidth = max(len(str(rev)) for rev in revs)
1462 revwidth = max(len(str(rev)) for rev in revs)
1462 filemode = {}
1463 filemode = {}
1463
1464
1464 write = None
1465 write = None
1465 dest = '<unnamed>'
1466 dest = '<unnamed>'
1466 if fp:
1467 if fp:
1467 dest = getattr(fp, 'name', dest)
1468 dest = getattr(fp, 'name', dest)
1468 def write(s, **kw):
1469 def write(s, **kw):
1469 fp.write(s)
1470 fp.write(s)
1470 elif not fntemplate:
1471 elif not fntemplate:
1471 write = repo.ui.write
1472 write = repo.ui.write
1472
1473
1473 for seqno, rev in enumerate(revs, 1):
1474 for seqno, rev in enumerate(revs, 1):
1474 ctx = repo[rev]
1475 ctx = repo[rev]
1475 fo = None
1476 fo = None
1476 if not fp and fntemplate:
1477 if not fp and fntemplate:
1477 desc_lines = ctx.description().rstrip().split('\n')
1478 desc_lines = ctx.description().rstrip().split('\n')
1478 desc = desc_lines[0] #Commit always has a first line.
1479 desc = desc_lines[0] #Commit always has a first line.
1479 fo = makefileobj(repo, fntemplate, ctx.node(), desc=desc,
1480 fo = makefileobj(repo, fntemplate, ctx.node(), desc=desc,
1480 total=total, seqno=seqno, revwidth=revwidth,
1481 total=total, seqno=seqno, revwidth=revwidth,
1481 mode='wb', modemap=filemode)
1482 mode='wb', modemap=filemode)
1482 dest = fo.name
1483 dest = fo.name
1483 def write(s, **kw):
1484 def write(s, **kw):
1484 fo.write(s)
1485 fo.write(s)
1485 if not dest.startswith('<'):
1486 if not dest.startswith('<'):
1486 repo.ui.note("%s\n" % dest)
1487 repo.ui.note("%s\n" % dest)
1487 _exportsingle(
1488 _exportsingle(
1488 repo, ctx, match, switch_parent, rev, seqno, write, opts)
1489 repo, ctx, match, switch_parent, rev, seqno, write, opts)
1489 if fo is not None:
1490 if fo is not None:
1490 fo.close()
1491 fo.close()
1491
1492
1492 def diffordiffstat(ui, repo, diffopts, node1, node2, match,
1493 def diffordiffstat(ui, repo, diffopts, node1, node2, match,
1493 changes=None, stat=False, fp=None, prefix='',
1494 changes=None, stat=False, fp=None, prefix='',
1494 root='', listsubrepos=False, hunksfilterfn=None):
1495 root='', listsubrepos=False, hunksfilterfn=None):
1495 '''show diff or diffstat.'''
1496 '''show diff or diffstat.'''
1496 if fp is None:
1497 if fp is None:
1497 write = ui.write
1498 write = ui.write
1498 else:
1499 else:
1499 def write(s, **kw):
1500 def write(s, **kw):
1500 fp.write(s)
1501 fp.write(s)
1501
1502
1502 if root:
1503 if root:
1503 relroot = pathutil.canonpath(repo.root, repo.getcwd(), root)
1504 relroot = pathutil.canonpath(repo.root, repo.getcwd(), root)
1504 else:
1505 else:
1505 relroot = ''
1506 relroot = ''
1506 if relroot != '':
1507 if relroot != '':
1507 # XXX relative roots currently don't work if the root is within a
1508 # XXX relative roots currently don't work if the root is within a
1508 # subrepo
1509 # subrepo
1509 uirelroot = match.uipath(relroot)
1510 uirelroot = match.uipath(relroot)
1510 relroot += '/'
1511 relroot += '/'
1511 for matchroot in match.files():
1512 for matchroot in match.files():
1512 if not matchroot.startswith(relroot):
1513 if not matchroot.startswith(relroot):
1513 ui.warn(_('warning: %s not inside relative root %s\n') % (
1514 ui.warn(_('warning: %s not inside relative root %s\n') % (
1514 match.uipath(matchroot), uirelroot))
1515 match.uipath(matchroot), uirelroot))
1515
1516
1516 if stat:
1517 if stat:
1517 diffopts = diffopts.copy(context=0)
1518 diffopts = diffopts.copy(context=0)
1518 width = 80
1519 width = 80
1519 if not ui.plain():
1520 if not ui.plain():
1520 width = ui.termwidth()
1521 width = ui.termwidth()
1521 chunks = patch.diff(repo, node1, node2, match, changes, opts=diffopts,
1522 chunks = patch.diff(repo, node1, node2, match, changes, opts=diffopts,
1522 prefix=prefix, relroot=relroot,
1523 prefix=prefix, relroot=relroot,
1523 hunksfilterfn=hunksfilterfn)
1524 hunksfilterfn=hunksfilterfn)
1524 for chunk, label in patch.diffstatui(util.iterlines(chunks),
1525 for chunk, label in patch.diffstatui(util.iterlines(chunks),
1525 width=width):
1526 width=width):
1526 write(chunk, label=label)
1527 write(chunk, label=label)
1527 else:
1528 else:
1528 for chunk, label in patch.diffui(repo, node1, node2, match,
1529 for chunk, label in patch.diffui(repo, node1, node2, match,
1529 changes, opts=diffopts, prefix=prefix,
1530 changes, opts=diffopts, prefix=prefix,
1530 relroot=relroot,
1531 relroot=relroot,
1531 hunksfilterfn=hunksfilterfn):
1532 hunksfilterfn=hunksfilterfn):
1532 write(chunk, label=label)
1533 write(chunk, label=label)
1533
1534
1534 if listsubrepos:
1535 if listsubrepos:
1535 ctx1 = repo[node1]
1536 ctx1 = repo[node1]
1536 ctx2 = repo[node2]
1537 ctx2 = repo[node2]
1537 for subpath, sub in scmutil.itersubrepos(ctx1, ctx2):
1538 for subpath, sub in scmutil.itersubrepos(ctx1, ctx2):
1538 tempnode2 = node2
1539 tempnode2 = node2
1539 try:
1540 try:
1540 if node2 is not None:
1541 if node2 is not None:
1541 tempnode2 = ctx2.substate[subpath][1]
1542 tempnode2 = ctx2.substate[subpath][1]
1542 except KeyError:
1543 except KeyError:
1543 # A subrepo that existed in node1 was deleted between node1 and
1544 # A subrepo that existed in node1 was deleted between node1 and
1544 # node2 (inclusive). Thus, ctx2's substate won't contain that
1545 # node2 (inclusive). Thus, ctx2's substate won't contain that
1545 # subpath. The best we can do is to ignore it.
1546 # subpath. The best we can do is to ignore it.
1546 tempnode2 = None
1547 tempnode2 = None
1547 submatch = matchmod.subdirmatcher(subpath, match)
1548 submatch = matchmod.subdirmatcher(subpath, match)
1548 sub.diff(ui, diffopts, tempnode2, submatch, changes=changes,
1549 sub.diff(ui, diffopts, tempnode2, submatch, changes=changes,
1549 stat=stat, fp=fp, prefix=prefix)
1550 stat=stat, fp=fp, prefix=prefix)
1550
1551
1551 def _changesetlabels(ctx):
1552 def _changesetlabels(ctx):
1552 labels = ['log.changeset', 'changeset.%s' % ctx.phasestr()]
1553 labels = ['log.changeset', 'changeset.%s' % ctx.phasestr()]
1553 if ctx.obsolete():
1554 if ctx.obsolete():
1554 labels.append('changeset.obsolete')
1555 labels.append('changeset.obsolete')
1555 if ctx.isunstable():
1556 if ctx.isunstable():
1556 labels.append('changeset.unstable')
1557 labels.append('changeset.unstable')
1557 for instability in ctx.instabilities():
1558 for instability in ctx.instabilities():
1558 labels.append('instability.%s' % instability)
1559 labels.append('instability.%s' % instability)
1559 return ' '.join(labels)
1560 return ' '.join(labels)
1560
1561
1561 class changeset_printer(object):
1562 class changeset_printer(object):
1562 '''show changeset information when templating not requested.'''
1563 '''show changeset information when templating not requested.'''
1563
1564
1564 def __init__(self, ui, repo, matchfn, diffopts, buffered):
1565 def __init__(self, ui, repo, matchfn, diffopts, buffered):
1565 self.ui = ui
1566 self.ui = ui
1566 self.repo = repo
1567 self.repo = repo
1567 self.buffered = buffered
1568 self.buffered = buffered
1568 self.matchfn = matchfn
1569 self.matchfn = matchfn
1569 self.diffopts = diffopts
1570 self.diffopts = diffopts
1570 self.header = {}
1571 self.header = {}
1571 self.hunk = {}
1572 self.hunk = {}
1572 self.lastheader = None
1573 self.lastheader = None
1573 self.footer = None
1574 self.footer = None
1574 self._columns = templatekw.getlogcolumns()
1575 self._columns = templatekw.getlogcolumns()
1575
1576
1576 def flush(self, ctx):
1577 def flush(self, ctx):
1577 rev = ctx.rev()
1578 rev = ctx.rev()
1578 if rev in self.header:
1579 if rev in self.header:
1579 h = self.header[rev]
1580 h = self.header[rev]
1580 if h != self.lastheader:
1581 if h != self.lastheader:
1581 self.lastheader = h
1582 self.lastheader = h
1582 self.ui.write(h)
1583 self.ui.write(h)
1583 del self.header[rev]
1584 del self.header[rev]
1584 if rev in self.hunk:
1585 if rev in self.hunk:
1585 self.ui.write(self.hunk[rev])
1586 self.ui.write(self.hunk[rev])
1586 del self.hunk[rev]
1587 del self.hunk[rev]
1587 return 1
1588 return 1
1588 return 0
1589 return 0
1589
1590
1590 def close(self):
1591 def close(self):
1591 if self.footer:
1592 if self.footer:
1592 self.ui.write(self.footer)
1593 self.ui.write(self.footer)
1593
1594
1594 def show(self, ctx, copies=None, matchfn=None, hunksfilterfn=None,
1595 def show(self, ctx, copies=None, matchfn=None, hunksfilterfn=None,
1595 **props):
1596 **props):
1596 props = pycompat.byteskwargs(props)
1597 props = pycompat.byteskwargs(props)
1597 if self.buffered:
1598 if self.buffered:
1598 self.ui.pushbuffer(labeled=True)
1599 self.ui.pushbuffer(labeled=True)
1599 self._show(ctx, copies, matchfn, hunksfilterfn, props)
1600 self._show(ctx, copies, matchfn, hunksfilterfn, props)
1600 self.hunk[ctx.rev()] = self.ui.popbuffer()
1601 self.hunk[ctx.rev()] = self.ui.popbuffer()
1601 else:
1602 else:
1602 self._show(ctx, copies, matchfn, hunksfilterfn, props)
1603 self._show(ctx, copies, matchfn, hunksfilterfn, props)
1603
1604
1604 def _show(self, ctx, copies, matchfn, hunksfilterfn, props):
1605 def _show(self, ctx, copies, matchfn, hunksfilterfn, props):
1605 '''show a single changeset or file revision'''
1606 '''show a single changeset or file revision'''
1606 changenode = ctx.node()
1607 changenode = ctx.node()
1607 rev = ctx.rev()
1608 rev = ctx.rev()
1608
1609
1609 if self.ui.quiet:
1610 if self.ui.quiet:
1610 self.ui.write("%s\n" % scmutil.formatchangeid(ctx),
1611 self.ui.write("%s\n" % scmutil.formatchangeid(ctx),
1611 label='log.node')
1612 label='log.node')
1612 return
1613 return
1613
1614
1614 columns = self._columns
1615 columns = self._columns
1615 self.ui.write(columns['changeset'] % scmutil.formatchangeid(ctx),
1616 self.ui.write(columns['changeset'] % scmutil.formatchangeid(ctx),
1616 label=_changesetlabels(ctx))
1617 label=_changesetlabels(ctx))
1617
1618
1618 # branches are shown first before any other names due to backwards
1619 # branches are shown first before any other names due to backwards
1619 # compatibility
1620 # compatibility
1620 branch = ctx.branch()
1621 branch = ctx.branch()
1621 # don't show the default branch name
1622 # don't show the default branch name
1622 if branch != 'default':
1623 if branch != 'default':
1623 self.ui.write(columns['branch'] % branch, label='log.branch')
1624 self.ui.write(columns['branch'] % branch, label='log.branch')
1624
1625
1625 for nsname, ns in self.repo.names.iteritems():
1626 for nsname, ns in self.repo.names.iteritems():
1626 # branches has special logic already handled above, so here we just
1627 # branches has special logic already handled above, so here we just
1627 # skip it
1628 # skip it
1628 if nsname == 'branches':
1629 if nsname == 'branches':
1629 continue
1630 continue
1630 # we will use the templatename as the color name since those two
1631 # we will use the templatename as the color name since those two
1631 # should be the same
1632 # should be the same
1632 for name in ns.names(self.repo, changenode):
1633 for name in ns.names(self.repo, changenode):
1633 self.ui.write(ns.logfmt % name,
1634 self.ui.write(ns.logfmt % name,
1634 label='log.%s' % ns.colorname)
1635 label='log.%s' % ns.colorname)
1635 if self.ui.debugflag:
1636 if self.ui.debugflag:
1636 self.ui.write(columns['phase'] % ctx.phasestr(), label='log.phase')
1637 self.ui.write(columns['phase'] % ctx.phasestr(), label='log.phase')
1637 for pctx in scmutil.meaningfulparents(self.repo, ctx):
1638 for pctx in scmutil.meaningfulparents(self.repo, ctx):
1638 label = 'log.parent changeset.%s' % pctx.phasestr()
1639 label = 'log.parent changeset.%s' % pctx.phasestr()
1639 self.ui.write(columns['parent'] % scmutil.formatchangeid(pctx),
1640 self.ui.write(columns['parent'] % scmutil.formatchangeid(pctx),
1640 label=label)
1641 label=label)
1641
1642
1642 if self.ui.debugflag and rev is not None:
1643 if self.ui.debugflag and rev is not None:
1643 mnode = ctx.manifestnode()
1644 mnode = ctx.manifestnode()
1644 mrev = self.repo.manifestlog._revlog.rev(mnode)
1645 mrev = self.repo.manifestlog._revlog.rev(mnode)
1645 self.ui.write(columns['manifest']
1646 self.ui.write(columns['manifest']
1646 % scmutil.formatrevnode(self.ui, mrev, mnode),
1647 % scmutil.formatrevnode(self.ui, mrev, mnode),
1647 label='ui.debug log.manifest')
1648 label='ui.debug log.manifest')
1648 self.ui.write(columns['user'] % ctx.user(), label='log.user')
1649 self.ui.write(columns['user'] % ctx.user(), label='log.user')
1649 self.ui.write(columns['date'] % util.datestr(ctx.date()),
1650 self.ui.write(columns['date'] % util.datestr(ctx.date()),
1650 label='log.date')
1651 label='log.date')
1651
1652
1652 if ctx.isunstable():
1653 if ctx.isunstable():
1653 instabilities = ctx.instabilities()
1654 instabilities = ctx.instabilities()
1654 self.ui.write(columns['instability'] % ', '.join(instabilities),
1655 self.ui.write(columns['instability'] % ', '.join(instabilities),
1655 label='log.instability')
1656 label='log.instability')
1656
1657
1657 elif ctx.obsolete():
1658 elif ctx.obsolete():
1658 self._showobsfate(ctx)
1659 self._showobsfate(ctx)
1659
1660
1660 self._exthook(ctx)
1661 self._exthook(ctx)
1661
1662
1662 if self.ui.debugflag:
1663 if self.ui.debugflag:
1663 files = ctx.p1().status(ctx)[:3]
1664 files = ctx.p1().status(ctx)[:3]
1664 for key, value in zip(['files', 'files+', 'files-'], files):
1665 for key, value in zip(['files', 'files+', 'files-'], files):
1665 if value:
1666 if value:
1666 self.ui.write(columns[key] % " ".join(value),
1667 self.ui.write(columns[key] % " ".join(value),
1667 label='ui.debug log.files')
1668 label='ui.debug log.files')
1668 elif ctx.files() and self.ui.verbose:
1669 elif ctx.files() and self.ui.verbose:
1669 self.ui.write(columns['files'] % " ".join(ctx.files()),
1670 self.ui.write(columns['files'] % " ".join(ctx.files()),
1670 label='ui.note log.files')
1671 label='ui.note log.files')
1671 if copies and self.ui.verbose:
1672 if copies and self.ui.verbose:
1672 copies = ['%s (%s)' % c for c in copies]
1673 copies = ['%s (%s)' % c for c in copies]
1673 self.ui.write(columns['copies'] % ' '.join(copies),
1674 self.ui.write(columns['copies'] % ' '.join(copies),
1674 label='ui.note log.copies')
1675 label='ui.note log.copies')
1675
1676
1676 extra = ctx.extra()
1677 extra = ctx.extra()
1677 if extra and self.ui.debugflag:
1678 if extra and self.ui.debugflag:
1678 for key, value in sorted(extra.items()):
1679 for key, value in sorted(extra.items()):
1679 self.ui.write(columns['extra'] % (key, util.escapestr(value)),
1680 self.ui.write(columns['extra'] % (key, util.escapestr(value)),
1680 label='ui.debug log.extra')
1681 label='ui.debug log.extra')
1681
1682
1682 description = ctx.description().strip()
1683 description = ctx.description().strip()
1683 if description:
1684 if description:
1684 if self.ui.verbose:
1685 if self.ui.verbose:
1685 self.ui.write(_("description:\n"),
1686 self.ui.write(_("description:\n"),
1686 label='ui.note log.description')
1687 label='ui.note log.description')
1687 self.ui.write(description,
1688 self.ui.write(description,
1688 label='ui.note log.description')
1689 label='ui.note log.description')
1689 self.ui.write("\n\n")
1690 self.ui.write("\n\n")
1690 else:
1691 else:
1691 self.ui.write(columns['summary'] % description.splitlines()[0],
1692 self.ui.write(columns['summary'] % description.splitlines()[0],
1692 label='log.summary')
1693 label='log.summary')
1693 self.ui.write("\n")
1694 self.ui.write("\n")
1694
1695
1695 self.showpatch(ctx, matchfn, hunksfilterfn=hunksfilterfn)
1696 self.showpatch(ctx, matchfn, hunksfilterfn=hunksfilterfn)
1696
1697
1697 def _showobsfate(self, ctx):
1698 def _showobsfate(self, ctx):
1698 obsfate = templatekw.showobsfate(repo=self.repo, ctx=ctx, ui=self.ui)
1699 obsfate = templatekw.showobsfate(repo=self.repo, ctx=ctx, ui=self.ui)
1699
1700
1700 if obsfate:
1701 if obsfate:
1701 for obsfateline in obsfate:
1702 for obsfateline in obsfate:
1702 self.ui.write(self._columns['obsolete'] % obsfateline,
1703 self.ui.write(self._columns['obsolete'] % obsfateline,
1703 label='log.obsfate')
1704 label='log.obsfate')
1704
1705
1705 def _exthook(self, ctx):
1706 def _exthook(self, ctx):
1706 '''empty method used by extension as a hook point
1707 '''empty method used by extension as a hook point
1707 '''
1708 '''
1708
1709
1709 def showpatch(self, ctx, matchfn, hunksfilterfn=None):
1710 def showpatch(self, ctx, matchfn, hunksfilterfn=None):
1710 if not matchfn:
1711 if not matchfn:
1711 matchfn = self.matchfn
1712 matchfn = self.matchfn
1712 if matchfn:
1713 if matchfn:
1713 stat = self.diffopts.get('stat')
1714 stat = self.diffopts.get('stat')
1714 diff = self.diffopts.get('patch')
1715 diff = self.diffopts.get('patch')
1715 diffopts = patch.diffallopts(self.ui, self.diffopts)
1716 diffopts = patch.diffallopts(self.ui, self.diffopts)
1716 node = ctx.node()
1717 node = ctx.node()
1717 prev = ctx.p1().node()
1718 prev = ctx.p1().node()
1718 if stat:
1719 if stat:
1719 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1720 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1720 match=matchfn, stat=True,
1721 match=matchfn, stat=True,
1721 hunksfilterfn=hunksfilterfn)
1722 hunksfilterfn=hunksfilterfn)
1722 if diff:
1723 if diff:
1723 if stat:
1724 if stat:
1724 self.ui.write("\n")
1725 self.ui.write("\n")
1725 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1726 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1726 match=matchfn, stat=False,
1727 match=matchfn, stat=False,
1727 hunksfilterfn=hunksfilterfn)
1728 hunksfilterfn=hunksfilterfn)
1728 self.ui.write("\n")
1729 self.ui.write("\n")
1729
1730
1730 class jsonchangeset(changeset_printer):
1731 class jsonchangeset(changeset_printer):
1731 '''format changeset information.'''
1732 '''format changeset information.'''
1732
1733
1733 def __init__(self, ui, repo, matchfn, diffopts, buffered):
1734 def __init__(self, ui, repo, matchfn, diffopts, buffered):
1734 changeset_printer.__init__(self, ui, repo, matchfn, diffopts, buffered)
1735 changeset_printer.__init__(self, ui, repo, matchfn, diffopts, buffered)
1735 self.cache = {}
1736 self.cache = {}
1736 self._first = True
1737 self._first = True
1737
1738
1738 def close(self):
1739 def close(self):
1739 if not self._first:
1740 if not self._first:
1740 self.ui.write("\n]\n")
1741 self.ui.write("\n]\n")
1741 else:
1742 else:
1742 self.ui.write("[]\n")
1743 self.ui.write("[]\n")
1743
1744
1744 def _show(self, ctx, copies, matchfn, hunksfilterfn, props):
1745 def _show(self, ctx, copies, matchfn, hunksfilterfn, props):
1745 '''show a single changeset or file revision'''
1746 '''show a single changeset or file revision'''
1746 rev = ctx.rev()
1747 rev = ctx.rev()
1747 if rev is None:
1748 if rev is None:
1748 jrev = jnode = 'null'
1749 jrev = jnode = 'null'
1749 else:
1750 else:
1750 jrev = '%d' % rev
1751 jrev = '%d' % rev
1751 jnode = '"%s"' % hex(ctx.node())
1752 jnode = '"%s"' % hex(ctx.node())
1752 j = encoding.jsonescape
1753 j = encoding.jsonescape
1753
1754
1754 if self._first:
1755 if self._first:
1755 self.ui.write("[\n {")
1756 self.ui.write("[\n {")
1756 self._first = False
1757 self._first = False
1757 else:
1758 else:
1758 self.ui.write(",\n {")
1759 self.ui.write(",\n {")
1759
1760
1760 if self.ui.quiet:
1761 if self.ui.quiet:
1761 self.ui.write(('\n "rev": %s') % jrev)
1762 self.ui.write(('\n "rev": %s') % jrev)
1762 self.ui.write((',\n "node": %s') % jnode)
1763 self.ui.write((',\n "node": %s') % jnode)
1763 self.ui.write('\n }')
1764 self.ui.write('\n }')
1764 return
1765 return
1765
1766
1766 self.ui.write(('\n "rev": %s') % jrev)
1767 self.ui.write(('\n "rev": %s') % jrev)
1767 self.ui.write((',\n "node": %s') % jnode)
1768 self.ui.write((',\n "node": %s') % jnode)
1768 self.ui.write((',\n "branch": "%s"') % j(ctx.branch()))
1769 self.ui.write((',\n "branch": "%s"') % j(ctx.branch()))
1769 self.ui.write((',\n "phase": "%s"') % ctx.phasestr())
1770 self.ui.write((',\n "phase": "%s"') % ctx.phasestr())
1770 self.ui.write((',\n "user": "%s"') % j(ctx.user()))
1771 self.ui.write((',\n "user": "%s"') % j(ctx.user()))
1771 self.ui.write((',\n "date": [%d, %d]') % ctx.date())
1772 self.ui.write((',\n "date": [%d, %d]') % ctx.date())
1772 self.ui.write((',\n "desc": "%s"') % j(ctx.description()))
1773 self.ui.write((',\n "desc": "%s"') % j(ctx.description()))
1773
1774
1774 self.ui.write((',\n "bookmarks": [%s]') %
1775 self.ui.write((',\n "bookmarks": [%s]') %
1775 ", ".join('"%s"' % j(b) for b in ctx.bookmarks()))
1776 ", ".join('"%s"' % j(b) for b in ctx.bookmarks()))
1776 self.ui.write((',\n "tags": [%s]') %
1777 self.ui.write((',\n "tags": [%s]') %
1777 ", ".join('"%s"' % j(t) for t in ctx.tags()))
1778 ", ".join('"%s"' % j(t) for t in ctx.tags()))
1778 self.ui.write((',\n "parents": [%s]') %
1779 self.ui.write((',\n "parents": [%s]') %
1779 ", ".join('"%s"' % c.hex() for c in ctx.parents()))
1780 ", ".join('"%s"' % c.hex() for c in ctx.parents()))
1780
1781
1781 if self.ui.debugflag:
1782 if self.ui.debugflag:
1782 if rev is None:
1783 if rev is None:
1783 jmanifestnode = 'null'
1784 jmanifestnode = 'null'
1784 else:
1785 else:
1785 jmanifestnode = '"%s"' % hex(ctx.manifestnode())
1786 jmanifestnode = '"%s"' % hex(ctx.manifestnode())
1786 self.ui.write((',\n "manifest": %s') % jmanifestnode)
1787 self.ui.write((',\n "manifest": %s') % jmanifestnode)
1787
1788
1788 self.ui.write((',\n "extra": {%s}') %
1789 self.ui.write((',\n "extra": {%s}') %
1789 ", ".join('"%s": "%s"' % (j(k), j(v))
1790 ", ".join('"%s": "%s"' % (j(k), j(v))
1790 for k, v in ctx.extra().items()))
1791 for k, v in ctx.extra().items()))
1791
1792
1792 files = ctx.p1().status(ctx)
1793 files = ctx.p1().status(ctx)
1793 self.ui.write((',\n "modified": [%s]') %
1794 self.ui.write((',\n "modified": [%s]') %
1794 ", ".join('"%s"' % j(f) for f in files[0]))
1795 ", ".join('"%s"' % j(f) for f in files[0]))
1795 self.ui.write((',\n "added": [%s]') %
1796 self.ui.write((',\n "added": [%s]') %
1796 ", ".join('"%s"' % j(f) for f in files[1]))
1797 ", ".join('"%s"' % j(f) for f in files[1]))
1797 self.ui.write((',\n "removed": [%s]') %
1798 self.ui.write((',\n "removed": [%s]') %
1798 ", ".join('"%s"' % j(f) for f in files[2]))
1799 ", ".join('"%s"' % j(f) for f in files[2]))
1799
1800
1800 elif self.ui.verbose:
1801 elif self.ui.verbose:
1801 self.ui.write((',\n "files": [%s]') %
1802 self.ui.write((',\n "files": [%s]') %
1802 ", ".join('"%s"' % j(f) for f in ctx.files()))
1803 ", ".join('"%s"' % j(f) for f in ctx.files()))
1803
1804
1804 if copies:
1805 if copies:
1805 self.ui.write((',\n "copies": {%s}') %
1806 self.ui.write((',\n "copies": {%s}') %
1806 ", ".join('"%s": "%s"' % (j(k), j(v))
1807 ", ".join('"%s": "%s"' % (j(k), j(v))
1807 for k, v in copies))
1808 for k, v in copies))
1808
1809
1809 matchfn = self.matchfn
1810 matchfn = self.matchfn
1810 if matchfn:
1811 if matchfn:
1811 stat = self.diffopts.get('stat')
1812 stat = self.diffopts.get('stat')
1812 diff = self.diffopts.get('patch')
1813 diff = self.diffopts.get('patch')
1813 diffopts = patch.difffeatureopts(self.ui, self.diffopts, git=True)
1814 diffopts = patch.difffeatureopts(self.ui, self.diffopts, git=True)
1814 node, prev = ctx.node(), ctx.p1().node()
1815 node, prev = ctx.node(), ctx.p1().node()
1815 if stat:
1816 if stat:
1816 self.ui.pushbuffer()
1817 self.ui.pushbuffer()
1817 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1818 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1818 match=matchfn, stat=True)
1819 match=matchfn, stat=True)
1819 self.ui.write((',\n "diffstat": "%s"')
1820 self.ui.write((',\n "diffstat": "%s"')
1820 % j(self.ui.popbuffer()))
1821 % j(self.ui.popbuffer()))
1821 if diff:
1822 if diff:
1822 self.ui.pushbuffer()
1823 self.ui.pushbuffer()
1823 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1824 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1824 match=matchfn, stat=False)
1825 match=matchfn, stat=False)
1825 self.ui.write((',\n "diff": "%s"') % j(self.ui.popbuffer()))
1826 self.ui.write((',\n "diff": "%s"') % j(self.ui.popbuffer()))
1826
1827
1827 self.ui.write("\n }")
1828 self.ui.write("\n }")
1828
1829
1829 class changeset_templater(changeset_printer):
1830 class changeset_templater(changeset_printer):
1830 '''format changeset information.
1831 '''format changeset information.
1831
1832
1832 Note: there are a variety of convenience functions to build a
1833 Note: there are a variety of convenience functions to build a
1833 changeset_templater for common cases. See functions such as:
1834 changeset_templater for common cases. See functions such as:
1834 makelogtemplater, show_changeset, buildcommittemplate, or other
1835 makelogtemplater, show_changeset, buildcommittemplate, or other
1835 functions that use changesest_templater.
1836 functions that use changesest_templater.
1836 '''
1837 '''
1837
1838
1838 # Arguments before "buffered" used to be positional. Consider not
1839 # Arguments before "buffered" used to be positional. Consider not
1839 # adding/removing arguments before "buffered" to not break callers.
1840 # adding/removing arguments before "buffered" to not break callers.
1840 def __init__(self, ui, repo, tmplspec, matchfn=None, diffopts=None,
1841 def __init__(self, ui, repo, tmplspec, matchfn=None, diffopts=None,
1841 buffered=False):
1842 buffered=False):
1842 diffopts = diffopts or {}
1843 diffopts = diffopts or {}
1843
1844
1844 changeset_printer.__init__(self, ui, repo, matchfn, diffopts, buffered)
1845 changeset_printer.__init__(self, ui, repo, matchfn, diffopts, buffered)
1845 self.t = formatter.loadtemplater(ui, tmplspec,
1846 self.t = formatter.loadtemplater(ui, tmplspec,
1846 cache=templatekw.defaulttempl)
1847 cache=templatekw.defaulttempl)
1847 self._counter = itertools.count()
1848 self._counter = itertools.count()
1848 self.cache = {}
1849 self.cache = {}
1849
1850
1850 self._tref = tmplspec.ref
1851 self._tref = tmplspec.ref
1851 self._parts = {'header': '', 'footer': '',
1852 self._parts = {'header': '', 'footer': '',
1852 tmplspec.ref: tmplspec.ref,
1853 tmplspec.ref: tmplspec.ref,
1853 'docheader': '', 'docfooter': '',
1854 'docheader': '', 'docfooter': '',
1854 'separator': ''}
1855 'separator': ''}
1855 if tmplspec.mapfile:
1856 if tmplspec.mapfile:
1856 # find correct templates for current mode, for backward
1857 # find correct templates for current mode, for backward
1857 # compatibility with 'log -v/-q/--debug' using a mapfile
1858 # compatibility with 'log -v/-q/--debug' using a mapfile
1858 tmplmodes = [
1859 tmplmodes = [
1859 (True, ''),
1860 (True, ''),
1860 (self.ui.verbose, '_verbose'),
1861 (self.ui.verbose, '_verbose'),
1861 (self.ui.quiet, '_quiet'),
1862 (self.ui.quiet, '_quiet'),
1862 (self.ui.debugflag, '_debug'),
1863 (self.ui.debugflag, '_debug'),
1863 ]
1864 ]
1864 for mode, postfix in tmplmodes:
1865 for mode, postfix in tmplmodes:
1865 for t in self._parts:
1866 for t in self._parts:
1866 cur = t + postfix
1867 cur = t + postfix
1867 if mode and cur in self.t:
1868 if mode and cur in self.t:
1868 self._parts[t] = cur
1869 self._parts[t] = cur
1869 else:
1870 else:
1870 partnames = [p for p in self._parts.keys() if p != tmplspec.ref]
1871 partnames = [p for p in self._parts.keys() if p != tmplspec.ref]
1871 m = formatter.templatepartsmap(tmplspec, self.t, partnames)
1872 m = formatter.templatepartsmap(tmplspec, self.t, partnames)
1872 self._parts.update(m)
1873 self._parts.update(m)
1873
1874
1874 if self._parts['docheader']:
1875 if self._parts['docheader']:
1875 self.ui.write(templater.stringify(self.t(self._parts['docheader'])))
1876 self.ui.write(templater.stringify(self.t(self._parts['docheader'])))
1876
1877
1877 def close(self):
1878 def close(self):
1878 if self._parts['docfooter']:
1879 if self._parts['docfooter']:
1879 if not self.footer:
1880 if not self.footer:
1880 self.footer = ""
1881 self.footer = ""
1881 self.footer += templater.stringify(self.t(self._parts['docfooter']))
1882 self.footer += templater.stringify(self.t(self._parts['docfooter']))
1882 return super(changeset_templater, self).close()
1883 return super(changeset_templater, self).close()
1883
1884
1884 def _show(self, ctx, copies, matchfn, hunksfilterfn, props):
1885 def _show(self, ctx, copies, matchfn, hunksfilterfn, props):
1885 '''show a single changeset or file revision'''
1886 '''show a single changeset or file revision'''
1886 props = props.copy()
1887 props = props.copy()
1887 props.update(templatekw.keywords)
1888 props.update(templatekw.keywords)
1888 props['templ'] = self.t
1889 props['templ'] = self.t
1889 props['ctx'] = ctx
1890 props['ctx'] = ctx
1890 props['repo'] = self.repo
1891 props['repo'] = self.repo
1891 props['ui'] = self.repo.ui
1892 props['ui'] = self.repo.ui
1892 props['index'] = index = next(self._counter)
1893 props['index'] = index = next(self._counter)
1893 props['revcache'] = {'copies': copies}
1894 props['revcache'] = {'copies': copies}
1894 props['cache'] = self.cache
1895 props['cache'] = self.cache
1895 props = pycompat.strkwargs(props)
1896 props = pycompat.strkwargs(props)
1896
1897
1897 # write separator, which wouldn't work well with the header part below
1898 # write separator, which wouldn't work well with the header part below
1898 # since there's inherently a conflict between header (across items) and
1899 # since there's inherently a conflict between header (across items) and
1899 # separator (per item)
1900 # separator (per item)
1900 if self._parts['separator'] and index > 0:
1901 if self._parts['separator'] and index > 0:
1901 self.ui.write(templater.stringify(self.t(self._parts['separator'])))
1902 self.ui.write(templater.stringify(self.t(self._parts['separator'])))
1902
1903
1903 # write header
1904 # write header
1904 if self._parts['header']:
1905 if self._parts['header']:
1905 h = templater.stringify(self.t(self._parts['header'], **props))
1906 h = templater.stringify(self.t(self._parts['header'], **props))
1906 if self.buffered:
1907 if self.buffered:
1907 self.header[ctx.rev()] = h
1908 self.header[ctx.rev()] = h
1908 else:
1909 else:
1909 if self.lastheader != h:
1910 if self.lastheader != h:
1910 self.lastheader = h
1911 self.lastheader = h
1911 self.ui.write(h)
1912 self.ui.write(h)
1912
1913
1913 # write changeset metadata, then patch if requested
1914 # write changeset metadata, then patch if requested
1914 key = self._parts[self._tref]
1915 key = self._parts[self._tref]
1915 self.ui.write(templater.stringify(self.t(key, **props)))
1916 self.ui.write(templater.stringify(self.t(key, **props)))
1916 self.showpatch(ctx, matchfn, hunksfilterfn=hunksfilterfn)
1917 self.showpatch(ctx, matchfn, hunksfilterfn=hunksfilterfn)
1917
1918
1918 if self._parts['footer']:
1919 if self._parts['footer']:
1919 if not self.footer:
1920 if not self.footer:
1920 self.footer = templater.stringify(
1921 self.footer = templater.stringify(
1921 self.t(self._parts['footer'], **props))
1922 self.t(self._parts['footer'], **props))
1922
1923
1923 def logtemplatespec(tmpl, mapfile):
1924 def logtemplatespec(tmpl, mapfile):
1924 if mapfile:
1925 if mapfile:
1925 return formatter.templatespec('changeset', tmpl, mapfile)
1926 return formatter.templatespec('changeset', tmpl, mapfile)
1926 else:
1927 else:
1927 return formatter.templatespec('', tmpl, None)
1928 return formatter.templatespec('', tmpl, None)
1928
1929
1929 def _lookuplogtemplate(ui, tmpl, style):
1930 def _lookuplogtemplate(ui, tmpl, style):
1930 """Find the template matching the given template spec or style
1931 """Find the template matching the given template spec or style
1931
1932
1932 See formatter.lookuptemplate() for details.
1933 See formatter.lookuptemplate() for details.
1933 """
1934 """
1934
1935
1935 # ui settings
1936 # ui settings
1936 if not tmpl and not style: # template are stronger than style
1937 if not tmpl and not style: # template are stronger than style
1937 tmpl = ui.config('ui', 'logtemplate')
1938 tmpl = ui.config('ui', 'logtemplate')
1938 if tmpl:
1939 if tmpl:
1939 return logtemplatespec(templater.unquotestring(tmpl), None)
1940 return logtemplatespec(templater.unquotestring(tmpl), None)
1940 else:
1941 else:
1941 style = util.expandpath(ui.config('ui', 'style'))
1942 style = util.expandpath(ui.config('ui', 'style'))
1942
1943
1943 if not tmpl and style:
1944 if not tmpl and style:
1944 mapfile = style
1945 mapfile = style
1945 if not os.path.split(mapfile)[0]:
1946 if not os.path.split(mapfile)[0]:
1946 mapname = (templater.templatepath('map-cmdline.' + mapfile)
1947 mapname = (templater.templatepath('map-cmdline.' + mapfile)
1947 or templater.templatepath(mapfile))
1948 or templater.templatepath(mapfile))
1948 if mapname:
1949 if mapname:
1949 mapfile = mapname
1950 mapfile = mapname
1950 return logtemplatespec(None, mapfile)
1951 return logtemplatespec(None, mapfile)
1951
1952
1952 if not tmpl:
1953 if not tmpl:
1953 return logtemplatespec(None, None)
1954 return logtemplatespec(None, None)
1954
1955
1955 return formatter.lookuptemplate(ui, 'changeset', tmpl)
1956 return formatter.lookuptemplate(ui, 'changeset', tmpl)
1956
1957
1957 def makelogtemplater(ui, repo, tmpl, buffered=False):
1958 def makelogtemplater(ui, repo, tmpl, buffered=False):
1958 """Create a changeset_templater from a literal template 'tmpl'
1959 """Create a changeset_templater from a literal template 'tmpl'
1959 byte-string."""
1960 byte-string."""
1960 spec = logtemplatespec(tmpl, None)
1961 spec = logtemplatespec(tmpl, None)
1961 return changeset_templater(ui, repo, spec, buffered=buffered)
1962 return changeset_templater(ui, repo, spec, buffered=buffered)
1962
1963
1963 def show_changeset(ui, repo, opts, buffered=False):
1964 def show_changeset(ui, repo, opts, buffered=False):
1964 """show one changeset using template or regular display.
1965 """show one changeset using template or regular display.
1965
1966
1966 Display format will be the first non-empty hit of:
1967 Display format will be the first non-empty hit of:
1967 1. option 'template'
1968 1. option 'template'
1968 2. option 'style'
1969 2. option 'style'
1969 3. [ui] setting 'logtemplate'
1970 3. [ui] setting 'logtemplate'
1970 4. [ui] setting 'style'
1971 4. [ui] setting 'style'
1971 If all of these values are either the unset or the empty string,
1972 If all of these values are either the unset or the empty string,
1972 regular display via changeset_printer() is done.
1973 regular display via changeset_printer() is done.
1973 """
1974 """
1974 # options
1975 # options
1975 match = None
1976 match = None
1976 if opts.get('patch') or opts.get('stat'):
1977 if opts.get('patch') or opts.get('stat'):
1977 match = scmutil.matchall(repo)
1978 match = scmutil.matchall(repo)
1978
1979
1979 if opts.get('template') == 'json':
1980 if opts.get('template') == 'json':
1980 return jsonchangeset(ui, repo, match, opts, buffered)
1981 return jsonchangeset(ui, repo, match, opts, buffered)
1981
1982
1982 spec = _lookuplogtemplate(ui, opts.get('template'), opts.get('style'))
1983 spec = _lookuplogtemplate(ui, opts.get('template'), opts.get('style'))
1983
1984
1984 if not spec.ref and not spec.tmpl and not spec.mapfile:
1985 if not spec.ref and not spec.tmpl and not spec.mapfile:
1985 return changeset_printer(ui, repo, match, opts, buffered)
1986 return changeset_printer(ui, repo, match, opts, buffered)
1986
1987
1987 return changeset_templater(ui, repo, spec, match, opts, buffered)
1988 return changeset_templater(ui, repo, spec, match, opts, buffered)
1988
1989
1989 def showmarker(fm, marker, index=None):
1990 def showmarker(fm, marker, index=None):
1990 """utility function to display obsolescence marker in a readable way
1991 """utility function to display obsolescence marker in a readable way
1991
1992
1992 To be used by debug function."""
1993 To be used by debug function."""
1993 if index is not None:
1994 if index is not None:
1994 fm.write('index', '%i ', index)
1995 fm.write('index', '%i ', index)
1995 fm.write('prednode', '%s ', hex(marker.prednode()))
1996 fm.write('prednode', '%s ', hex(marker.prednode()))
1996 succs = marker.succnodes()
1997 succs = marker.succnodes()
1997 fm.condwrite(succs, 'succnodes', '%s ',
1998 fm.condwrite(succs, 'succnodes', '%s ',
1998 fm.formatlist(map(hex, succs), name='node'))
1999 fm.formatlist(map(hex, succs), name='node'))
1999 fm.write('flag', '%X ', marker.flags())
2000 fm.write('flag', '%X ', marker.flags())
2000 parents = marker.parentnodes()
2001 parents = marker.parentnodes()
2001 if parents is not None:
2002 if parents is not None:
2002 fm.write('parentnodes', '{%s} ',
2003 fm.write('parentnodes', '{%s} ',
2003 fm.formatlist(map(hex, parents), name='node', sep=', '))
2004 fm.formatlist(map(hex, parents), name='node', sep=', '))
2004 fm.write('date', '(%s) ', fm.formatdate(marker.date()))
2005 fm.write('date', '(%s) ', fm.formatdate(marker.date()))
2005 meta = marker.metadata().copy()
2006 meta = marker.metadata().copy()
2006 meta.pop('date', None)
2007 meta.pop('date', None)
2007 fm.write('metadata', '{%s}', fm.formatdict(meta, fmt='%r: %r', sep=', '))
2008 fm.write('metadata', '{%s}', fm.formatdict(meta, fmt='%r: %r', sep=', '))
2008 fm.plain('\n')
2009 fm.plain('\n')
2009
2010
2010 def finddate(ui, repo, date):
2011 def finddate(ui, repo, date):
2011 """Find the tipmost changeset that matches the given date spec"""
2012 """Find the tipmost changeset that matches the given date spec"""
2012
2013
2013 df = util.matchdate(date)
2014 df = util.matchdate(date)
2014 m = scmutil.matchall(repo)
2015 m = scmutil.matchall(repo)
2015 results = {}
2016 results = {}
2016
2017
2017 def prep(ctx, fns):
2018 def prep(ctx, fns):
2018 d = ctx.date()
2019 d = ctx.date()
2019 if df(d[0]):
2020 if df(d[0]):
2020 results[ctx.rev()] = d
2021 results[ctx.rev()] = d
2021
2022
2022 for ctx in walkchangerevs(repo, m, {'rev': None}, prep):
2023 for ctx in walkchangerevs(repo, m, {'rev': None}, prep):
2023 rev = ctx.rev()
2024 rev = ctx.rev()
2024 if rev in results:
2025 if rev in results:
2025 ui.status(_("found revision %s from %s\n") %
2026 ui.status(_("found revision %s from %s\n") %
2026 (rev, util.datestr(results[rev])))
2027 (rev, util.datestr(results[rev])))
2027 return '%d' % rev
2028 return '%d' % rev
2028
2029
2029 raise error.Abort(_("revision matching date not found"))
2030 raise error.Abort(_("revision matching date not found"))
2030
2031
2031 def increasingwindows(windowsize=8, sizelimit=512):
2032 def increasingwindows(windowsize=8, sizelimit=512):
2032 while True:
2033 while True:
2033 yield windowsize
2034 yield windowsize
2034 if windowsize < sizelimit:
2035 if windowsize < sizelimit:
2035 windowsize *= 2
2036 windowsize *= 2
2036
2037
2037 class FileWalkError(Exception):
2038 class FileWalkError(Exception):
2038 pass
2039 pass
2039
2040
2040 def walkfilerevs(repo, match, follow, revs, fncache):
2041 def walkfilerevs(repo, match, follow, revs, fncache):
2041 '''Walks the file history for the matched files.
2042 '''Walks the file history for the matched files.
2042
2043
2043 Returns the changeset revs that are involved in the file history.
2044 Returns the changeset revs that are involved in the file history.
2044
2045
2045 Throws FileWalkError if the file history can't be walked using
2046 Throws FileWalkError if the file history can't be walked using
2046 filelogs alone.
2047 filelogs alone.
2047 '''
2048 '''
2048 wanted = set()
2049 wanted = set()
2049 copies = []
2050 copies = []
2050 minrev, maxrev = min(revs), max(revs)
2051 minrev, maxrev = min(revs), max(revs)
2051 def filerevgen(filelog, last):
2052 def filerevgen(filelog, last):
2052 """
2053 """
2053 Only files, no patterns. Check the history of each file.
2054 Only files, no patterns. Check the history of each file.
2054
2055
2055 Examines filelog entries within minrev, maxrev linkrev range
2056 Examines filelog entries within minrev, maxrev linkrev range
2056 Returns an iterator yielding (linkrev, parentlinkrevs, copied)
2057 Returns an iterator yielding (linkrev, parentlinkrevs, copied)
2057 tuples in backwards order
2058 tuples in backwards order
2058 """
2059 """
2059 cl_count = len(repo)
2060 cl_count = len(repo)
2060 revs = []
2061 revs = []
2061 for j in xrange(0, last + 1):
2062 for j in xrange(0, last + 1):
2062 linkrev = filelog.linkrev(j)
2063 linkrev = filelog.linkrev(j)
2063 if linkrev < minrev:
2064 if linkrev < minrev:
2064 continue
2065 continue
2065 # only yield rev for which we have the changelog, it can
2066 # only yield rev for which we have the changelog, it can
2066 # happen while doing "hg log" during a pull or commit
2067 # happen while doing "hg log" during a pull or commit
2067 if linkrev >= cl_count:
2068 if linkrev >= cl_count:
2068 break
2069 break
2069
2070
2070 parentlinkrevs = []
2071 parentlinkrevs = []
2071 for p in filelog.parentrevs(j):
2072 for p in filelog.parentrevs(j):
2072 if p != nullrev:
2073 if p != nullrev:
2073 parentlinkrevs.append(filelog.linkrev(p))
2074 parentlinkrevs.append(filelog.linkrev(p))
2074 n = filelog.node(j)
2075 n = filelog.node(j)
2075 revs.append((linkrev, parentlinkrevs,
2076 revs.append((linkrev, parentlinkrevs,
2076 follow and filelog.renamed(n)))
2077 follow and filelog.renamed(n)))
2077
2078
2078 return reversed(revs)
2079 return reversed(revs)
2079 def iterfiles():
2080 def iterfiles():
2080 pctx = repo['.']
2081 pctx = repo['.']
2081 for filename in match.files():
2082 for filename in match.files():
2082 if follow:
2083 if follow:
2083 if filename not in pctx:
2084 if filename not in pctx:
2084 raise error.Abort(_('cannot follow file not in parent '
2085 raise error.Abort(_('cannot follow file not in parent '
2085 'revision: "%s"') % filename)
2086 'revision: "%s"') % filename)
2086 yield filename, pctx[filename].filenode()
2087 yield filename, pctx[filename].filenode()
2087 else:
2088 else:
2088 yield filename, None
2089 yield filename, None
2089 for filename_node in copies:
2090 for filename_node in copies:
2090 yield filename_node
2091 yield filename_node
2091
2092
2092 for file_, node in iterfiles():
2093 for file_, node in iterfiles():
2093 filelog = repo.file(file_)
2094 filelog = repo.file(file_)
2094 if not len(filelog):
2095 if not len(filelog):
2095 if node is None:
2096 if node is None:
2096 # A zero count may be a directory or deleted file, so
2097 # A zero count may be a directory or deleted file, so
2097 # try to find matching entries on the slow path.
2098 # try to find matching entries on the slow path.
2098 if follow:
2099 if follow:
2099 raise error.Abort(
2100 raise error.Abort(
2100 _('cannot follow nonexistent file: "%s"') % file_)
2101 _('cannot follow nonexistent file: "%s"') % file_)
2101 raise FileWalkError("Cannot walk via filelog")
2102 raise FileWalkError("Cannot walk via filelog")
2102 else:
2103 else:
2103 continue
2104 continue
2104
2105
2105 if node is None:
2106 if node is None:
2106 last = len(filelog) - 1
2107 last = len(filelog) - 1
2107 else:
2108 else:
2108 last = filelog.rev(node)
2109 last = filelog.rev(node)
2109
2110
2110 # keep track of all ancestors of the file
2111 # keep track of all ancestors of the file
2111 ancestors = {filelog.linkrev(last)}
2112 ancestors = {filelog.linkrev(last)}
2112
2113
2113 # iterate from latest to oldest revision
2114 # iterate from latest to oldest revision
2114 for rev, flparentlinkrevs, copied in filerevgen(filelog, last):
2115 for rev, flparentlinkrevs, copied in filerevgen(filelog, last):
2115 if not follow:
2116 if not follow:
2116 if rev > maxrev:
2117 if rev > maxrev:
2117 continue
2118 continue
2118 else:
2119 else:
2119 # Note that last might not be the first interesting
2120 # Note that last might not be the first interesting
2120 # rev to us:
2121 # rev to us:
2121 # if the file has been changed after maxrev, we'll
2122 # if the file has been changed after maxrev, we'll
2122 # have linkrev(last) > maxrev, and we still need
2123 # have linkrev(last) > maxrev, and we still need
2123 # to explore the file graph
2124 # to explore the file graph
2124 if rev not in ancestors:
2125 if rev not in ancestors:
2125 continue
2126 continue
2126 # XXX insert 1327 fix here
2127 # XXX insert 1327 fix here
2127 if flparentlinkrevs:
2128 if flparentlinkrevs:
2128 ancestors.update(flparentlinkrevs)
2129 ancestors.update(flparentlinkrevs)
2129
2130
2130 fncache.setdefault(rev, []).append(file_)
2131 fncache.setdefault(rev, []).append(file_)
2131 wanted.add(rev)
2132 wanted.add(rev)
2132 if copied:
2133 if copied:
2133 copies.append(copied)
2134 copies.append(copied)
2134
2135
2135 return wanted
2136 return wanted
2136
2137
2137 class _followfilter(object):
2138 class _followfilter(object):
2138 def __init__(self, repo, onlyfirst=False):
2139 def __init__(self, repo, onlyfirst=False):
2139 self.repo = repo
2140 self.repo = repo
2140 self.startrev = nullrev
2141 self.startrev = nullrev
2141 self.roots = set()
2142 self.roots = set()
2142 self.onlyfirst = onlyfirst
2143 self.onlyfirst = onlyfirst
2143
2144
2144 def match(self, rev):
2145 def match(self, rev):
2145 def realparents(rev):
2146 def realparents(rev):
2146 if self.onlyfirst:
2147 if self.onlyfirst:
2147 return self.repo.changelog.parentrevs(rev)[0:1]
2148 return self.repo.changelog.parentrevs(rev)[0:1]
2148 else:
2149 else:
2149 return filter(lambda x: x != nullrev,
2150 return filter(lambda x: x != nullrev,
2150 self.repo.changelog.parentrevs(rev))
2151 self.repo.changelog.parentrevs(rev))
2151
2152
2152 if self.startrev == nullrev:
2153 if self.startrev == nullrev:
2153 self.startrev = rev
2154 self.startrev = rev
2154 return True
2155 return True
2155
2156
2156 if rev > self.startrev:
2157 if rev > self.startrev:
2157 # forward: all descendants
2158 # forward: all descendants
2158 if not self.roots:
2159 if not self.roots:
2159 self.roots.add(self.startrev)
2160 self.roots.add(self.startrev)
2160 for parent in realparents(rev):
2161 for parent in realparents(rev):
2161 if parent in self.roots:
2162 if parent in self.roots:
2162 self.roots.add(rev)
2163 self.roots.add(rev)
2163 return True
2164 return True
2164 else:
2165 else:
2165 # backwards: all parents
2166 # backwards: all parents
2166 if not self.roots:
2167 if not self.roots:
2167 self.roots.update(realparents(self.startrev))
2168 self.roots.update(realparents(self.startrev))
2168 if rev in self.roots:
2169 if rev in self.roots:
2169 self.roots.remove(rev)
2170 self.roots.remove(rev)
2170 self.roots.update(realparents(rev))
2171 self.roots.update(realparents(rev))
2171 return True
2172 return True
2172
2173
2173 return False
2174 return False
2174
2175
2175 def walkchangerevs(repo, match, opts, prepare):
2176 def walkchangerevs(repo, match, opts, prepare):
2176 '''Iterate over files and the revs in which they changed.
2177 '''Iterate over files and the revs in which they changed.
2177
2178
2178 Callers most commonly need to iterate backwards over the history
2179 Callers most commonly need to iterate backwards over the history
2179 in which they are interested. Doing so has awful (quadratic-looking)
2180 in which they are interested. Doing so has awful (quadratic-looking)
2180 performance, so we use iterators in a "windowed" way.
2181 performance, so we use iterators in a "windowed" way.
2181
2182
2182 We walk a window of revisions in the desired order. Within the
2183 We walk a window of revisions in the desired order. Within the
2183 window, we first walk forwards to gather data, then in the desired
2184 window, we first walk forwards to gather data, then in the desired
2184 order (usually backwards) to display it.
2185 order (usually backwards) to display it.
2185
2186
2186 This function returns an iterator yielding contexts. Before
2187 This function returns an iterator yielding contexts. Before
2187 yielding each context, the iterator will first call the prepare
2188 yielding each context, the iterator will first call the prepare
2188 function on each context in the window in forward order.'''
2189 function on each context in the window in forward order.'''
2189
2190
2190 follow = opts.get('follow') or opts.get('follow_first')
2191 follow = opts.get('follow') or opts.get('follow_first')
2191 revs = _logrevs(repo, opts)
2192 revs = _logrevs(repo, opts)
2192 if not revs:
2193 if not revs:
2193 return []
2194 return []
2194 wanted = set()
2195 wanted = set()
2195 slowpath = match.anypats() or ((match.isexact() or match.prefix()) and
2196 slowpath = match.anypats() or ((match.isexact() or match.prefix()) and
2196 opts.get('removed'))
2197 opts.get('removed'))
2197 fncache = {}
2198 fncache = {}
2198 change = repo.changectx
2199 change = repo.changectx
2199
2200
2200 # First step is to fill wanted, the set of revisions that we want to yield.
2201 # First step is to fill wanted, the set of revisions that we want to yield.
2201 # When it does not induce extra cost, we also fill fncache for revisions in
2202 # When it does not induce extra cost, we also fill fncache for revisions in
2202 # wanted: a cache of filenames that were changed (ctx.files()) and that
2203 # wanted: a cache of filenames that were changed (ctx.files()) and that
2203 # match the file filtering conditions.
2204 # match the file filtering conditions.
2204
2205
2205 if match.always():
2206 if match.always():
2206 # No files, no patterns. Display all revs.
2207 # No files, no patterns. Display all revs.
2207 wanted = revs
2208 wanted = revs
2208 elif not slowpath:
2209 elif not slowpath:
2209 # We only have to read through the filelog to find wanted revisions
2210 # We only have to read through the filelog to find wanted revisions
2210
2211
2211 try:
2212 try:
2212 wanted = walkfilerevs(repo, match, follow, revs, fncache)
2213 wanted = walkfilerevs(repo, match, follow, revs, fncache)
2213 except FileWalkError:
2214 except FileWalkError:
2214 slowpath = True
2215 slowpath = True
2215
2216
2216 # We decided to fall back to the slowpath because at least one
2217 # We decided to fall back to the slowpath because at least one
2217 # of the paths was not a file. Check to see if at least one of them
2218 # of the paths was not a file. Check to see if at least one of them
2218 # existed in history, otherwise simply return
2219 # existed in history, otherwise simply return
2219 for path in match.files():
2220 for path in match.files():
2220 if path == '.' or path in repo.store:
2221 if path == '.' or path in repo.store:
2221 break
2222 break
2222 else:
2223 else:
2223 return []
2224 return []
2224
2225
2225 if slowpath:
2226 if slowpath:
2226 # We have to read the changelog to match filenames against
2227 # We have to read the changelog to match filenames against
2227 # changed files
2228 # changed files
2228
2229
2229 if follow:
2230 if follow:
2230 raise error.Abort(_('can only follow copies/renames for explicit '
2231 raise error.Abort(_('can only follow copies/renames for explicit '
2231 'filenames'))
2232 'filenames'))
2232
2233
2233 # The slow path checks files modified in every changeset.
2234 # The slow path checks files modified in every changeset.
2234 # This is really slow on large repos, so compute the set lazily.
2235 # This is really slow on large repos, so compute the set lazily.
2235 class lazywantedset(object):
2236 class lazywantedset(object):
2236 def __init__(self):
2237 def __init__(self):
2237 self.set = set()
2238 self.set = set()
2238 self.revs = set(revs)
2239 self.revs = set(revs)
2239
2240
2240 # No need to worry about locality here because it will be accessed
2241 # No need to worry about locality here because it will be accessed
2241 # in the same order as the increasing window below.
2242 # in the same order as the increasing window below.
2242 def __contains__(self, value):
2243 def __contains__(self, value):
2243 if value in self.set:
2244 if value in self.set:
2244 return True
2245 return True
2245 elif not value in self.revs:
2246 elif not value in self.revs:
2246 return False
2247 return False
2247 else:
2248 else:
2248 self.revs.discard(value)
2249 self.revs.discard(value)
2249 ctx = change(value)
2250 ctx = change(value)
2250 matches = filter(match, ctx.files())
2251 matches = filter(match, ctx.files())
2251 if matches:
2252 if matches:
2252 fncache[value] = matches
2253 fncache[value] = matches
2253 self.set.add(value)
2254 self.set.add(value)
2254 return True
2255 return True
2255 return False
2256 return False
2256
2257
2257 def discard(self, value):
2258 def discard(self, value):
2258 self.revs.discard(value)
2259 self.revs.discard(value)
2259 self.set.discard(value)
2260 self.set.discard(value)
2260
2261
2261 wanted = lazywantedset()
2262 wanted = lazywantedset()
2262
2263
2263 # it might be worthwhile to do this in the iterator if the rev range
2264 # it might be worthwhile to do this in the iterator if the rev range
2264 # is descending and the prune args are all within that range
2265 # is descending and the prune args are all within that range
2265 for rev in opts.get('prune', ()):
2266 for rev in opts.get('prune', ()):
2266 rev = repo[rev].rev()
2267 rev = repo[rev].rev()
2267 ff = _followfilter(repo)
2268 ff = _followfilter(repo)
2268 stop = min(revs[0], revs[-1])
2269 stop = min(revs[0], revs[-1])
2269 for x in xrange(rev, stop - 1, -1):
2270 for x in xrange(rev, stop - 1, -1):
2270 if ff.match(x):
2271 if ff.match(x):
2271 wanted = wanted - [x]
2272 wanted = wanted - [x]
2272
2273
2273 # Now that wanted is correctly initialized, we can iterate over the
2274 # Now that wanted is correctly initialized, we can iterate over the
2274 # revision range, yielding only revisions in wanted.
2275 # revision range, yielding only revisions in wanted.
2275 def iterate():
2276 def iterate():
2276 if follow and match.always():
2277 if follow and match.always():
2277 ff = _followfilter(repo, onlyfirst=opts.get('follow_first'))
2278 ff = _followfilter(repo, onlyfirst=opts.get('follow_first'))
2278 def want(rev):
2279 def want(rev):
2279 return ff.match(rev) and rev in wanted
2280 return ff.match(rev) and rev in wanted
2280 else:
2281 else:
2281 def want(rev):
2282 def want(rev):
2282 return rev in wanted
2283 return rev in wanted
2283
2284
2284 it = iter(revs)
2285 it = iter(revs)
2285 stopiteration = False
2286 stopiteration = False
2286 for windowsize in increasingwindows():
2287 for windowsize in increasingwindows():
2287 nrevs = []
2288 nrevs = []
2288 for i in xrange(windowsize):
2289 for i in xrange(windowsize):
2289 rev = next(it, None)
2290 rev = next(it, None)
2290 if rev is None:
2291 if rev is None:
2291 stopiteration = True
2292 stopiteration = True
2292 break
2293 break
2293 elif want(rev):
2294 elif want(rev):
2294 nrevs.append(rev)
2295 nrevs.append(rev)
2295 for rev in sorted(nrevs):
2296 for rev in sorted(nrevs):
2296 fns = fncache.get(rev)
2297 fns = fncache.get(rev)
2297 ctx = change(rev)
2298 ctx = change(rev)
2298 if not fns:
2299 if not fns:
2299 def fns_generator():
2300 def fns_generator():
2300 for f in ctx.files():
2301 for f in ctx.files():
2301 if match(f):
2302 if match(f):
2302 yield f
2303 yield f
2303 fns = fns_generator()
2304 fns = fns_generator()
2304 prepare(ctx, fns)
2305 prepare(ctx, fns)
2305 for rev in nrevs:
2306 for rev in nrevs:
2306 yield change(rev)
2307 yield change(rev)
2307
2308
2308 if stopiteration:
2309 if stopiteration:
2309 break
2310 break
2310
2311
2311 return iterate()
2312 return iterate()
2312
2313
2313 def _makefollowlogfilematcher(repo, files, followfirst):
2314 def _makefollowlogfilematcher(repo, files, followfirst):
2314 # When displaying a revision with --patch --follow FILE, we have
2315 # When displaying a revision with --patch --follow FILE, we have
2315 # to know which file of the revision must be diffed. With
2316 # to know which file of the revision must be diffed. With
2316 # --follow, we want the names of the ancestors of FILE in the
2317 # --follow, we want the names of the ancestors of FILE in the
2317 # revision, stored in "fcache". "fcache" is populated by
2318 # revision, stored in "fcache". "fcache" is populated by
2318 # reproducing the graph traversal already done by --follow revset
2319 # reproducing the graph traversal already done by --follow revset
2319 # and relating revs to file names (which is not "correct" but
2320 # and relating revs to file names (which is not "correct" but
2320 # good enough).
2321 # good enough).
2321 fcache = {}
2322 fcache = {}
2322 fcacheready = [False]
2323 fcacheready = [False]
2323 pctx = repo['.']
2324 pctx = repo['.']
2324
2325
2325 def populate():
2326 def populate():
2326 for fn in files:
2327 for fn in files:
2327 fctx = pctx[fn]
2328 fctx = pctx[fn]
2328 fcache.setdefault(fctx.introrev(), set()).add(fctx.path())
2329 fcache.setdefault(fctx.introrev(), set()).add(fctx.path())
2329 for c in fctx.ancestors(followfirst=followfirst):
2330 for c in fctx.ancestors(followfirst=followfirst):
2330 fcache.setdefault(c.rev(), set()).add(c.path())
2331 fcache.setdefault(c.rev(), set()).add(c.path())
2331
2332
2332 def filematcher(rev):
2333 def filematcher(rev):
2333 if not fcacheready[0]:
2334 if not fcacheready[0]:
2334 # Lazy initialization
2335 # Lazy initialization
2335 fcacheready[0] = True
2336 fcacheready[0] = True
2336 populate()
2337 populate()
2337 return scmutil.matchfiles(repo, fcache.get(rev, []))
2338 return scmutil.matchfiles(repo, fcache.get(rev, []))
2338
2339
2339 return filematcher
2340 return filematcher
2340
2341
2341 def _makenofollowlogfilematcher(repo, pats, opts):
2342 def _makenofollowlogfilematcher(repo, pats, opts):
2342 '''hook for extensions to override the filematcher for non-follow cases'''
2343 '''hook for extensions to override the filematcher for non-follow cases'''
2343 return None
2344 return None
2344
2345
2345 def _makelogrevset(repo, pats, opts, revs):
2346 def _makelogrevset(repo, pats, opts, revs):
2346 """Return (expr, filematcher) where expr is a revset string built
2347 """Return (expr, filematcher) where expr is a revset string built
2347 from log options and file patterns or None. If --stat or --patch
2348 from log options and file patterns or None. If --stat or --patch
2348 are not passed filematcher is None. Otherwise it is a callable
2349 are not passed filematcher is None. Otherwise it is a callable
2349 taking a revision number and returning a match objects filtering
2350 taking a revision number and returning a match objects filtering
2350 the files to be detailed when displaying the revision.
2351 the files to be detailed when displaying the revision.
2351 """
2352 """
2352 opt2revset = {
2353 opt2revset = {
2353 'no_merges': ('not merge()', None),
2354 'no_merges': ('not merge()', None),
2354 'only_merges': ('merge()', None),
2355 'only_merges': ('merge()', None),
2355 '_ancestors': ('ancestors(%(val)s)', None),
2356 '_ancestors': ('ancestors(%(val)s)', None),
2356 '_fancestors': ('_firstancestors(%(val)s)', None),
2357 '_fancestors': ('_firstancestors(%(val)s)', None),
2357 '_descendants': ('descendants(%(val)s)', None),
2358 '_descendants': ('descendants(%(val)s)', None),
2358 '_fdescendants': ('_firstdescendants(%(val)s)', None),
2359 '_fdescendants': ('_firstdescendants(%(val)s)', None),
2359 '_matchfiles': ('_matchfiles(%(val)s)', None),
2360 '_matchfiles': ('_matchfiles(%(val)s)', None),
2360 'date': ('date(%(val)r)', None),
2361 'date': ('date(%(val)r)', None),
2361 'branch': ('branch(%(val)r)', ' or '),
2362 'branch': ('branch(%(val)r)', ' or '),
2362 '_patslog': ('filelog(%(val)r)', ' or '),
2363 '_patslog': ('filelog(%(val)r)', ' or '),
2363 '_patsfollow': ('follow(%(val)r)', ' or '),
2364 '_patsfollow': ('follow(%(val)r)', ' or '),
2364 '_patsfollowfirst': ('_followfirst(%(val)r)', ' or '),
2365 '_patsfollowfirst': ('_followfirst(%(val)r)', ' or '),
2365 'keyword': ('keyword(%(val)r)', ' or '),
2366 'keyword': ('keyword(%(val)r)', ' or '),
2366 'prune': ('not (%(val)r or ancestors(%(val)r))', ' and '),
2367 'prune': ('not (%(val)r or ancestors(%(val)r))', ' and '),
2367 'user': ('user(%(val)r)', ' or '),
2368 'user': ('user(%(val)r)', ' or '),
2368 }
2369 }
2369
2370
2370 opts = dict(opts)
2371 opts = dict(opts)
2371 # follow or not follow?
2372 # follow or not follow?
2372 follow = opts.get('follow') or opts.get('follow_first')
2373 follow = opts.get('follow') or opts.get('follow_first')
2373 if opts.get('follow_first'):
2374 if opts.get('follow_first'):
2374 followfirst = 1
2375 followfirst = 1
2375 else:
2376 else:
2376 followfirst = 0
2377 followfirst = 0
2377 # --follow with FILE behavior depends on revs...
2378 # --follow with FILE behavior depends on revs...
2378 it = iter(revs)
2379 it = iter(revs)
2379 startrev = next(it)
2380 startrev = next(it)
2380 followdescendants = startrev < next(it, startrev)
2381 followdescendants = startrev < next(it, startrev)
2381
2382
2382 # branch and only_branch are really aliases and must be handled at
2383 # branch and only_branch are really aliases and must be handled at
2383 # the same time
2384 # the same time
2384 opts['branch'] = opts.get('branch', []) + opts.get('only_branch', [])
2385 opts['branch'] = opts.get('branch', []) + opts.get('only_branch', [])
2385 opts['branch'] = [repo.lookupbranch(b) for b in opts['branch']]
2386 opts['branch'] = [repo.lookupbranch(b) for b in opts['branch']]
2386 # pats/include/exclude are passed to match.match() directly in
2387 # pats/include/exclude are passed to match.match() directly in
2387 # _matchfiles() revset but walkchangerevs() builds its matcher with
2388 # _matchfiles() revset but walkchangerevs() builds its matcher with
2388 # scmutil.match(). The difference is input pats are globbed on
2389 # scmutil.match(). The difference is input pats are globbed on
2389 # platforms without shell expansion (windows).
2390 # platforms without shell expansion (windows).
2390 wctx = repo[None]
2391 wctx = repo[None]
2391 match, pats = scmutil.matchandpats(wctx, pats, opts)
2392 match, pats = scmutil.matchandpats(wctx, pats, opts)
2392 slowpath = match.anypats() or ((match.isexact() or match.prefix()) and
2393 slowpath = match.anypats() or ((match.isexact() or match.prefix()) and
2393 opts.get('removed'))
2394 opts.get('removed'))
2394 if not slowpath:
2395 if not slowpath:
2395 for f in match.files():
2396 for f in match.files():
2396 if follow and f not in wctx:
2397 if follow and f not in wctx:
2397 # If the file exists, it may be a directory, so let it
2398 # If the file exists, it may be a directory, so let it
2398 # take the slow path.
2399 # take the slow path.
2399 if os.path.exists(repo.wjoin(f)):
2400 if os.path.exists(repo.wjoin(f)):
2400 slowpath = True
2401 slowpath = True
2401 continue
2402 continue
2402 else:
2403 else:
2403 raise error.Abort(_('cannot follow file not in parent '
2404 raise error.Abort(_('cannot follow file not in parent '
2404 'revision: "%s"') % f)
2405 'revision: "%s"') % f)
2405 filelog = repo.file(f)
2406 filelog = repo.file(f)
2406 if not filelog:
2407 if not filelog:
2407 # A zero count may be a directory or deleted file, so
2408 # A zero count may be a directory or deleted file, so
2408 # try to find matching entries on the slow path.
2409 # try to find matching entries on the slow path.
2409 if follow:
2410 if follow:
2410 raise error.Abort(
2411 raise error.Abort(
2411 _('cannot follow nonexistent file: "%s"') % f)
2412 _('cannot follow nonexistent file: "%s"') % f)
2412 slowpath = True
2413 slowpath = True
2413
2414
2414 # We decided to fall back to the slowpath because at least one
2415 # We decided to fall back to the slowpath because at least one
2415 # of the paths was not a file. Check to see if at least one of them
2416 # of the paths was not a file. Check to see if at least one of them
2416 # existed in history - in that case, we'll continue down the
2417 # existed in history - in that case, we'll continue down the
2417 # slowpath; otherwise, we can turn off the slowpath
2418 # slowpath; otherwise, we can turn off the slowpath
2418 if slowpath:
2419 if slowpath:
2419 for path in match.files():
2420 for path in match.files():
2420 if path == '.' or path in repo.store:
2421 if path == '.' or path in repo.store:
2421 break
2422 break
2422 else:
2423 else:
2423 slowpath = False
2424 slowpath = False
2424
2425
2425 fpats = ('_patsfollow', '_patsfollowfirst')
2426 fpats = ('_patsfollow', '_patsfollowfirst')
2426 fnopats = (('_ancestors', '_fancestors'),
2427 fnopats = (('_ancestors', '_fancestors'),
2427 ('_descendants', '_fdescendants'))
2428 ('_descendants', '_fdescendants'))
2428 if slowpath:
2429 if slowpath:
2429 # See walkchangerevs() slow path.
2430 # See walkchangerevs() slow path.
2430 #
2431 #
2431 # pats/include/exclude cannot be represented as separate
2432 # pats/include/exclude cannot be represented as separate
2432 # revset expressions as their filtering logic applies at file
2433 # revset expressions as their filtering logic applies at file
2433 # level. For instance "-I a -X a" matches a revision touching
2434 # level. For instance "-I a -X a" matches a revision touching
2434 # "a" and "b" while "file(a) and not file(b)" does
2435 # "a" and "b" while "file(a) and not file(b)" does
2435 # not. Besides, filesets are evaluated against the working
2436 # not. Besides, filesets are evaluated against the working
2436 # directory.
2437 # directory.
2437 matchargs = ['r:', 'd:relpath']
2438 matchargs = ['r:', 'd:relpath']
2438 for p in pats:
2439 for p in pats:
2439 matchargs.append('p:' + p)
2440 matchargs.append('p:' + p)
2440 for p in opts.get('include', []):
2441 for p in opts.get('include', []):
2441 matchargs.append('i:' + p)
2442 matchargs.append('i:' + p)
2442 for p in opts.get('exclude', []):
2443 for p in opts.get('exclude', []):
2443 matchargs.append('x:' + p)
2444 matchargs.append('x:' + p)
2444 matchargs = ','.join(('%r' % p) for p in matchargs)
2445 matchargs = ','.join(('%r' % p) for p in matchargs)
2445 opts['_matchfiles'] = matchargs
2446 opts['_matchfiles'] = matchargs
2446 if follow:
2447 if follow:
2447 opts[fnopats[0][followfirst]] = '.'
2448 opts[fnopats[0][followfirst]] = '.'
2448 else:
2449 else:
2449 if follow:
2450 if follow:
2450 if pats:
2451 if pats:
2451 # follow() revset interprets its file argument as a
2452 # follow() revset interprets its file argument as a
2452 # manifest entry, so use match.files(), not pats.
2453 # manifest entry, so use match.files(), not pats.
2453 opts[fpats[followfirst]] = list(match.files())
2454 opts[fpats[followfirst]] = list(match.files())
2454 else:
2455 else:
2455 op = fnopats[followdescendants][followfirst]
2456 op = fnopats[followdescendants][followfirst]
2456 opts[op] = 'rev(%d)' % startrev
2457 opts[op] = 'rev(%d)' % startrev
2457 else:
2458 else:
2458 opts['_patslog'] = list(pats)
2459 opts['_patslog'] = list(pats)
2459
2460
2460 filematcher = None
2461 filematcher = None
2461 if opts.get('patch') or opts.get('stat'):
2462 if opts.get('patch') or opts.get('stat'):
2462 # When following files, track renames via a special matcher.
2463 # When following files, track renames via a special matcher.
2463 # If we're forced to take the slowpath it means we're following
2464 # If we're forced to take the slowpath it means we're following
2464 # at least one pattern/directory, so don't bother with rename tracking.
2465 # at least one pattern/directory, so don't bother with rename tracking.
2465 if follow and not match.always() and not slowpath:
2466 if follow and not match.always() and not slowpath:
2466 # _makefollowlogfilematcher expects its files argument to be
2467 # _makefollowlogfilematcher expects its files argument to be
2467 # relative to the repo root, so use match.files(), not pats.
2468 # relative to the repo root, so use match.files(), not pats.
2468 filematcher = _makefollowlogfilematcher(repo, match.files(),
2469 filematcher = _makefollowlogfilematcher(repo, match.files(),
2469 followfirst)
2470 followfirst)
2470 else:
2471 else:
2471 filematcher = _makenofollowlogfilematcher(repo, pats, opts)
2472 filematcher = _makenofollowlogfilematcher(repo, pats, opts)
2472 if filematcher is None:
2473 if filematcher is None:
2473 filematcher = lambda rev: match
2474 filematcher = lambda rev: match
2474
2475
2475 expr = []
2476 expr = []
2476 for op, val in sorted(opts.iteritems()):
2477 for op, val in sorted(opts.iteritems()):
2477 if not val:
2478 if not val:
2478 continue
2479 continue
2479 if op not in opt2revset:
2480 if op not in opt2revset:
2480 continue
2481 continue
2481 revop, andor = opt2revset[op]
2482 revop, andor = opt2revset[op]
2482 if '%(val)' not in revop:
2483 if '%(val)' not in revop:
2483 expr.append(revop)
2484 expr.append(revop)
2484 else:
2485 else:
2485 if not isinstance(val, list):
2486 if not isinstance(val, list):
2486 e = revop % {'val': val}
2487 e = revop % {'val': val}
2487 else:
2488 else:
2488 e = '(' + andor.join((revop % {'val': v}) for v in val) + ')'
2489 e = '(' + andor.join((revop % {'val': v}) for v in val) + ')'
2489 expr.append(e)
2490 expr.append(e)
2490
2491
2491 if expr:
2492 if expr:
2492 expr = '(' + ' and '.join(expr) + ')'
2493 expr = '(' + ' and '.join(expr) + ')'
2493 else:
2494 else:
2494 expr = None
2495 expr = None
2495 return expr, filematcher
2496 return expr, filematcher
2496
2497
2497 def _logrevs(repo, opts):
2498 def _logrevs(repo, opts):
2498 # Default --rev value depends on --follow but --follow behavior
2499 # Default --rev value depends on --follow but --follow behavior
2499 # depends on revisions resolved from --rev...
2500 # depends on revisions resolved from --rev...
2500 follow = opts.get('follow') or opts.get('follow_first')
2501 follow = opts.get('follow') or opts.get('follow_first')
2501 if opts.get('rev'):
2502 if opts.get('rev'):
2502 revs = scmutil.revrange(repo, opts['rev'])
2503 revs = scmutil.revrange(repo, opts['rev'])
2503 elif follow and repo.dirstate.p1() == nullid:
2504 elif follow and repo.dirstate.p1() == nullid:
2504 revs = smartset.baseset()
2505 revs = smartset.baseset()
2505 elif follow:
2506 elif follow:
2506 revs = repo.revs('reverse(:.)')
2507 revs = repo.revs('reverse(:.)')
2507 else:
2508 else:
2508 revs = smartset.spanset(repo)
2509 revs = smartset.spanset(repo)
2509 revs.reverse()
2510 revs.reverse()
2510 return revs
2511 return revs
2511
2512
2512 def getgraphlogrevs(repo, pats, opts):
2513 def getgraphlogrevs(repo, pats, opts):
2513 """Return (revs, expr, filematcher) where revs is an iterable of
2514 """Return (revs, expr, filematcher) where revs is an iterable of
2514 revision numbers, expr is a revset string built from log options
2515 revision numbers, expr is a revset string built from log options
2515 and file patterns or None, and used to filter 'revs'. If --stat or
2516 and file patterns or None, and used to filter 'revs'. If --stat or
2516 --patch are not passed filematcher is None. Otherwise it is a
2517 --patch are not passed filematcher is None. Otherwise it is a
2517 callable taking a revision number and returning a match objects
2518 callable taking a revision number and returning a match objects
2518 filtering the files to be detailed when displaying the revision.
2519 filtering the files to be detailed when displaying the revision.
2519 """
2520 """
2520 limit = loglimit(opts)
2521 limit = loglimit(opts)
2521 revs = _logrevs(repo, opts)
2522 revs = _logrevs(repo, opts)
2522 if not revs:
2523 if not revs:
2523 return smartset.baseset(), None, None
2524 return smartset.baseset(), None, None
2524 expr, filematcher = _makelogrevset(repo, pats, opts, revs)
2525 expr, filematcher = _makelogrevset(repo, pats, opts, revs)
2525 if opts.get('rev'):
2526 if opts.get('rev'):
2526 # User-specified revs might be unsorted, but don't sort before
2527 # User-specified revs might be unsorted, but don't sort before
2527 # _makelogrevset because it might depend on the order of revs
2528 # _makelogrevset because it might depend on the order of revs
2528 if not (revs.isdescending() or revs.istopo()):
2529 if not (revs.isdescending() or revs.istopo()):
2529 revs.sort(reverse=True)
2530 revs.sort(reverse=True)
2530 if expr:
2531 if expr:
2531 matcher = revset.match(repo.ui, expr)
2532 matcher = revset.match(repo.ui, expr)
2532 revs = matcher(repo, revs)
2533 revs = matcher(repo, revs)
2533 if limit is not None:
2534 if limit is not None:
2534 limitedrevs = []
2535 limitedrevs = []
2535 for idx, rev in enumerate(revs):
2536 for idx, rev in enumerate(revs):
2536 if idx >= limit:
2537 if idx >= limit:
2537 break
2538 break
2538 limitedrevs.append(rev)
2539 limitedrevs.append(rev)
2539 revs = smartset.baseset(limitedrevs)
2540 revs = smartset.baseset(limitedrevs)
2540
2541
2541 return revs, expr, filematcher
2542 return revs, expr, filematcher
2542
2543
2543 def getlogrevs(repo, pats, opts):
2544 def getlogrevs(repo, pats, opts):
2544 """Return (revs, expr, filematcher) where revs is an iterable of
2545 """Return (revs, expr, filematcher) where revs is an iterable of
2545 revision numbers, expr is a revset string built from log options
2546 revision numbers, expr is a revset string built from log options
2546 and file patterns or None, and used to filter 'revs'. If --stat or
2547 and file patterns or None, and used to filter 'revs'. If --stat or
2547 --patch are not passed filematcher is None. Otherwise it is a
2548 --patch are not passed filematcher is None. Otherwise it is a
2548 callable taking a revision number and returning a match objects
2549 callable taking a revision number and returning a match objects
2549 filtering the files to be detailed when displaying the revision.
2550 filtering the files to be detailed when displaying the revision.
2550 """
2551 """
2551 limit = loglimit(opts)
2552 limit = loglimit(opts)
2552 revs = _logrevs(repo, opts)
2553 revs = _logrevs(repo, opts)
2553 if not revs:
2554 if not revs:
2554 return smartset.baseset([]), None, None
2555 return smartset.baseset([]), None, None
2555 expr, filematcher = _makelogrevset(repo, pats, opts, revs)
2556 expr, filematcher = _makelogrevset(repo, pats, opts, revs)
2556 if expr:
2557 if expr:
2557 matcher = revset.match(repo.ui, expr)
2558 matcher = revset.match(repo.ui, expr)
2558 revs = matcher(repo, revs)
2559 revs = matcher(repo, revs)
2559 if limit is not None:
2560 if limit is not None:
2560 limitedrevs = []
2561 limitedrevs = []
2561 for idx, r in enumerate(revs):
2562 for idx, r in enumerate(revs):
2562 if limit <= idx:
2563 if limit <= idx:
2563 break
2564 break
2564 limitedrevs.append(r)
2565 limitedrevs.append(r)
2565 revs = smartset.baseset(limitedrevs)
2566 revs = smartset.baseset(limitedrevs)
2566
2567
2567 return revs, expr, filematcher
2568 return revs, expr, filematcher
2568
2569
2569 def _parselinerangelogopt(repo, opts):
2570 def _parselinerangelogopt(repo, opts):
2570 """Parse --line-range log option and return a list of tuples (filename,
2571 """Parse --line-range log option and return a list of tuples (filename,
2571 (fromline, toline)).
2572 (fromline, toline)).
2572 """
2573 """
2573 linerangebyfname = []
2574 linerangebyfname = []
2574 for pat in opts.get('line_range', []):
2575 for pat in opts.get('line_range', []):
2575 try:
2576 try:
2576 pat, linerange = pat.rsplit(',', 1)
2577 pat, linerange = pat.rsplit(',', 1)
2577 except ValueError:
2578 except ValueError:
2578 raise error.Abort(_('malformatted line-range pattern %s') % pat)
2579 raise error.Abort(_('malformatted line-range pattern %s') % pat)
2579 try:
2580 try:
2580 fromline, toline = map(int, linerange.split(':'))
2581 fromline, toline = map(int, linerange.split(':'))
2581 except ValueError:
2582 except ValueError:
2582 raise error.Abort(_("invalid line range for %s") % pat)
2583 raise error.Abort(_("invalid line range for %s") % pat)
2583 msg = _("line range pattern '%s' must match exactly one file") % pat
2584 msg = _("line range pattern '%s' must match exactly one file") % pat
2584 fname = scmutil.parsefollowlinespattern(repo, None, pat, msg)
2585 fname = scmutil.parsefollowlinespattern(repo, None, pat, msg)
2585 linerangebyfname.append(
2586 linerangebyfname.append(
2586 (fname, util.processlinerange(fromline, toline)))
2587 (fname, util.processlinerange(fromline, toline)))
2587 return linerangebyfname
2588 return linerangebyfname
2588
2589
2589 def getloglinerangerevs(repo, userrevs, opts):
2590 def getloglinerangerevs(repo, userrevs, opts):
2590 """Return (revs, filematcher, hunksfilter).
2591 """Return (revs, filematcher, hunksfilter).
2591
2592
2592 "revs" are revisions obtained by processing "line-range" log options and
2593 "revs" are revisions obtained by processing "line-range" log options and
2593 walking block ancestors of each specified file/line-range.
2594 walking block ancestors of each specified file/line-range.
2594
2595
2595 "filematcher(rev) -> match" is a factory function returning a match object
2596 "filematcher(rev) -> match" is a factory function returning a match object
2596 for a given revision for file patterns specified in --line-range option.
2597 for a given revision for file patterns specified in --line-range option.
2597 If neither --stat nor --patch options are passed, "filematcher" is None.
2598 If neither --stat nor --patch options are passed, "filematcher" is None.
2598
2599
2599 "hunksfilter(rev) -> filterfn(fctx, hunks)" is a factory function
2600 "hunksfilter(rev) -> filterfn(fctx, hunks)" is a factory function
2600 returning a hunks filtering function.
2601 returning a hunks filtering function.
2601 If neither --stat nor --patch options are passed, "filterhunks" is None.
2602 If neither --stat nor --patch options are passed, "filterhunks" is None.
2602 """
2603 """
2603 wctx = repo[None]
2604 wctx = repo[None]
2604
2605
2605 # Two-levels map of "rev -> file ctx -> [line range]".
2606 # Two-levels map of "rev -> file ctx -> [line range]".
2606 linerangesbyrev = {}
2607 linerangesbyrev = {}
2607 for fname, (fromline, toline) in _parselinerangelogopt(repo, opts):
2608 for fname, (fromline, toline) in _parselinerangelogopt(repo, opts):
2608 if fname not in wctx:
2609 if fname not in wctx:
2609 raise error.Abort(_('cannot follow file not in parent '
2610 raise error.Abort(_('cannot follow file not in parent '
2610 'revision: "%s"') % fname)
2611 'revision: "%s"') % fname)
2611 fctx = wctx.filectx(fname)
2612 fctx = wctx.filectx(fname)
2612 for fctx, linerange in dagop.blockancestors(fctx, fromline, toline):
2613 for fctx, linerange in dagop.blockancestors(fctx, fromline, toline):
2613 rev = fctx.introrev()
2614 rev = fctx.introrev()
2614 if rev not in userrevs:
2615 if rev not in userrevs:
2615 continue
2616 continue
2616 linerangesbyrev.setdefault(
2617 linerangesbyrev.setdefault(
2617 rev, {}).setdefault(
2618 rev, {}).setdefault(
2618 fctx.path(), []).append(linerange)
2619 fctx.path(), []).append(linerange)
2619
2620
2620 filematcher = None
2621 filematcher = None
2621 hunksfilter = None
2622 hunksfilter = None
2622 if opts.get('patch') or opts.get('stat'):
2623 if opts.get('patch') or opts.get('stat'):
2623
2624
2624 def nofilterhunksfn(fctx, hunks):
2625 def nofilterhunksfn(fctx, hunks):
2625 return hunks
2626 return hunks
2626
2627
2627 def hunksfilter(rev):
2628 def hunksfilter(rev):
2628 fctxlineranges = linerangesbyrev.get(rev)
2629 fctxlineranges = linerangesbyrev.get(rev)
2629 if fctxlineranges is None:
2630 if fctxlineranges is None:
2630 return nofilterhunksfn
2631 return nofilterhunksfn
2631
2632
2632 def filterfn(fctx, hunks):
2633 def filterfn(fctx, hunks):
2633 lineranges = fctxlineranges.get(fctx.path())
2634 lineranges = fctxlineranges.get(fctx.path())
2634 if lineranges is not None:
2635 if lineranges is not None:
2635 for hr, lines in hunks:
2636 for hr, lines in hunks:
2636 if hr is None: # binary
2637 if hr is None: # binary
2637 yield hr, lines
2638 yield hr, lines
2638 continue
2639 continue
2639 if any(mdiff.hunkinrange(hr[2:], lr)
2640 if any(mdiff.hunkinrange(hr[2:], lr)
2640 for lr in lineranges):
2641 for lr in lineranges):
2641 yield hr, lines
2642 yield hr, lines
2642 else:
2643 else:
2643 for hunk in hunks:
2644 for hunk in hunks:
2644 yield hunk
2645 yield hunk
2645
2646
2646 return filterfn
2647 return filterfn
2647
2648
2648 def filematcher(rev):
2649 def filematcher(rev):
2649 files = list(linerangesbyrev.get(rev, []))
2650 files = list(linerangesbyrev.get(rev, []))
2650 return scmutil.matchfiles(repo, files)
2651 return scmutil.matchfiles(repo, files)
2651
2652
2652 revs = sorted(linerangesbyrev, reverse=True)
2653 revs = sorted(linerangesbyrev, reverse=True)
2653
2654
2654 return revs, filematcher, hunksfilter
2655 return revs, filematcher, hunksfilter
2655
2656
2656 def _graphnodeformatter(ui, displayer):
2657 def _graphnodeformatter(ui, displayer):
2657 spec = ui.config('ui', 'graphnodetemplate')
2658 spec = ui.config('ui', 'graphnodetemplate')
2658 if not spec:
2659 if not spec:
2659 return templatekw.showgraphnode # fast path for "{graphnode}"
2660 return templatekw.showgraphnode # fast path for "{graphnode}"
2660
2661
2661 spec = templater.unquotestring(spec)
2662 spec = templater.unquotestring(spec)
2662 templ = formatter.maketemplater(ui, spec)
2663 templ = formatter.maketemplater(ui, spec)
2663 cache = {}
2664 cache = {}
2664 if isinstance(displayer, changeset_templater):
2665 if isinstance(displayer, changeset_templater):
2665 cache = displayer.cache # reuse cache of slow templates
2666 cache = displayer.cache # reuse cache of slow templates
2666 props = templatekw.keywords.copy()
2667 props = templatekw.keywords.copy()
2667 props['templ'] = templ
2668 props['templ'] = templ
2668 props['cache'] = cache
2669 props['cache'] = cache
2669 def formatnode(repo, ctx):
2670 def formatnode(repo, ctx):
2670 props['ctx'] = ctx
2671 props['ctx'] = ctx
2671 props['repo'] = repo
2672 props['repo'] = repo
2672 props['ui'] = repo.ui
2673 props['ui'] = repo.ui
2673 props['revcache'] = {}
2674 props['revcache'] = {}
2674 return templ.render(props)
2675 return templ.render(props)
2675 return formatnode
2676 return formatnode
2676
2677
2677 def displaygraph(ui, repo, dag, displayer, edgefn, getrenamed=None,
2678 def displaygraph(ui, repo, dag, displayer, edgefn, getrenamed=None,
2678 filematcher=None, props=None):
2679 filematcher=None, props=None):
2679 props = props or {}
2680 props = props or {}
2680 formatnode = _graphnodeformatter(ui, displayer)
2681 formatnode = _graphnodeformatter(ui, displayer)
2681 state = graphmod.asciistate()
2682 state = graphmod.asciistate()
2682 styles = state['styles']
2683 styles = state['styles']
2683
2684
2684 # only set graph styling if HGPLAIN is not set.
2685 # only set graph styling if HGPLAIN is not set.
2685 if ui.plain('graph'):
2686 if ui.plain('graph'):
2686 # set all edge styles to |, the default pre-3.8 behaviour
2687 # set all edge styles to |, the default pre-3.8 behaviour
2687 styles.update(dict.fromkeys(styles, '|'))
2688 styles.update(dict.fromkeys(styles, '|'))
2688 else:
2689 else:
2689 edgetypes = {
2690 edgetypes = {
2690 'parent': graphmod.PARENT,
2691 'parent': graphmod.PARENT,
2691 'grandparent': graphmod.GRANDPARENT,
2692 'grandparent': graphmod.GRANDPARENT,
2692 'missing': graphmod.MISSINGPARENT
2693 'missing': graphmod.MISSINGPARENT
2693 }
2694 }
2694 for name, key in edgetypes.items():
2695 for name, key in edgetypes.items():
2695 # experimental config: experimental.graphstyle.*
2696 # experimental config: experimental.graphstyle.*
2696 styles[key] = ui.config('experimental', 'graphstyle.%s' % name,
2697 styles[key] = ui.config('experimental', 'graphstyle.%s' % name,
2697 styles[key])
2698 styles[key])
2698 if not styles[key]:
2699 if not styles[key]:
2699 styles[key] = None
2700 styles[key] = None
2700
2701
2701 # experimental config: experimental.graphshorten
2702 # experimental config: experimental.graphshorten
2702 state['graphshorten'] = ui.configbool('experimental', 'graphshorten')
2703 state['graphshorten'] = ui.configbool('experimental', 'graphshorten')
2703
2704
2704 for rev, type, ctx, parents in dag:
2705 for rev, type, ctx, parents in dag:
2705 char = formatnode(repo, ctx)
2706 char = formatnode(repo, ctx)
2706 copies = None
2707 copies = None
2707 if getrenamed and ctx.rev():
2708 if getrenamed and ctx.rev():
2708 copies = []
2709 copies = []
2709 for fn in ctx.files():
2710 for fn in ctx.files():
2710 rename = getrenamed(fn, ctx.rev())
2711 rename = getrenamed(fn, ctx.rev())
2711 if rename:
2712 if rename:
2712 copies.append((fn, rename[0]))
2713 copies.append((fn, rename[0]))
2713 revmatchfn = None
2714 revmatchfn = None
2714 if filematcher is not None:
2715 if filematcher is not None:
2715 revmatchfn = filematcher(ctx.rev())
2716 revmatchfn = filematcher(ctx.rev())
2716 edges = edgefn(type, char, state, rev, parents)
2717 edges = edgefn(type, char, state, rev, parents)
2717 firstedge = next(edges)
2718 firstedge = next(edges)
2718 width = firstedge[2]
2719 width = firstedge[2]
2719 displayer.show(ctx, copies=copies, matchfn=revmatchfn,
2720 displayer.show(ctx, copies=copies, matchfn=revmatchfn,
2720 _graphwidth=width, **props)
2721 _graphwidth=width, **pycompat.strkwargs(props))
2721 lines = displayer.hunk.pop(rev).split('\n')
2722 lines = displayer.hunk.pop(rev).split('\n')
2722 if not lines[-1]:
2723 if not lines[-1]:
2723 del lines[-1]
2724 del lines[-1]
2724 displayer.flush(ctx)
2725 displayer.flush(ctx)
2725 for type, char, width, coldata in itertools.chain([firstedge], edges):
2726 for type, char, width, coldata in itertools.chain([firstedge], edges):
2726 graphmod.ascii(ui, state, type, char, lines, coldata)
2727 graphmod.ascii(ui, state, type, char, lines, coldata)
2727 lines = []
2728 lines = []
2728 displayer.close()
2729 displayer.close()
2729
2730
2730 def graphlog(ui, repo, pats, opts):
2731 def graphlog(ui, repo, pats, opts):
2731 # Parameters are identical to log command ones
2732 # Parameters are identical to log command ones
2732 revs, expr, filematcher = getgraphlogrevs(repo, pats, opts)
2733 revs, expr, filematcher = getgraphlogrevs(repo, pats, opts)
2733 revdag = graphmod.dagwalker(repo, revs)
2734 revdag = graphmod.dagwalker(repo, revs)
2734
2735
2735 getrenamed = None
2736 getrenamed = None
2736 if opts.get('copies'):
2737 if opts.get('copies'):
2737 endrev = None
2738 endrev = None
2738 if opts.get('rev'):
2739 if opts.get('rev'):
2739 endrev = scmutil.revrange(repo, opts.get('rev')).max() + 1
2740 endrev = scmutil.revrange(repo, opts.get('rev')).max() + 1
2740 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
2741 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
2741
2742
2742 ui.pager('log')
2743 ui.pager('log')
2743 displayer = show_changeset(ui, repo, opts, buffered=True)
2744 displayer = show_changeset(ui, repo, opts, buffered=True)
2744 displaygraph(ui, repo, revdag, displayer, graphmod.asciiedges, getrenamed,
2745 displaygraph(ui, repo, revdag, displayer, graphmod.asciiedges, getrenamed,
2745 filematcher)
2746 filematcher)
2746
2747
2747 def checkunsupportedgraphflags(pats, opts):
2748 def checkunsupportedgraphflags(pats, opts):
2748 for op in ["newest_first"]:
2749 for op in ["newest_first"]:
2749 if op in opts and opts[op]:
2750 if op in opts and opts[op]:
2750 raise error.Abort(_("-G/--graph option is incompatible with --%s")
2751 raise error.Abort(_("-G/--graph option is incompatible with --%s")
2751 % op.replace("_", "-"))
2752 % op.replace("_", "-"))
2752
2753
2753 def graphrevs(repo, nodes, opts):
2754 def graphrevs(repo, nodes, opts):
2754 limit = loglimit(opts)
2755 limit = loglimit(opts)
2755 nodes.reverse()
2756 nodes.reverse()
2756 if limit is not None:
2757 if limit is not None:
2757 nodes = nodes[:limit]
2758 nodes = nodes[:limit]
2758 return graphmod.nodes(repo, nodes)
2759 return graphmod.nodes(repo, nodes)
2759
2760
2760 def add(ui, repo, match, prefix, explicitonly, **opts):
2761 def add(ui, repo, match, prefix, explicitonly, **opts):
2761 join = lambda f: os.path.join(prefix, f)
2762 join = lambda f: os.path.join(prefix, f)
2762 bad = []
2763 bad = []
2763
2764
2764 badfn = lambda x, y: bad.append(x) or match.bad(x, y)
2765 badfn = lambda x, y: bad.append(x) or match.bad(x, y)
2765 names = []
2766 names = []
2766 wctx = repo[None]
2767 wctx = repo[None]
2767 cca = None
2768 cca = None
2768 abort, warn = scmutil.checkportabilityalert(ui)
2769 abort, warn = scmutil.checkportabilityalert(ui)
2769 if abort or warn:
2770 if abort or warn:
2770 cca = scmutil.casecollisionauditor(ui, abort, repo.dirstate)
2771 cca = scmutil.casecollisionauditor(ui, abort, repo.dirstate)
2771
2772
2772 badmatch = matchmod.badmatch(match, badfn)
2773 badmatch = matchmod.badmatch(match, badfn)
2773 dirstate = repo.dirstate
2774 dirstate = repo.dirstate
2774 # We don't want to just call wctx.walk here, since it would return a lot of
2775 # We don't want to just call wctx.walk here, since it would return a lot of
2775 # clean files, which we aren't interested in and takes time.
2776 # clean files, which we aren't interested in and takes time.
2776 for f in sorted(dirstate.walk(badmatch, subrepos=sorted(wctx.substate),
2777 for f in sorted(dirstate.walk(badmatch, subrepos=sorted(wctx.substate),
2777 unknown=True, ignored=False, full=False)):
2778 unknown=True, ignored=False, full=False)):
2778 exact = match.exact(f)
2779 exact = match.exact(f)
2779 if exact or not explicitonly and f not in wctx and repo.wvfs.lexists(f):
2780 if exact or not explicitonly and f not in wctx and repo.wvfs.lexists(f):
2780 if cca:
2781 if cca:
2781 cca(f)
2782 cca(f)
2782 names.append(f)
2783 names.append(f)
2783 if ui.verbose or not exact:
2784 if ui.verbose or not exact:
2784 ui.status(_('adding %s\n') % match.rel(f))
2785 ui.status(_('adding %s\n') % match.rel(f))
2785
2786
2786 for subpath in sorted(wctx.substate):
2787 for subpath in sorted(wctx.substate):
2787 sub = wctx.sub(subpath)
2788 sub = wctx.sub(subpath)
2788 try:
2789 try:
2789 submatch = matchmod.subdirmatcher(subpath, match)
2790 submatch = matchmod.subdirmatcher(subpath, match)
2790 if opts.get(r'subrepos'):
2791 if opts.get(r'subrepos'):
2791 bad.extend(sub.add(ui, submatch, prefix, False, **opts))
2792 bad.extend(sub.add(ui, submatch, prefix, False, **opts))
2792 else:
2793 else:
2793 bad.extend(sub.add(ui, submatch, prefix, True, **opts))
2794 bad.extend(sub.add(ui, submatch, prefix, True, **opts))
2794 except error.LookupError:
2795 except error.LookupError:
2795 ui.status(_("skipping missing subrepository: %s\n")
2796 ui.status(_("skipping missing subrepository: %s\n")
2796 % join(subpath))
2797 % join(subpath))
2797
2798
2798 if not opts.get(r'dry_run'):
2799 if not opts.get(r'dry_run'):
2799 rejected = wctx.add(names, prefix)
2800 rejected = wctx.add(names, prefix)
2800 bad.extend(f for f in rejected if f in match.files())
2801 bad.extend(f for f in rejected if f in match.files())
2801 return bad
2802 return bad
2802
2803
2803 def addwebdirpath(repo, serverpath, webconf):
2804 def addwebdirpath(repo, serverpath, webconf):
2804 webconf[serverpath] = repo.root
2805 webconf[serverpath] = repo.root
2805 repo.ui.debug('adding %s = %s\n' % (serverpath, repo.root))
2806 repo.ui.debug('adding %s = %s\n' % (serverpath, repo.root))
2806
2807
2807 for r in repo.revs('filelog("path:.hgsub")'):
2808 for r in repo.revs('filelog("path:.hgsub")'):
2808 ctx = repo[r]
2809 ctx = repo[r]
2809 for subpath in ctx.substate:
2810 for subpath in ctx.substate:
2810 ctx.sub(subpath).addwebdirpath(serverpath, webconf)
2811 ctx.sub(subpath).addwebdirpath(serverpath, webconf)
2811
2812
2812 def forget(ui, repo, match, prefix, explicitonly):
2813 def forget(ui, repo, match, prefix, explicitonly):
2813 join = lambda f: os.path.join(prefix, f)
2814 join = lambda f: os.path.join(prefix, f)
2814 bad = []
2815 bad = []
2815 badfn = lambda x, y: bad.append(x) or match.bad(x, y)
2816 badfn = lambda x, y: bad.append(x) or match.bad(x, y)
2816 wctx = repo[None]
2817 wctx = repo[None]
2817 forgot = []
2818 forgot = []
2818
2819
2819 s = repo.status(match=matchmod.badmatch(match, badfn), clean=True)
2820 s = repo.status(match=matchmod.badmatch(match, badfn), clean=True)
2820 forget = sorted(s.modified + s.added + s.deleted + s.clean)
2821 forget = sorted(s.modified + s.added + s.deleted + s.clean)
2821 if explicitonly:
2822 if explicitonly:
2822 forget = [f for f in forget if match.exact(f)]
2823 forget = [f for f in forget if match.exact(f)]
2823
2824
2824 for subpath in sorted(wctx.substate):
2825 for subpath in sorted(wctx.substate):
2825 sub = wctx.sub(subpath)
2826 sub = wctx.sub(subpath)
2826 try:
2827 try:
2827 submatch = matchmod.subdirmatcher(subpath, match)
2828 submatch = matchmod.subdirmatcher(subpath, match)
2828 subbad, subforgot = sub.forget(submatch, prefix)
2829 subbad, subforgot = sub.forget(submatch, prefix)
2829 bad.extend([subpath + '/' + f for f in subbad])
2830 bad.extend([subpath + '/' + f for f in subbad])
2830 forgot.extend([subpath + '/' + f for f in subforgot])
2831 forgot.extend([subpath + '/' + f for f in subforgot])
2831 except error.LookupError:
2832 except error.LookupError:
2832 ui.status(_("skipping missing subrepository: %s\n")
2833 ui.status(_("skipping missing subrepository: %s\n")
2833 % join(subpath))
2834 % join(subpath))
2834
2835
2835 if not explicitonly:
2836 if not explicitonly:
2836 for f in match.files():
2837 for f in match.files():
2837 if f not in repo.dirstate and not repo.wvfs.isdir(f):
2838 if f not in repo.dirstate and not repo.wvfs.isdir(f):
2838 if f not in forgot:
2839 if f not in forgot:
2839 if repo.wvfs.exists(f):
2840 if repo.wvfs.exists(f):
2840 # Don't complain if the exact case match wasn't given.
2841 # Don't complain if the exact case match wasn't given.
2841 # But don't do this until after checking 'forgot', so
2842 # But don't do this until after checking 'forgot', so
2842 # that subrepo files aren't normalized, and this op is
2843 # that subrepo files aren't normalized, and this op is
2843 # purely from data cached by the status walk above.
2844 # purely from data cached by the status walk above.
2844 if repo.dirstate.normalize(f) in repo.dirstate:
2845 if repo.dirstate.normalize(f) in repo.dirstate:
2845 continue
2846 continue
2846 ui.warn(_('not removing %s: '
2847 ui.warn(_('not removing %s: '
2847 'file is already untracked\n')
2848 'file is already untracked\n')
2848 % match.rel(f))
2849 % match.rel(f))
2849 bad.append(f)
2850 bad.append(f)
2850
2851
2851 for f in forget:
2852 for f in forget:
2852 if ui.verbose or not match.exact(f):
2853 if ui.verbose or not match.exact(f):
2853 ui.status(_('removing %s\n') % match.rel(f))
2854 ui.status(_('removing %s\n') % match.rel(f))
2854
2855
2855 rejected = wctx.forget(forget, prefix)
2856 rejected = wctx.forget(forget, prefix)
2856 bad.extend(f for f in rejected if f in match.files())
2857 bad.extend(f for f in rejected if f in match.files())
2857 forgot.extend(f for f in forget if f not in rejected)
2858 forgot.extend(f for f in forget if f not in rejected)
2858 return bad, forgot
2859 return bad, forgot
2859
2860
2860 def files(ui, ctx, m, fm, fmt, subrepos):
2861 def files(ui, ctx, m, fm, fmt, subrepos):
2861 rev = ctx.rev()
2862 rev = ctx.rev()
2862 ret = 1
2863 ret = 1
2863 ds = ctx.repo().dirstate
2864 ds = ctx.repo().dirstate
2864
2865
2865 for f in ctx.matches(m):
2866 for f in ctx.matches(m):
2866 if rev is None and ds[f] == 'r':
2867 if rev is None and ds[f] == 'r':
2867 continue
2868 continue
2868 fm.startitem()
2869 fm.startitem()
2869 if ui.verbose:
2870 if ui.verbose:
2870 fc = ctx[f]
2871 fc = ctx[f]
2871 fm.write('size flags', '% 10d % 1s ', fc.size(), fc.flags())
2872 fm.write('size flags', '% 10d % 1s ', fc.size(), fc.flags())
2872 fm.data(abspath=f)
2873 fm.data(abspath=f)
2873 fm.write('path', fmt, m.rel(f))
2874 fm.write('path', fmt, m.rel(f))
2874 ret = 0
2875 ret = 0
2875
2876
2876 for subpath in sorted(ctx.substate):
2877 for subpath in sorted(ctx.substate):
2877 submatch = matchmod.subdirmatcher(subpath, m)
2878 submatch = matchmod.subdirmatcher(subpath, m)
2878 if (subrepos or m.exact(subpath) or any(submatch.files())):
2879 if (subrepos or m.exact(subpath) or any(submatch.files())):
2879 sub = ctx.sub(subpath)
2880 sub = ctx.sub(subpath)
2880 try:
2881 try:
2881 recurse = m.exact(subpath) or subrepos
2882 recurse = m.exact(subpath) or subrepos
2882 if sub.printfiles(ui, submatch, fm, fmt, recurse) == 0:
2883 if sub.printfiles(ui, submatch, fm, fmt, recurse) == 0:
2883 ret = 0
2884 ret = 0
2884 except error.LookupError:
2885 except error.LookupError:
2885 ui.status(_("skipping missing subrepository: %s\n")
2886 ui.status(_("skipping missing subrepository: %s\n")
2886 % m.abs(subpath))
2887 % m.abs(subpath))
2887
2888
2888 return ret
2889 return ret
2889
2890
2890 def remove(ui, repo, m, prefix, after, force, subrepos, warnings=None):
2891 def remove(ui, repo, m, prefix, after, force, subrepos, warnings=None):
2891 join = lambda f: os.path.join(prefix, f)
2892 join = lambda f: os.path.join(prefix, f)
2892 ret = 0
2893 ret = 0
2893 s = repo.status(match=m, clean=True)
2894 s = repo.status(match=m, clean=True)
2894 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
2895 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
2895
2896
2896 wctx = repo[None]
2897 wctx = repo[None]
2897
2898
2898 if warnings is None:
2899 if warnings is None:
2899 warnings = []
2900 warnings = []
2900 warn = True
2901 warn = True
2901 else:
2902 else:
2902 warn = False
2903 warn = False
2903
2904
2904 subs = sorted(wctx.substate)
2905 subs = sorted(wctx.substate)
2905 total = len(subs)
2906 total = len(subs)
2906 count = 0
2907 count = 0
2907 for subpath in subs:
2908 for subpath in subs:
2908 count += 1
2909 count += 1
2909 submatch = matchmod.subdirmatcher(subpath, m)
2910 submatch = matchmod.subdirmatcher(subpath, m)
2910 if subrepos or m.exact(subpath) or any(submatch.files()):
2911 if subrepos or m.exact(subpath) or any(submatch.files()):
2911 ui.progress(_('searching'), count, total=total, unit=_('subrepos'))
2912 ui.progress(_('searching'), count, total=total, unit=_('subrepos'))
2912 sub = wctx.sub(subpath)
2913 sub = wctx.sub(subpath)
2913 try:
2914 try:
2914 if sub.removefiles(submatch, prefix, after, force, subrepos,
2915 if sub.removefiles(submatch, prefix, after, force, subrepos,
2915 warnings):
2916 warnings):
2916 ret = 1
2917 ret = 1
2917 except error.LookupError:
2918 except error.LookupError:
2918 warnings.append(_("skipping missing subrepository: %s\n")
2919 warnings.append(_("skipping missing subrepository: %s\n")
2919 % join(subpath))
2920 % join(subpath))
2920 ui.progress(_('searching'), None)
2921 ui.progress(_('searching'), None)
2921
2922
2922 # warn about failure to delete explicit files/dirs
2923 # warn about failure to delete explicit files/dirs
2923 deleteddirs = util.dirs(deleted)
2924 deleteddirs = util.dirs(deleted)
2924 files = m.files()
2925 files = m.files()
2925 total = len(files)
2926 total = len(files)
2926 count = 0
2927 count = 0
2927 for f in files:
2928 for f in files:
2928 def insubrepo():
2929 def insubrepo():
2929 for subpath in wctx.substate:
2930 for subpath in wctx.substate:
2930 if f.startswith(subpath + '/'):
2931 if f.startswith(subpath + '/'):
2931 return True
2932 return True
2932 return False
2933 return False
2933
2934
2934 count += 1
2935 count += 1
2935 ui.progress(_('deleting'), count, total=total, unit=_('files'))
2936 ui.progress(_('deleting'), count, total=total, unit=_('files'))
2936 isdir = f in deleteddirs or wctx.hasdir(f)
2937 isdir = f in deleteddirs or wctx.hasdir(f)
2937 if (f in repo.dirstate or isdir or f == '.'
2938 if (f in repo.dirstate or isdir or f == '.'
2938 or insubrepo() or f in subs):
2939 or insubrepo() or f in subs):
2939 continue
2940 continue
2940
2941
2941 if repo.wvfs.exists(f):
2942 if repo.wvfs.exists(f):
2942 if repo.wvfs.isdir(f):
2943 if repo.wvfs.isdir(f):
2943 warnings.append(_('not removing %s: no tracked files\n')
2944 warnings.append(_('not removing %s: no tracked files\n')
2944 % m.rel(f))
2945 % m.rel(f))
2945 else:
2946 else:
2946 warnings.append(_('not removing %s: file is untracked\n')
2947 warnings.append(_('not removing %s: file is untracked\n')
2947 % m.rel(f))
2948 % m.rel(f))
2948 # missing files will generate a warning elsewhere
2949 # missing files will generate a warning elsewhere
2949 ret = 1
2950 ret = 1
2950 ui.progress(_('deleting'), None)
2951 ui.progress(_('deleting'), None)
2951
2952
2952 if force:
2953 if force:
2953 list = modified + deleted + clean + added
2954 list = modified + deleted + clean + added
2954 elif after:
2955 elif after:
2955 list = deleted
2956 list = deleted
2956 remaining = modified + added + clean
2957 remaining = modified + added + clean
2957 total = len(remaining)
2958 total = len(remaining)
2958 count = 0
2959 count = 0
2959 for f in remaining:
2960 for f in remaining:
2960 count += 1
2961 count += 1
2961 ui.progress(_('skipping'), count, total=total, unit=_('files'))
2962 ui.progress(_('skipping'), count, total=total, unit=_('files'))
2962 if ui.verbose or (f in files):
2963 if ui.verbose or (f in files):
2963 warnings.append(_('not removing %s: file still exists\n')
2964 warnings.append(_('not removing %s: file still exists\n')
2964 % m.rel(f))
2965 % m.rel(f))
2965 ret = 1
2966 ret = 1
2966 ui.progress(_('skipping'), None)
2967 ui.progress(_('skipping'), None)
2967 else:
2968 else:
2968 list = deleted + clean
2969 list = deleted + clean
2969 total = len(modified) + len(added)
2970 total = len(modified) + len(added)
2970 count = 0
2971 count = 0
2971 for f in modified:
2972 for f in modified:
2972 count += 1
2973 count += 1
2973 ui.progress(_('skipping'), count, total=total, unit=_('files'))
2974 ui.progress(_('skipping'), count, total=total, unit=_('files'))
2974 warnings.append(_('not removing %s: file is modified (use -f'
2975 warnings.append(_('not removing %s: file is modified (use -f'
2975 ' to force removal)\n') % m.rel(f))
2976 ' to force removal)\n') % m.rel(f))
2976 ret = 1
2977 ret = 1
2977 for f in added:
2978 for f in added:
2978 count += 1
2979 count += 1
2979 ui.progress(_('skipping'), count, total=total, unit=_('files'))
2980 ui.progress(_('skipping'), count, total=total, unit=_('files'))
2980 warnings.append(_("not removing %s: file has been marked for add"
2981 warnings.append(_("not removing %s: file has been marked for add"
2981 " (use 'hg forget' to undo add)\n") % m.rel(f))
2982 " (use 'hg forget' to undo add)\n") % m.rel(f))
2982 ret = 1
2983 ret = 1
2983 ui.progress(_('skipping'), None)
2984 ui.progress(_('skipping'), None)
2984
2985
2985 list = sorted(list)
2986 list = sorted(list)
2986 total = len(list)
2987 total = len(list)
2987 count = 0
2988 count = 0
2988 for f in list:
2989 for f in list:
2989 count += 1
2990 count += 1
2990 if ui.verbose or not m.exact(f):
2991 if ui.verbose or not m.exact(f):
2991 ui.progress(_('deleting'), count, total=total, unit=_('files'))
2992 ui.progress(_('deleting'), count, total=total, unit=_('files'))
2992 ui.status(_('removing %s\n') % m.rel(f))
2993 ui.status(_('removing %s\n') % m.rel(f))
2993 ui.progress(_('deleting'), None)
2994 ui.progress(_('deleting'), None)
2994
2995
2995 with repo.wlock():
2996 with repo.wlock():
2996 if not after:
2997 if not after:
2997 for f in list:
2998 for f in list:
2998 if f in added:
2999 if f in added:
2999 continue # we never unlink added files on remove
3000 continue # we never unlink added files on remove
3000 repo.wvfs.unlinkpath(f, ignoremissing=True)
3001 repo.wvfs.unlinkpath(f, ignoremissing=True)
3001 repo[None].forget(list)
3002 repo[None].forget(list)
3002
3003
3003 if warn:
3004 if warn:
3004 for warning in warnings:
3005 for warning in warnings:
3005 ui.warn(warning)
3006 ui.warn(warning)
3006
3007
3007 return ret
3008 return ret
3008
3009
3009 def cat(ui, repo, ctx, matcher, basefm, fntemplate, prefix, **opts):
3010 def cat(ui, repo, ctx, matcher, basefm, fntemplate, prefix, **opts):
3010 err = 1
3011 err = 1
3012 opts = pycompat.byteskwargs(opts)
3011
3013
3012 def write(path):
3014 def write(path):
3013 filename = None
3015 filename = None
3014 if fntemplate:
3016 if fntemplate:
3015 filename = makefilename(repo, fntemplate, ctx.node(),
3017 filename = makefilename(repo, fntemplate, ctx.node(),
3016 pathname=os.path.join(prefix, path))
3018 pathname=os.path.join(prefix, path))
3017 # attempt to create the directory if it does not already exist
3019 # attempt to create the directory if it does not already exist
3018 try:
3020 try:
3019 os.makedirs(os.path.dirname(filename))
3021 os.makedirs(os.path.dirname(filename))
3020 except OSError:
3022 except OSError:
3021 pass
3023 pass
3022 with formatter.maybereopen(basefm, filename, opts) as fm:
3024 with formatter.maybereopen(basefm, filename, opts) as fm:
3023 data = ctx[path].data()
3025 data = ctx[path].data()
3024 if opts.get('decode'):
3026 if opts.get('decode'):
3025 data = repo.wwritedata(path, data)
3027 data = repo.wwritedata(path, data)
3026 fm.startitem()
3028 fm.startitem()
3027 fm.write('data', '%s', data)
3029 fm.write('data', '%s', data)
3028 fm.data(abspath=path, path=matcher.rel(path))
3030 fm.data(abspath=path, path=matcher.rel(path))
3029
3031
3030 # Automation often uses hg cat on single files, so special case it
3032 # Automation often uses hg cat on single files, so special case it
3031 # for performance to avoid the cost of parsing the manifest.
3033 # for performance to avoid the cost of parsing the manifest.
3032 if len(matcher.files()) == 1 and not matcher.anypats():
3034 if len(matcher.files()) == 1 and not matcher.anypats():
3033 file = matcher.files()[0]
3035 file = matcher.files()[0]
3034 mfl = repo.manifestlog
3036 mfl = repo.manifestlog
3035 mfnode = ctx.manifestnode()
3037 mfnode = ctx.manifestnode()
3036 try:
3038 try:
3037 if mfnode and mfl[mfnode].find(file)[0]:
3039 if mfnode and mfl[mfnode].find(file)[0]:
3038 write(file)
3040 write(file)
3039 return 0
3041 return 0
3040 except KeyError:
3042 except KeyError:
3041 pass
3043 pass
3042
3044
3043 for abs in ctx.walk(matcher):
3045 for abs in ctx.walk(matcher):
3044 write(abs)
3046 write(abs)
3045 err = 0
3047 err = 0
3046
3048
3047 for subpath in sorted(ctx.substate):
3049 for subpath in sorted(ctx.substate):
3048 sub = ctx.sub(subpath)
3050 sub = ctx.sub(subpath)
3049 try:
3051 try:
3050 submatch = matchmod.subdirmatcher(subpath, matcher)
3052 submatch = matchmod.subdirmatcher(subpath, matcher)
3051
3053
3052 if not sub.cat(submatch, basefm, fntemplate,
3054 if not sub.cat(submatch, basefm, fntemplate,
3053 os.path.join(prefix, sub._path), **opts):
3055 os.path.join(prefix, sub._path),
3056 **pycompat.strkwargs(opts)):
3054 err = 0
3057 err = 0
3055 except error.RepoLookupError:
3058 except error.RepoLookupError:
3056 ui.status(_("skipping missing subrepository: %s\n")
3059 ui.status(_("skipping missing subrepository: %s\n")
3057 % os.path.join(prefix, subpath))
3060 % os.path.join(prefix, subpath))
3058
3061
3059 return err
3062 return err
3060
3063
3061 def commit(ui, repo, commitfunc, pats, opts):
3064 def commit(ui, repo, commitfunc, pats, opts):
3062 '''commit the specified files or all outstanding changes'''
3065 '''commit the specified files or all outstanding changes'''
3063 date = opts.get('date')
3066 date = opts.get('date')
3064 if date:
3067 if date:
3065 opts['date'] = util.parsedate(date)
3068 opts['date'] = util.parsedate(date)
3066 message = logmessage(ui, opts)
3069 message = logmessage(ui, opts)
3067 matcher = scmutil.match(repo[None], pats, opts)
3070 matcher = scmutil.match(repo[None], pats, opts)
3068
3071
3069 dsguard = None
3072 dsguard = None
3070 # extract addremove carefully -- this function can be called from a command
3073 # extract addremove carefully -- this function can be called from a command
3071 # that doesn't support addremove
3074 # that doesn't support addremove
3072 if opts.get('addremove'):
3075 if opts.get('addremove'):
3073 dsguard = dirstateguard.dirstateguard(repo, 'commit')
3076 dsguard = dirstateguard.dirstateguard(repo, 'commit')
3074 with dsguard or util.nullcontextmanager():
3077 with dsguard or util.nullcontextmanager():
3075 if dsguard:
3078 if dsguard:
3076 if scmutil.addremove(repo, matcher, "", opts) != 0:
3079 if scmutil.addremove(repo, matcher, "", opts) != 0:
3077 raise error.Abort(
3080 raise error.Abort(
3078 _("failed to mark all new/missing files as added/removed"))
3081 _("failed to mark all new/missing files as added/removed"))
3079
3082
3080 return commitfunc(ui, repo, message, matcher, opts)
3083 return commitfunc(ui, repo, message, matcher, opts)
3081
3084
3082 def samefile(f, ctx1, ctx2):
3085 def samefile(f, ctx1, ctx2):
3083 if f in ctx1.manifest():
3086 if f in ctx1.manifest():
3084 a = ctx1.filectx(f)
3087 a = ctx1.filectx(f)
3085 if f in ctx2.manifest():
3088 if f in ctx2.manifest():
3086 b = ctx2.filectx(f)
3089 b = ctx2.filectx(f)
3087 return (not a.cmp(b)
3090 return (not a.cmp(b)
3088 and a.flags() == b.flags())
3091 and a.flags() == b.flags())
3089 else:
3092 else:
3090 return False
3093 return False
3091 else:
3094 else:
3092 return f not in ctx2.manifest()
3095 return f not in ctx2.manifest()
3093
3096
3094 def amend(ui, repo, old, extra, pats, opts):
3097 def amend(ui, repo, old, extra, pats, opts):
3095 # avoid cycle context -> subrepo -> cmdutil
3098 # avoid cycle context -> subrepo -> cmdutil
3096 from . import context
3099 from . import context
3097
3100
3098 # amend will reuse the existing user if not specified, but the obsolete
3101 # amend will reuse the existing user if not specified, but the obsolete
3099 # marker creation requires that the current user's name is specified.
3102 # marker creation requires that the current user's name is specified.
3100 if obsolete.isenabled(repo, obsolete.createmarkersopt):
3103 if obsolete.isenabled(repo, obsolete.createmarkersopt):
3101 ui.username() # raise exception if username not set
3104 ui.username() # raise exception if username not set
3102
3105
3103 ui.note(_('amending changeset %s\n') % old)
3106 ui.note(_('amending changeset %s\n') % old)
3104 base = old.p1()
3107 base = old.p1()
3105
3108
3106 with repo.wlock(), repo.lock(), repo.transaction('amend'):
3109 with repo.wlock(), repo.lock(), repo.transaction('amend'):
3107 # Participating changesets:
3110 # Participating changesets:
3108 #
3111 #
3109 # wctx o - workingctx that contains changes from working copy
3112 # wctx o - workingctx that contains changes from working copy
3110 # | to go into amending commit
3113 # | to go into amending commit
3111 # |
3114 # |
3112 # old o - changeset to amend
3115 # old o - changeset to amend
3113 # |
3116 # |
3114 # base o - first parent of the changeset to amend
3117 # base o - first parent of the changeset to amend
3115 wctx = repo[None]
3118 wctx = repo[None]
3116
3119
3117 # Copy to avoid mutating input
3120 # Copy to avoid mutating input
3118 extra = extra.copy()
3121 extra = extra.copy()
3119 # Update extra dict from amended commit (e.g. to preserve graft
3122 # Update extra dict from amended commit (e.g. to preserve graft
3120 # source)
3123 # source)
3121 extra.update(old.extra())
3124 extra.update(old.extra())
3122
3125
3123 # Also update it from the from the wctx
3126 # Also update it from the from the wctx
3124 extra.update(wctx.extra())
3127 extra.update(wctx.extra())
3125
3128
3126 user = opts.get('user') or old.user()
3129 user = opts.get('user') or old.user()
3127 date = opts.get('date') or old.date()
3130 date = opts.get('date') or old.date()
3128
3131
3129 # Parse the date to allow comparison between date and old.date()
3132 # Parse the date to allow comparison between date and old.date()
3130 date = util.parsedate(date)
3133 date = util.parsedate(date)
3131
3134
3132 if len(old.parents()) > 1:
3135 if len(old.parents()) > 1:
3133 # ctx.files() isn't reliable for merges, so fall back to the
3136 # ctx.files() isn't reliable for merges, so fall back to the
3134 # slower repo.status() method
3137 # slower repo.status() method
3135 files = set([fn for st in repo.status(base, old)[:3]
3138 files = set([fn for st in repo.status(base, old)[:3]
3136 for fn in st])
3139 for fn in st])
3137 else:
3140 else:
3138 files = set(old.files())
3141 files = set(old.files())
3139
3142
3140 # add/remove the files to the working copy if the "addremove" option
3143 # add/remove the files to the working copy if the "addremove" option
3141 # was specified.
3144 # was specified.
3142 matcher = scmutil.match(wctx, pats, opts)
3145 matcher = scmutil.match(wctx, pats, opts)
3143 if (opts.get('addremove')
3146 if (opts.get('addremove')
3144 and scmutil.addremove(repo, matcher, "", opts)):
3147 and scmutil.addremove(repo, matcher, "", opts)):
3145 raise error.Abort(
3148 raise error.Abort(
3146 _("failed to mark all new/missing files as added/removed"))
3149 _("failed to mark all new/missing files as added/removed"))
3147
3150
3148 # Check subrepos. This depends on in-place wctx._status update in
3151 # Check subrepos. This depends on in-place wctx._status update in
3149 # subrepo.precommit(). To minimize the risk of this hack, we do
3152 # subrepo.precommit(). To minimize the risk of this hack, we do
3150 # nothing if .hgsub does not exist.
3153 # nothing if .hgsub does not exist.
3151 if '.hgsub' in wctx or '.hgsub' in old:
3154 if '.hgsub' in wctx or '.hgsub' in old:
3152 from . import subrepo # avoid cycle: cmdutil -> subrepo -> cmdutil
3155 from . import subrepo # avoid cycle: cmdutil -> subrepo -> cmdutil
3153 subs, commitsubs, newsubstate = subrepo.precommit(
3156 subs, commitsubs, newsubstate = subrepo.precommit(
3154 ui, wctx, wctx._status, matcher)
3157 ui, wctx, wctx._status, matcher)
3155 # amend should abort if commitsubrepos is enabled
3158 # amend should abort if commitsubrepos is enabled
3156 assert not commitsubs
3159 assert not commitsubs
3157 if subs:
3160 if subs:
3158 subrepo.writestate(repo, newsubstate)
3161 subrepo.writestate(repo, newsubstate)
3159
3162
3160 filestoamend = set(f for f in wctx.files() if matcher(f))
3163 filestoamend = set(f for f in wctx.files() if matcher(f))
3161
3164
3162 changes = (len(filestoamend) > 0)
3165 changes = (len(filestoamend) > 0)
3163 if changes:
3166 if changes:
3164 # Recompute copies (avoid recording a -> b -> a)
3167 # Recompute copies (avoid recording a -> b -> a)
3165 copied = copies.pathcopies(base, wctx, matcher)
3168 copied = copies.pathcopies(base, wctx, matcher)
3166 if old.p2:
3169 if old.p2:
3167 copied.update(copies.pathcopies(old.p2(), wctx, matcher))
3170 copied.update(copies.pathcopies(old.p2(), wctx, matcher))
3168
3171
3169 # Prune files which were reverted by the updates: if old
3172 # Prune files which were reverted by the updates: if old
3170 # introduced file X and the file was renamed in the working
3173 # introduced file X and the file was renamed in the working
3171 # copy, then those two files are the same and
3174 # copy, then those two files are the same and
3172 # we can discard X from our list of files. Likewise if X
3175 # we can discard X from our list of files. Likewise if X
3173 # was removed, it's no longer relevant. If X is missing (aka
3176 # was removed, it's no longer relevant. If X is missing (aka
3174 # deleted), old X must be preserved.
3177 # deleted), old X must be preserved.
3175 files.update(filestoamend)
3178 files.update(filestoamend)
3176 files = [f for f in files if (not samefile(f, wctx, base)
3179 files = [f for f in files if (not samefile(f, wctx, base)
3177 or f in wctx.deleted())]
3180 or f in wctx.deleted())]
3178
3181
3179 def filectxfn(repo, ctx_, path):
3182 def filectxfn(repo, ctx_, path):
3180 try:
3183 try:
3181 # If the file being considered is not amongst the files
3184 # If the file being considered is not amongst the files
3182 # to be amended, we should return the file context from the
3185 # to be amended, we should return the file context from the
3183 # old changeset. This avoids issues when only some files in
3186 # old changeset. This avoids issues when only some files in
3184 # the working copy are being amended but there are also
3187 # the working copy are being amended but there are also
3185 # changes to other files from the old changeset.
3188 # changes to other files from the old changeset.
3186 if path not in filestoamend:
3189 if path not in filestoamend:
3187 return old.filectx(path)
3190 return old.filectx(path)
3188
3191
3189 # Return None for removed files.
3192 # Return None for removed files.
3190 if path in wctx.removed():
3193 if path in wctx.removed():
3191 return None
3194 return None
3192
3195
3193 fctx = wctx[path]
3196 fctx = wctx[path]
3194 flags = fctx.flags()
3197 flags = fctx.flags()
3195 mctx = context.memfilectx(repo,
3198 mctx = context.memfilectx(repo,
3196 fctx.path(), fctx.data(),
3199 fctx.path(), fctx.data(),
3197 islink='l' in flags,
3200 islink='l' in flags,
3198 isexec='x' in flags,
3201 isexec='x' in flags,
3199 copied=copied.get(path))
3202 copied=copied.get(path))
3200 return mctx
3203 return mctx
3201 except KeyError:
3204 except KeyError:
3202 return None
3205 return None
3203 else:
3206 else:
3204 ui.note(_('copying changeset %s to %s\n') % (old, base))
3207 ui.note(_('copying changeset %s to %s\n') % (old, base))
3205
3208
3206 # Use version of files as in the old cset
3209 # Use version of files as in the old cset
3207 def filectxfn(repo, ctx_, path):
3210 def filectxfn(repo, ctx_, path):
3208 try:
3211 try:
3209 return old.filectx(path)
3212 return old.filectx(path)
3210 except KeyError:
3213 except KeyError:
3211 return None
3214 return None
3212
3215
3213 # See if we got a message from -m or -l, if not, open the editor with
3216 # See if we got a message from -m or -l, if not, open the editor with
3214 # the message of the changeset to amend.
3217 # the message of the changeset to amend.
3215 message = logmessage(ui, opts)
3218 message = logmessage(ui, opts)
3216
3219
3217 editform = mergeeditform(old, 'commit.amend')
3220 editform = mergeeditform(old, 'commit.amend')
3218 editor = getcommiteditor(editform=editform,
3221 editor = getcommiteditor(editform=editform,
3219 **pycompat.strkwargs(opts))
3222 **pycompat.strkwargs(opts))
3220
3223
3221 if not message:
3224 if not message:
3222 editor = getcommiteditor(edit=True, editform=editform)
3225 editor = getcommiteditor(edit=True, editform=editform)
3223 message = old.description()
3226 message = old.description()
3224
3227
3225 pureextra = extra.copy()
3228 pureextra = extra.copy()
3226 extra['amend_source'] = old.hex()
3229 extra['amend_source'] = old.hex()
3227
3230
3228 new = context.memctx(repo,
3231 new = context.memctx(repo,
3229 parents=[base.node(), old.p2().node()],
3232 parents=[base.node(), old.p2().node()],
3230 text=message,
3233 text=message,
3231 files=files,
3234 files=files,
3232 filectxfn=filectxfn,
3235 filectxfn=filectxfn,
3233 user=user,
3236 user=user,
3234 date=date,
3237 date=date,
3235 extra=extra,
3238 extra=extra,
3236 editor=editor)
3239 editor=editor)
3237
3240
3238 newdesc = changelog.stripdesc(new.description())
3241 newdesc = changelog.stripdesc(new.description())
3239 if ((not changes)
3242 if ((not changes)
3240 and newdesc == old.description()
3243 and newdesc == old.description()
3241 and user == old.user()
3244 and user == old.user()
3242 and date == old.date()
3245 and date == old.date()
3243 and pureextra == old.extra()):
3246 and pureextra == old.extra()):
3244 # nothing changed. continuing here would create a new node
3247 # nothing changed. continuing here would create a new node
3245 # anyway because of the amend_source noise.
3248 # anyway because of the amend_source noise.
3246 #
3249 #
3247 # This not what we expect from amend.
3250 # This not what we expect from amend.
3248 return old.node()
3251 return old.node()
3249
3252
3250 if opts.get('secret'):
3253 if opts.get('secret'):
3251 commitphase = 'secret'
3254 commitphase = 'secret'
3252 else:
3255 else:
3253 commitphase = old.phase()
3256 commitphase = old.phase()
3254 overrides = {('phases', 'new-commit'): commitphase}
3257 overrides = {('phases', 'new-commit'): commitphase}
3255 with ui.configoverride(overrides, 'amend'):
3258 with ui.configoverride(overrides, 'amend'):
3256 newid = repo.commitctx(new)
3259 newid = repo.commitctx(new)
3257
3260
3258 # Reroute the working copy parent to the new changeset
3261 # Reroute the working copy parent to the new changeset
3259 repo.setparents(newid, nullid)
3262 repo.setparents(newid, nullid)
3260 mapping = {old.node(): (newid,)}
3263 mapping = {old.node(): (newid,)}
3261 obsmetadata = None
3264 obsmetadata = None
3262 if opts.get('note'):
3265 if opts.get('note'):
3263 obsmetadata = {'note': opts['note']}
3266 obsmetadata = {'note': opts['note']}
3264 scmutil.cleanupnodes(repo, mapping, 'amend', metadata=obsmetadata)
3267 scmutil.cleanupnodes(repo, mapping, 'amend', metadata=obsmetadata)
3265
3268
3266 # Fixing the dirstate because localrepo.commitctx does not update
3269 # Fixing the dirstate because localrepo.commitctx does not update
3267 # it. This is rather convenient because we did not need to update
3270 # it. This is rather convenient because we did not need to update
3268 # the dirstate for all the files in the new commit which commitctx
3271 # the dirstate for all the files in the new commit which commitctx
3269 # could have done if it updated the dirstate. Now, we can
3272 # could have done if it updated the dirstate. Now, we can
3270 # selectively update the dirstate only for the amended files.
3273 # selectively update the dirstate only for the amended files.
3271 dirstate = repo.dirstate
3274 dirstate = repo.dirstate
3272
3275
3273 # Update the state of the files which were added and
3276 # Update the state of the files which were added and
3274 # and modified in the amend to "normal" in the dirstate.
3277 # and modified in the amend to "normal" in the dirstate.
3275 normalfiles = set(wctx.modified() + wctx.added()) & filestoamend
3278 normalfiles = set(wctx.modified() + wctx.added()) & filestoamend
3276 for f in normalfiles:
3279 for f in normalfiles:
3277 dirstate.normal(f)
3280 dirstate.normal(f)
3278
3281
3279 # Update the state of files which were removed in the amend
3282 # Update the state of files which were removed in the amend
3280 # to "removed" in the dirstate.
3283 # to "removed" in the dirstate.
3281 removedfiles = set(wctx.removed()) & filestoamend
3284 removedfiles = set(wctx.removed()) & filestoamend
3282 for f in removedfiles:
3285 for f in removedfiles:
3283 dirstate.drop(f)
3286 dirstate.drop(f)
3284
3287
3285 return newid
3288 return newid
3286
3289
3287 def commiteditor(repo, ctx, subs, editform=''):
3290 def commiteditor(repo, ctx, subs, editform=''):
3288 if ctx.description():
3291 if ctx.description():
3289 return ctx.description()
3292 return ctx.description()
3290 return commitforceeditor(repo, ctx, subs, editform=editform,
3293 return commitforceeditor(repo, ctx, subs, editform=editform,
3291 unchangedmessagedetection=True)
3294 unchangedmessagedetection=True)
3292
3295
3293 def commitforceeditor(repo, ctx, subs, finishdesc=None, extramsg=None,
3296 def commitforceeditor(repo, ctx, subs, finishdesc=None, extramsg=None,
3294 editform='', unchangedmessagedetection=False):
3297 editform='', unchangedmessagedetection=False):
3295 if not extramsg:
3298 if not extramsg:
3296 extramsg = _("Leave message empty to abort commit.")
3299 extramsg = _("Leave message empty to abort commit.")
3297
3300
3298 forms = [e for e in editform.split('.') if e]
3301 forms = [e for e in editform.split('.') if e]
3299 forms.insert(0, 'changeset')
3302 forms.insert(0, 'changeset')
3300 templatetext = None
3303 templatetext = None
3301 while forms:
3304 while forms:
3302 ref = '.'.join(forms)
3305 ref = '.'.join(forms)
3303 if repo.ui.config('committemplate', ref):
3306 if repo.ui.config('committemplate', ref):
3304 templatetext = committext = buildcommittemplate(
3307 templatetext = committext = buildcommittemplate(
3305 repo, ctx, subs, extramsg, ref)
3308 repo, ctx, subs, extramsg, ref)
3306 break
3309 break
3307 forms.pop()
3310 forms.pop()
3308 else:
3311 else:
3309 committext = buildcommittext(repo, ctx, subs, extramsg)
3312 committext = buildcommittext(repo, ctx, subs, extramsg)
3310
3313
3311 # run editor in the repository root
3314 # run editor in the repository root
3312 olddir = pycompat.getcwd()
3315 olddir = pycompat.getcwd()
3313 os.chdir(repo.root)
3316 os.chdir(repo.root)
3314
3317
3315 # make in-memory changes visible to external process
3318 # make in-memory changes visible to external process
3316 tr = repo.currenttransaction()
3319 tr = repo.currenttransaction()
3317 repo.dirstate.write(tr)
3320 repo.dirstate.write(tr)
3318 pending = tr and tr.writepending() and repo.root
3321 pending = tr and tr.writepending() and repo.root
3319
3322
3320 editortext = repo.ui.edit(committext, ctx.user(), ctx.extra(),
3323 editortext = repo.ui.edit(committext, ctx.user(), ctx.extra(),
3321 editform=editform, pending=pending,
3324 editform=editform, pending=pending,
3322 repopath=repo.path, action='commit')
3325 repopath=repo.path, action='commit')
3323 text = editortext
3326 text = editortext
3324
3327
3325 # strip away anything below this special string (used for editors that want
3328 # strip away anything below this special string (used for editors that want
3326 # to display the diff)
3329 # to display the diff)
3327 stripbelow = re.search(_linebelow, text, flags=re.MULTILINE)
3330 stripbelow = re.search(_linebelow, text, flags=re.MULTILINE)
3328 if stripbelow:
3331 if stripbelow:
3329 text = text[:stripbelow.start()]
3332 text = text[:stripbelow.start()]
3330
3333
3331 text = re.sub("(?m)^HG:.*(\n|$)", "", text)
3334 text = re.sub("(?m)^HG:.*(\n|$)", "", text)
3332 os.chdir(olddir)
3335 os.chdir(olddir)
3333
3336
3334 if finishdesc:
3337 if finishdesc:
3335 text = finishdesc(text)
3338 text = finishdesc(text)
3336 if not text.strip():
3339 if not text.strip():
3337 raise error.Abort(_("empty commit message"))
3340 raise error.Abort(_("empty commit message"))
3338 if unchangedmessagedetection and editortext == templatetext:
3341 if unchangedmessagedetection and editortext == templatetext:
3339 raise error.Abort(_("commit message unchanged"))
3342 raise error.Abort(_("commit message unchanged"))
3340
3343
3341 return text
3344 return text
3342
3345
3343 def buildcommittemplate(repo, ctx, subs, extramsg, ref):
3346 def buildcommittemplate(repo, ctx, subs, extramsg, ref):
3344 ui = repo.ui
3347 ui = repo.ui
3345 spec = formatter.templatespec(ref, None, None)
3348 spec = formatter.templatespec(ref, None, None)
3346 t = changeset_templater(ui, repo, spec, None, {}, False)
3349 t = changeset_templater(ui, repo, spec, None, {}, False)
3347 t.t.cache.update((k, templater.unquotestring(v))
3350 t.t.cache.update((k, templater.unquotestring(v))
3348 for k, v in repo.ui.configitems('committemplate'))
3351 for k, v in repo.ui.configitems('committemplate'))
3349
3352
3350 if not extramsg:
3353 if not extramsg:
3351 extramsg = '' # ensure that extramsg is string
3354 extramsg = '' # ensure that extramsg is string
3352
3355
3353 ui.pushbuffer()
3356 ui.pushbuffer()
3354 t.show(ctx, extramsg=extramsg)
3357 t.show(ctx, extramsg=extramsg)
3355 return ui.popbuffer()
3358 return ui.popbuffer()
3356
3359
3357 def hgprefix(msg):
3360 def hgprefix(msg):
3358 return "\n".join(["HG: %s" % a for a in msg.split("\n") if a])
3361 return "\n".join(["HG: %s" % a for a in msg.split("\n") if a])
3359
3362
3360 def buildcommittext(repo, ctx, subs, extramsg):
3363 def buildcommittext(repo, ctx, subs, extramsg):
3361 edittext = []
3364 edittext = []
3362 modified, added, removed = ctx.modified(), ctx.added(), ctx.removed()
3365 modified, added, removed = ctx.modified(), ctx.added(), ctx.removed()
3363 if ctx.description():
3366 if ctx.description():
3364 edittext.append(ctx.description())
3367 edittext.append(ctx.description())
3365 edittext.append("")
3368 edittext.append("")
3366 edittext.append("") # Empty line between message and comments.
3369 edittext.append("") # Empty line between message and comments.
3367 edittext.append(hgprefix(_("Enter commit message."
3370 edittext.append(hgprefix(_("Enter commit message."
3368 " Lines beginning with 'HG:' are removed.")))
3371 " Lines beginning with 'HG:' are removed.")))
3369 edittext.append(hgprefix(extramsg))
3372 edittext.append(hgprefix(extramsg))
3370 edittext.append("HG: --")
3373 edittext.append("HG: --")
3371 edittext.append(hgprefix(_("user: %s") % ctx.user()))
3374 edittext.append(hgprefix(_("user: %s") % ctx.user()))
3372 if ctx.p2():
3375 if ctx.p2():
3373 edittext.append(hgprefix(_("branch merge")))
3376 edittext.append(hgprefix(_("branch merge")))
3374 if ctx.branch():
3377 if ctx.branch():
3375 edittext.append(hgprefix(_("branch '%s'") % ctx.branch()))
3378 edittext.append(hgprefix(_("branch '%s'") % ctx.branch()))
3376 if bookmarks.isactivewdirparent(repo):
3379 if bookmarks.isactivewdirparent(repo):
3377 edittext.append(hgprefix(_("bookmark '%s'") % repo._activebookmark))
3380 edittext.append(hgprefix(_("bookmark '%s'") % repo._activebookmark))
3378 edittext.extend([hgprefix(_("subrepo %s") % s) for s in subs])
3381 edittext.extend([hgprefix(_("subrepo %s") % s) for s in subs])
3379 edittext.extend([hgprefix(_("added %s") % f) for f in added])
3382 edittext.extend([hgprefix(_("added %s") % f) for f in added])
3380 edittext.extend([hgprefix(_("changed %s") % f) for f in modified])
3383 edittext.extend([hgprefix(_("changed %s") % f) for f in modified])
3381 edittext.extend([hgprefix(_("removed %s") % f) for f in removed])
3384 edittext.extend([hgprefix(_("removed %s") % f) for f in removed])
3382 if not added and not modified and not removed:
3385 if not added and not modified and not removed:
3383 edittext.append(hgprefix(_("no files changed")))
3386 edittext.append(hgprefix(_("no files changed")))
3384 edittext.append("")
3387 edittext.append("")
3385
3388
3386 return "\n".join(edittext)
3389 return "\n".join(edittext)
3387
3390
3388 def commitstatus(repo, node, branch, bheads=None, opts=None):
3391 def commitstatus(repo, node, branch, bheads=None, opts=None):
3389 if opts is None:
3392 if opts is None:
3390 opts = {}
3393 opts = {}
3391 ctx = repo[node]
3394 ctx = repo[node]
3392 parents = ctx.parents()
3395 parents = ctx.parents()
3393
3396
3394 if (not opts.get('amend') and bheads and node not in bheads and not
3397 if (not opts.get('amend') and bheads and node not in bheads and not
3395 [x for x in parents if x.node() in bheads and x.branch() == branch]):
3398 [x for x in parents if x.node() in bheads and x.branch() == branch]):
3396 repo.ui.status(_('created new head\n'))
3399 repo.ui.status(_('created new head\n'))
3397 # The message is not printed for initial roots. For the other
3400 # The message is not printed for initial roots. For the other
3398 # changesets, it is printed in the following situations:
3401 # changesets, it is printed in the following situations:
3399 #
3402 #
3400 # Par column: for the 2 parents with ...
3403 # Par column: for the 2 parents with ...
3401 # N: null or no parent
3404 # N: null or no parent
3402 # B: parent is on another named branch
3405 # B: parent is on another named branch
3403 # C: parent is a regular non head changeset
3406 # C: parent is a regular non head changeset
3404 # H: parent was a branch head of the current branch
3407 # H: parent was a branch head of the current branch
3405 # Msg column: whether we print "created new head" message
3408 # Msg column: whether we print "created new head" message
3406 # In the following, it is assumed that there already exists some
3409 # In the following, it is assumed that there already exists some
3407 # initial branch heads of the current branch, otherwise nothing is
3410 # initial branch heads of the current branch, otherwise nothing is
3408 # printed anyway.
3411 # printed anyway.
3409 #
3412 #
3410 # Par Msg Comment
3413 # Par Msg Comment
3411 # N N y additional topo root
3414 # N N y additional topo root
3412 #
3415 #
3413 # B N y additional branch root
3416 # B N y additional branch root
3414 # C N y additional topo head
3417 # C N y additional topo head
3415 # H N n usual case
3418 # H N n usual case
3416 #
3419 #
3417 # B B y weird additional branch root
3420 # B B y weird additional branch root
3418 # C B y branch merge
3421 # C B y branch merge
3419 # H B n merge with named branch
3422 # H B n merge with named branch
3420 #
3423 #
3421 # C C y additional head from merge
3424 # C C y additional head from merge
3422 # C H n merge with a head
3425 # C H n merge with a head
3423 #
3426 #
3424 # H H n head merge: head count decreases
3427 # H H n head merge: head count decreases
3425
3428
3426 if not opts.get('close_branch'):
3429 if not opts.get('close_branch'):
3427 for r in parents:
3430 for r in parents:
3428 if r.closesbranch() and r.branch() == branch:
3431 if r.closesbranch() and r.branch() == branch:
3429 repo.ui.status(_('reopening closed branch head %d\n') % r)
3432 repo.ui.status(_('reopening closed branch head %d\n') % r)
3430
3433
3431 if repo.ui.debugflag:
3434 if repo.ui.debugflag:
3432 repo.ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
3435 repo.ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
3433 elif repo.ui.verbose:
3436 elif repo.ui.verbose:
3434 repo.ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
3437 repo.ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
3435
3438
3436 def postcommitstatus(repo, pats, opts):
3439 def postcommitstatus(repo, pats, opts):
3437 return repo.status(match=scmutil.match(repo[None], pats, opts))
3440 return repo.status(match=scmutil.match(repo[None], pats, opts))
3438
3441
3439 def revert(ui, repo, ctx, parents, *pats, **opts):
3442 def revert(ui, repo, ctx, parents, *pats, **opts):
3440 opts = pycompat.byteskwargs(opts)
3443 opts = pycompat.byteskwargs(opts)
3441 parent, p2 = parents
3444 parent, p2 = parents
3442 node = ctx.node()
3445 node = ctx.node()
3443
3446
3444 mf = ctx.manifest()
3447 mf = ctx.manifest()
3445 if node == p2:
3448 if node == p2:
3446 parent = p2
3449 parent = p2
3447
3450
3448 # need all matching names in dirstate and manifest of target rev,
3451 # need all matching names in dirstate and manifest of target rev,
3449 # so have to walk both. do not print errors if files exist in one
3452 # so have to walk both. do not print errors if files exist in one
3450 # but not other. in both cases, filesets should be evaluated against
3453 # but not other. in both cases, filesets should be evaluated against
3451 # workingctx to get consistent result (issue4497). this means 'set:**'
3454 # workingctx to get consistent result (issue4497). this means 'set:**'
3452 # cannot be used to select missing files from target rev.
3455 # cannot be used to select missing files from target rev.
3453
3456
3454 # `names` is a mapping for all elements in working copy and target revision
3457 # `names` is a mapping for all elements in working copy and target revision
3455 # The mapping is in the form:
3458 # The mapping is in the form:
3456 # <asb path in repo> -> (<path from CWD>, <exactly specified by matcher?>)
3459 # <asb path in repo> -> (<path from CWD>, <exactly specified by matcher?>)
3457 names = {}
3460 names = {}
3458
3461
3459 with repo.wlock():
3462 with repo.wlock():
3460 ## filling of the `names` mapping
3463 ## filling of the `names` mapping
3461 # walk dirstate to fill `names`
3464 # walk dirstate to fill `names`
3462
3465
3463 interactive = opts.get('interactive', False)
3466 interactive = opts.get('interactive', False)
3464 wctx = repo[None]
3467 wctx = repo[None]
3465 m = scmutil.match(wctx, pats, opts)
3468 m = scmutil.match(wctx, pats, opts)
3466
3469
3467 # we'll need this later
3470 # we'll need this later
3468 targetsubs = sorted(s for s in wctx.substate if m(s))
3471 targetsubs = sorted(s for s in wctx.substate if m(s))
3469
3472
3470 if not m.always():
3473 if not m.always():
3471 matcher = matchmod.badmatch(m, lambda x, y: False)
3474 matcher = matchmod.badmatch(m, lambda x, y: False)
3472 for abs in wctx.walk(matcher):
3475 for abs in wctx.walk(matcher):
3473 names[abs] = m.rel(abs), m.exact(abs)
3476 names[abs] = m.rel(abs), m.exact(abs)
3474
3477
3475 # walk target manifest to fill `names`
3478 # walk target manifest to fill `names`
3476
3479
3477 def badfn(path, msg):
3480 def badfn(path, msg):
3478 if path in names:
3481 if path in names:
3479 return
3482 return
3480 if path in ctx.substate:
3483 if path in ctx.substate:
3481 return
3484 return
3482 path_ = path + '/'
3485 path_ = path + '/'
3483 for f in names:
3486 for f in names:
3484 if f.startswith(path_):
3487 if f.startswith(path_):
3485 return
3488 return
3486 ui.warn("%s: %s\n" % (m.rel(path), msg))
3489 ui.warn("%s: %s\n" % (m.rel(path), msg))
3487
3490
3488 for abs in ctx.walk(matchmod.badmatch(m, badfn)):
3491 for abs in ctx.walk(matchmod.badmatch(m, badfn)):
3489 if abs not in names:
3492 if abs not in names:
3490 names[abs] = m.rel(abs), m.exact(abs)
3493 names[abs] = m.rel(abs), m.exact(abs)
3491
3494
3492 # Find status of all file in `names`.
3495 # Find status of all file in `names`.
3493 m = scmutil.matchfiles(repo, names)
3496 m = scmutil.matchfiles(repo, names)
3494
3497
3495 changes = repo.status(node1=node, match=m,
3498 changes = repo.status(node1=node, match=m,
3496 unknown=True, ignored=True, clean=True)
3499 unknown=True, ignored=True, clean=True)
3497 else:
3500 else:
3498 changes = repo.status(node1=node, match=m)
3501 changes = repo.status(node1=node, match=m)
3499 for kind in changes:
3502 for kind in changes:
3500 for abs in kind:
3503 for abs in kind:
3501 names[abs] = m.rel(abs), m.exact(abs)
3504 names[abs] = m.rel(abs), m.exact(abs)
3502
3505
3503 m = scmutil.matchfiles(repo, names)
3506 m = scmutil.matchfiles(repo, names)
3504
3507
3505 modified = set(changes.modified)
3508 modified = set(changes.modified)
3506 added = set(changes.added)
3509 added = set(changes.added)
3507 removed = set(changes.removed)
3510 removed = set(changes.removed)
3508 _deleted = set(changes.deleted)
3511 _deleted = set(changes.deleted)
3509 unknown = set(changes.unknown)
3512 unknown = set(changes.unknown)
3510 unknown.update(changes.ignored)
3513 unknown.update(changes.ignored)
3511 clean = set(changes.clean)
3514 clean = set(changes.clean)
3512 modadded = set()
3515 modadded = set()
3513
3516
3514 # We need to account for the state of the file in the dirstate,
3517 # We need to account for the state of the file in the dirstate,
3515 # even when we revert against something else than parent. This will
3518 # even when we revert against something else than parent. This will
3516 # slightly alter the behavior of revert (doing back up or not, delete
3519 # slightly alter the behavior of revert (doing back up or not, delete
3517 # or just forget etc).
3520 # or just forget etc).
3518 if parent == node:
3521 if parent == node:
3519 dsmodified = modified
3522 dsmodified = modified
3520 dsadded = added
3523 dsadded = added
3521 dsremoved = removed
3524 dsremoved = removed
3522 # store all local modifications, useful later for rename detection
3525 # store all local modifications, useful later for rename detection
3523 localchanges = dsmodified | dsadded
3526 localchanges = dsmodified | dsadded
3524 modified, added, removed = set(), set(), set()
3527 modified, added, removed = set(), set(), set()
3525 else:
3528 else:
3526 changes = repo.status(node1=parent, match=m)
3529 changes = repo.status(node1=parent, match=m)
3527 dsmodified = set(changes.modified)
3530 dsmodified = set(changes.modified)
3528 dsadded = set(changes.added)
3531 dsadded = set(changes.added)
3529 dsremoved = set(changes.removed)
3532 dsremoved = set(changes.removed)
3530 # store all local modifications, useful later for rename detection
3533 # store all local modifications, useful later for rename detection
3531 localchanges = dsmodified | dsadded
3534 localchanges = dsmodified | dsadded
3532
3535
3533 # only take into account for removes between wc and target
3536 # only take into account for removes between wc and target
3534 clean |= dsremoved - removed
3537 clean |= dsremoved - removed
3535 dsremoved &= removed
3538 dsremoved &= removed
3536 # distinct between dirstate remove and other
3539 # distinct between dirstate remove and other
3537 removed -= dsremoved
3540 removed -= dsremoved
3538
3541
3539 modadded = added & dsmodified
3542 modadded = added & dsmodified
3540 added -= modadded
3543 added -= modadded
3541
3544
3542 # tell newly modified apart.
3545 # tell newly modified apart.
3543 dsmodified &= modified
3546 dsmodified &= modified
3544 dsmodified |= modified & dsadded # dirstate added may need backup
3547 dsmodified |= modified & dsadded # dirstate added may need backup
3545 modified -= dsmodified
3548 modified -= dsmodified
3546
3549
3547 # We need to wait for some post-processing to update this set
3550 # We need to wait for some post-processing to update this set
3548 # before making the distinction. The dirstate will be used for
3551 # before making the distinction. The dirstate will be used for
3549 # that purpose.
3552 # that purpose.
3550 dsadded = added
3553 dsadded = added
3551
3554
3552 # in case of merge, files that are actually added can be reported as
3555 # in case of merge, files that are actually added can be reported as
3553 # modified, we need to post process the result
3556 # modified, we need to post process the result
3554 if p2 != nullid:
3557 if p2 != nullid:
3555 mergeadd = set(dsmodified)
3558 mergeadd = set(dsmodified)
3556 for path in dsmodified:
3559 for path in dsmodified:
3557 if path in mf:
3560 if path in mf:
3558 mergeadd.remove(path)
3561 mergeadd.remove(path)
3559 dsadded |= mergeadd
3562 dsadded |= mergeadd
3560 dsmodified -= mergeadd
3563 dsmodified -= mergeadd
3561
3564
3562 # if f is a rename, update `names` to also revert the source
3565 # if f is a rename, update `names` to also revert the source
3563 cwd = repo.getcwd()
3566 cwd = repo.getcwd()
3564 for f in localchanges:
3567 for f in localchanges:
3565 src = repo.dirstate.copied(f)
3568 src = repo.dirstate.copied(f)
3566 # XXX should we check for rename down to target node?
3569 # XXX should we check for rename down to target node?
3567 if src and src not in names and repo.dirstate[src] == 'r':
3570 if src and src not in names and repo.dirstate[src] == 'r':
3568 dsremoved.add(src)
3571 dsremoved.add(src)
3569 names[src] = (repo.pathto(src, cwd), True)
3572 names[src] = (repo.pathto(src, cwd), True)
3570
3573
3571 # determine the exact nature of the deleted changesets
3574 # determine the exact nature of the deleted changesets
3572 deladded = set(_deleted)
3575 deladded = set(_deleted)
3573 for path in _deleted:
3576 for path in _deleted:
3574 if path in mf:
3577 if path in mf:
3575 deladded.remove(path)
3578 deladded.remove(path)
3576 deleted = _deleted - deladded
3579 deleted = _deleted - deladded
3577
3580
3578 # distinguish between file to forget and the other
3581 # distinguish between file to forget and the other
3579 added = set()
3582 added = set()
3580 for abs in dsadded:
3583 for abs in dsadded:
3581 if repo.dirstate[abs] != 'a':
3584 if repo.dirstate[abs] != 'a':
3582 added.add(abs)
3585 added.add(abs)
3583 dsadded -= added
3586 dsadded -= added
3584
3587
3585 for abs in deladded:
3588 for abs in deladded:
3586 if repo.dirstate[abs] == 'a':
3589 if repo.dirstate[abs] == 'a':
3587 dsadded.add(abs)
3590 dsadded.add(abs)
3588 deladded -= dsadded
3591 deladded -= dsadded
3589
3592
3590 # For files marked as removed, we check if an unknown file is present at
3593 # For files marked as removed, we check if an unknown file is present at
3591 # the same path. If a such file exists it may need to be backed up.
3594 # the same path. If a such file exists it may need to be backed up.
3592 # Making the distinction at this stage helps have simpler backup
3595 # Making the distinction at this stage helps have simpler backup
3593 # logic.
3596 # logic.
3594 removunk = set()
3597 removunk = set()
3595 for abs in removed:
3598 for abs in removed:
3596 target = repo.wjoin(abs)
3599 target = repo.wjoin(abs)
3597 if os.path.lexists(target):
3600 if os.path.lexists(target):
3598 removunk.add(abs)
3601 removunk.add(abs)
3599 removed -= removunk
3602 removed -= removunk
3600
3603
3601 dsremovunk = set()
3604 dsremovunk = set()
3602 for abs in dsremoved:
3605 for abs in dsremoved:
3603 target = repo.wjoin(abs)
3606 target = repo.wjoin(abs)
3604 if os.path.lexists(target):
3607 if os.path.lexists(target):
3605 dsremovunk.add(abs)
3608 dsremovunk.add(abs)
3606 dsremoved -= dsremovunk
3609 dsremoved -= dsremovunk
3607
3610
3608 # action to be actually performed by revert
3611 # action to be actually performed by revert
3609 # (<list of file>, message>) tuple
3612 # (<list of file>, message>) tuple
3610 actions = {'revert': ([], _('reverting %s\n')),
3613 actions = {'revert': ([], _('reverting %s\n')),
3611 'add': ([], _('adding %s\n')),
3614 'add': ([], _('adding %s\n')),
3612 'remove': ([], _('removing %s\n')),
3615 'remove': ([], _('removing %s\n')),
3613 'drop': ([], _('removing %s\n')),
3616 'drop': ([], _('removing %s\n')),
3614 'forget': ([], _('forgetting %s\n')),
3617 'forget': ([], _('forgetting %s\n')),
3615 'undelete': ([], _('undeleting %s\n')),
3618 'undelete': ([], _('undeleting %s\n')),
3616 'noop': (None, _('no changes needed to %s\n')),
3619 'noop': (None, _('no changes needed to %s\n')),
3617 'unknown': (None, _('file not managed: %s\n')),
3620 'unknown': (None, _('file not managed: %s\n')),
3618 }
3621 }
3619
3622
3620 # "constant" that convey the backup strategy.
3623 # "constant" that convey the backup strategy.
3621 # All set to `discard` if `no-backup` is set do avoid checking
3624 # All set to `discard` if `no-backup` is set do avoid checking
3622 # no_backup lower in the code.
3625 # no_backup lower in the code.
3623 # These values are ordered for comparison purposes
3626 # These values are ordered for comparison purposes
3624 backupinteractive = 3 # do backup if interactively modified
3627 backupinteractive = 3 # do backup if interactively modified
3625 backup = 2 # unconditionally do backup
3628 backup = 2 # unconditionally do backup
3626 check = 1 # check if the existing file differs from target
3629 check = 1 # check if the existing file differs from target
3627 discard = 0 # never do backup
3630 discard = 0 # never do backup
3628 if opts.get('no_backup'):
3631 if opts.get('no_backup'):
3629 backupinteractive = backup = check = discard
3632 backupinteractive = backup = check = discard
3630 if interactive:
3633 if interactive:
3631 dsmodifiedbackup = backupinteractive
3634 dsmodifiedbackup = backupinteractive
3632 else:
3635 else:
3633 dsmodifiedbackup = backup
3636 dsmodifiedbackup = backup
3634 tobackup = set()
3637 tobackup = set()
3635
3638
3636 backupanddel = actions['remove']
3639 backupanddel = actions['remove']
3637 if not opts.get('no_backup'):
3640 if not opts.get('no_backup'):
3638 backupanddel = actions['drop']
3641 backupanddel = actions['drop']
3639
3642
3640 disptable = (
3643 disptable = (
3641 # dispatch table:
3644 # dispatch table:
3642 # file state
3645 # file state
3643 # action
3646 # action
3644 # make backup
3647 # make backup
3645
3648
3646 ## Sets that results that will change file on disk
3649 ## Sets that results that will change file on disk
3647 # Modified compared to target, no local change
3650 # Modified compared to target, no local change
3648 (modified, actions['revert'], discard),
3651 (modified, actions['revert'], discard),
3649 # Modified compared to target, but local file is deleted
3652 # Modified compared to target, but local file is deleted
3650 (deleted, actions['revert'], discard),
3653 (deleted, actions['revert'], discard),
3651 # Modified compared to target, local change
3654 # Modified compared to target, local change
3652 (dsmodified, actions['revert'], dsmodifiedbackup),
3655 (dsmodified, actions['revert'], dsmodifiedbackup),
3653 # Added since target
3656 # Added since target
3654 (added, actions['remove'], discard),
3657 (added, actions['remove'], discard),
3655 # Added in working directory
3658 # Added in working directory
3656 (dsadded, actions['forget'], discard),
3659 (dsadded, actions['forget'], discard),
3657 # Added since target, have local modification
3660 # Added since target, have local modification
3658 (modadded, backupanddel, backup),
3661 (modadded, backupanddel, backup),
3659 # Added since target but file is missing in working directory
3662 # Added since target but file is missing in working directory
3660 (deladded, actions['drop'], discard),
3663 (deladded, actions['drop'], discard),
3661 # Removed since target, before working copy parent
3664 # Removed since target, before working copy parent
3662 (removed, actions['add'], discard),
3665 (removed, actions['add'], discard),
3663 # Same as `removed` but an unknown file exists at the same path
3666 # Same as `removed` but an unknown file exists at the same path
3664 (removunk, actions['add'], check),
3667 (removunk, actions['add'], check),
3665 # Removed since targe, marked as such in working copy parent
3668 # Removed since targe, marked as such in working copy parent
3666 (dsremoved, actions['undelete'], discard),
3669 (dsremoved, actions['undelete'], discard),
3667 # Same as `dsremoved` but an unknown file exists at the same path
3670 # Same as `dsremoved` but an unknown file exists at the same path
3668 (dsremovunk, actions['undelete'], check),
3671 (dsremovunk, actions['undelete'], check),
3669 ## the following sets does not result in any file changes
3672 ## the following sets does not result in any file changes
3670 # File with no modification
3673 # File with no modification
3671 (clean, actions['noop'], discard),
3674 (clean, actions['noop'], discard),
3672 # Existing file, not tracked anywhere
3675 # Existing file, not tracked anywhere
3673 (unknown, actions['unknown'], discard),
3676 (unknown, actions['unknown'], discard),
3674 )
3677 )
3675
3678
3676 for abs, (rel, exact) in sorted(names.items()):
3679 for abs, (rel, exact) in sorted(names.items()):
3677 # target file to be touch on disk (relative to cwd)
3680 # target file to be touch on disk (relative to cwd)
3678 target = repo.wjoin(abs)
3681 target = repo.wjoin(abs)
3679 # search the entry in the dispatch table.
3682 # search the entry in the dispatch table.
3680 # if the file is in any of these sets, it was touched in the working
3683 # if the file is in any of these sets, it was touched in the working
3681 # directory parent and we are sure it needs to be reverted.
3684 # directory parent and we are sure it needs to be reverted.
3682 for table, (xlist, msg), dobackup in disptable:
3685 for table, (xlist, msg), dobackup in disptable:
3683 if abs not in table:
3686 if abs not in table:
3684 continue
3687 continue
3685 if xlist is not None:
3688 if xlist is not None:
3686 xlist.append(abs)
3689 xlist.append(abs)
3687 if dobackup:
3690 if dobackup:
3688 # If in interactive mode, don't automatically create
3691 # If in interactive mode, don't automatically create
3689 # .orig files (issue4793)
3692 # .orig files (issue4793)
3690 if dobackup == backupinteractive:
3693 if dobackup == backupinteractive:
3691 tobackup.add(abs)
3694 tobackup.add(abs)
3692 elif (backup <= dobackup or wctx[abs].cmp(ctx[abs])):
3695 elif (backup <= dobackup or wctx[abs].cmp(ctx[abs])):
3693 bakname = scmutil.origpath(ui, repo, rel)
3696 bakname = scmutil.origpath(ui, repo, rel)
3694 ui.note(_('saving current version of %s as %s\n') %
3697 ui.note(_('saving current version of %s as %s\n') %
3695 (rel, bakname))
3698 (rel, bakname))
3696 if not opts.get('dry_run'):
3699 if not opts.get('dry_run'):
3697 if interactive:
3700 if interactive:
3698 util.copyfile(target, bakname)
3701 util.copyfile(target, bakname)
3699 else:
3702 else:
3700 util.rename(target, bakname)
3703 util.rename(target, bakname)
3701 if ui.verbose or not exact:
3704 if ui.verbose or not exact:
3702 if not isinstance(msg, bytes):
3705 if not isinstance(msg, bytes):
3703 msg = msg(abs)
3706 msg = msg(abs)
3704 ui.status(msg % rel)
3707 ui.status(msg % rel)
3705 elif exact:
3708 elif exact:
3706 ui.warn(msg % rel)
3709 ui.warn(msg % rel)
3707 break
3710 break
3708
3711
3709 if not opts.get('dry_run'):
3712 if not opts.get('dry_run'):
3710 needdata = ('revert', 'add', 'undelete')
3713 needdata = ('revert', 'add', 'undelete')
3711 _revertprefetch(repo, ctx, *[actions[name][0] for name in needdata])
3714 _revertprefetch(repo, ctx, *[actions[name][0] for name in needdata])
3712 _performrevert(repo, parents, ctx, actions, interactive, tobackup)
3715 _performrevert(repo, parents, ctx, actions, interactive, tobackup)
3713
3716
3714 if targetsubs:
3717 if targetsubs:
3715 # Revert the subrepos on the revert list
3718 # Revert the subrepos on the revert list
3716 for sub in targetsubs:
3719 for sub in targetsubs:
3717 try:
3720 try:
3718 wctx.sub(sub).revert(ctx.substate[sub], *pats,
3721 wctx.sub(sub).revert(ctx.substate[sub], *pats,
3719 **pycompat.strkwargs(opts))
3722 **pycompat.strkwargs(opts))
3720 except KeyError:
3723 except KeyError:
3721 raise error.Abort("subrepository '%s' does not exist in %s!"
3724 raise error.Abort("subrepository '%s' does not exist in %s!"
3722 % (sub, short(ctx.node())))
3725 % (sub, short(ctx.node())))
3723
3726
3724 def _revertprefetch(repo, ctx, *files):
3727 def _revertprefetch(repo, ctx, *files):
3725 """Let extension changing the storage layer prefetch content"""
3728 """Let extension changing the storage layer prefetch content"""
3726
3729
3727 def _performrevert(repo, parents, ctx, actions, interactive=False,
3730 def _performrevert(repo, parents, ctx, actions, interactive=False,
3728 tobackup=None):
3731 tobackup=None):
3729 """function that actually perform all the actions computed for revert
3732 """function that actually perform all the actions computed for revert
3730
3733
3731 This is an independent function to let extension to plug in and react to
3734 This is an independent function to let extension to plug in and react to
3732 the imminent revert.
3735 the imminent revert.
3733
3736
3734 Make sure you have the working directory locked when calling this function.
3737 Make sure you have the working directory locked when calling this function.
3735 """
3738 """
3736 parent, p2 = parents
3739 parent, p2 = parents
3737 node = ctx.node()
3740 node = ctx.node()
3738 excluded_files = []
3741 excluded_files = []
3739 matcher_opts = {"exclude": excluded_files}
3742 matcher_opts = {"exclude": excluded_files}
3740
3743
3741 def checkout(f):
3744 def checkout(f):
3742 fc = ctx[f]
3745 fc = ctx[f]
3743 repo.wwrite(f, fc.data(), fc.flags())
3746 repo.wwrite(f, fc.data(), fc.flags())
3744
3747
3745 def doremove(f):
3748 def doremove(f):
3746 try:
3749 try:
3747 repo.wvfs.unlinkpath(f)
3750 repo.wvfs.unlinkpath(f)
3748 except OSError:
3751 except OSError:
3749 pass
3752 pass
3750 repo.dirstate.remove(f)
3753 repo.dirstate.remove(f)
3751
3754
3752 audit_path = pathutil.pathauditor(repo.root, cached=True)
3755 audit_path = pathutil.pathauditor(repo.root, cached=True)
3753 for f in actions['forget'][0]:
3756 for f in actions['forget'][0]:
3754 if interactive:
3757 if interactive:
3755 choice = repo.ui.promptchoice(
3758 choice = repo.ui.promptchoice(
3756 _("forget added file %s (Yn)?$$ &Yes $$ &No") % f)
3759 _("forget added file %s (Yn)?$$ &Yes $$ &No") % f)
3757 if choice == 0:
3760 if choice == 0:
3758 repo.dirstate.drop(f)
3761 repo.dirstate.drop(f)
3759 else:
3762 else:
3760 excluded_files.append(repo.wjoin(f))
3763 excluded_files.append(repo.wjoin(f))
3761 else:
3764 else:
3762 repo.dirstate.drop(f)
3765 repo.dirstate.drop(f)
3763 for f in actions['remove'][0]:
3766 for f in actions['remove'][0]:
3764 audit_path(f)
3767 audit_path(f)
3765 if interactive:
3768 if interactive:
3766 choice = repo.ui.promptchoice(
3769 choice = repo.ui.promptchoice(
3767 _("remove added file %s (Yn)?$$ &Yes $$ &No") % f)
3770 _("remove added file %s (Yn)?$$ &Yes $$ &No") % f)
3768 if choice == 0:
3771 if choice == 0:
3769 doremove(f)
3772 doremove(f)
3770 else:
3773 else:
3771 excluded_files.append(repo.wjoin(f))
3774 excluded_files.append(repo.wjoin(f))
3772 else:
3775 else:
3773 doremove(f)
3776 doremove(f)
3774 for f in actions['drop'][0]:
3777 for f in actions['drop'][0]:
3775 audit_path(f)
3778 audit_path(f)
3776 repo.dirstate.remove(f)
3779 repo.dirstate.remove(f)
3777
3780
3778 normal = None
3781 normal = None
3779 if node == parent:
3782 if node == parent:
3780 # We're reverting to our parent. If possible, we'd like status
3783 # We're reverting to our parent. If possible, we'd like status
3781 # to report the file as clean. We have to use normallookup for
3784 # to report the file as clean. We have to use normallookup for
3782 # merges to avoid losing information about merged/dirty files.
3785 # merges to avoid losing information about merged/dirty files.
3783 if p2 != nullid:
3786 if p2 != nullid:
3784 normal = repo.dirstate.normallookup
3787 normal = repo.dirstate.normallookup
3785 else:
3788 else:
3786 normal = repo.dirstate.normal
3789 normal = repo.dirstate.normal
3787
3790
3788 newlyaddedandmodifiedfiles = set()
3791 newlyaddedandmodifiedfiles = set()
3789 if interactive:
3792 if interactive:
3790 # Prompt the user for changes to revert
3793 # Prompt the user for changes to revert
3791 torevert = [repo.wjoin(f) for f in actions['revert'][0]]
3794 torevert = [repo.wjoin(f) for f in actions['revert'][0]]
3792 m = scmutil.match(ctx, torevert, matcher_opts)
3795 m = scmutil.match(ctx, torevert, matcher_opts)
3793 diffopts = patch.difffeatureopts(repo.ui, whitespace=True)
3796 diffopts = patch.difffeatureopts(repo.ui, whitespace=True)
3794 diffopts.nodates = True
3797 diffopts.nodates = True
3795 diffopts.git = True
3798 diffopts.git = True
3796 operation = 'discard'
3799 operation = 'discard'
3797 reversehunks = True
3800 reversehunks = True
3798 if node != parent:
3801 if node != parent:
3799 operation = 'apply'
3802 operation = 'apply'
3800 reversehunks = False
3803 reversehunks = False
3801 if reversehunks:
3804 if reversehunks:
3802 diff = patch.diff(repo, ctx.node(), None, m, opts=diffopts)
3805 diff = patch.diff(repo, ctx.node(), None, m, opts=diffopts)
3803 else:
3806 else:
3804 diff = patch.diff(repo, None, ctx.node(), m, opts=diffopts)
3807 diff = patch.diff(repo, None, ctx.node(), m, opts=diffopts)
3805 originalchunks = patch.parsepatch(diff)
3808 originalchunks = patch.parsepatch(diff)
3806
3809
3807 try:
3810 try:
3808
3811
3809 chunks, opts = recordfilter(repo.ui, originalchunks,
3812 chunks, opts = recordfilter(repo.ui, originalchunks,
3810 operation=operation)
3813 operation=operation)
3811 if reversehunks:
3814 if reversehunks:
3812 chunks = patch.reversehunks(chunks)
3815 chunks = patch.reversehunks(chunks)
3813
3816
3814 except error.PatchError as err:
3817 except error.PatchError as err:
3815 raise error.Abort(_('error parsing patch: %s') % err)
3818 raise error.Abort(_('error parsing patch: %s') % err)
3816
3819
3817 newlyaddedandmodifiedfiles = newandmodified(chunks, originalchunks)
3820 newlyaddedandmodifiedfiles = newandmodified(chunks, originalchunks)
3818 if tobackup is None:
3821 if tobackup is None:
3819 tobackup = set()
3822 tobackup = set()
3820 # Apply changes
3823 # Apply changes
3821 fp = stringio()
3824 fp = stringio()
3822 for c in chunks:
3825 for c in chunks:
3823 # Create a backup file only if this hunk should be backed up
3826 # Create a backup file only if this hunk should be backed up
3824 if ishunk(c) and c.header.filename() in tobackup:
3827 if ishunk(c) and c.header.filename() in tobackup:
3825 abs = c.header.filename()
3828 abs = c.header.filename()
3826 target = repo.wjoin(abs)
3829 target = repo.wjoin(abs)
3827 bakname = scmutil.origpath(repo.ui, repo, m.rel(abs))
3830 bakname = scmutil.origpath(repo.ui, repo, m.rel(abs))
3828 util.copyfile(target, bakname)
3831 util.copyfile(target, bakname)
3829 tobackup.remove(abs)
3832 tobackup.remove(abs)
3830 c.write(fp)
3833 c.write(fp)
3831 dopatch = fp.tell()
3834 dopatch = fp.tell()
3832 fp.seek(0)
3835 fp.seek(0)
3833 if dopatch:
3836 if dopatch:
3834 try:
3837 try:
3835 patch.internalpatch(repo.ui, repo, fp, 1, eolmode=None)
3838 patch.internalpatch(repo.ui, repo, fp, 1, eolmode=None)
3836 except error.PatchError as err:
3839 except error.PatchError as err:
3837 raise error.Abort(str(err))
3840 raise error.Abort(str(err))
3838 del fp
3841 del fp
3839 else:
3842 else:
3840 for f in actions['revert'][0]:
3843 for f in actions['revert'][0]:
3841 checkout(f)
3844 checkout(f)
3842 if normal:
3845 if normal:
3843 normal(f)
3846 normal(f)
3844
3847
3845 for f in actions['add'][0]:
3848 for f in actions['add'][0]:
3846 # Don't checkout modified files, they are already created by the diff
3849 # Don't checkout modified files, they are already created by the diff
3847 if f not in newlyaddedandmodifiedfiles:
3850 if f not in newlyaddedandmodifiedfiles:
3848 checkout(f)
3851 checkout(f)
3849 repo.dirstate.add(f)
3852 repo.dirstate.add(f)
3850
3853
3851 normal = repo.dirstate.normallookup
3854 normal = repo.dirstate.normallookup
3852 if node == parent and p2 == nullid:
3855 if node == parent and p2 == nullid:
3853 normal = repo.dirstate.normal
3856 normal = repo.dirstate.normal
3854 for f in actions['undelete'][0]:
3857 for f in actions['undelete'][0]:
3855 checkout(f)
3858 checkout(f)
3856 normal(f)
3859 normal(f)
3857
3860
3858 copied = copies.pathcopies(repo[parent], ctx)
3861 copied = copies.pathcopies(repo[parent], ctx)
3859
3862
3860 for f in actions['add'][0] + actions['undelete'][0] + actions['revert'][0]:
3863 for f in actions['add'][0] + actions['undelete'][0] + actions['revert'][0]:
3861 if f in copied:
3864 if f in copied:
3862 repo.dirstate.copy(copied[f], f)
3865 repo.dirstate.copy(copied[f], f)
3863
3866
3864 class command(registrar.command):
3867 class command(registrar.command):
3865 """deprecated: used registrar.command instead"""
3868 """deprecated: used registrar.command instead"""
3866 def _doregister(self, func, name, *args, **kwargs):
3869 def _doregister(self, func, name, *args, **kwargs):
3867 func._deprecatedregistrar = True # flag for deprecwarn in extensions.py
3870 func._deprecatedregistrar = True # flag for deprecwarn in extensions.py
3868 return super(command, self)._doregister(func, name, *args, **kwargs)
3871 return super(command, self)._doregister(func, name, *args, **kwargs)
3869
3872
3870 # a list of (ui, repo, otherpeer, opts, missing) functions called by
3873 # a list of (ui, repo, otherpeer, opts, missing) functions called by
3871 # commands.outgoing. "missing" is "missing" of the result of
3874 # commands.outgoing. "missing" is "missing" of the result of
3872 # "findcommonoutgoing()"
3875 # "findcommonoutgoing()"
3873 outgoinghooks = util.hooks()
3876 outgoinghooks = util.hooks()
3874
3877
3875 # a list of (ui, repo) functions called by commands.summary
3878 # a list of (ui, repo) functions called by commands.summary
3876 summaryhooks = util.hooks()
3879 summaryhooks = util.hooks()
3877
3880
3878 # a list of (ui, repo, opts, changes) functions called by commands.summary.
3881 # a list of (ui, repo, opts, changes) functions called by commands.summary.
3879 #
3882 #
3880 # functions should return tuple of booleans below, if 'changes' is None:
3883 # functions should return tuple of booleans below, if 'changes' is None:
3881 # (whether-incomings-are-needed, whether-outgoings-are-needed)
3884 # (whether-incomings-are-needed, whether-outgoings-are-needed)
3882 #
3885 #
3883 # otherwise, 'changes' is a tuple of tuples below:
3886 # otherwise, 'changes' is a tuple of tuples below:
3884 # - (sourceurl, sourcebranch, sourcepeer, incoming)
3887 # - (sourceurl, sourcebranch, sourcepeer, incoming)
3885 # - (desturl, destbranch, destpeer, outgoing)
3888 # - (desturl, destbranch, destpeer, outgoing)
3886 summaryremotehooks = util.hooks()
3889 summaryremotehooks = util.hooks()
3887
3890
3888 # A list of state files kept by multistep operations like graft.
3891 # A list of state files kept by multistep operations like graft.
3889 # Since graft cannot be aborted, it is considered 'clearable' by update.
3892 # Since graft cannot be aborted, it is considered 'clearable' by update.
3890 # note: bisect is intentionally excluded
3893 # note: bisect is intentionally excluded
3891 # (state file, clearable, allowcommit, error, hint)
3894 # (state file, clearable, allowcommit, error, hint)
3892 unfinishedstates = [
3895 unfinishedstates = [
3893 ('graftstate', True, False, _('graft in progress'),
3896 ('graftstate', True, False, _('graft in progress'),
3894 _("use 'hg graft --continue' or 'hg update' to abort")),
3897 _("use 'hg graft --continue' or 'hg update' to abort")),
3895 ('updatestate', True, False, _('last update was interrupted'),
3898 ('updatestate', True, False, _('last update was interrupted'),
3896 _("use 'hg update' to get a consistent checkout"))
3899 _("use 'hg update' to get a consistent checkout"))
3897 ]
3900 ]
3898
3901
3899 def checkunfinished(repo, commit=False):
3902 def checkunfinished(repo, commit=False):
3900 '''Look for an unfinished multistep operation, like graft, and abort
3903 '''Look for an unfinished multistep operation, like graft, and abort
3901 if found. It's probably good to check this right before
3904 if found. It's probably good to check this right before
3902 bailifchanged().
3905 bailifchanged().
3903 '''
3906 '''
3904 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3907 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3905 if commit and allowcommit:
3908 if commit and allowcommit:
3906 continue
3909 continue
3907 if repo.vfs.exists(f):
3910 if repo.vfs.exists(f):
3908 raise error.Abort(msg, hint=hint)
3911 raise error.Abort(msg, hint=hint)
3909
3912
3910 def clearunfinished(repo):
3913 def clearunfinished(repo):
3911 '''Check for unfinished operations (as above), and clear the ones
3914 '''Check for unfinished operations (as above), and clear the ones
3912 that are clearable.
3915 that are clearable.
3913 '''
3916 '''
3914 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3917 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3915 if not clearable and repo.vfs.exists(f):
3918 if not clearable and repo.vfs.exists(f):
3916 raise error.Abort(msg, hint=hint)
3919 raise error.Abort(msg, hint=hint)
3917 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3920 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3918 if clearable and repo.vfs.exists(f):
3921 if clearable and repo.vfs.exists(f):
3919 util.unlink(repo.vfs.join(f))
3922 util.unlink(repo.vfs.join(f))
3920
3923
3921 afterresolvedstates = [
3924 afterresolvedstates = [
3922 ('graftstate',
3925 ('graftstate',
3923 _('hg graft --continue')),
3926 _('hg graft --continue')),
3924 ]
3927 ]
3925
3928
3926 def howtocontinue(repo):
3929 def howtocontinue(repo):
3927 '''Check for an unfinished operation and return the command to finish
3930 '''Check for an unfinished operation and return the command to finish
3928 it.
3931 it.
3929
3932
3930 afterresolvedstates tuples define a .hg/{file} and the corresponding
3933 afterresolvedstates tuples define a .hg/{file} and the corresponding
3931 command needed to finish it.
3934 command needed to finish it.
3932
3935
3933 Returns a (msg, warning) tuple. 'msg' is a string and 'warning' is
3936 Returns a (msg, warning) tuple. 'msg' is a string and 'warning' is
3934 a boolean.
3937 a boolean.
3935 '''
3938 '''
3936 contmsg = _("continue: %s")
3939 contmsg = _("continue: %s")
3937 for f, msg in afterresolvedstates:
3940 for f, msg in afterresolvedstates:
3938 if repo.vfs.exists(f):
3941 if repo.vfs.exists(f):
3939 return contmsg % msg, True
3942 return contmsg % msg, True
3940 if repo[None].dirty(missing=True, merge=False, branch=False):
3943 if repo[None].dirty(missing=True, merge=False, branch=False):
3941 return contmsg % _("hg commit"), False
3944 return contmsg % _("hg commit"), False
3942 return None, None
3945 return None, None
3943
3946
3944 def checkafterresolved(repo):
3947 def checkafterresolved(repo):
3945 '''Inform the user about the next action after completing hg resolve
3948 '''Inform the user about the next action after completing hg resolve
3946
3949
3947 If there's a matching afterresolvedstates, howtocontinue will yield
3950 If there's a matching afterresolvedstates, howtocontinue will yield
3948 repo.ui.warn as the reporter.
3951 repo.ui.warn as the reporter.
3949
3952
3950 Otherwise, it will yield repo.ui.note.
3953 Otherwise, it will yield repo.ui.note.
3951 '''
3954 '''
3952 msg, warning = howtocontinue(repo)
3955 msg, warning = howtocontinue(repo)
3953 if msg is not None:
3956 if msg is not None:
3954 if warning:
3957 if warning:
3955 repo.ui.warn("%s\n" % msg)
3958 repo.ui.warn("%s\n" % msg)
3956 else:
3959 else:
3957 repo.ui.note("%s\n" % msg)
3960 repo.ui.note("%s\n" % msg)
3958
3961
3959 def wrongtooltocontinue(repo, task):
3962 def wrongtooltocontinue(repo, task):
3960 '''Raise an abort suggesting how to properly continue if there is an
3963 '''Raise an abort suggesting how to properly continue if there is an
3961 active task.
3964 active task.
3962
3965
3963 Uses howtocontinue() to find the active task.
3966 Uses howtocontinue() to find the active task.
3964
3967
3965 If there's no task (repo.ui.note for 'hg commit'), it does not offer
3968 If there's no task (repo.ui.note for 'hg commit'), it does not offer
3966 a hint.
3969 a hint.
3967 '''
3970 '''
3968 after = howtocontinue(repo)
3971 after = howtocontinue(repo)
3969 hint = None
3972 hint = None
3970 if after[1]:
3973 if after[1]:
3971 hint = after[0]
3974 hint = after[0]
3972 raise error.Abort(_('no %s in progress') % task, hint=hint)
3975 raise error.Abort(_('no %s in progress') % task, hint=hint)
General Comments 0
You need to be logged in to leave comments. Login now