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