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