##// END OF EJS Templates
cmdutil: use internal separators when building the terse list...
Matt Harbison -
r38221:51e420a7 default
parent child Browse files
Show More
@@ -1,3258 +1,3258 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
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 = os.path.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, os.path.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)
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 + pycompat.ossep
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(util.pconvert(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 rev = ctx.rev()
2137 rev = ctx.rev()
2138 ret = 1
2138 ret = 1
2139 ds = ctx.repo().dirstate
2139 ds = ctx.repo().dirstate
2140
2140
2141 for f in ctx.matches(m):
2141 for f in ctx.matches(m):
2142 if rev is None and ds[f] == 'r':
2142 if rev is None and ds[f] == 'r':
2143 continue
2143 continue
2144 fm.startitem()
2144 fm.startitem()
2145 if ui.verbose:
2145 if ui.verbose:
2146 fc = ctx[f]
2146 fc = ctx[f]
2147 fm.write('size flags', '% 10d % 1s ', fc.size(), fc.flags())
2147 fm.write('size flags', '% 10d % 1s ', fc.size(), fc.flags())
2148 fm.data(abspath=f)
2148 fm.data(abspath=f)
2149 fm.write('path', fmt, m.rel(f))
2149 fm.write('path', fmt, m.rel(f))
2150 ret = 0
2150 ret = 0
2151
2151
2152 for subpath in sorted(ctx.substate):
2152 for subpath in sorted(ctx.substate):
2153 submatch = matchmod.subdirmatcher(subpath, m)
2153 submatch = matchmod.subdirmatcher(subpath, m)
2154 if (subrepos or m.exact(subpath) or any(submatch.files())):
2154 if (subrepos or m.exact(subpath) or any(submatch.files())):
2155 sub = ctx.sub(subpath)
2155 sub = ctx.sub(subpath)
2156 try:
2156 try:
2157 recurse = m.exact(subpath) or subrepos
2157 recurse = m.exact(subpath) or subrepos
2158 if sub.printfiles(ui, submatch, fm, fmt, recurse) == 0:
2158 if sub.printfiles(ui, submatch, fm, fmt, recurse) == 0:
2159 ret = 0
2159 ret = 0
2160 except error.LookupError:
2160 except error.LookupError:
2161 ui.status(_("skipping missing subrepository: %s\n")
2161 ui.status(_("skipping missing subrepository: %s\n")
2162 % m.abs(subpath))
2162 % m.abs(subpath))
2163
2163
2164 return ret
2164 return ret
2165
2165
2166 def remove(ui, repo, m, prefix, after, force, subrepos, dryrun, warnings=None):
2166 def remove(ui, repo, m, prefix, after, force, subrepos, dryrun, warnings=None):
2167 join = lambda f: os.path.join(prefix, f)
2167 join = lambda f: os.path.join(prefix, f)
2168 ret = 0
2168 ret = 0
2169 s = repo.status(match=m, clean=True)
2169 s = repo.status(match=m, clean=True)
2170 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
2170 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
2171
2171
2172 wctx = repo[None]
2172 wctx = repo[None]
2173
2173
2174 if warnings is None:
2174 if warnings is None:
2175 warnings = []
2175 warnings = []
2176 warn = True
2176 warn = True
2177 else:
2177 else:
2178 warn = False
2178 warn = False
2179
2179
2180 subs = sorted(wctx.substate)
2180 subs = sorted(wctx.substate)
2181 total = len(subs)
2181 total = len(subs)
2182 count = 0
2182 count = 0
2183 for subpath in subs:
2183 for subpath in subs:
2184 count += 1
2184 count += 1
2185 submatch = matchmod.subdirmatcher(subpath, m)
2185 submatch = matchmod.subdirmatcher(subpath, m)
2186 if subrepos or m.exact(subpath) or any(submatch.files()):
2186 if subrepos or m.exact(subpath) or any(submatch.files()):
2187 ui.progress(_('searching'), count, total=total, unit=_('subrepos'))
2187 ui.progress(_('searching'), count, total=total, unit=_('subrepos'))
2188 sub = wctx.sub(subpath)
2188 sub = wctx.sub(subpath)
2189 try:
2189 try:
2190 if sub.removefiles(submatch, prefix, after, force, subrepos,
2190 if sub.removefiles(submatch, prefix, after, force, subrepos,
2191 dryrun, warnings):
2191 dryrun, warnings):
2192 ret = 1
2192 ret = 1
2193 except error.LookupError:
2193 except error.LookupError:
2194 warnings.append(_("skipping missing subrepository: %s\n")
2194 warnings.append(_("skipping missing subrepository: %s\n")
2195 % join(subpath))
2195 % join(subpath))
2196 ui.progress(_('searching'), None)
2196 ui.progress(_('searching'), None)
2197
2197
2198 # warn about failure to delete explicit files/dirs
2198 # warn about failure to delete explicit files/dirs
2199 deleteddirs = util.dirs(deleted)
2199 deleteddirs = util.dirs(deleted)
2200 files = m.files()
2200 files = m.files()
2201 total = len(files)
2201 total = len(files)
2202 count = 0
2202 count = 0
2203 for f in files:
2203 for f in files:
2204 def insubrepo():
2204 def insubrepo():
2205 for subpath in wctx.substate:
2205 for subpath in wctx.substate:
2206 if f.startswith(subpath + '/'):
2206 if f.startswith(subpath + '/'):
2207 return True
2207 return True
2208 return False
2208 return False
2209
2209
2210 count += 1
2210 count += 1
2211 ui.progress(_('deleting'), count, total=total, unit=_('files'))
2211 ui.progress(_('deleting'), count, total=total, unit=_('files'))
2212 isdir = f in deleteddirs or wctx.hasdir(f)
2212 isdir = f in deleteddirs or wctx.hasdir(f)
2213 if (f in repo.dirstate or isdir or f == '.'
2213 if (f in repo.dirstate or isdir or f == '.'
2214 or insubrepo() or f in subs):
2214 or insubrepo() or f in subs):
2215 continue
2215 continue
2216
2216
2217 if repo.wvfs.exists(f):
2217 if repo.wvfs.exists(f):
2218 if repo.wvfs.isdir(f):
2218 if repo.wvfs.isdir(f):
2219 warnings.append(_('not removing %s: no tracked files\n')
2219 warnings.append(_('not removing %s: no tracked files\n')
2220 % m.rel(f))
2220 % m.rel(f))
2221 else:
2221 else:
2222 warnings.append(_('not removing %s: file is untracked\n')
2222 warnings.append(_('not removing %s: file is untracked\n')
2223 % m.rel(f))
2223 % m.rel(f))
2224 # missing files will generate a warning elsewhere
2224 # missing files will generate a warning elsewhere
2225 ret = 1
2225 ret = 1
2226 ui.progress(_('deleting'), None)
2226 ui.progress(_('deleting'), None)
2227
2227
2228 if force:
2228 if force:
2229 list = modified + deleted + clean + added
2229 list = modified + deleted + clean + added
2230 elif after:
2230 elif after:
2231 list = deleted
2231 list = deleted
2232 remaining = modified + added + clean
2232 remaining = modified + added + clean
2233 total = len(remaining)
2233 total = len(remaining)
2234 count = 0
2234 count = 0
2235 for f in remaining:
2235 for f in remaining:
2236 count += 1
2236 count += 1
2237 ui.progress(_('skipping'), count, total=total, unit=_('files'))
2237 ui.progress(_('skipping'), count, total=total, unit=_('files'))
2238 if ui.verbose or (f in files):
2238 if ui.verbose or (f in files):
2239 warnings.append(_('not removing %s: file still exists\n')
2239 warnings.append(_('not removing %s: file still exists\n')
2240 % m.rel(f))
2240 % m.rel(f))
2241 ret = 1
2241 ret = 1
2242 ui.progress(_('skipping'), None)
2242 ui.progress(_('skipping'), None)
2243 else:
2243 else:
2244 list = deleted + clean
2244 list = deleted + clean
2245 total = len(modified) + len(added)
2245 total = len(modified) + len(added)
2246 count = 0
2246 count = 0
2247 for f in modified:
2247 for f in modified:
2248 count += 1
2248 count += 1
2249 ui.progress(_('skipping'), count, total=total, unit=_('files'))
2249 ui.progress(_('skipping'), count, total=total, unit=_('files'))
2250 warnings.append(_('not removing %s: file is modified (use -f'
2250 warnings.append(_('not removing %s: file is modified (use -f'
2251 ' to force removal)\n') % m.rel(f))
2251 ' to force removal)\n') % m.rel(f))
2252 ret = 1
2252 ret = 1
2253 for f in added:
2253 for f in added:
2254 count += 1
2254 count += 1
2255 ui.progress(_('skipping'), count, total=total, unit=_('files'))
2255 ui.progress(_('skipping'), count, total=total, unit=_('files'))
2256 warnings.append(_("not removing %s: file has been marked for add"
2256 warnings.append(_("not removing %s: file has been marked for add"
2257 " (use 'hg forget' to undo add)\n") % m.rel(f))
2257 " (use 'hg forget' to undo add)\n") % m.rel(f))
2258 ret = 1
2258 ret = 1
2259 ui.progress(_('skipping'), None)
2259 ui.progress(_('skipping'), None)
2260
2260
2261 list = sorted(list)
2261 list = sorted(list)
2262 total = len(list)
2262 total = len(list)
2263 count = 0
2263 count = 0
2264 for f in list:
2264 for f in list:
2265 count += 1
2265 count += 1
2266 if ui.verbose or not m.exact(f):
2266 if ui.verbose or not m.exact(f):
2267 ui.progress(_('deleting'), count, total=total, unit=_('files'))
2267 ui.progress(_('deleting'), count, total=total, unit=_('files'))
2268 ui.status(_('removing %s\n') % m.rel(f))
2268 ui.status(_('removing %s\n') % m.rel(f))
2269 ui.progress(_('deleting'), None)
2269 ui.progress(_('deleting'), None)
2270
2270
2271 if not dryrun:
2271 if not dryrun:
2272 with repo.wlock():
2272 with repo.wlock():
2273 if not after:
2273 if not after:
2274 for f in list:
2274 for f in list:
2275 if f in added:
2275 if f in added:
2276 continue # we never unlink added files on remove
2276 continue # we never unlink added files on remove
2277 repo.wvfs.unlinkpath(f, ignoremissing=True)
2277 repo.wvfs.unlinkpath(f, ignoremissing=True)
2278 repo[None].forget(list)
2278 repo[None].forget(list)
2279
2279
2280 if warn:
2280 if warn:
2281 for warning in warnings:
2281 for warning in warnings:
2282 ui.warn(warning)
2282 ui.warn(warning)
2283
2283
2284 return ret
2284 return ret
2285
2285
2286 def _updatecatformatter(fm, ctx, matcher, path, decode):
2286 def _updatecatformatter(fm, ctx, matcher, path, decode):
2287 """Hook for adding data to the formatter used by ``hg cat``.
2287 """Hook for adding data to the formatter used by ``hg cat``.
2288
2288
2289 Extensions (e.g., lfs) can wrap this to inject keywords/data, but must call
2289 Extensions (e.g., lfs) can wrap this to inject keywords/data, but must call
2290 this method first."""
2290 this method first."""
2291 data = ctx[path].data()
2291 data = ctx[path].data()
2292 if decode:
2292 if decode:
2293 data = ctx.repo().wwritedata(path, data)
2293 data = ctx.repo().wwritedata(path, data)
2294 fm.startitem()
2294 fm.startitem()
2295 fm.write('data', '%s', data)
2295 fm.write('data', '%s', data)
2296 fm.data(abspath=path, path=matcher.rel(path))
2296 fm.data(abspath=path, path=matcher.rel(path))
2297
2297
2298 def cat(ui, repo, ctx, matcher, basefm, fntemplate, prefix, **opts):
2298 def cat(ui, repo, ctx, matcher, basefm, fntemplate, prefix, **opts):
2299 err = 1
2299 err = 1
2300 opts = pycompat.byteskwargs(opts)
2300 opts = pycompat.byteskwargs(opts)
2301
2301
2302 def write(path):
2302 def write(path):
2303 filename = None
2303 filename = None
2304 if fntemplate:
2304 if fntemplate:
2305 filename = makefilename(ctx, fntemplate,
2305 filename = makefilename(ctx, fntemplate,
2306 pathname=os.path.join(prefix, path))
2306 pathname=os.path.join(prefix, path))
2307 # attempt to create the directory if it does not already exist
2307 # attempt to create the directory if it does not already exist
2308 try:
2308 try:
2309 os.makedirs(os.path.dirname(filename))
2309 os.makedirs(os.path.dirname(filename))
2310 except OSError:
2310 except OSError:
2311 pass
2311 pass
2312 with formatter.maybereopen(basefm, filename) as fm:
2312 with formatter.maybereopen(basefm, filename) as fm:
2313 _updatecatformatter(fm, ctx, matcher, path, opts.get('decode'))
2313 _updatecatformatter(fm, ctx, matcher, path, opts.get('decode'))
2314
2314
2315 # Automation often uses hg cat on single files, so special case it
2315 # Automation often uses hg cat on single files, so special case it
2316 # for performance to avoid the cost of parsing the manifest.
2316 # for performance to avoid the cost of parsing the manifest.
2317 if len(matcher.files()) == 1 and not matcher.anypats():
2317 if len(matcher.files()) == 1 and not matcher.anypats():
2318 file = matcher.files()[0]
2318 file = matcher.files()[0]
2319 mfl = repo.manifestlog
2319 mfl = repo.manifestlog
2320 mfnode = ctx.manifestnode()
2320 mfnode = ctx.manifestnode()
2321 try:
2321 try:
2322 if mfnode and mfl[mfnode].find(file)[0]:
2322 if mfnode and mfl[mfnode].find(file)[0]:
2323 scmutil.prefetchfiles(repo, [ctx.rev()], matcher)
2323 scmutil.prefetchfiles(repo, [ctx.rev()], matcher)
2324 write(file)
2324 write(file)
2325 return 0
2325 return 0
2326 except KeyError:
2326 except KeyError:
2327 pass
2327 pass
2328
2328
2329 scmutil.prefetchfiles(repo, [ctx.rev()], matcher)
2329 scmutil.prefetchfiles(repo, [ctx.rev()], matcher)
2330
2330
2331 for abs in ctx.walk(matcher):
2331 for abs in ctx.walk(matcher):
2332 write(abs)
2332 write(abs)
2333 err = 0
2333 err = 0
2334
2334
2335 for subpath in sorted(ctx.substate):
2335 for subpath in sorted(ctx.substate):
2336 sub = ctx.sub(subpath)
2336 sub = ctx.sub(subpath)
2337 try:
2337 try:
2338 submatch = matchmod.subdirmatcher(subpath, matcher)
2338 submatch = matchmod.subdirmatcher(subpath, matcher)
2339
2339
2340 if not sub.cat(submatch, basefm, fntemplate,
2340 if not sub.cat(submatch, basefm, fntemplate,
2341 os.path.join(prefix, sub._path),
2341 os.path.join(prefix, sub._path),
2342 **pycompat.strkwargs(opts)):
2342 **pycompat.strkwargs(opts)):
2343 err = 0
2343 err = 0
2344 except error.RepoLookupError:
2344 except error.RepoLookupError:
2345 ui.status(_("skipping missing subrepository: %s\n")
2345 ui.status(_("skipping missing subrepository: %s\n")
2346 % os.path.join(prefix, subpath))
2346 % os.path.join(prefix, subpath))
2347
2347
2348 return err
2348 return err
2349
2349
2350 def commit(ui, repo, commitfunc, pats, opts):
2350 def commit(ui, repo, commitfunc, pats, opts):
2351 '''commit the specified files or all outstanding changes'''
2351 '''commit the specified files or all outstanding changes'''
2352 date = opts.get('date')
2352 date = opts.get('date')
2353 if date:
2353 if date:
2354 opts['date'] = dateutil.parsedate(date)
2354 opts['date'] = dateutil.parsedate(date)
2355 message = logmessage(ui, opts)
2355 message = logmessage(ui, opts)
2356 matcher = scmutil.match(repo[None], pats, opts)
2356 matcher = scmutil.match(repo[None], pats, opts)
2357
2357
2358 dsguard = None
2358 dsguard = None
2359 # extract addremove carefully -- this function can be called from a command
2359 # extract addremove carefully -- this function can be called from a command
2360 # that doesn't support addremove
2360 # that doesn't support addremove
2361 if opts.get('addremove'):
2361 if opts.get('addremove'):
2362 dsguard = dirstateguard.dirstateguard(repo, 'commit')
2362 dsguard = dirstateguard.dirstateguard(repo, 'commit')
2363 with dsguard or util.nullcontextmanager():
2363 with dsguard or util.nullcontextmanager():
2364 if dsguard:
2364 if dsguard:
2365 if scmutil.addremove(repo, matcher, "", opts) != 0:
2365 if scmutil.addremove(repo, matcher, "", opts) != 0:
2366 raise error.Abort(
2366 raise error.Abort(
2367 _("failed to mark all new/missing files as added/removed"))
2367 _("failed to mark all new/missing files as added/removed"))
2368
2368
2369 return commitfunc(ui, repo, message, matcher, opts)
2369 return commitfunc(ui, repo, message, matcher, opts)
2370
2370
2371 def samefile(f, ctx1, ctx2):
2371 def samefile(f, ctx1, ctx2):
2372 if f in ctx1.manifest():
2372 if f in ctx1.manifest():
2373 a = ctx1.filectx(f)
2373 a = ctx1.filectx(f)
2374 if f in ctx2.manifest():
2374 if f in ctx2.manifest():
2375 b = ctx2.filectx(f)
2375 b = ctx2.filectx(f)
2376 return (not a.cmp(b)
2376 return (not a.cmp(b)
2377 and a.flags() == b.flags())
2377 and a.flags() == b.flags())
2378 else:
2378 else:
2379 return False
2379 return False
2380 else:
2380 else:
2381 return f not in ctx2.manifest()
2381 return f not in ctx2.manifest()
2382
2382
2383 def amend(ui, repo, old, extra, pats, opts):
2383 def amend(ui, repo, old, extra, pats, opts):
2384 # avoid cycle context -> subrepo -> cmdutil
2384 # avoid cycle context -> subrepo -> cmdutil
2385 from . import context
2385 from . import context
2386
2386
2387 # amend will reuse the existing user if not specified, but the obsolete
2387 # amend will reuse the existing user if not specified, but the obsolete
2388 # marker creation requires that the current user's name is specified.
2388 # marker creation requires that the current user's name is specified.
2389 if obsolete.isenabled(repo, obsolete.createmarkersopt):
2389 if obsolete.isenabled(repo, obsolete.createmarkersopt):
2390 ui.username() # raise exception if username not set
2390 ui.username() # raise exception if username not set
2391
2391
2392 ui.note(_('amending changeset %s\n') % old)
2392 ui.note(_('amending changeset %s\n') % old)
2393 base = old.p1()
2393 base = old.p1()
2394
2394
2395 with repo.wlock(), repo.lock(), repo.transaction('amend'):
2395 with repo.wlock(), repo.lock(), repo.transaction('amend'):
2396 # Participating changesets:
2396 # Participating changesets:
2397 #
2397 #
2398 # wctx o - workingctx that contains changes from working copy
2398 # wctx o - workingctx that contains changes from working copy
2399 # | to go into amending commit
2399 # | to go into amending commit
2400 # |
2400 # |
2401 # old o - changeset to amend
2401 # old o - changeset to amend
2402 # |
2402 # |
2403 # base o - first parent of the changeset to amend
2403 # base o - first parent of the changeset to amend
2404 wctx = repo[None]
2404 wctx = repo[None]
2405
2405
2406 # Copy to avoid mutating input
2406 # Copy to avoid mutating input
2407 extra = extra.copy()
2407 extra = extra.copy()
2408 # Update extra dict from amended commit (e.g. to preserve graft
2408 # Update extra dict from amended commit (e.g. to preserve graft
2409 # source)
2409 # source)
2410 extra.update(old.extra())
2410 extra.update(old.extra())
2411
2411
2412 # Also update it from the from the wctx
2412 # Also update it from the from the wctx
2413 extra.update(wctx.extra())
2413 extra.update(wctx.extra())
2414
2414
2415 user = opts.get('user') or old.user()
2415 user = opts.get('user') or old.user()
2416 date = opts.get('date') or old.date()
2416 date = opts.get('date') or old.date()
2417
2417
2418 # Parse the date to allow comparison between date and old.date()
2418 # Parse the date to allow comparison between date and old.date()
2419 date = dateutil.parsedate(date)
2419 date = dateutil.parsedate(date)
2420
2420
2421 if len(old.parents()) > 1:
2421 if len(old.parents()) > 1:
2422 # ctx.files() isn't reliable for merges, so fall back to the
2422 # ctx.files() isn't reliable for merges, so fall back to the
2423 # slower repo.status() method
2423 # slower repo.status() method
2424 files = set([fn for st in repo.status(base, old)[:3]
2424 files = set([fn for st in repo.status(base, old)[:3]
2425 for fn in st])
2425 for fn in st])
2426 else:
2426 else:
2427 files = set(old.files())
2427 files = set(old.files())
2428
2428
2429 # add/remove the files to the working copy if the "addremove" option
2429 # add/remove the files to the working copy if the "addremove" option
2430 # was specified.
2430 # was specified.
2431 matcher = scmutil.match(wctx, pats, opts)
2431 matcher = scmutil.match(wctx, pats, opts)
2432 if (opts.get('addremove')
2432 if (opts.get('addremove')
2433 and scmutil.addremove(repo, matcher, "", opts)):
2433 and scmutil.addremove(repo, matcher, "", opts)):
2434 raise error.Abort(
2434 raise error.Abort(
2435 _("failed to mark all new/missing files as added/removed"))
2435 _("failed to mark all new/missing files as added/removed"))
2436
2436
2437 # Check subrepos. This depends on in-place wctx._status update in
2437 # Check subrepos. This depends on in-place wctx._status update in
2438 # subrepo.precommit(). To minimize the risk of this hack, we do
2438 # subrepo.precommit(). To minimize the risk of this hack, we do
2439 # nothing if .hgsub does not exist.
2439 # nothing if .hgsub does not exist.
2440 if '.hgsub' in wctx or '.hgsub' in old:
2440 if '.hgsub' in wctx or '.hgsub' in old:
2441 subs, commitsubs, newsubstate = subrepoutil.precommit(
2441 subs, commitsubs, newsubstate = subrepoutil.precommit(
2442 ui, wctx, wctx._status, matcher)
2442 ui, wctx, wctx._status, matcher)
2443 # amend should abort if commitsubrepos is enabled
2443 # amend should abort if commitsubrepos is enabled
2444 assert not commitsubs
2444 assert not commitsubs
2445 if subs:
2445 if subs:
2446 subrepoutil.writestate(repo, newsubstate)
2446 subrepoutil.writestate(repo, newsubstate)
2447
2447
2448 ms = mergemod.mergestate.read(repo)
2448 ms = mergemod.mergestate.read(repo)
2449 mergeutil.checkunresolved(ms)
2449 mergeutil.checkunresolved(ms)
2450
2450
2451 filestoamend = set(f for f in wctx.files() if matcher(f))
2451 filestoamend = set(f for f in wctx.files() if matcher(f))
2452
2452
2453 changes = (len(filestoamend) > 0)
2453 changes = (len(filestoamend) > 0)
2454 if changes:
2454 if changes:
2455 # Recompute copies (avoid recording a -> b -> a)
2455 # Recompute copies (avoid recording a -> b -> a)
2456 copied = copies.pathcopies(base, wctx, matcher)
2456 copied = copies.pathcopies(base, wctx, matcher)
2457 if old.p2:
2457 if old.p2:
2458 copied.update(copies.pathcopies(old.p2(), wctx, matcher))
2458 copied.update(copies.pathcopies(old.p2(), wctx, matcher))
2459
2459
2460 # Prune files which were reverted by the updates: if old
2460 # Prune files which were reverted by the updates: if old
2461 # introduced file X and the file was renamed in the working
2461 # introduced file X and the file was renamed in the working
2462 # copy, then those two files are the same and
2462 # copy, then those two files are the same and
2463 # we can discard X from our list of files. Likewise if X
2463 # we can discard X from our list of files. Likewise if X
2464 # was removed, it's no longer relevant. If X is missing (aka
2464 # was removed, it's no longer relevant. If X is missing (aka
2465 # deleted), old X must be preserved.
2465 # deleted), old X must be preserved.
2466 files.update(filestoamend)
2466 files.update(filestoamend)
2467 files = [f for f in files if (not samefile(f, wctx, base)
2467 files = [f for f in files if (not samefile(f, wctx, base)
2468 or f in wctx.deleted())]
2468 or f in wctx.deleted())]
2469
2469
2470 def filectxfn(repo, ctx_, path):
2470 def filectxfn(repo, ctx_, path):
2471 try:
2471 try:
2472 # If the file being considered is not amongst the files
2472 # If the file being considered is not amongst the files
2473 # to be amended, we should return the file context from the
2473 # to be amended, we should return the file context from the
2474 # old changeset. This avoids issues when only some files in
2474 # old changeset. This avoids issues when only some files in
2475 # the working copy are being amended but there are also
2475 # the working copy are being amended but there are also
2476 # changes to other files from the old changeset.
2476 # changes to other files from the old changeset.
2477 if path not in filestoamend:
2477 if path not in filestoamend:
2478 return old.filectx(path)
2478 return old.filectx(path)
2479
2479
2480 # Return None for removed files.
2480 # Return None for removed files.
2481 if path in wctx.removed():
2481 if path in wctx.removed():
2482 return None
2482 return None
2483
2483
2484 fctx = wctx[path]
2484 fctx = wctx[path]
2485 flags = fctx.flags()
2485 flags = fctx.flags()
2486 mctx = context.memfilectx(repo, ctx_,
2486 mctx = context.memfilectx(repo, ctx_,
2487 fctx.path(), fctx.data(),
2487 fctx.path(), fctx.data(),
2488 islink='l' in flags,
2488 islink='l' in flags,
2489 isexec='x' in flags,
2489 isexec='x' in flags,
2490 copied=copied.get(path))
2490 copied=copied.get(path))
2491 return mctx
2491 return mctx
2492 except KeyError:
2492 except KeyError:
2493 return None
2493 return None
2494 else:
2494 else:
2495 ui.note(_('copying changeset %s to %s\n') % (old, base))
2495 ui.note(_('copying changeset %s to %s\n') % (old, base))
2496
2496
2497 # Use version of files as in the old cset
2497 # Use version of files as in the old cset
2498 def filectxfn(repo, ctx_, path):
2498 def filectxfn(repo, ctx_, path):
2499 try:
2499 try:
2500 return old.filectx(path)
2500 return old.filectx(path)
2501 except KeyError:
2501 except KeyError:
2502 return None
2502 return None
2503
2503
2504 # See if we got a message from -m or -l, if not, open the editor with
2504 # See if we got a message from -m or -l, if not, open the editor with
2505 # the message of the changeset to amend.
2505 # the message of the changeset to amend.
2506 message = logmessage(ui, opts)
2506 message = logmessage(ui, opts)
2507
2507
2508 editform = mergeeditform(old, 'commit.amend')
2508 editform = mergeeditform(old, 'commit.amend')
2509 editor = getcommiteditor(editform=editform,
2509 editor = getcommiteditor(editform=editform,
2510 **pycompat.strkwargs(opts))
2510 **pycompat.strkwargs(opts))
2511
2511
2512 if not message:
2512 if not message:
2513 editor = getcommiteditor(edit=True, editform=editform)
2513 editor = getcommiteditor(edit=True, editform=editform)
2514 message = old.description()
2514 message = old.description()
2515
2515
2516 pureextra = extra.copy()
2516 pureextra = extra.copy()
2517 extra['amend_source'] = old.hex()
2517 extra['amend_source'] = old.hex()
2518
2518
2519 new = context.memctx(repo,
2519 new = context.memctx(repo,
2520 parents=[base.node(), old.p2().node()],
2520 parents=[base.node(), old.p2().node()],
2521 text=message,
2521 text=message,
2522 files=files,
2522 files=files,
2523 filectxfn=filectxfn,
2523 filectxfn=filectxfn,
2524 user=user,
2524 user=user,
2525 date=date,
2525 date=date,
2526 extra=extra,
2526 extra=extra,
2527 editor=editor)
2527 editor=editor)
2528
2528
2529 newdesc = changelog.stripdesc(new.description())
2529 newdesc = changelog.stripdesc(new.description())
2530 if ((not changes)
2530 if ((not changes)
2531 and newdesc == old.description()
2531 and newdesc == old.description()
2532 and user == old.user()
2532 and user == old.user()
2533 and date == old.date()
2533 and date == old.date()
2534 and pureextra == old.extra()):
2534 and pureextra == old.extra()):
2535 # nothing changed. continuing here would create a new node
2535 # nothing changed. continuing here would create a new node
2536 # anyway because of the amend_source noise.
2536 # anyway because of the amend_source noise.
2537 #
2537 #
2538 # This not what we expect from amend.
2538 # This not what we expect from amend.
2539 return old.node()
2539 return old.node()
2540
2540
2541 if opts.get('secret'):
2541 if opts.get('secret'):
2542 commitphase = 'secret'
2542 commitphase = 'secret'
2543 else:
2543 else:
2544 commitphase = old.phase()
2544 commitphase = old.phase()
2545 overrides = {('phases', 'new-commit'): commitphase}
2545 overrides = {('phases', 'new-commit'): commitphase}
2546 with ui.configoverride(overrides, 'amend'):
2546 with ui.configoverride(overrides, 'amend'):
2547 newid = repo.commitctx(new)
2547 newid = repo.commitctx(new)
2548
2548
2549 # Reroute the working copy parent to the new changeset
2549 # Reroute the working copy parent to the new changeset
2550 repo.setparents(newid, nullid)
2550 repo.setparents(newid, nullid)
2551 mapping = {old.node(): (newid,)}
2551 mapping = {old.node(): (newid,)}
2552 obsmetadata = None
2552 obsmetadata = None
2553 if opts.get('note'):
2553 if opts.get('note'):
2554 obsmetadata = {'note': opts['note']}
2554 obsmetadata = {'note': opts['note']}
2555 scmutil.cleanupnodes(repo, mapping, 'amend', metadata=obsmetadata)
2555 scmutil.cleanupnodes(repo, mapping, 'amend', metadata=obsmetadata)
2556
2556
2557 # Fixing the dirstate because localrepo.commitctx does not update
2557 # Fixing the dirstate because localrepo.commitctx does not update
2558 # it. This is rather convenient because we did not need to update
2558 # it. This is rather convenient because we did not need to update
2559 # the dirstate for all the files in the new commit which commitctx
2559 # the dirstate for all the files in the new commit which commitctx
2560 # could have done if it updated the dirstate. Now, we can
2560 # could have done if it updated the dirstate. Now, we can
2561 # selectively update the dirstate only for the amended files.
2561 # selectively update the dirstate only for the amended files.
2562 dirstate = repo.dirstate
2562 dirstate = repo.dirstate
2563
2563
2564 # Update the state of the files which were added and
2564 # Update the state of the files which were added and
2565 # and modified in the amend to "normal" in the dirstate.
2565 # and modified in the amend to "normal" in the dirstate.
2566 normalfiles = set(wctx.modified() + wctx.added()) & filestoamend
2566 normalfiles = set(wctx.modified() + wctx.added()) & filestoamend
2567 for f in normalfiles:
2567 for f in normalfiles:
2568 dirstate.normal(f)
2568 dirstate.normal(f)
2569
2569
2570 # Update the state of files which were removed in the amend
2570 # Update the state of files which were removed in the amend
2571 # to "removed" in the dirstate.
2571 # to "removed" in the dirstate.
2572 removedfiles = set(wctx.removed()) & filestoamend
2572 removedfiles = set(wctx.removed()) & filestoamend
2573 for f in removedfiles:
2573 for f in removedfiles:
2574 dirstate.drop(f)
2574 dirstate.drop(f)
2575
2575
2576 return newid
2576 return newid
2577
2577
2578 def commiteditor(repo, ctx, subs, editform=''):
2578 def commiteditor(repo, ctx, subs, editform=''):
2579 if ctx.description():
2579 if ctx.description():
2580 return ctx.description()
2580 return ctx.description()
2581 return commitforceeditor(repo, ctx, subs, editform=editform,
2581 return commitforceeditor(repo, ctx, subs, editform=editform,
2582 unchangedmessagedetection=True)
2582 unchangedmessagedetection=True)
2583
2583
2584 def commitforceeditor(repo, ctx, subs, finishdesc=None, extramsg=None,
2584 def commitforceeditor(repo, ctx, subs, finishdesc=None, extramsg=None,
2585 editform='', unchangedmessagedetection=False):
2585 editform='', unchangedmessagedetection=False):
2586 if not extramsg:
2586 if not extramsg:
2587 extramsg = _("Leave message empty to abort commit.")
2587 extramsg = _("Leave message empty to abort commit.")
2588
2588
2589 forms = [e for e in editform.split('.') if e]
2589 forms = [e for e in editform.split('.') if e]
2590 forms.insert(0, 'changeset')
2590 forms.insert(0, 'changeset')
2591 templatetext = None
2591 templatetext = None
2592 while forms:
2592 while forms:
2593 ref = '.'.join(forms)
2593 ref = '.'.join(forms)
2594 if repo.ui.config('committemplate', ref):
2594 if repo.ui.config('committemplate', ref):
2595 templatetext = committext = buildcommittemplate(
2595 templatetext = committext = buildcommittemplate(
2596 repo, ctx, subs, extramsg, ref)
2596 repo, ctx, subs, extramsg, ref)
2597 break
2597 break
2598 forms.pop()
2598 forms.pop()
2599 else:
2599 else:
2600 committext = buildcommittext(repo, ctx, subs, extramsg)
2600 committext = buildcommittext(repo, ctx, subs, extramsg)
2601
2601
2602 # run editor in the repository root
2602 # run editor in the repository root
2603 olddir = pycompat.getcwd()
2603 olddir = pycompat.getcwd()
2604 os.chdir(repo.root)
2604 os.chdir(repo.root)
2605
2605
2606 # make in-memory changes visible to external process
2606 # make in-memory changes visible to external process
2607 tr = repo.currenttransaction()
2607 tr = repo.currenttransaction()
2608 repo.dirstate.write(tr)
2608 repo.dirstate.write(tr)
2609 pending = tr and tr.writepending() and repo.root
2609 pending = tr and tr.writepending() and repo.root
2610
2610
2611 editortext = repo.ui.edit(committext, ctx.user(), ctx.extra(),
2611 editortext = repo.ui.edit(committext, ctx.user(), ctx.extra(),
2612 editform=editform, pending=pending,
2612 editform=editform, pending=pending,
2613 repopath=repo.path, action='commit')
2613 repopath=repo.path, action='commit')
2614 text = editortext
2614 text = editortext
2615
2615
2616 # strip away anything below this special string (used for editors that want
2616 # strip away anything below this special string (used for editors that want
2617 # to display the diff)
2617 # to display the diff)
2618 stripbelow = re.search(_linebelow, text, flags=re.MULTILINE)
2618 stripbelow = re.search(_linebelow, text, flags=re.MULTILINE)
2619 if stripbelow:
2619 if stripbelow:
2620 text = text[:stripbelow.start()]
2620 text = text[:stripbelow.start()]
2621
2621
2622 text = re.sub("(?m)^HG:.*(\n|$)", "", text)
2622 text = re.sub("(?m)^HG:.*(\n|$)", "", text)
2623 os.chdir(olddir)
2623 os.chdir(olddir)
2624
2624
2625 if finishdesc:
2625 if finishdesc:
2626 text = finishdesc(text)
2626 text = finishdesc(text)
2627 if not text.strip():
2627 if not text.strip():
2628 raise error.Abort(_("empty commit message"))
2628 raise error.Abort(_("empty commit message"))
2629 if unchangedmessagedetection and editortext == templatetext:
2629 if unchangedmessagedetection and editortext == templatetext:
2630 raise error.Abort(_("commit message unchanged"))
2630 raise error.Abort(_("commit message unchanged"))
2631
2631
2632 return text
2632 return text
2633
2633
2634 def buildcommittemplate(repo, ctx, subs, extramsg, ref):
2634 def buildcommittemplate(repo, ctx, subs, extramsg, ref):
2635 ui = repo.ui
2635 ui = repo.ui
2636 spec = formatter.templatespec(ref, None, None)
2636 spec = formatter.templatespec(ref, None, None)
2637 t = logcmdutil.changesettemplater(ui, repo, spec)
2637 t = logcmdutil.changesettemplater(ui, repo, spec)
2638 t.t.cache.update((k, templater.unquotestring(v))
2638 t.t.cache.update((k, templater.unquotestring(v))
2639 for k, v in repo.ui.configitems('committemplate'))
2639 for k, v in repo.ui.configitems('committemplate'))
2640
2640
2641 if not extramsg:
2641 if not extramsg:
2642 extramsg = '' # ensure that extramsg is string
2642 extramsg = '' # ensure that extramsg is string
2643
2643
2644 ui.pushbuffer()
2644 ui.pushbuffer()
2645 t.show(ctx, extramsg=extramsg)
2645 t.show(ctx, extramsg=extramsg)
2646 return ui.popbuffer()
2646 return ui.popbuffer()
2647
2647
2648 def hgprefix(msg):
2648 def hgprefix(msg):
2649 return "\n".join(["HG: %s" % a for a in msg.split("\n") if a])
2649 return "\n".join(["HG: %s" % a for a in msg.split("\n") if a])
2650
2650
2651 def buildcommittext(repo, ctx, subs, extramsg):
2651 def buildcommittext(repo, ctx, subs, extramsg):
2652 edittext = []
2652 edittext = []
2653 modified, added, removed = ctx.modified(), ctx.added(), ctx.removed()
2653 modified, added, removed = ctx.modified(), ctx.added(), ctx.removed()
2654 if ctx.description():
2654 if ctx.description():
2655 edittext.append(ctx.description())
2655 edittext.append(ctx.description())
2656 edittext.append("")
2656 edittext.append("")
2657 edittext.append("") # Empty line between message and comments.
2657 edittext.append("") # Empty line between message and comments.
2658 edittext.append(hgprefix(_("Enter commit message."
2658 edittext.append(hgprefix(_("Enter commit message."
2659 " Lines beginning with 'HG:' are removed.")))
2659 " Lines beginning with 'HG:' are removed.")))
2660 edittext.append(hgprefix(extramsg))
2660 edittext.append(hgprefix(extramsg))
2661 edittext.append("HG: --")
2661 edittext.append("HG: --")
2662 edittext.append(hgprefix(_("user: %s") % ctx.user()))
2662 edittext.append(hgprefix(_("user: %s") % ctx.user()))
2663 if ctx.p2():
2663 if ctx.p2():
2664 edittext.append(hgprefix(_("branch merge")))
2664 edittext.append(hgprefix(_("branch merge")))
2665 if ctx.branch():
2665 if ctx.branch():
2666 edittext.append(hgprefix(_("branch '%s'") % ctx.branch()))
2666 edittext.append(hgprefix(_("branch '%s'") % ctx.branch()))
2667 if bookmarks.isactivewdirparent(repo):
2667 if bookmarks.isactivewdirparent(repo):
2668 edittext.append(hgprefix(_("bookmark '%s'") % repo._activebookmark))
2668 edittext.append(hgprefix(_("bookmark '%s'") % repo._activebookmark))
2669 edittext.extend([hgprefix(_("subrepo %s") % s) for s in subs])
2669 edittext.extend([hgprefix(_("subrepo %s") % s) for s in subs])
2670 edittext.extend([hgprefix(_("added %s") % f) for f in added])
2670 edittext.extend([hgprefix(_("added %s") % f) for f in added])
2671 edittext.extend([hgprefix(_("changed %s") % f) for f in modified])
2671 edittext.extend([hgprefix(_("changed %s") % f) for f in modified])
2672 edittext.extend([hgprefix(_("removed %s") % f) for f in removed])
2672 edittext.extend([hgprefix(_("removed %s") % f) for f in removed])
2673 if not added and not modified and not removed:
2673 if not added and not modified and not removed:
2674 edittext.append(hgprefix(_("no files changed")))
2674 edittext.append(hgprefix(_("no files changed")))
2675 edittext.append("")
2675 edittext.append("")
2676
2676
2677 return "\n".join(edittext)
2677 return "\n".join(edittext)
2678
2678
2679 def commitstatus(repo, node, branch, bheads=None, opts=None):
2679 def commitstatus(repo, node, branch, bheads=None, opts=None):
2680 if opts is None:
2680 if opts is None:
2681 opts = {}
2681 opts = {}
2682 ctx = repo[node]
2682 ctx = repo[node]
2683 parents = ctx.parents()
2683 parents = ctx.parents()
2684
2684
2685 if (not opts.get('amend') and bheads and node not in bheads and not
2685 if (not opts.get('amend') and bheads and node not in bheads and not
2686 [x for x in parents if x.node() in bheads and x.branch() == branch]):
2686 [x for x in parents if x.node() in bheads and x.branch() == branch]):
2687 repo.ui.status(_('created new head\n'))
2687 repo.ui.status(_('created new head\n'))
2688 # The message is not printed for initial roots. For the other
2688 # The message is not printed for initial roots. For the other
2689 # changesets, it is printed in the following situations:
2689 # changesets, it is printed in the following situations:
2690 #
2690 #
2691 # Par column: for the 2 parents with ...
2691 # Par column: for the 2 parents with ...
2692 # N: null or no parent
2692 # N: null or no parent
2693 # B: parent is on another named branch
2693 # B: parent is on another named branch
2694 # C: parent is a regular non head changeset
2694 # C: parent is a regular non head changeset
2695 # H: parent was a branch head of the current branch
2695 # H: parent was a branch head of the current branch
2696 # Msg column: whether we print "created new head" message
2696 # Msg column: whether we print "created new head" message
2697 # In the following, it is assumed that there already exists some
2697 # In the following, it is assumed that there already exists some
2698 # initial branch heads of the current branch, otherwise nothing is
2698 # initial branch heads of the current branch, otherwise nothing is
2699 # printed anyway.
2699 # printed anyway.
2700 #
2700 #
2701 # Par Msg Comment
2701 # Par Msg Comment
2702 # N N y additional topo root
2702 # N N y additional topo root
2703 #
2703 #
2704 # B N y additional branch root
2704 # B N y additional branch root
2705 # C N y additional topo head
2705 # C N y additional topo head
2706 # H N n usual case
2706 # H N n usual case
2707 #
2707 #
2708 # B B y weird additional branch root
2708 # B B y weird additional branch root
2709 # C B y branch merge
2709 # C B y branch merge
2710 # H B n merge with named branch
2710 # H B n merge with named branch
2711 #
2711 #
2712 # C C y additional head from merge
2712 # C C y additional head from merge
2713 # C H n merge with a head
2713 # C H n merge with a head
2714 #
2714 #
2715 # H H n head merge: head count decreases
2715 # H H n head merge: head count decreases
2716
2716
2717 if not opts.get('close_branch'):
2717 if not opts.get('close_branch'):
2718 for r in parents:
2718 for r in parents:
2719 if r.closesbranch() and r.branch() == branch:
2719 if r.closesbranch() and r.branch() == branch:
2720 repo.ui.status(_('reopening closed branch head %d\n') % r.rev())
2720 repo.ui.status(_('reopening closed branch head %d\n') % r.rev())
2721
2721
2722 if repo.ui.debugflag:
2722 if repo.ui.debugflag:
2723 repo.ui.write(_('committed changeset %d:%s\n') % (ctx.rev(), ctx.hex()))
2723 repo.ui.write(_('committed changeset %d:%s\n') % (ctx.rev(), ctx.hex()))
2724 elif repo.ui.verbose:
2724 elif repo.ui.verbose:
2725 repo.ui.write(_('committed changeset %d:%s\n') % (ctx.rev(), ctx))
2725 repo.ui.write(_('committed changeset %d:%s\n') % (ctx.rev(), ctx))
2726
2726
2727 def postcommitstatus(repo, pats, opts):
2727 def postcommitstatus(repo, pats, opts):
2728 return repo.status(match=scmutil.match(repo[None], pats, opts))
2728 return repo.status(match=scmutil.match(repo[None], pats, opts))
2729
2729
2730 def revert(ui, repo, ctx, parents, *pats, **opts):
2730 def revert(ui, repo, ctx, parents, *pats, **opts):
2731 opts = pycompat.byteskwargs(opts)
2731 opts = pycompat.byteskwargs(opts)
2732 parent, p2 = parents
2732 parent, p2 = parents
2733 node = ctx.node()
2733 node = ctx.node()
2734
2734
2735 mf = ctx.manifest()
2735 mf = ctx.manifest()
2736 if node == p2:
2736 if node == p2:
2737 parent = p2
2737 parent = p2
2738
2738
2739 # need all matching names in dirstate and manifest of target rev,
2739 # need all matching names in dirstate and manifest of target rev,
2740 # so have to walk both. do not print errors if files exist in one
2740 # so have to walk both. do not print errors if files exist in one
2741 # but not other. in both cases, filesets should be evaluated against
2741 # but not other. in both cases, filesets should be evaluated against
2742 # workingctx to get consistent result (issue4497). this means 'set:**'
2742 # workingctx to get consistent result (issue4497). this means 'set:**'
2743 # cannot be used to select missing files from target rev.
2743 # cannot be used to select missing files from target rev.
2744
2744
2745 # `names` is a mapping for all elements in working copy and target revision
2745 # `names` is a mapping for all elements in working copy and target revision
2746 # The mapping is in the form:
2746 # The mapping is in the form:
2747 # <asb path in repo> -> (<path from CWD>, <exactly specified by matcher?>)
2747 # <asb path in repo> -> (<path from CWD>, <exactly specified by matcher?>)
2748 names = {}
2748 names = {}
2749
2749
2750 with repo.wlock():
2750 with repo.wlock():
2751 ## filling of the `names` mapping
2751 ## filling of the `names` mapping
2752 # walk dirstate to fill `names`
2752 # walk dirstate to fill `names`
2753
2753
2754 interactive = opts.get('interactive', False)
2754 interactive = opts.get('interactive', False)
2755 wctx = repo[None]
2755 wctx = repo[None]
2756 m = scmutil.match(wctx, pats, opts)
2756 m = scmutil.match(wctx, pats, opts)
2757
2757
2758 # we'll need this later
2758 # we'll need this later
2759 targetsubs = sorted(s for s in wctx.substate if m(s))
2759 targetsubs = sorted(s for s in wctx.substate if m(s))
2760
2760
2761 if not m.always():
2761 if not m.always():
2762 matcher = matchmod.badmatch(m, lambda x, y: False)
2762 matcher = matchmod.badmatch(m, lambda x, y: False)
2763 for abs in wctx.walk(matcher):
2763 for abs in wctx.walk(matcher):
2764 names[abs] = m.rel(abs), m.exact(abs)
2764 names[abs] = m.rel(abs), m.exact(abs)
2765
2765
2766 # walk target manifest to fill `names`
2766 # walk target manifest to fill `names`
2767
2767
2768 def badfn(path, msg):
2768 def badfn(path, msg):
2769 if path in names:
2769 if path in names:
2770 return
2770 return
2771 if path in ctx.substate:
2771 if path in ctx.substate:
2772 return
2772 return
2773 path_ = path + '/'
2773 path_ = path + '/'
2774 for f in names:
2774 for f in names:
2775 if f.startswith(path_):
2775 if f.startswith(path_):
2776 return
2776 return
2777 ui.warn("%s: %s\n" % (m.rel(path), msg))
2777 ui.warn("%s: %s\n" % (m.rel(path), msg))
2778
2778
2779 for abs in ctx.walk(matchmod.badmatch(m, badfn)):
2779 for abs in ctx.walk(matchmod.badmatch(m, badfn)):
2780 if abs not in names:
2780 if abs not in names:
2781 names[abs] = m.rel(abs), m.exact(abs)
2781 names[abs] = m.rel(abs), m.exact(abs)
2782
2782
2783 # Find status of all file in `names`.
2783 # Find status of all file in `names`.
2784 m = scmutil.matchfiles(repo, names)
2784 m = scmutil.matchfiles(repo, names)
2785
2785
2786 changes = repo.status(node1=node, match=m,
2786 changes = repo.status(node1=node, match=m,
2787 unknown=True, ignored=True, clean=True)
2787 unknown=True, ignored=True, clean=True)
2788 else:
2788 else:
2789 changes = repo.status(node1=node, match=m)
2789 changes = repo.status(node1=node, match=m)
2790 for kind in changes:
2790 for kind in changes:
2791 for abs in kind:
2791 for abs in kind:
2792 names[abs] = m.rel(abs), m.exact(abs)
2792 names[abs] = m.rel(abs), m.exact(abs)
2793
2793
2794 m = scmutil.matchfiles(repo, names)
2794 m = scmutil.matchfiles(repo, names)
2795
2795
2796 modified = set(changes.modified)
2796 modified = set(changes.modified)
2797 added = set(changes.added)
2797 added = set(changes.added)
2798 removed = set(changes.removed)
2798 removed = set(changes.removed)
2799 _deleted = set(changes.deleted)
2799 _deleted = set(changes.deleted)
2800 unknown = set(changes.unknown)
2800 unknown = set(changes.unknown)
2801 unknown.update(changes.ignored)
2801 unknown.update(changes.ignored)
2802 clean = set(changes.clean)
2802 clean = set(changes.clean)
2803 modadded = set()
2803 modadded = set()
2804
2804
2805 # We need to account for the state of the file in the dirstate,
2805 # We need to account for the state of the file in the dirstate,
2806 # even when we revert against something else than parent. This will
2806 # even when we revert against something else than parent. This will
2807 # slightly alter the behavior of revert (doing back up or not, delete
2807 # slightly alter the behavior of revert (doing back up or not, delete
2808 # or just forget etc).
2808 # or just forget etc).
2809 if parent == node:
2809 if parent == node:
2810 dsmodified = modified
2810 dsmodified = modified
2811 dsadded = added
2811 dsadded = added
2812 dsremoved = removed
2812 dsremoved = removed
2813 # store all local modifications, useful later for rename detection
2813 # store all local modifications, useful later for rename detection
2814 localchanges = dsmodified | dsadded
2814 localchanges = dsmodified | dsadded
2815 modified, added, removed = set(), set(), set()
2815 modified, added, removed = set(), set(), set()
2816 else:
2816 else:
2817 changes = repo.status(node1=parent, match=m)
2817 changes = repo.status(node1=parent, match=m)
2818 dsmodified = set(changes.modified)
2818 dsmodified = set(changes.modified)
2819 dsadded = set(changes.added)
2819 dsadded = set(changes.added)
2820 dsremoved = set(changes.removed)
2820 dsremoved = set(changes.removed)
2821 # store all local modifications, useful later for rename detection
2821 # store all local modifications, useful later for rename detection
2822 localchanges = dsmodified | dsadded
2822 localchanges = dsmodified | dsadded
2823
2823
2824 # only take into account for removes between wc and target
2824 # only take into account for removes between wc and target
2825 clean |= dsremoved - removed
2825 clean |= dsremoved - removed
2826 dsremoved &= removed
2826 dsremoved &= removed
2827 # distinct between dirstate remove and other
2827 # distinct between dirstate remove and other
2828 removed -= dsremoved
2828 removed -= dsremoved
2829
2829
2830 modadded = added & dsmodified
2830 modadded = added & dsmodified
2831 added -= modadded
2831 added -= modadded
2832
2832
2833 # tell newly modified apart.
2833 # tell newly modified apart.
2834 dsmodified &= modified
2834 dsmodified &= modified
2835 dsmodified |= modified & dsadded # dirstate added may need backup
2835 dsmodified |= modified & dsadded # dirstate added may need backup
2836 modified -= dsmodified
2836 modified -= dsmodified
2837
2837
2838 # We need to wait for some post-processing to update this set
2838 # We need to wait for some post-processing to update this set
2839 # before making the distinction. The dirstate will be used for
2839 # before making the distinction. The dirstate will be used for
2840 # that purpose.
2840 # that purpose.
2841 dsadded = added
2841 dsadded = added
2842
2842
2843 # in case of merge, files that are actually added can be reported as
2843 # in case of merge, files that are actually added can be reported as
2844 # modified, we need to post process the result
2844 # modified, we need to post process the result
2845 if p2 != nullid:
2845 if p2 != nullid:
2846 mergeadd = set(dsmodified)
2846 mergeadd = set(dsmodified)
2847 for path in dsmodified:
2847 for path in dsmodified:
2848 if path in mf:
2848 if path in mf:
2849 mergeadd.remove(path)
2849 mergeadd.remove(path)
2850 dsadded |= mergeadd
2850 dsadded |= mergeadd
2851 dsmodified -= mergeadd
2851 dsmodified -= mergeadd
2852
2852
2853 # if f is a rename, update `names` to also revert the source
2853 # if f is a rename, update `names` to also revert the source
2854 cwd = repo.getcwd()
2854 cwd = repo.getcwd()
2855 for f in localchanges:
2855 for f in localchanges:
2856 src = repo.dirstate.copied(f)
2856 src = repo.dirstate.copied(f)
2857 # XXX should we check for rename down to target node?
2857 # XXX should we check for rename down to target node?
2858 if src and src not in names and repo.dirstate[src] == 'r':
2858 if src and src not in names and repo.dirstate[src] == 'r':
2859 dsremoved.add(src)
2859 dsremoved.add(src)
2860 names[src] = (repo.pathto(src, cwd), True)
2860 names[src] = (repo.pathto(src, cwd), True)
2861
2861
2862 # determine the exact nature of the deleted changesets
2862 # determine the exact nature of the deleted changesets
2863 deladded = set(_deleted)
2863 deladded = set(_deleted)
2864 for path in _deleted:
2864 for path in _deleted:
2865 if path in mf:
2865 if path in mf:
2866 deladded.remove(path)
2866 deladded.remove(path)
2867 deleted = _deleted - deladded
2867 deleted = _deleted - deladded
2868
2868
2869 # distinguish between file to forget and the other
2869 # distinguish between file to forget and the other
2870 added = set()
2870 added = set()
2871 for abs in dsadded:
2871 for abs in dsadded:
2872 if repo.dirstate[abs] != 'a':
2872 if repo.dirstate[abs] != 'a':
2873 added.add(abs)
2873 added.add(abs)
2874 dsadded -= added
2874 dsadded -= added
2875
2875
2876 for abs in deladded:
2876 for abs in deladded:
2877 if repo.dirstate[abs] == 'a':
2877 if repo.dirstate[abs] == 'a':
2878 dsadded.add(abs)
2878 dsadded.add(abs)
2879 deladded -= dsadded
2879 deladded -= dsadded
2880
2880
2881 # For files marked as removed, we check if an unknown file is present at
2881 # For files marked as removed, we check if an unknown file is present at
2882 # the same path. If a such file exists it may need to be backed up.
2882 # the same path. If a such file exists it may need to be backed up.
2883 # Making the distinction at this stage helps have simpler backup
2883 # Making the distinction at this stage helps have simpler backup
2884 # logic.
2884 # logic.
2885 removunk = set()
2885 removunk = set()
2886 for abs in removed:
2886 for abs in removed:
2887 target = repo.wjoin(abs)
2887 target = repo.wjoin(abs)
2888 if os.path.lexists(target):
2888 if os.path.lexists(target):
2889 removunk.add(abs)
2889 removunk.add(abs)
2890 removed -= removunk
2890 removed -= removunk
2891
2891
2892 dsremovunk = set()
2892 dsremovunk = set()
2893 for abs in dsremoved:
2893 for abs in dsremoved:
2894 target = repo.wjoin(abs)
2894 target = repo.wjoin(abs)
2895 if os.path.lexists(target):
2895 if os.path.lexists(target):
2896 dsremovunk.add(abs)
2896 dsremovunk.add(abs)
2897 dsremoved -= dsremovunk
2897 dsremoved -= dsremovunk
2898
2898
2899 # action to be actually performed by revert
2899 # action to be actually performed by revert
2900 # (<list of file>, message>) tuple
2900 # (<list of file>, message>) tuple
2901 actions = {'revert': ([], _('reverting %s\n')),
2901 actions = {'revert': ([], _('reverting %s\n')),
2902 'add': ([], _('adding %s\n')),
2902 'add': ([], _('adding %s\n')),
2903 'remove': ([], _('removing %s\n')),
2903 'remove': ([], _('removing %s\n')),
2904 'drop': ([], _('removing %s\n')),
2904 'drop': ([], _('removing %s\n')),
2905 'forget': ([], _('forgetting %s\n')),
2905 'forget': ([], _('forgetting %s\n')),
2906 'undelete': ([], _('undeleting %s\n')),
2906 'undelete': ([], _('undeleting %s\n')),
2907 'noop': (None, _('no changes needed to %s\n')),
2907 'noop': (None, _('no changes needed to %s\n')),
2908 'unknown': (None, _('file not managed: %s\n')),
2908 'unknown': (None, _('file not managed: %s\n')),
2909 }
2909 }
2910
2910
2911 # "constant" that convey the backup strategy.
2911 # "constant" that convey the backup strategy.
2912 # All set to `discard` if `no-backup` is set do avoid checking
2912 # All set to `discard` if `no-backup` is set do avoid checking
2913 # no_backup lower in the code.
2913 # no_backup lower in the code.
2914 # These values are ordered for comparison purposes
2914 # These values are ordered for comparison purposes
2915 backupinteractive = 3 # do backup if interactively modified
2915 backupinteractive = 3 # do backup if interactively modified
2916 backup = 2 # unconditionally do backup
2916 backup = 2 # unconditionally do backup
2917 check = 1 # check if the existing file differs from target
2917 check = 1 # check if the existing file differs from target
2918 discard = 0 # never do backup
2918 discard = 0 # never do backup
2919 if opts.get('no_backup'):
2919 if opts.get('no_backup'):
2920 backupinteractive = backup = check = discard
2920 backupinteractive = backup = check = discard
2921 if interactive:
2921 if interactive:
2922 dsmodifiedbackup = backupinteractive
2922 dsmodifiedbackup = backupinteractive
2923 else:
2923 else:
2924 dsmodifiedbackup = backup
2924 dsmodifiedbackup = backup
2925 tobackup = set()
2925 tobackup = set()
2926
2926
2927 backupanddel = actions['remove']
2927 backupanddel = actions['remove']
2928 if not opts.get('no_backup'):
2928 if not opts.get('no_backup'):
2929 backupanddel = actions['drop']
2929 backupanddel = actions['drop']
2930
2930
2931 disptable = (
2931 disptable = (
2932 # dispatch table:
2932 # dispatch table:
2933 # file state
2933 # file state
2934 # action
2934 # action
2935 # make backup
2935 # make backup
2936
2936
2937 ## Sets that results that will change file on disk
2937 ## Sets that results that will change file on disk
2938 # Modified compared to target, no local change
2938 # Modified compared to target, no local change
2939 (modified, actions['revert'], discard),
2939 (modified, actions['revert'], discard),
2940 # Modified compared to target, but local file is deleted
2940 # Modified compared to target, but local file is deleted
2941 (deleted, actions['revert'], discard),
2941 (deleted, actions['revert'], discard),
2942 # Modified compared to target, local change
2942 # Modified compared to target, local change
2943 (dsmodified, actions['revert'], dsmodifiedbackup),
2943 (dsmodified, actions['revert'], dsmodifiedbackup),
2944 # Added since target
2944 # Added since target
2945 (added, actions['remove'], discard),
2945 (added, actions['remove'], discard),
2946 # Added in working directory
2946 # Added in working directory
2947 (dsadded, actions['forget'], discard),
2947 (dsadded, actions['forget'], discard),
2948 # Added since target, have local modification
2948 # Added since target, have local modification
2949 (modadded, backupanddel, backup),
2949 (modadded, backupanddel, backup),
2950 # Added since target but file is missing in working directory
2950 # Added since target but file is missing in working directory
2951 (deladded, actions['drop'], discard),
2951 (deladded, actions['drop'], discard),
2952 # Removed since target, before working copy parent
2952 # Removed since target, before working copy parent
2953 (removed, actions['add'], discard),
2953 (removed, actions['add'], discard),
2954 # Same as `removed` but an unknown file exists at the same path
2954 # Same as `removed` but an unknown file exists at the same path
2955 (removunk, actions['add'], check),
2955 (removunk, actions['add'], check),
2956 # Removed since targe, marked as such in working copy parent
2956 # Removed since targe, marked as such in working copy parent
2957 (dsremoved, actions['undelete'], discard),
2957 (dsremoved, actions['undelete'], discard),
2958 # Same as `dsremoved` but an unknown file exists at the same path
2958 # Same as `dsremoved` but an unknown file exists at the same path
2959 (dsremovunk, actions['undelete'], check),
2959 (dsremovunk, actions['undelete'], check),
2960 ## the following sets does not result in any file changes
2960 ## the following sets does not result in any file changes
2961 # File with no modification
2961 # File with no modification
2962 (clean, actions['noop'], discard),
2962 (clean, actions['noop'], discard),
2963 # Existing file, not tracked anywhere
2963 # Existing file, not tracked anywhere
2964 (unknown, actions['unknown'], discard),
2964 (unknown, actions['unknown'], discard),
2965 )
2965 )
2966
2966
2967 for abs, (rel, exact) in sorted(names.items()):
2967 for abs, (rel, exact) in sorted(names.items()):
2968 # target file to be touch on disk (relative to cwd)
2968 # target file to be touch on disk (relative to cwd)
2969 target = repo.wjoin(abs)
2969 target = repo.wjoin(abs)
2970 # search the entry in the dispatch table.
2970 # search the entry in the dispatch table.
2971 # if the file is in any of these sets, it was touched in the working
2971 # if the file is in any of these sets, it was touched in the working
2972 # directory parent and we are sure it needs to be reverted.
2972 # directory parent and we are sure it needs to be reverted.
2973 for table, (xlist, msg), dobackup in disptable:
2973 for table, (xlist, msg), dobackup in disptable:
2974 if abs not in table:
2974 if abs not in table:
2975 continue
2975 continue
2976 if xlist is not None:
2976 if xlist is not None:
2977 xlist.append(abs)
2977 xlist.append(abs)
2978 if dobackup:
2978 if dobackup:
2979 # If in interactive mode, don't automatically create
2979 # If in interactive mode, don't automatically create
2980 # .orig files (issue4793)
2980 # .orig files (issue4793)
2981 if dobackup == backupinteractive:
2981 if dobackup == backupinteractive:
2982 tobackup.add(abs)
2982 tobackup.add(abs)
2983 elif (backup <= dobackup or wctx[abs].cmp(ctx[abs])):
2983 elif (backup <= dobackup or wctx[abs].cmp(ctx[abs])):
2984 bakname = scmutil.origpath(ui, repo, rel)
2984 bakname = scmutil.origpath(ui, repo, rel)
2985 ui.note(_('saving current version of %s as %s\n') %
2985 ui.note(_('saving current version of %s as %s\n') %
2986 (rel, bakname))
2986 (rel, bakname))
2987 if not opts.get('dry_run'):
2987 if not opts.get('dry_run'):
2988 if interactive:
2988 if interactive:
2989 util.copyfile(target, bakname)
2989 util.copyfile(target, bakname)
2990 else:
2990 else:
2991 util.rename(target, bakname)
2991 util.rename(target, bakname)
2992 if ui.verbose or not exact:
2992 if ui.verbose or not exact:
2993 if not isinstance(msg, bytes):
2993 if not isinstance(msg, bytes):
2994 msg = msg(abs)
2994 msg = msg(abs)
2995 ui.status(msg % rel)
2995 ui.status(msg % rel)
2996 elif exact:
2996 elif exact:
2997 ui.warn(msg % rel)
2997 ui.warn(msg % rel)
2998 break
2998 break
2999
2999
3000 if not opts.get('dry_run'):
3000 if not opts.get('dry_run'):
3001 needdata = ('revert', 'add', 'undelete')
3001 needdata = ('revert', 'add', 'undelete')
3002 oplist = [actions[name][0] for name in needdata]
3002 oplist = [actions[name][0] for name in needdata]
3003 prefetch = scmutil.prefetchfiles
3003 prefetch = scmutil.prefetchfiles
3004 matchfiles = scmutil.matchfiles
3004 matchfiles = scmutil.matchfiles
3005 prefetch(repo, [ctx.rev()],
3005 prefetch(repo, [ctx.rev()],
3006 matchfiles(repo,
3006 matchfiles(repo,
3007 [f for sublist in oplist for f in sublist]))
3007 [f for sublist in oplist for f in sublist]))
3008 _performrevert(repo, parents, ctx, actions, interactive, tobackup)
3008 _performrevert(repo, parents, ctx, actions, interactive, tobackup)
3009
3009
3010 if targetsubs:
3010 if targetsubs:
3011 # Revert the subrepos on the revert list
3011 # Revert the subrepos on the revert list
3012 for sub in targetsubs:
3012 for sub in targetsubs:
3013 try:
3013 try:
3014 wctx.sub(sub).revert(ctx.substate[sub], *pats,
3014 wctx.sub(sub).revert(ctx.substate[sub], *pats,
3015 **pycompat.strkwargs(opts))
3015 **pycompat.strkwargs(opts))
3016 except KeyError:
3016 except KeyError:
3017 raise error.Abort("subrepository '%s' does not exist in %s!"
3017 raise error.Abort("subrepository '%s' does not exist in %s!"
3018 % (sub, short(ctx.node())))
3018 % (sub, short(ctx.node())))
3019
3019
3020 def _performrevert(repo, parents, ctx, actions, interactive=False,
3020 def _performrevert(repo, parents, ctx, actions, interactive=False,
3021 tobackup=None):
3021 tobackup=None):
3022 """function that actually perform all the actions computed for revert
3022 """function that actually perform all the actions computed for revert
3023
3023
3024 This is an independent function to let extension to plug in and react to
3024 This is an independent function to let extension to plug in and react to
3025 the imminent revert.
3025 the imminent revert.
3026
3026
3027 Make sure you have the working directory locked when calling this function.
3027 Make sure you have the working directory locked when calling this function.
3028 """
3028 """
3029 parent, p2 = parents
3029 parent, p2 = parents
3030 node = ctx.node()
3030 node = ctx.node()
3031 excluded_files = []
3031 excluded_files = []
3032
3032
3033 def checkout(f):
3033 def checkout(f):
3034 fc = ctx[f]
3034 fc = ctx[f]
3035 repo.wwrite(f, fc.data(), fc.flags())
3035 repo.wwrite(f, fc.data(), fc.flags())
3036
3036
3037 def doremove(f):
3037 def doremove(f):
3038 try:
3038 try:
3039 repo.wvfs.unlinkpath(f)
3039 repo.wvfs.unlinkpath(f)
3040 except OSError:
3040 except OSError:
3041 pass
3041 pass
3042 repo.dirstate.remove(f)
3042 repo.dirstate.remove(f)
3043
3043
3044 audit_path = pathutil.pathauditor(repo.root, cached=True)
3044 audit_path = pathutil.pathauditor(repo.root, cached=True)
3045 for f in actions['forget'][0]:
3045 for f in actions['forget'][0]:
3046 if interactive:
3046 if interactive:
3047 choice = repo.ui.promptchoice(
3047 choice = repo.ui.promptchoice(
3048 _("forget added file %s (Yn)?$$ &Yes $$ &No") % f)
3048 _("forget added file %s (Yn)?$$ &Yes $$ &No") % f)
3049 if choice == 0:
3049 if choice == 0:
3050 repo.dirstate.drop(f)
3050 repo.dirstate.drop(f)
3051 else:
3051 else:
3052 excluded_files.append(f)
3052 excluded_files.append(f)
3053 else:
3053 else:
3054 repo.dirstate.drop(f)
3054 repo.dirstate.drop(f)
3055 for f in actions['remove'][0]:
3055 for f in actions['remove'][0]:
3056 audit_path(f)
3056 audit_path(f)
3057 if interactive:
3057 if interactive:
3058 choice = repo.ui.promptchoice(
3058 choice = repo.ui.promptchoice(
3059 _("remove added file %s (Yn)?$$ &Yes $$ &No") % f)
3059 _("remove added file %s (Yn)?$$ &Yes $$ &No") % f)
3060 if choice == 0:
3060 if choice == 0:
3061 doremove(f)
3061 doremove(f)
3062 else:
3062 else:
3063 excluded_files.append(f)
3063 excluded_files.append(f)
3064 else:
3064 else:
3065 doremove(f)
3065 doremove(f)
3066 for f in actions['drop'][0]:
3066 for f in actions['drop'][0]:
3067 audit_path(f)
3067 audit_path(f)
3068 repo.dirstate.remove(f)
3068 repo.dirstate.remove(f)
3069
3069
3070 normal = None
3070 normal = None
3071 if node == parent:
3071 if node == parent:
3072 # We're reverting to our parent. If possible, we'd like status
3072 # We're reverting to our parent. If possible, we'd like status
3073 # to report the file as clean. We have to use normallookup for
3073 # to report the file as clean. We have to use normallookup for
3074 # merges to avoid losing information about merged/dirty files.
3074 # merges to avoid losing information about merged/dirty files.
3075 if p2 != nullid:
3075 if p2 != nullid:
3076 normal = repo.dirstate.normallookup
3076 normal = repo.dirstate.normallookup
3077 else:
3077 else:
3078 normal = repo.dirstate.normal
3078 normal = repo.dirstate.normal
3079
3079
3080 newlyaddedandmodifiedfiles = set()
3080 newlyaddedandmodifiedfiles = set()
3081 if interactive:
3081 if interactive:
3082 # Prompt the user for changes to revert
3082 # Prompt the user for changes to revert
3083 torevert = [f for f in actions['revert'][0] if f not in excluded_files]
3083 torevert = [f for f in actions['revert'][0] if f not in excluded_files]
3084 m = scmutil.matchfiles(repo, torevert)
3084 m = scmutil.matchfiles(repo, torevert)
3085 diffopts = patch.difffeatureopts(repo.ui, whitespace=True)
3085 diffopts = patch.difffeatureopts(repo.ui, whitespace=True)
3086 diffopts.nodates = True
3086 diffopts.nodates = True
3087 diffopts.git = True
3087 diffopts.git = True
3088 operation = 'discard'
3088 operation = 'discard'
3089 reversehunks = True
3089 reversehunks = True
3090 if node != parent:
3090 if node != parent:
3091 operation = 'apply'
3091 operation = 'apply'
3092 reversehunks = False
3092 reversehunks = False
3093 if reversehunks:
3093 if reversehunks:
3094 diff = patch.diff(repo, ctx.node(), None, m, opts=diffopts)
3094 diff = patch.diff(repo, ctx.node(), None, m, opts=diffopts)
3095 else:
3095 else:
3096 diff = patch.diff(repo, None, ctx.node(), m, opts=diffopts)
3096 diff = patch.diff(repo, None, ctx.node(), m, opts=diffopts)
3097 originalchunks = patch.parsepatch(diff)
3097 originalchunks = patch.parsepatch(diff)
3098
3098
3099 try:
3099 try:
3100
3100
3101 chunks, opts = recordfilter(repo.ui, originalchunks,
3101 chunks, opts = recordfilter(repo.ui, originalchunks,
3102 operation=operation)
3102 operation=operation)
3103 if reversehunks:
3103 if reversehunks:
3104 chunks = patch.reversehunks(chunks)
3104 chunks = patch.reversehunks(chunks)
3105
3105
3106 except error.PatchError as err:
3106 except error.PatchError as err:
3107 raise error.Abort(_('error parsing patch: %s') % err)
3107 raise error.Abort(_('error parsing patch: %s') % err)
3108
3108
3109 newlyaddedandmodifiedfiles = newandmodified(chunks, originalchunks)
3109 newlyaddedandmodifiedfiles = newandmodified(chunks, originalchunks)
3110 if tobackup is None:
3110 if tobackup is None:
3111 tobackup = set()
3111 tobackup = set()
3112 # Apply changes
3112 # Apply changes
3113 fp = stringio()
3113 fp = stringio()
3114 for c in chunks:
3114 for c in chunks:
3115 # Create a backup file only if this hunk should be backed up
3115 # Create a backup file only if this hunk should be backed up
3116 if ishunk(c) and c.header.filename() in tobackup:
3116 if ishunk(c) and c.header.filename() in tobackup:
3117 abs = c.header.filename()
3117 abs = c.header.filename()
3118 target = repo.wjoin(abs)
3118 target = repo.wjoin(abs)
3119 bakname = scmutil.origpath(repo.ui, repo, m.rel(abs))
3119 bakname = scmutil.origpath(repo.ui, repo, m.rel(abs))
3120 util.copyfile(target, bakname)
3120 util.copyfile(target, bakname)
3121 tobackup.remove(abs)
3121 tobackup.remove(abs)
3122 c.write(fp)
3122 c.write(fp)
3123 dopatch = fp.tell()
3123 dopatch = fp.tell()
3124 fp.seek(0)
3124 fp.seek(0)
3125 if dopatch:
3125 if dopatch:
3126 try:
3126 try:
3127 patch.internalpatch(repo.ui, repo, fp, 1, eolmode=None)
3127 patch.internalpatch(repo.ui, repo, fp, 1, eolmode=None)
3128 except error.PatchError as err:
3128 except error.PatchError as err:
3129 raise error.Abort(pycompat.bytestr(err))
3129 raise error.Abort(pycompat.bytestr(err))
3130 del fp
3130 del fp
3131 else:
3131 else:
3132 for f in actions['revert'][0]:
3132 for f in actions['revert'][0]:
3133 checkout(f)
3133 checkout(f)
3134 if normal:
3134 if normal:
3135 normal(f)
3135 normal(f)
3136
3136
3137 for f in actions['add'][0]:
3137 for f in actions['add'][0]:
3138 # Don't checkout modified files, they are already created by the diff
3138 # Don't checkout modified files, they are already created by the diff
3139 if f not in newlyaddedandmodifiedfiles:
3139 if f not in newlyaddedandmodifiedfiles:
3140 checkout(f)
3140 checkout(f)
3141 repo.dirstate.add(f)
3141 repo.dirstate.add(f)
3142
3142
3143 normal = repo.dirstate.normallookup
3143 normal = repo.dirstate.normallookup
3144 if node == parent and p2 == nullid:
3144 if node == parent and p2 == nullid:
3145 normal = repo.dirstate.normal
3145 normal = repo.dirstate.normal
3146 for f in actions['undelete'][0]:
3146 for f in actions['undelete'][0]:
3147 checkout(f)
3147 checkout(f)
3148 normal(f)
3148 normal(f)
3149
3149
3150 copied = copies.pathcopies(repo[parent], ctx)
3150 copied = copies.pathcopies(repo[parent], ctx)
3151
3151
3152 for f in actions['add'][0] + actions['undelete'][0] + actions['revert'][0]:
3152 for f in actions['add'][0] + actions['undelete'][0] + actions['revert'][0]:
3153 if f in copied:
3153 if f in copied:
3154 repo.dirstate.copy(copied[f], f)
3154 repo.dirstate.copy(copied[f], f)
3155
3155
3156 # a list of (ui, repo, otherpeer, opts, missing) functions called by
3156 # a list of (ui, repo, otherpeer, opts, missing) functions called by
3157 # commands.outgoing. "missing" is "missing" of the result of
3157 # commands.outgoing. "missing" is "missing" of the result of
3158 # "findcommonoutgoing()"
3158 # "findcommonoutgoing()"
3159 outgoinghooks = util.hooks()
3159 outgoinghooks = util.hooks()
3160
3160
3161 # a list of (ui, repo) functions called by commands.summary
3161 # a list of (ui, repo) functions called by commands.summary
3162 summaryhooks = util.hooks()
3162 summaryhooks = util.hooks()
3163
3163
3164 # a list of (ui, repo, opts, changes) functions called by commands.summary.
3164 # a list of (ui, repo, opts, changes) functions called by commands.summary.
3165 #
3165 #
3166 # functions should return tuple of booleans below, if 'changes' is None:
3166 # functions should return tuple of booleans below, if 'changes' is None:
3167 # (whether-incomings-are-needed, whether-outgoings-are-needed)
3167 # (whether-incomings-are-needed, whether-outgoings-are-needed)
3168 #
3168 #
3169 # otherwise, 'changes' is a tuple of tuples below:
3169 # otherwise, 'changes' is a tuple of tuples below:
3170 # - (sourceurl, sourcebranch, sourcepeer, incoming)
3170 # - (sourceurl, sourcebranch, sourcepeer, incoming)
3171 # - (desturl, destbranch, destpeer, outgoing)
3171 # - (desturl, destbranch, destpeer, outgoing)
3172 summaryremotehooks = util.hooks()
3172 summaryremotehooks = util.hooks()
3173
3173
3174 # A list of state files kept by multistep operations like graft.
3174 # A list of state files kept by multistep operations like graft.
3175 # Since graft cannot be aborted, it is considered 'clearable' by update.
3175 # Since graft cannot be aborted, it is considered 'clearable' by update.
3176 # note: bisect is intentionally excluded
3176 # note: bisect is intentionally excluded
3177 # (state file, clearable, allowcommit, error, hint)
3177 # (state file, clearable, allowcommit, error, hint)
3178 unfinishedstates = [
3178 unfinishedstates = [
3179 ('graftstate', True, False, _('graft in progress'),
3179 ('graftstate', True, False, _('graft in progress'),
3180 _("use 'hg graft --continue' or 'hg update' to abort")),
3180 _("use 'hg graft --continue' or 'hg update' to abort")),
3181 ('updatestate', True, False, _('last update was interrupted'),
3181 ('updatestate', True, False, _('last update was interrupted'),
3182 _("use 'hg update' to get a consistent checkout"))
3182 _("use 'hg update' to get a consistent checkout"))
3183 ]
3183 ]
3184
3184
3185 def checkunfinished(repo, commit=False):
3185 def checkunfinished(repo, commit=False):
3186 '''Look for an unfinished multistep operation, like graft, and abort
3186 '''Look for an unfinished multistep operation, like graft, and abort
3187 if found. It's probably good to check this right before
3187 if found. It's probably good to check this right before
3188 bailifchanged().
3188 bailifchanged().
3189 '''
3189 '''
3190 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3190 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3191 if commit and allowcommit:
3191 if commit and allowcommit:
3192 continue
3192 continue
3193 if repo.vfs.exists(f):
3193 if repo.vfs.exists(f):
3194 raise error.Abort(msg, hint=hint)
3194 raise error.Abort(msg, hint=hint)
3195
3195
3196 def clearunfinished(repo):
3196 def clearunfinished(repo):
3197 '''Check for unfinished operations (as above), and clear the ones
3197 '''Check for unfinished operations (as above), and clear the ones
3198 that are clearable.
3198 that are clearable.
3199 '''
3199 '''
3200 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3200 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3201 if not clearable and repo.vfs.exists(f):
3201 if not clearable and repo.vfs.exists(f):
3202 raise error.Abort(msg, hint=hint)
3202 raise error.Abort(msg, hint=hint)
3203 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3203 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3204 if clearable and repo.vfs.exists(f):
3204 if clearable and repo.vfs.exists(f):
3205 util.unlink(repo.vfs.join(f))
3205 util.unlink(repo.vfs.join(f))
3206
3206
3207 afterresolvedstates = [
3207 afterresolvedstates = [
3208 ('graftstate',
3208 ('graftstate',
3209 _('hg graft --continue')),
3209 _('hg graft --continue')),
3210 ]
3210 ]
3211
3211
3212 def howtocontinue(repo):
3212 def howtocontinue(repo):
3213 '''Check for an unfinished operation and return the command to finish
3213 '''Check for an unfinished operation and return the command to finish
3214 it.
3214 it.
3215
3215
3216 afterresolvedstates tuples define a .hg/{file} and the corresponding
3216 afterresolvedstates tuples define a .hg/{file} and the corresponding
3217 command needed to finish it.
3217 command needed to finish it.
3218
3218
3219 Returns a (msg, warning) tuple. 'msg' is a string and 'warning' is
3219 Returns a (msg, warning) tuple. 'msg' is a string and 'warning' is
3220 a boolean.
3220 a boolean.
3221 '''
3221 '''
3222 contmsg = _("continue: %s")
3222 contmsg = _("continue: %s")
3223 for f, msg in afterresolvedstates:
3223 for f, msg in afterresolvedstates:
3224 if repo.vfs.exists(f):
3224 if repo.vfs.exists(f):
3225 return contmsg % msg, True
3225 return contmsg % msg, True
3226 if repo[None].dirty(missing=True, merge=False, branch=False):
3226 if repo[None].dirty(missing=True, merge=False, branch=False):
3227 return contmsg % _("hg commit"), False
3227 return contmsg % _("hg commit"), False
3228 return None, None
3228 return None, None
3229
3229
3230 def checkafterresolved(repo):
3230 def checkafterresolved(repo):
3231 '''Inform the user about the next action after completing hg resolve
3231 '''Inform the user about the next action after completing hg resolve
3232
3232
3233 If there's a matching afterresolvedstates, howtocontinue will yield
3233 If there's a matching afterresolvedstates, howtocontinue will yield
3234 repo.ui.warn as the reporter.
3234 repo.ui.warn as the reporter.
3235
3235
3236 Otherwise, it will yield repo.ui.note.
3236 Otherwise, it will yield repo.ui.note.
3237 '''
3237 '''
3238 msg, warning = howtocontinue(repo)
3238 msg, warning = howtocontinue(repo)
3239 if msg is not None:
3239 if msg is not None:
3240 if warning:
3240 if warning:
3241 repo.ui.warn("%s\n" % msg)
3241 repo.ui.warn("%s\n" % msg)
3242 else:
3242 else:
3243 repo.ui.note("%s\n" % msg)
3243 repo.ui.note("%s\n" % msg)
3244
3244
3245 def wrongtooltocontinue(repo, task):
3245 def wrongtooltocontinue(repo, task):
3246 '''Raise an abort suggesting how to properly continue if there is an
3246 '''Raise an abort suggesting how to properly continue if there is an
3247 active task.
3247 active task.
3248
3248
3249 Uses howtocontinue() to find the active task.
3249 Uses howtocontinue() to find the active task.
3250
3250
3251 If there's no task (repo.ui.note for 'hg commit'), it does not offer
3251 If there's no task (repo.ui.note for 'hg commit'), it does not offer
3252 a hint.
3252 a hint.
3253 '''
3253 '''
3254 after = howtocontinue(repo)
3254 after = howtocontinue(repo)
3255 hint = None
3255 hint = None
3256 if after[1]:
3256 if after[1]:
3257 hint = after[0]
3257 hint = after[0]
3258 raise error.Abort(_('no %s in progress') % task, hint=hint)
3258 raise error.Abort(_('no %s in progress') % task, hint=hint)
General Comments 0
You need to be logged in to leave comments. Login now