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