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