##// END OF EJS Templates
py3: fix handling of keyword arguments in revert...
Pulkit Goyal -
r35148:3da4bd50 default
parent child Browse files
Show More
@@ -1,3978 +1,3980 b''
1 # cmdutil.py - help for command processing in mercurial
1 # cmdutil.py - help for command processing in mercurial
2 #
2 #
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 from __future__ import absolute_import
8 from __future__ import absolute_import
9
9
10 import errno
10 import errno
11 import itertools
11 import itertools
12 import os
12 import os
13 import re
13 import re
14 import tempfile
14 import tempfile
15
15
16 from .i18n import _
16 from .i18n import _
17 from .node import (
17 from .node import (
18 hex,
18 hex,
19 nullid,
19 nullid,
20 nullrev,
20 nullrev,
21 short,
21 short,
22 )
22 )
23
23
24 from . import (
24 from . import (
25 bookmarks,
25 bookmarks,
26 changelog,
26 changelog,
27 copies,
27 copies,
28 crecord as crecordmod,
28 crecord as crecordmod,
29 dagop,
29 dagop,
30 dirstateguard,
30 dirstateguard,
31 encoding,
31 encoding,
32 error,
32 error,
33 formatter,
33 formatter,
34 graphmod,
34 graphmod,
35 match as matchmod,
35 match as matchmod,
36 mdiff,
36 mdiff,
37 obsolete,
37 obsolete,
38 patch,
38 patch,
39 pathutil,
39 pathutil,
40 pycompat,
40 pycompat,
41 registrar,
41 registrar,
42 revlog,
42 revlog,
43 revset,
43 revset,
44 scmutil,
44 scmutil,
45 smartset,
45 smartset,
46 templatekw,
46 templatekw,
47 templater,
47 templater,
48 util,
48 util,
49 vfs as vfsmod,
49 vfs as vfsmod,
50 )
50 )
51 stringio = util.stringio
51 stringio = util.stringio
52
52
53 # templates of common command options
53 # templates of common command options
54
54
55 dryrunopts = [
55 dryrunopts = [
56 ('n', 'dry-run', None,
56 ('n', 'dry-run', None,
57 _('do not perform actions, just print output')),
57 _('do not perform actions, just print output')),
58 ]
58 ]
59
59
60 remoteopts = [
60 remoteopts = [
61 ('e', 'ssh', '',
61 ('e', 'ssh', '',
62 _('specify ssh command to use'), _('CMD')),
62 _('specify ssh command to use'), _('CMD')),
63 ('', 'remotecmd', '',
63 ('', 'remotecmd', '',
64 _('specify hg command to run on the remote side'), _('CMD')),
64 _('specify hg command to run on the remote side'), _('CMD')),
65 ('', 'insecure', None,
65 ('', 'insecure', None,
66 _('do not verify server certificate (ignoring web.cacerts config)')),
66 _('do not verify server certificate (ignoring web.cacerts config)')),
67 ]
67 ]
68
68
69 walkopts = [
69 walkopts = [
70 ('I', 'include', [],
70 ('I', 'include', [],
71 _('include names matching the given patterns'), _('PATTERN')),
71 _('include names matching the given patterns'), _('PATTERN')),
72 ('X', 'exclude', [],
72 ('X', 'exclude', [],
73 _('exclude names matching the given patterns'), _('PATTERN')),
73 _('exclude names matching the given patterns'), _('PATTERN')),
74 ]
74 ]
75
75
76 commitopts = [
76 commitopts = [
77 ('m', 'message', '',
77 ('m', 'message', '',
78 _('use text as commit message'), _('TEXT')),
78 _('use text as commit message'), _('TEXT')),
79 ('l', 'logfile', '',
79 ('l', 'logfile', '',
80 _('read commit message from file'), _('FILE')),
80 _('read commit message from file'), _('FILE')),
81 ]
81 ]
82
82
83 commitopts2 = [
83 commitopts2 = [
84 ('d', 'date', '',
84 ('d', 'date', '',
85 _('record the specified date as commit date'), _('DATE')),
85 _('record the specified date as commit date'), _('DATE')),
86 ('u', 'user', '',
86 ('u', 'user', '',
87 _('record the specified user as committer'), _('USER')),
87 _('record the specified user as committer'), _('USER')),
88 ]
88 ]
89
89
90 # hidden for now
90 # hidden for now
91 formatteropts = [
91 formatteropts = [
92 ('T', 'template', '',
92 ('T', 'template', '',
93 _('display with template (EXPERIMENTAL)'), _('TEMPLATE')),
93 _('display with template (EXPERIMENTAL)'), _('TEMPLATE')),
94 ]
94 ]
95
95
96 templateopts = [
96 templateopts = [
97 ('', 'style', '',
97 ('', 'style', '',
98 _('display using template map file (DEPRECATED)'), _('STYLE')),
98 _('display using template map file (DEPRECATED)'), _('STYLE')),
99 ('T', 'template', '',
99 ('T', 'template', '',
100 _('display with template'), _('TEMPLATE')),
100 _('display with template'), _('TEMPLATE')),
101 ]
101 ]
102
102
103 logopts = [
103 logopts = [
104 ('p', 'patch', None, _('show patch')),
104 ('p', 'patch', None, _('show patch')),
105 ('g', 'git', None, _('use git extended diff format')),
105 ('g', 'git', None, _('use git extended diff format')),
106 ('l', 'limit', '',
106 ('l', 'limit', '',
107 _('limit number of changes displayed'), _('NUM')),
107 _('limit number of changes displayed'), _('NUM')),
108 ('M', 'no-merges', None, _('do not show merges')),
108 ('M', 'no-merges', None, _('do not show merges')),
109 ('', 'stat', None, _('output diffstat-style summary of changes')),
109 ('', 'stat', None, _('output diffstat-style summary of changes')),
110 ('G', 'graph', None, _("show the revision DAG")),
110 ('G', 'graph', None, _("show the revision DAG")),
111 ] + templateopts
111 ] + templateopts
112
112
113 diffopts = [
113 diffopts = [
114 ('a', 'text', None, _('treat all files as text')),
114 ('a', 'text', None, _('treat all files as text')),
115 ('g', 'git', None, _('use git extended diff format')),
115 ('g', 'git', None, _('use git extended diff format')),
116 ('', 'binary', None, _('generate binary diffs in git mode (default)')),
116 ('', 'binary', None, _('generate binary diffs in git mode (default)')),
117 ('', 'nodates', None, _('omit dates from diff headers'))
117 ('', 'nodates', None, _('omit dates from diff headers'))
118 ]
118 ]
119
119
120 diffwsopts = [
120 diffwsopts = [
121 ('w', 'ignore-all-space', None,
121 ('w', 'ignore-all-space', None,
122 _('ignore white space when comparing lines')),
122 _('ignore white space when comparing lines')),
123 ('b', 'ignore-space-change', None,
123 ('b', 'ignore-space-change', None,
124 _('ignore changes in the amount of white space')),
124 _('ignore changes in the amount of white space')),
125 ('B', 'ignore-blank-lines', None,
125 ('B', 'ignore-blank-lines', None,
126 _('ignore changes whose lines are all blank')),
126 _('ignore changes whose lines are all blank')),
127 ('Z', 'ignore-space-at-eol', None,
127 ('Z', 'ignore-space-at-eol', None,
128 _('ignore changes in whitespace at EOL')),
128 _('ignore changes in whitespace at EOL')),
129 ]
129 ]
130
130
131 diffopts2 = [
131 diffopts2 = [
132 ('', 'noprefix', None, _('omit a/ and b/ prefixes from filenames')),
132 ('', 'noprefix', None, _('omit a/ and b/ prefixes from filenames')),
133 ('p', 'show-function', None, _('show which function each change is in')),
133 ('p', 'show-function', None, _('show which function each change is in')),
134 ('', 'reverse', None, _('produce a diff that undoes the changes')),
134 ('', 'reverse', None, _('produce a diff that undoes the changes')),
135 ] + diffwsopts + [
135 ] + diffwsopts + [
136 ('U', 'unified', '',
136 ('U', 'unified', '',
137 _('number of lines of context to show'), _('NUM')),
137 _('number of lines of context to show'), _('NUM')),
138 ('', 'stat', None, _('output diffstat-style summary of changes')),
138 ('', 'stat', None, _('output diffstat-style summary of changes')),
139 ('', 'root', '', _('produce diffs relative to subdirectory'), _('DIR')),
139 ('', 'root', '', _('produce diffs relative to subdirectory'), _('DIR')),
140 ]
140 ]
141
141
142 mergetoolopts = [
142 mergetoolopts = [
143 ('t', 'tool', '', _('specify merge tool')),
143 ('t', 'tool', '', _('specify merge tool')),
144 ]
144 ]
145
145
146 similarityopts = [
146 similarityopts = [
147 ('s', 'similarity', '',
147 ('s', 'similarity', '',
148 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
148 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
149 ]
149 ]
150
150
151 subrepoopts = [
151 subrepoopts = [
152 ('S', 'subrepos', None,
152 ('S', 'subrepos', None,
153 _('recurse into subrepositories'))
153 _('recurse into subrepositories'))
154 ]
154 ]
155
155
156 debugrevlogopts = [
156 debugrevlogopts = [
157 ('c', 'changelog', False, _('open changelog')),
157 ('c', 'changelog', False, _('open changelog')),
158 ('m', 'manifest', False, _('open manifest')),
158 ('m', 'manifest', False, _('open manifest')),
159 ('', 'dir', '', _('open directory manifest')),
159 ('', 'dir', '', _('open directory manifest')),
160 ]
160 ]
161
161
162 # special string such that everything below this line will be ingored in the
162 # special string such that everything below this line will be ingored in the
163 # editor text
163 # editor text
164 _linebelow = "^HG: ------------------------ >8 ------------------------$"
164 _linebelow = "^HG: ------------------------ >8 ------------------------$"
165
165
166 def ishunk(x):
166 def ishunk(x):
167 hunkclasses = (crecordmod.uihunk, patch.recordhunk)
167 hunkclasses = (crecordmod.uihunk, patch.recordhunk)
168 return isinstance(x, hunkclasses)
168 return isinstance(x, hunkclasses)
169
169
170 def newandmodified(chunks, originalchunks):
170 def newandmodified(chunks, originalchunks):
171 newlyaddedandmodifiedfiles = set()
171 newlyaddedandmodifiedfiles = set()
172 for chunk in chunks:
172 for chunk in chunks:
173 if ishunk(chunk) and chunk.header.isnewfile() and chunk not in \
173 if ishunk(chunk) and chunk.header.isnewfile() and chunk not in \
174 originalchunks:
174 originalchunks:
175 newlyaddedandmodifiedfiles.add(chunk.header.filename())
175 newlyaddedandmodifiedfiles.add(chunk.header.filename())
176 return newlyaddedandmodifiedfiles
176 return newlyaddedandmodifiedfiles
177
177
178 def parsealiases(cmd):
178 def parsealiases(cmd):
179 return cmd.lstrip("^").split("|")
179 return cmd.lstrip("^").split("|")
180
180
181 def setupwrapcolorwrite(ui):
181 def setupwrapcolorwrite(ui):
182 # wrap ui.write so diff output can be labeled/colorized
182 # wrap ui.write so diff output can be labeled/colorized
183 def wrapwrite(orig, *args, **kw):
183 def wrapwrite(orig, *args, **kw):
184 label = kw.pop('label', '')
184 label = kw.pop('label', '')
185 for chunk, l in patch.difflabel(lambda: args):
185 for chunk, l in patch.difflabel(lambda: args):
186 orig(chunk, label=label + l)
186 orig(chunk, label=label + l)
187
187
188 oldwrite = ui.write
188 oldwrite = ui.write
189 def wrap(*args, **kwargs):
189 def wrap(*args, **kwargs):
190 return wrapwrite(oldwrite, *args, **kwargs)
190 return wrapwrite(oldwrite, *args, **kwargs)
191 setattr(ui, 'write', wrap)
191 setattr(ui, 'write', wrap)
192 return oldwrite
192 return oldwrite
193
193
194 def filterchunks(ui, originalhunks, usecurses, testfile, operation=None):
194 def filterchunks(ui, originalhunks, usecurses, testfile, operation=None):
195 if usecurses:
195 if usecurses:
196 if testfile:
196 if testfile:
197 recordfn = crecordmod.testdecorator(testfile,
197 recordfn = crecordmod.testdecorator(testfile,
198 crecordmod.testchunkselector)
198 crecordmod.testchunkselector)
199 else:
199 else:
200 recordfn = crecordmod.chunkselector
200 recordfn = crecordmod.chunkselector
201
201
202 return crecordmod.filterpatch(ui, originalhunks, recordfn, operation)
202 return crecordmod.filterpatch(ui, originalhunks, recordfn, operation)
203
203
204 else:
204 else:
205 return patch.filterpatch(ui, originalhunks, operation)
205 return patch.filterpatch(ui, originalhunks, operation)
206
206
207 def recordfilter(ui, originalhunks, operation=None):
207 def recordfilter(ui, originalhunks, operation=None):
208 """ Prompts the user to filter the originalhunks and return a list of
208 """ Prompts the user to filter the originalhunks and return a list of
209 selected hunks.
209 selected hunks.
210 *operation* is used for to build ui messages to indicate the user what
210 *operation* is used for to build ui messages to indicate the user what
211 kind of filtering they are doing: reverting, committing, shelving, etc.
211 kind of filtering they are doing: reverting, committing, shelving, etc.
212 (see patch.filterpatch).
212 (see patch.filterpatch).
213 """
213 """
214 usecurses = crecordmod.checkcurses(ui)
214 usecurses = crecordmod.checkcurses(ui)
215 testfile = ui.config('experimental', 'crecordtest')
215 testfile = ui.config('experimental', 'crecordtest')
216 oldwrite = setupwrapcolorwrite(ui)
216 oldwrite = setupwrapcolorwrite(ui)
217 try:
217 try:
218 newchunks, newopts = filterchunks(ui, originalhunks, usecurses,
218 newchunks, newopts = filterchunks(ui, originalhunks, usecurses,
219 testfile, operation)
219 testfile, operation)
220 finally:
220 finally:
221 ui.write = oldwrite
221 ui.write = oldwrite
222 return newchunks, newopts
222 return newchunks, newopts
223
223
224 def dorecord(ui, repo, commitfunc, cmdsuggest, backupall,
224 def dorecord(ui, repo, commitfunc, cmdsuggest, backupall,
225 filterfn, *pats, **opts):
225 filterfn, *pats, **opts):
226 from . import merge as mergemod
226 from . import merge as mergemod
227 opts = pycompat.byteskwargs(opts)
227 opts = pycompat.byteskwargs(opts)
228 if not ui.interactive():
228 if not ui.interactive():
229 if cmdsuggest:
229 if cmdsuggest:
230 msg = _('running non-interactively, use %s instead') % cmdsuggest
230 msg = _('running non-interactively, use %s instead') % cmdsuggest
231 else:
231 else:
232 msg = _('running non-interactively')
232 msg = _('running non-interactively')
233 raise error.Abort(msg)
233 raise error.Abort(msg)
234
234
235 # make sure username is set before going interactive
235 # make sure username is set before going interactive
236 if not opts.get('user'):
236 if not opts.get('user'):
237 ui.username() # raise exception, username not provided
237 ui.username() # raise exception, username not provided
238
238
239 def recordfunc(ui, repo, message, match, opts):
239 def recordfunc(ui, repo, message, match, opts):
240 """This is generic record driver.
240 """This is generic record driver.
241
241
242 Its job is to interactively filter local changes, and
242 Its job is to interactively filter local changes, and
243 accordingly prepare working directory into a state in which the
243 accordingly prepare working directory into a state in which the
244 job can be delegated to a non-interactive commit command such as
244 job can be delegated to a non-interactive commit command such as
245 'commit' or 'qrefresh'.
245 'commit' or 'qrefresh'.
246
246
247 After the actual job is done by non-interactive command, the
247 After the actual job is done by non-interactive command, the
248 working directory is restored to its original state.
248 working directory is restored to its original state.
249
249
250 In the end we'll record interesting changes, and everything else
250 In the end we'll record interesting changes, and everything else
251 will be left in place, so the user can continue working.
251 will be left in place, so the user can continue working.
252 """
252 """
253
253
254 checkunfinished(repo, commit=True)
254 checkunfinished(repo, commit=True)
255 wctx = repo[None]
255 wctx = repo[None]
256 merge = len(wctx.parents()) > 1
256 merge = len(wctx.parents()) > 1
257 if merge:
257 if merge:
258 raise error.Abort(_('cannot partially commit a merge '
258 raise error.Abort(_('cannot partially commit a merge '
259 '(use "hg commit" instead)'))
259 '(use "hg commit" instead)'))
260
260
261 def fail(f, msg):
261 def fail(f, msg):
262 raise error.Abort('%s: %s' % (f, msg))
262 raise error.Abort('%s: %s' % (f, msg))
263
263
264 force = opts.get('force')
264 force = opts.get('force')
265 if not force:
265 if not force:
266 vdirs = []
266 vdirs = []
267 match.explicitdir = vdirs.append
267 match.explicitdir = vdirs.append
268 match.bad = fail
268 match.bad = fail
269
269
270 status = repo.status(match=match)
270 status = repo.status(match=match)
271 if not force:
271 if not force:
272 repo.checkcommitpatterns(wctx, vdirs, match, status, fail)
272 repo.checkcommitpatterns(wctx, vdirs, match, status, fail)
273 diffopts = patch.difffeatureopts(ui, opts=opts, whitespace=True)
273 diffopts = patch.difffeatureopts(ui, opts=opts, whitespace=True)
274 diffopts.nodates = True
274 diffopts.nodates = True
275 diffopts.git = True
275 diffopts.git = True
276 diffopts.showfunc = True
276 diffopts.showfunc = True
277 originaldiff = patch.diff(repo, changes=status, opts=diffopts)
277 originaldiff = patch.diff(repo, changes=status, opts=diffopts)
278 originalchunks = patch.parsepatch(originaldiff)
278 originalchunks = patch.parsepatch(originaldiff)
279
279
280 # 1. filter patch, since we are intending to apply subset of it
280 # 1. filter patch, since we are intending to apply subset of it
281 try:
281 try:
282 chunks, newopts = filterfn(ui, originalchunks)
282 chunks, newopts = filterfn(ui, originalchunks)
283 except error.PatchError as err:
283 except error.PatchError as err:
284 raise error.Abort(_('error parsing patch: %s') % err)
284 raise error.Abort(_('error parsing patch: %s') % err)
285 opts.update(newopts)
285 opts.update(newopts)
286
286
287 # We need to keep a backup of files that have been newly added and
287 # We need to keep a backup of files that have been newly added and
288 # modified during the recording process because there is a previous
288 # modified during the recording process because there is a previous
289 # version without the edit in the workdir
289 # version without the edit in the workdir
290 newlyaddedandmodifiedfiles = newandmodified(chunks, originalchunks)
290 newlyaddedandmodifiedfiles = newandmodified(chunks, originalchunks)
291 contenders = set()
291 contenders = set()
292 for h in chunks:
292 for h in chunks:
293 try:
293 try:
294 contenders.update(set(h.files()))
294 contenders.update(set(h.files()))
295 except AttributeError:
295 except AttributeError:
296 pass
296 pass
297
297
298 changed = status.modified + status.added + status.removed
298 changed = status.modified + status.added + status.removed
299 newfiles = [f for f in changed if f in contenders]
299 newfiles = [f for f in changed if f in contenders]
300 if not newfiles:
300 if not newfiles:
301 ui.status(_('no changes to record\n'))
301 ui.status(_('no changes to record\n'))
302 return 0
302 return 0
303
303
304 modified = set(status.modified)
304 modified = set(status.modified)
305
305
306 # 2. backup changed files, so we can restore them in the end
306 # 2. backup changed files, so we can restore them in the end
307
307
308 if backupall:
308 if backupall:
309 tobackup = changed
309 tobackup = changed
310 else:
310 else:
311 tobackup = [f for f in newfiles if f in modified or f in \
311 tobackup = [f for f in newfiles if f in modified or f in \
312 newlyaddedandmodifiedfiles]
312 newlyaddedandmodifiedfiles]
313 backups = {}
313 backups = {}
314 if tobackup:
314 if tobackup:
315 backupdir = repo.vfs.join('record-backups')
315 backupdir = repo.vfs.join('record-backups')
316 try:
316 try:
317 os.mkdir(backupdir)
317 os.mkdir(backupdir)
318 except OSError as err:
318 except OSError as err:
319 if err.errno != errno.EEXIST:
319 if err.errno != errno.EEXIST:
320 raise
320 raise
321 try:
321 try:
322 # backup continues
322 # backup continues
323 for f in tobackup:
323 for f in tobackup:
324 fd, tmpname = tempfile.mkstemp(prefix=f.replace('/', '_')+'.',
324 fd, tmpname = tempfile.mkstemp(prefix=f.replace('/', '_')+'.',
325 dir=backupdir)
325 dir=backupdir)
326 os.close(fd)
326 os.close(fd)
327 ui.debug('backup %r as %r\n' % (f, tmpname))
327 ui.debug('backup %r as %r\n' % (f, tmpname))
328 util.copyfile(repo.wjoin(f), tmpname, copystat=True)
328 util.copyfile(repo.wjoin(f), tmpname, copystat=True)
329 backups[f] = tmpname
329 backups[f] = tmpname
330
330
331 fp = stringio()
331 fp = stringio()
332 for c in chunks:
332 for c in chunks:
333 fname = c.filename()
333 fname = c.filename()
334 if fname in backups:
334 if fname in backups:
335 c.write(fp)
335 c.write(fp)
336 dopatch = fp.tell()
336 dopatch = fp.tell()
337 fp.seek(0)
337 fp.seek(0)
338
338
339 # 2.5 optionally review / modify patch in text editor
339 # 2.5 optionally review / modify patch in text editor
340 if opts.get('review', False):
340 if opts.get('review', False):
341 patchtext = (crecordmod.diffhelptext
341 patchtext = (crecordmod.diffhelptext
342 + crecordmod.patchhelptext
342 + crecordmod.patchhelptext
343 + fp.read())
343 + fp.read())
344 reviewedpatch = ui.edit(patchtext, "",
344 reviewedpatch = ui.edit(patchtext, "",
345 action="diff",
345 action="diff",
346 repopath=repo.path)
346 repopath=repo.path)
347 fp.truncate(0)
347 fp.truncate(0)
348 fp.write(reviewedpatch)
348 fp.write(reviewedpatch)
349 fp.seek(0)
349 fp.seek(0)
350
350
351 [os.unlink(repo.wjoin(c)) for c in newlyaddedandmodifiedfiles]
351 [os.unlink(repo.wjoin(c)) for c in newlyaddedandmodifiedfiles]
352 # 3a. apply filtered patch to clean repo (clean)
352 # 3a. apply filtered patch to clean repo (clean)
353 if backups:
353 if backups:
354 # Equivalent to hg.revert
354 # Equivalent to hg.revert
355 m = scmutil.matchfiles(repo, backups.keys())
355 m = scmutil.matchfiles(repo, backups.keys())
356 mergemod.update(repo, repo.dirstate.p1(),
356 mergemod.update(repo, repo.dirstate.p1(),
357 False, True, matcher=m)
357 False, True, matcher=m)
358
358
359 # 3b. (apply)
359 # 3b. (apply)
360 if dopatch:
360 if dopatch:
361 try:
361 try:
362 ui.debug('applying patch\n')
362 ui.debug('applying patch\n')
363 ui.debug(fp.getvalue())
363 ui.debug(fp.getvalue())
364 patch.internalpatch(ui, repo, fp, 1, eolmode=None)
364 patch.internalpatch(ui, repo, fp, 1, eolmode=None)
365 except error.PatchError as err:
365 except error.PatchError as err:
366 raise error.Abort(str(err))
366 raise error.Abort(str(err))
367 del fp
367 del fp
368
368
369 # 4. We prepared working directory according to filtered
369 # 4. We prepared working directory according to filtered
370 # patch. Now is the time to delegate the job to
370 # patch. Now is the time to delegate the job to
371 # commit/qrefresh or the like!
371 # commit/qrefresh or the like!
372
372
373 # Make all of the pathnames absolute.
373 # Make all of the pathnames absolute.
374 newfiles = [repo.wjoin(nf) for nf in newfiles]
374 newfiles = [repo.wjoin(nf) for nf in newfiles]
375 return commitfunc(ui, repo, *newfiles, **opts)
375 return commitfunc(ui, repo, *newfiles, **opts)
376 finally:
376 finally:
377 # 5. finally restore backed-up files
377 # 5. finally restore backed-up files
378 try:
378 try:
379 dirstate = repo.dirstate
379 dirstate = repo.dirstate
380 for realname, tmpname in backups.iteritems():
380 for realname, tmpname in backups.iteritems():
381 ui.debug('restoring %r to %r\n' % (tmpname, realname))
381 ui.debug('restoring %r to %r\n' % (tmpname, realname))
382
382
383 if dirstate[realname] == 'n':
383 if dirstate[realname] == 'n':
384 # without normallookup, restoring timestamp
384 # without normallookup, restoring timestamp
385 # may cause partially committed files
385 # may cause partially committed files
386 # to be treated as unmodified
386 # to be treated as unmodified
387 dirstate.normallookup(realname)
387 dirstate.normallookup(realname)
388
388
389 # copystat=True here and above are a hack to trick any
389 # copystat=True here and above are a hack to trick any
390 # editors that have f open that we haven't modified them.
390 # editors that have f open that we haven't modified them.
391 #
391 #
392 # Also note that this racy as an editor could notice the
392 # Also note that this racy as an editor could notice the
393 # file's mtime before we've finished writing it.
393 # file's mtime before we've finished writing it.
394 util.copyfile(tmpname, repo.wjoin(realname), copystat=True)
394 util.copyfile(tmpname, repo.wjoin(realname), copystat=True)
395 os.unlink(tmpname)
395 os.unlink(tmpname)
396 if tobackup:
396 if tobackup:
397 os.rmdir(backupdir)
397 os.rmdir(backupdir)
398 except OSError:
398 except OSError:
399 pass
399 pass
400
400
401 def recordinwlock(ui, repo, message, match, opts):
401 def recordinwlock(ui, repo, message, match, opts):
402 with repo.wlock():
402 with repo.wlock():
403 return recordfunc(ui, repo, message, match, opts)
403 return recordfunc(ui, repo, message, match, opts)
404
404
405 return commit(ui, repo, recordinwlock, pats, opts)
405 return commit(ui, repo, recordinwlock, pats, opts)
406
406
407 class dirnode(object):
407 class dirnode(object):
408 """
408 """
409 Represent a directory in user working copy with information required for
409 Represent a directory in user working copy with information required for
410 the purpose of tersing its status.
410 the purpose of tersing its status.
411
411
412 path is the path to the directory
412 path is the path to the directory
413
413
414 statuses is a set of statuses of all files in this directory (this includes
414 statuses is a set of statuses of all files in this directory (this includes
415 all the files in all the subdirectories too)
415 all the files in all the subdirectories too)
416
416
417 files is a list of files which are direct child of this directory
417 files is a list of files which are direct child of this directory
418
418
419 subdirs is a dictionary of sub-directory name as the key and it's own
419 subdirs is a dictionary of sub-directory name as the key and it's own
420 dirnode object as the value
420 dirnode object as the value
421 """
421 """
422
422
423 def __init__(self, dirpath):
423 def __init__(self, dirpath):
424 self.path = dirpath
424 self.path = dirpath
425 self.statuses = set([])
425 self.statuses = set([])
426 self.files = []
426 self.files = []
427 self.subdirs = {}
427 self.subdirs = {}
428
428
429 def _addfileindir(self, filename, status):
429 def _addfileindir(self, filename, status):
430 """Add a file in this directory as a direct child."""
430 """Add a file in this directory as a direct child."""
431 self.files.append((filename, status))
431 self.files.append((filename, status))
432
432
433 def addfile(self, filename, status):
433 def addfile(self, filename, status):
434 """
434 """
435 Add a file to this directory or to its direct parent directory.
435 Add a file to this directory or to its direct parent directory.
436
436
437 If the file is not direct child of this directory, we traverse to the
437 If the file is not direct child of this directory, we traverse to the
438 directory of which this file is a direct child of and add the file
438 directory of which this file is a direct child of and add the file
439 there.
439 there.
440 """
440 """
441
441
442 # the filename contains a path separator, it means it's not the direct
442 # the filename contains a path separator, it means it's not the direct
443 # child of this directory
443 # child of this directory
444 if '/' in filename:
444 if '/' in filename:
445 subdir, filep = filename.split('/', 1)
445 subdir, filep = filename.split('/', 1)
446
446
447 # does the dirnode object for subdir exists
447 # does the dirnode object for subdir exists
448 if subdir not in self.subdirs:
448 if subdir not in self.subdirs:
449 subdirpath = os.path.join(self.path, subdir)
449 subdirpath = os.path.join(self.path, subdir)
450 self.subdirs[subdir] = dirnode(subdirpath)
450 self.subdirs[subdir] = dirnode(subdirpath)
451
451
452 # try adding the file in subdir
452 # try adding the file in subdir
453 self.subdirs[subdir].addfile(filep, status)
453 self.subdirs[subdir].addfile(filep, status)
454
454
455 else:
455 else:
456 self._addfileindir(filename, status)
456 self._addfileindir(filename, status)
457
457
458 if status not in self.statuses:
458 if status not in self.statuses:
459 self.statuses.add(status)
459 self.statuses.add(status)
460
460
461 def iterfilepaths(self):
461 def iterfilepaths(self):
462 """Yield (status, path) for files directly under this directory."""
462 """Yield (status, path) for files directly under this directory."""
463 for f, st in self.files:
463 for f, st in self.files:
464 yield st, os.path.join(self.path, f)
464 yield st, os.path.join(self.path, f)
465
465
466 def tersewalk(self, terseargs):
466 def tersewalk(self, terseargs):
467 """
467 """
468 Yield (status, path) obtained by processing the status of this
468 Yield (status, path) obtained by processing the status of this
469 dirnode.
469 dirnode.
470
470
471 terseargs is the string of arguments passed by the user with `--terse`
471 terseargs is the string of arguments passed by the user with `--terse`
472 flag.
472 flag.
473
473
474 Following are the cases which can happen:
474 Following are the cases which can happen:
475
475
476 1) All the files in the directory (including all the files in its
476 1) All the files in the directory (including all the files in its
477 subdirectories) share the same status and the user has asked us to terse
477 subdirectories) share the same status and the user has asked us to terse
478 that status. -> yield (status, dirpath)
478 that status. -> yield (status, dirpath)
479
479
480 2) Otherwise, we do following:
480 2) Otherwise, we do following:
481
481
482 a) Yield (status, filepath) for all the files which are in this
482 a) Yield (status, filepath) for all the files which are in this
483 directory (only the ones in this directory, not the subdirs)
483 directory (only the ones in this directory, not the subdirs)
484
484
485 b) Recurse the function on all the subdirectories of this
485 b) Recurse the function on all the subdirectories of this
486 directory
486 directory
487 """
487 """
488
488
489 if len(self.statuses) == 1:
489 if len(self.statuses) == 1:
490 onlyst = self.statuses.pop()
490 onlyst = self.statuses.pop()
491
491
492 # Making sure we terse only when the status abbreviation is
492 # Making sure we terse only when the status abbreviation is
493 # passed as terse argument
493 # passed as terse argument
494 if onlyst in terseargs:
494 if onlyst in terseargs:
495 yield onlyst, self.path + pycompat.ossep
495 yield onlyst, self.path + pycompat.ossep
496 return
496 return
497
497
498 # add the files to status list
498 # add the files to status list
499 for st, fpath in self.iterfilepaths():
499 for st, fpath in self.iterfilepaths():
500 yield st, fpath
500 yield st, fpath
501
501
502 #recurse on the subdirs
502 #recurse on the subdirs
503 for dirobj in self.subdirs.values():
503 for dirobj in self.subdirs.values():
504 for st, fpath in dirobj.tersewalk(terseargs):
504 for st, fpath in dirobj.tersewalk(terseargs):
505 yield st, fpath
505 yield st, fpath
506
506
507 def tersedir(statuslist, terseargs):
507 def tersedir(statuslist, terseargs):
508 """
508 """
509 Terse the status if all the files in a directory shares the same status.
509 Terse the status if all the files in a directory shares the same status.
510
510
511 statuslist is scmutil.status() object which contains a list of files for
511 statuslist is scmutil.status() object which contains a list of files for
512 each status.
512 each status.
513 terseargs is string which is passed by the user as the argument to `--terse`
513 terseargs is string which is passed by the user as the argument to `--terse`
514 flag.
514 flag.
515
515
516 The function makes a tree of objects of dirnode class, and at each node it
516 The function makes a tree of objects of dirnode class, and at each node it
517 stores the information required to know whether we can terse a certain
517 stores the information required to know whether we can terse a certain
518 directory or not.
518 directory or not.
519 """
519 """
520 # the order matters here as that is used to produce final list
520 # the order matters here as that is used to produce final list
521 allst = ('m', 'a', 'r', 'd', 'u', 'i', 'c')
521 allst = ('m', 'a', 'r', 'd', 'u', 'i', 'c')
522
522
523 # checking the argument validity
523 # checking the argument validity
524 for s in pycompat.bytestr(terseargs):
524 for s in pycompat.bytestr(terseargs):
525 if s not in allst:
525 if s not in allst:
526 raise error.Abort(_("'%s' not recognized") % s)
526 raise error.Abort(_("'%s' not recognized") % s)
527
527
528 # creating a dirnode object for the root of the repo
528 # creating a dirnode object for the root of the repo
529 rootobj = dirnode('')
529 rootobj = dirnode('')
530 pstatus = ('modified', 'added', 'deleted', 'clean', 'unknown',
530 pstatus = ('modified', 'added', 'deleted', 'clean', 'unknown',
531 'ignored', 'removed')
531 'ignored', 'removed')
532
532
533 tersedict = {}
533 tersedict = {}
534 for attrname in pstatus:
534 for attrname in pstatus:
535 statuschar = attrname[0:1]
535 statuschar = attrname[0:1]
536 for f in getattr(statuslist, attrname):
536 for f in getattr(statuslist, attrname):
537 rootobj.addfile(f, statuschar)
537 rootobj.addfile(f, statuschar)
538 tersedict[statuschar] = []
538 tersedict[statuschar] = []
539
539
540 # we won't be tersing the root dir, so add files in it
540 # we won't be tersing the root dir, so add files in it
541 for st, fpath in rootobj.iterfilepaths():
541 for st, fpath in rootobj.iterfilepaths():
542 tersedict[st].append(fpath)
542 tersedict[st].append(fpath)
543
543
544 # process each sub-directory and build tersedict
544 # process each sub-directory and build tersedict
545 for subdir in rootobj.subdirs.values():
545 for subdir in rootobj.subdirs.values():
546 for st, f in subdir.tersewalk(terseargs):
546 for st, f in subdir.tersewalk(terseargs):
547 tersedict[st].append(f)
547 tersedict[st].append(f)
548
548
549 tersedlist = []
549 tersedlist = []
550 for st in allst:
550 for st in allst:
551 tersedict[st].sort()
551 tersedict[st].sort()
552 tersedlist.append(tersedict[st])
552 tersedlist.append(tersedict[st])
553
553
554 return tersedlist
554 return tersedlist
555
555
556 def _commentlines(raw):
556 def _commentlines(raw):
557 '''Surround lineswith a comment char and a new line'''
557 '''Surround lineswith a comment char and a new line'''
558 lines = raw.splitlines()
558 lines = raw.splitlines()
559 commentedlines = ['# %s' % line for line in lines]
559 commentedlines = ['# %s' % line for line in lines]
560 return '\n'.join(commentedlines) + '\n'
560 return '\n'.join(commentedlines) + '\n'
561
561
562 def _conflictsmsg(repo):
562 def _conflictsmsg(repo):
563 # avoid merge cycle
563 # avoid merge cycle
564 from . import merge as mergemod
564 from . import merge as mergemod
565 mergestate = mergemod.mergestate.read(repo)
565 mergestate = mergemod.mergestate.read(repo)
566 if not mergestate.active():
566 if not mergestate.active():
567 return
567 return
568
568
569 m = scmutil.match(repo[None])
569 m = scmutil.match(repo[None])
570 unresolvedlist = [f for f in mergestate.unresolved() if m(f)]
570 unresolvedlist = [f for f in mergestate.unresolved() if m(f)]
571 if unresolvedlist:
571 if unresolvedlist:
572 mergeliststr = '\n'.join(
572 mergeliststr = '\n'.join(
573 [' %s' % util.pathto(repo.root, pycompat.getcwd(), path)
573 [' %s' % util.pathto(repo.root, pycompat.getcwd(), path)
574 for path in unresolvedlist])
574 for path in unresolvedlist])
575 msg = _('''Unresolved merge conflicts:
575 msg = _('''Unresolved merge conflicts:
576
576
577 %s
577 %s
578
578
579 To mark files as resolved: hg resolve --mark FILE''') % mergeliststr
579 To mark files as resolved: hg resolve --mark FILE''') % mergeliststr
580 else:
580 else:
581 msg = _('No unresolved merge conflicts.')
581 msg = _('No unresolved merge conflicts.')
582
582
583 return _commentlines(msg)
583 return _commentlines(msg)
584
584
585 def _helpmessage(continuecmd, abortcmd):
585 def _helpmessage(continuecmd, abortcmd):
586 msg = _('To continue: %s\n'
586 msg = _('To continue: %s\n'
587 'To abort: %s') % (continuecmd, abortcmd)
587 'To abort: %s') % (continuecmd, abortcmd)
588 return _commentlines(msg)
588 return _commentlines(msg)
589
589
590 def _rebasemsg():
590 def _rebasemsg():
591 return _helpmessage('hg rebase --continue', 'hg rebase --abort')
591 return _helpmessage('hg rebase --continue', 'hg rebase --abort')
592
592
593 def _histeditmsg():
593 def _histeditmsg():
594 return _helpmessage('hg histedit --continue', 'hg histedit --abort')
594 return _helpmessage('hg histedit --continue', 'hg histedit --abort')
595
595
596 def _unshelvemsg():
596 def _unshelvemsg():
597 return _helpmessage('hg unshelve --continue', 'hg unshelve --abort')
597 return _helpmessage('hg unshelve --continue', 'hg unshelve --abort')
598
598
599 def _updatecleanmsg(dest=None):
599 def _updatecleanmsg(dest=None):
600 warning = _('warning: this will discard uncommitted changes')
600 warning = _('warning: this will discard uncommitted changes')
601 return 'hg update --clean %s (%s)' % (dest or '.', warning)
601 return 'hg update --clean %s (%s)' % (dest or '.', warning)
602
602
603 def _graftmsg():
603 def _graftmsg():
604 # tweakdefaults requires `update` to have a rev hence the `.`
604 # tweakdefaults requires `update` to have a rev hence the `.`
605 return _helpmessage('hg graft --continue', _updatecleanmsg())
605 return _helpmessage('hg graft --continue', _updatecleanmsg())
606
606
607 def _mergemsg():
607 def _mergemsg():
608 # tweakdefaults requires `update` to have a rev hence the `.`
608 # tweakdefaults requires `update` to have a rev hence the `.`
609 return _helpmessage('hg commit', _updatecleanmsg())
609 return _helpmessage('hg commit', _updatecleanmsg())
610
610
611 def _bisectmsg():
611 def _bisectmsg():
612 msg = _('To mark the changeset good: hg bisect --good\n'
612 msg = _('To mark the changeset good: hg bisect --good\n'
613 'To mark the changeset bad: hg bisect --bad\n'
613 'To mark the changeset bad: hg bisect --bad\n'
614 'To abort: hg bisect --reset\n')
614 'To abort: hg bisect --reset\n')
615 return _commentlines(msg)
615 return _commentlines(msg)
616
616
617 def fileexistspredicate(filename):
617 def fileexistspredicate(filename):
618 return lambda repo: repo.vfs.exists(filename)
618 return lambda repo: repo.vfs.exists(filename)
619
619
620 def _mergepredicate(repo):
620 def _mergepredicate(repo):
621 return len(repo[None].parents()) > 1
621 return len(repo[None].parents()) > 1
622
622
623 STATES = (
623 STATES = (
624 # (state, predicate to detect states, helpful message function)
624 # (state, predicate to detect states, helpful message function)
625 ('histedit', fileexistspredicate('histedit-state'), _histeditmsg),
625 ('histedit', fileexistspredicate('histedit-state'), _histeditmsg),
626 ('bisect', fileexistspredicate('bisect.state'), _bisectmsg),
626 ('bisect', fileexistspredicate('bisect.state'), _bisectmsg),
627 ('graft', fileexistspredicate('graftstate'), _graftmsg),
627 ('graft', fileexistspredicate('graftstate'), _graftmsg),
628 ('unshelve', fileexistspredicate('unshelverebasestate'), _unshelvemsg),
628 ('unshelve', fileexistspredicate('unshelverebasestate'), _unshelvemsg),
629 ('rebase', fileexistspredicate('rebasestate'), _rebasemsg),
629 ('rebase', fileexistspredicate('rebasestate'), _rebasemsg),
630 # The merge state is part of a list that will be iterated over.
630 # The merge state is part of a list that will be iterated over.
631 # They need to be last because some of the other unfinished states may also
631 # They need to be last because some of the other unfinished states may also
632 # be in a merge or update state (eg. rebase, histedit, graft, etc).
632 # be in a merge or update state (eg. rebase, histedit, graft, etc).
633 # We want those to have priority.
633 # We want those to have priority.
634 ('merge', _mergepredicate, _mergemsg),
634 ('merge', _mergepredicate, _mergemsg),
635 )
635 )
636
636
637 def _getrepostate(repo):
637 def _getrepostate(repo):
638 # experimental config: commands.status.skipstates
638 # experimental config: commands.status.skipstates
639 skip = set(repo.ui.configlist('commands', 'status.skipstates'))
639 skip = set(repo.ui.configlist('commands', 'status.skipstates'))
640 for state, statedetectionpredicate, msgfn in STATES:
640 for state, statedetectionpredicate, msgfn in STATES:
641 if state in skip:
641 if state in skip:
642 continue
642 continue
643 if statedetectionpredicate(repo):
643 if statedetectionpredicate(repo):
644 return (state, statedetectionpredicate, msgfn)
644 return (state, statedetectionpredicate, msgfn)
645
645
646 def morestatus(repo, fm):
646 def morestatus(repo, fm):
647 statetuple = _getrepostate(repo)
647 statetuple = _getrepostate(repo)
648 label = 'status.morestatus'
648 label = 'status.morestatus'
649 if statetuple:
649 if statetuple:
650 fm.startitem()
650 fm.startitem()
651 state, statedetectionpredicate, helpfulmsg = statetuple
651 state, statedetectionpredicate, helpfulmsg = statetuple
652 statemsg = _('The repository is in an unfinished *%s* state.') % state
652 statemsg = _('The repository is in an unfinished *%s* state.') % state
653 fm.write('statemsg', '%s\n', _commentlines(statemsg), label=label)
653 fm.write('statemsg', '%s\n', _commentlines(statemsg), label=label)
654 conmsg = _conflictsmsg(repo)
654 conmsg = _conflictsmsg(repo)
655 if conmsg:
655 if conmsg:
656 fm.write('conflictsmsg', '%s\n', conmsg, label=label)
656 fm.write('conflictsmsg', '%s\n', conmsg, label=label)
657 if helpfulmsg:
657 if helpfulmsg:
658 helpmsg = helpfulmsg()
658 helpmsg = helpfulmsg()
659 fm.write('helpmsg', '%s\n', helpmsg, label=label)
659 fm.write('helpmsg', '%s\n', helpmsg, label=label)
660
660
661 def findpossible(cmd, table, strict=False):
661 def findpossible(cmd, table, strict=False):
662 """
662 """
663 Return cmd -> (aliases, command table entry)
663 Return cmd -> (aliases, command table entry)
664 for each matching command.
664 for each matching command.
665 Return debug commands (or their aliases) only if no normal command matches.
665 Return debug commands (or their aliases) only if no normal command matches.
666 """
666 """
667 choice = {}
667 choice = {}
668 debugchoice = {}
668 debugchoice = {}
669
669
670 if cmd in table:
670 if cmd in table:
671 # short-circuit exact matches, "log" alias beats "^log|history"
671 # short-circuit exact matches, "log" alias beats "^log|history"
672 keys = [cmd]
672 keys = [cmd]
673 else:
673 else:
674 keys = table.keys()
674 keys = table.keys()
675
675
676 allcmds = []
676 allcmds = []
677 for e in keys:
677 for e in keys:
678 aliases = parsealiases(e)
678 aliases = parsealiases(e)
679 allcmds.extend(aliases)
679 allcmds.extend(aliases)
680 found = None
680 found = None
681 if cmd in aliases:
681 if cmd in aliases:
682 found = cmd
682 found = cmd
683 elif not strict:
683 elif not strict:
684 for a in aliases:
684 for a in aliases:
685 if a.startswith(cmd):
685 if a.startswith(cmd):
686 found = a
686 found = a
687 break
687 break
688 if found is not None:
688 if found is not None:
689 if aliases[0].startswith("debug") or found.startswith("debug"):
689 if aliases[0].startswith("debug") or found.startswith("debug"):
690 debugchoice[found] = (aliases, table[e])
690 debugchoice[found] = (aliases, table[e])
691 else:
691 else:
692 choice[found] = (aliases, table[e])
692 choice[found] = (aliases, table[e])
693
693
694 if not choice and debugchoice:
694 if not choice and debugchoice:
695 choice = debugchoice
695 choice = debugchoice
696
696
697 return choice, allcmds
697 return choice, allcmds
698
698
699 def findcmd(cmd, table, strict=True):
699 def findcmd(cmd, table, strict=True):
700 """Return (aliases, command table entry) for command string."""
700 """Return (aliases, command table entry) for command string."""
701 choice, allcmds = findpossible(cmd, table, strict)
701 choice, allcmds = findpossible(cmd, table, strict)
702
702
703 if cmd in choice:
703 if cmd in choice:
704 return choice[cmd]
704 return choice[cmd]
705
705
706 if len(choice) > 1:
706 if len(choice) > 1:
707 clist = sorted(choice)
707 clist = sorted(choice)
708 raise error.AmbiguousCommand(cmd, clist)
708 raise error.AmbiguousCommand(cmd, clist)
709
709
710 if choice:
710 if choice:
711 return list(choice.values())[0]
711 return list(choice.values())[0]
712
712
713 raise error.UnknownCommand(cmd, allcmds)
713 raise error.UnknownCommand(cmd, allcmds)
714
714
715 def findrepo(p):
715 def findrepo(p):
716 while not os.path.isdir(os.path.join(p, ".hg")):
716 while not os.path.isdir(os.path.join(p, ".hg")):
717 oldp, p = p, os.path.dirname(p)
717 oldp, p = p, os.path.dirname(p)
718 if p == oldp:
718 if p == oldp:
719 return None
719 return None
720
720
721 return p
721 return p
722
722
723 def bailifchanged(repo, merge=True, hint=None):
723 def bailifchanged(repo, merge=True, hint=None):
724 """ enforce the precondition that working directory must be clean.
724 """ enforce the precondition that working directory must be clean.
725
725
726 'merge' can be set to false if a pending uncommitted merge should be
726 'merge' can be set to false if a pending uncommitted merge should be
727 ignored (such as when 'update --check' runs).
727 ignored (such as when 'update --check' runs).
728
728
729 'hint' is the usual hint given to Abort exception.
729 'hint' is the usual hint given to Abort exception.
730 """
730 """
731
731
732 if merge and repo.dirstate.p2() != nullid:
732 if merge and repo.dirstate.p2() != nullid:
733 raise error.Abort(_('outstanding uncommitted merge'), hint=hint)
733 raise error.Abort(_('outstanding uncommitted merge'), hint=hint)
734 modified, added, removed, deleted = repo.status()[:4]
734 modified, added, removed, deleted = repo.status()[:4]
735 if modified or added or removed or deleted:
735 if modified or added or removed or deleted:
736 raise error.Abort(_('uncommitted changes'), hint=hint)
736 raise error.Abort(_('uncommitted changes'), hint=hint)
737 ctx = repo[None]
737 ctx = repo[None]
738 for s in sorted(ctx.substate):
738 for s in sorted(ctx.substate):
739 ctx.sub(s).bailifchanged(hint=hint)
739 ctx.sub(s).bailifchanged(hint=hint)
740
740
741 def logmessage(ui, opts):
741 def logmessage(ui, opts):
742 """ get the log message according to -m and -l option """
742 """ get the log message according to -m and -l option """
743 message = opts.get('message')
743 message = opts.get('message')
744 logfile = opts.get('logfile')
744 logfile = opts.get('logfile')
745
745
746 if message and logfile:
746 if message and logfile:
747 raise error.Abort(_('options --message and --logfile are mutually '
747 raise error.Abort(_('options --message and --logfile are mutually '
748 'exclusive'))
748 'exclusive'))
749 if not message and logfile:
749 if not message and logfile:
750 try:
750 try:
751 if isstdiofilename(logfile):
751 if isstdiofilename(logfile):
752 message = ui.fin.read()
752 message = ui.fin.read()
753 else:
753 else:
754 message = '\n'.join(util.readfile(logfile).splitlines())
754 message = '\n'.join(util.readfile(logfile).splitlines())
755 except IOError as inst:
755 except IOError as inst:
756 raise error.Abort(_("can't read commit message '%s': %s") %
756 raise error.Abort(_("can't read commit message '%s': %s") %
757 (logfile, encoding.strtolocal(inst.strerror)))
757 (logfile, encoding.strtolocal(inst.strerror)))
758 return message
758 return message
759
759
760 def mergeeditform(ctxorbool, baseformname):
760 def mergeeditform(ctxorbool, baseformname):
761 """return appropriate editform name (referencing a committemplate)
761 """return appropriate editform name (referencing a committemplate)
762
762
763 'ctxorbool' is either a ctx to be committed, or a bool indicating whether
763 'ctxorbool' is either a ctx to be committed, or a bool indicating whether
764 merging is committed.
764 merging is committed.
765
765
766 This returns baseformname with '.merge' appended if it is a merge,
766 This returns baseformname with '.merge' appended if it is a merge,
767 otherwise '.normal' is appended.
767 otherwise '.normal' is appended.
768 """
768 """
769 if isinstance(ctxorbool, bool):
769 if isinstance(ctxorbool, bool):
770 if ctxorbool:
770 if ctxorbool:
771 return baseformname + ".merge"
771 return baseformname + ".merge"
772 elif 1 < len(ctxorbool.parents()):
772 elif 1 < len(ctxorbool.parents()):
773 return baseformname + ".merge"
773 return baseformname + ".merge"
774
774
775 return baseformname + ".normal"
775 return baseformname + ".normal"
776
776
777 def getcommiteditor(edit=False, finishdesc=None, extramsg=None,
777 def getcommiteditor(edit=False, finishdesc=None, extramsg=None,
778 editform='', **opts):
778 editform='', **opts):
779 """get appropriate commit message editor according to '--edit' option
779 """get appropriate commit message editor according to '--edit' option
780
780
781 'finishdesc' is a function to be called with edited commit message
781 'finishdesc' is a function to be called with edited commit message
782 (= 'description' of the new changeset) just after editing, but
782 (= 'description' of the new changeset) just after editing, but
783 before checking empty-ness. It should return actual text to be
783 before checking empty-ness. It should return actual text to be
784 stored into history. This allows to change description before
784 stored into history. This allows to change description before
785 storing.
785 storing.
786
786
787 'extramsg' is a extra message to be shown in the editor instead of
787 'extramsg' is a extra message to be shown in the editor instead of
788 'Leave message empty to abort commit' line. 'HG: ' prefix and EOL
788 'Leave message empty to abort commit' line. 'HG: ' prefix and EOL
789 is automatically added.
789 is automatically added.
790
790
791 'editform' is a dot-separated list of names, to distinguish
791 'editform' is a dot-separated list of names, to distinguish
792 the purpose of commit text editing.
792 the purpose of commit text editing.
793
793
794 'getcommiteditor' returns 'commitforceeditor' regardless of
794 'getcommiteditor' returns 'commitforceeditor' regardless of
795 'edit', if one of 'finishdesc' or 'extramsg' is specified, because
795 'edit', if one of 'finishdesc' or 'extramsg' is specified, because
796 they are specific for usage in MQ.
796 they are specific for usage in MQ.
797 """
797 """
798 if edit or finishdesc or extramsg:
798 if edit or finishdesc or extramsg:
799 return lambda r, c, s: commitforceeditor(r, c, s,
799 return lambda r, c, s: commitforceeditor(r, c, s,
800 finishdesc=finishdesc,
800 finishdesc=finishdesc,
801 extramsg=extramsg,
801 extramsg=extramsg,
802 editform=editform)
802 editform=editform)
803 elif editform:
803 elif editform:
804 return lambda r, c, s: commiteditor(r, c, s, editform=editform)
804 return lambda r, c, s: commiteditor(r, c, s, editform=editform)
805 else:
805 else:
806 return commiteditor
806 return commiteditor
807
807
808 def loglimit(opts):
808 def loglimit(opts):
809 """get the log limit according to option -l/--limit"""
809 """get the log limit according to option -l/--limit"""
810 limit = opts.get('limit')
810 limit = opts.get('limit')
811 if limit:
811 if limit:
812 try:
812 try:
813 limit = int(limit)
813 limit = int(limit)
814 except ValueError:
814 except ValueError:
815 raise error.Abort(_('limit must be a positive integer'))
815 raise error.Abort(_('limit must be a positive integer'))
816 if limit <= 0:
816 if limit <= 0:
817 raise error.Abort(_('limit must be positive'))
817 raise error.Abort(_('limit must be positive'))
818 else:
818 else:
819 limit = None
819 limit = None
820 return limit
820 return limit
821
821
822 def makefilename(repo, pat, node, desc=None,
822 def makefilename(repo, pat, node, desc=None,
823 total=None, seqno=None, revwidth=None, pathname=None):
823 total=None, seqno=None, revwidth=None, pathname=None):
824 node_expander = {
824 node_expander = {
825 'H': lambda: hex(node),
825 'H': lambda: hex(node),
826 'R': lambda: str(repo.changelog.rev(node)),
826 'R': lambda: str(repo.changelog.rev(node)),
827 'h': lambda: short(node),
827 'h': lambda: short(node),
828 'm': lambda: re.sub('[^\w]', '_', str(desc))
828 'm': lambda: re.sub('[^\w]', '_', str(desc))
829 }
829 }
830 expander = {
830 expander = {
831 '%': lambda: '%',
831 '%': lambda: '%',
832 'b': lambda: os.path.basename(repo.root),
832 'b': lambda: os.path.basename(repo.root),
833 }
833 }
834
834
835 try:
835 try:
836 if node:
836 if node:
837 expander.update(node_expander)
837 expander.update(node_expander)
838 if node:
838 if node:
839 expander['r'] = (lambda:
839 expander['r'] = (lambda:
840 str(repo.changelog.rev(node)).zfill(revwidth or 0))
840 str(repo.changelog.rev(node)).zfill(revwidth or 0))
841 if total is not None:
841 if total is not None:
842 expander['N'] = lambda: str(total)
842 expander['N'] = lambda: str(total)
843 if seqno is not None:
843 if seqno is not None:
844 expander['n'] = lambda: str(seqno)
844 expander['n'] = lambda: str(seqno)
845 if total is not None and seqno is not None:
845 if total is not None and seqno is not None:
846 expander['n'] = lambda: str(seqno).zfill(len(str(total)))
846 expander['n'] = lambda: str(seqno).zfill(len(str(total)))
847 if pathname is not None:
847 if pathname is not None:
848 expander['s'] = lambda: os.path.basename(pathname)
848 expander['s'] = lambda: os.path.basename(pathname)
849 expander['d'] = lambda: os.path.dirname(pathname) or '.'
849 expander['d'] = lambda: os.path.dirname(pathname) or '.'
850 expander['p'] = lambda: pathname
850 expander['p'] = lambda: pathname
851
851
852 newname = []
852 newname = []
853 patlen = len(pat)
853 patlen = len(pat)
854 i = 0
854 i = 0
855 while i < patlen:
855 while i < patlen:
856 c = pat[i:i + 1]
856 c = pat[i:i + 1]
857 if c == '%':
857 if c == '%':
858 i += 1
858 i += 1
859 c = pat[i:i + 1]
859 c = pat[i:i + 1]
860 c = expander[c]()
860 c = expander[c]()
861 newname.append(c)
861 newname.append(c)
862 i += 1
862 i += 1
863 return ''.join(newname)
863 return ''.join(newname)
864 except KeyError as inst:
864 except KeyError as inst:
865 raise error.Abort(_("invalid format spec '%%%s' in output filename") %
865 raise error.Abort(_("invalid format spec '%%%s' in output filename") %
866 inst.args[0])
866 inst.args[0])
867
867
868 def isstdiofilename(pat):
868 def isstdiofilename(pat):
869 """True if the given pat looks like a filename denoting stdin/stdout"""
869 """True if the given pat looks like a filename denoting stdin/stdout"""
870 return not pat or pat == '-'
870 return not pat or pat == '-'
871
871
872 class _unclosablefile(object):
872 class _unclosablefile(object):
873 def __init__(self, fp):
873 def __init__(self, fp):
874 self._fp = fp
874 self._fp = fp
875
875
876 def close(self):
876 def close(self):
877 pass
877 pass
878
878
879 def __iter__(self):
879 def __iter__(self):
880 return iter(self._fp)
880 return iter(self._fp)
881
881
882 def __getattr__(self, attr):
882 def __getattr__(self, attr):
883 return getattr(self._fp, attr)
883 return getattr(self._fp, attr)
884
884
885 def __enter__(self):
885 def __enter__(self):
886 return self
886 return self
887
887
888 def __exit__(self, exc_type, exc_value, exc_tb):
888 def __exit__(self, exc_type, exc_value, exc_tb):
889 pass
889 pass
890
890
891 def makefileobj(repo, pat, node=None, desc=None, total=None,
891 def makefileobj(repo, pat, node=None, desc=None, total=None,
892 seqno=None, revwidth=None, mode='wb', modemap=None,
892 seqno=None, revwidth=None, mode='wb', modemap=None,
893 pathname=None):
893 pathname=None):
894
894
895 writable = mode not in ('r', 'rb')
895 writable = mode not in ('r', 'rb')
896
896
897 if isstdiofilename(pat):
897 if isstdiofilename(pat):
898 if writable:
898 if writable:
899 fp = repo.ui.fout
899 fp = repo.ui.fout
900 else:
900 else:
901 fp = repo.ui.fin
901 fp = repo.ui.fin
902 return _unclosablefile(fp)
902 return _unclosablefile(fp)
903 fn = makefilename(repo, pat, node, desc, total, seqno, revwidth, pathname)
903 fn = makefilename(repo, pat, node, desc, total, seqno, revwidth, pathname)
904 if modemap is not None:
904 if modemap is not None:
905 mode = modemap.get(fn, mode)
905 mode = modemap.get(fn, mode)
906 if mode == 'wb':
906 if mode == 'wb':
907 modemap[fn] = 'ab'
907 modemap[fn] = 'ab'
908 return open(fn, mode)
908 return open(fn, mode)
909
909
910 def openrevlog(repo, cmd, file_, opts):
910 def openrevlog(repo, cmd, file_, opts):
911 """opens the changelog, manifest, a filelog or a given revlog"""
911 """opens the changelog, manifest, a filelog or a given revlog"""
912 cl = opts['changelog']
912 cl = opts['changelog']
913 mf = opts['manifest']
913 mf = opts['manifest']
914 dir = opts['dir']
914 dir = opts['dir']
915 msg = None
915 msg = None
916 if cl and mf:
916 if cl and mf:
917 msg = _('cannot specify --changelog and --manifest at the same time')
917 msg = _('cannot specify --changelog and --manifest at the same time')
918 elif cl and dir:
918 elif cl and dir:
919 msg = _('cannot specify --changelog and --dir at the same time')
919 msg = _('cannot specify --changelog and --dir at the same time')
920 elif cl or mf or dir:
920 elif cl or mf or dir:
921 if file_:
921 if file_:
922 msg = _('cannot specify filename with --changelog or --manifest')
922 msg = _('cannot specify filename with --changelog or --manifest')
923 elif not repo:
923 elif not repo:
924 msg = _('cannot specify --changelog or --manifest or --dir '
924 msg = _('cannot specify --changelog or --manifest or --dir '
925 'without a repository')
925 'without a repository')
926 if msg:
926 if msg:
927 raise error.Abort(msg)
927 raise error.Abort(msg)
928
928
929 r = None
929 r = None
930 if repo:
930 if repo:
931 if cl:
931 if cl:
932 r = repo.unfiltered().changelog
932 r = repo.unfiltered().changelog
933 elif dir:
933 elif dir:
934 if 'treemanifest' not in repo.requirements:
934 if 'treemanifest' not in repo.requirements:
935 raise error.Abort(_("--dir can only be used on repos with "
935 raise error.Abort(_("--dir can only be used on repos with "
936 "treemanifest enabled"))
936 "treemanifest enabled"))
937 dirlog = repo.manifestlog._revlog.dirlog(dir)
937 dirlog = repo.manifestlog._revlog.dirlog(dir)
938 if len(dirlog):
938 if len(dirlog):
939 r = dirlog
939 r = dirlog
940 elif mf:
940 elif mf:
941 r = repo.manifestlog._revlog
941 r = repo.manifestlog._revlog
942 elif file_:
942 elif file_:
943 filelog = repo.file(file_)
943 filelog = repo.file(file_)
944 if len(filelog):
944 if len(filelog):
945 r = filelog
945 r = filelog
946 if not r:
946 if not r:
947 if not file_:
947 if not file_:
948 raise error.CommandError(cmd, _('invalid arguments'))
948 raise error.CommandError(cmd, _('invalid arguments'))
949 if not os.path.isfile(file_):
949 if not os.path.isfile(file_):
950 raise error.Abort(_("revlog '%s' not found") % file_)
950 raise error.Abort(_("revlog '%s' not found") % file_)
951 r = revlog.revlog(vfsmod.vfs(pycompat.getcwd(), audit=False),
951 r = revlog.revlog(vfsmod.vfs(pycompat.getcwd(), audit=False),
952 file_[:-2] + ".i")
952 file_[:-2] + ".i")
953 return r
953 return r
954
954
955 def copy(ui, repo, pats, opts, rename=False):
955 def copy(ui, repo, pats, opts, rename=False):
956 # called with the repo lock held
956 # called with the repo lock held
957 #
957 #
958 # hgsep => pathname that uses "/" to separate directories
958 # hgsep => pathname that uses "/" to separate directories
959 # ossep => pathname that uses os.sep to separate directories
959 # ossep => pathname that uses os.sep to separate directories
960 cwd = repo.getcwd()
960 cwd = repo.getcwd()
961 targets = {}
961 targets = {}
962 after = opts.get("after")
962 after = opts.get("after")
963 dryrun = opts.get("dry_run")
963 dryrun = opts.get("dry_run")
964 wctx = repo[None]
964 wctx = repo[None]
965
965
966 def walkpat(pat):
966 def walkpat(pat):
967 srcs = []
967 srcs = []
968 if after:
968 if after:
969 badstates = '?'
969 badstates = '?'
970 else:
970 else:
971 badstates = '?r'
971 badstates = '?r'
972 m = scmutil.match(wctx, [pat], opts, globbed=True)
972 m = scmutil.match(wctx, [pat], opts, globbed=True)
973 for abs in wctx.walk(m):
973 for abs in wctx.walk(m):
974 state = repo.dirstate[abs]
974 state = repo.dirstate[abs]
975 rel = m.rel(abs)
975 rel = m.rel(abs)
976 exact = m.exact(abs)
976 exact = m.exact(abs)
977 if state in badstates:
977 if state in badstates:
978 if exact and state == '?':
978 if exact and state == '?':
979 ui.warn(_('%s: not copying - file is not managed\n') % rel)
979 ui.warn(_('%s: not copying - file is not managed\n') % rel)
980 if exact and state == 'r':
980 if exact and state == 'r':
981 ui.warn(_('%s: not copying - file has been marked for'
981 ui.warn(_('%s: not copying - file has been marked for'
982 ' remove\n') % rel)
982 ' remove\n') % rel)
983 continue
983 continue
984 # abs: hgsep
984 # abs: hgsep
985 # rel: ossep
985 # rel: ossep
986 srcs.append((abs, rel, exact))
986 srcs.append((abs, rel, exact))
987 return srcs
987 return srcs
988
988
989 # abssrc: hgsep
989 # abssrc: hgsep
990 # relsrc: ossep
990 # relsrc: ossep
991 # otarget: ossep
991 # otarget: ossep
992 def copyfile(abssrc, relsrc, otarget, exact):
992 def copyfile(abssrc, relsrc, otarget, exact):
993 abstarget = pathutil.canonpath(repo.root, cwd, otarget)
993 abstarget = pathutil.canonpath(repo.root, cwd, otarget)
994 if '/' in abstarget:
994 if '/' in abstarget:
995 # We cannot normalize abstarget itself, this would prevent
995 # We cannot normalize abstarget itself, this would prevent
996 # case only renames, like a => A.
996 # case only renames, like a => A.
997 abspath, absname = abstarget.rsplit('/', 1)
997 abspath, absname = abstarget.rsplit('/', 1)
998 abstarget = repo.dirstate.normalize(abspath) + '/' + absname
998 abstarget = repo.dirstate.normalize(abspath) + '/' + absname
999 reltarget = repo.pathto(abstarget, cwd)
999 reltarget = repo.pathto(abstarget, cwd)
1000 target = repo.wjoin(abstarget)
1000 target = repo.wjoin(abstarget)
1001 src = repo.wjoin(abssrc)
1001 src = repo.wjoin(abssrc)
1002 state = repo.dirstate[abstarget]
1002 state = repo.dirstate[abstarget]
1003
1003
1004 scmutil.checkportable(ui, abstarget)
1004 scmutil.checkportable(ui, abstarget)
1005
1005
1006 # check for collisions
1006 # check for collisions
1007 prevsrc = targets.get(abstarget)
1007 prevsrc = targets.get(abstarget)
1008 if prevsrc is not None:
1008 if prevsrc is not None:
1009 ui.warn(_('%s: not overwriting - %s collides with %s\n') %
1009 ui.warn(_('%s: not overwriting - %s collides with %s\n') %
1010 (reltarget, repo.pathto(abssrc, cwd),
1010 (reltarget, repo.pathto(abssrc, cwd),
1011 repo.pathto(prevsrc, cwd)))
1011 repo.pathto(prevsrc, cwd)))
1012 return
1012 return
1013
1013
1014 # check for overwrites
1014 # check for overwrites
1015 exists = os.path.lexists(target)
1015 exists = os.path.lexists(target)
1016 samefile = False
1016 samefile = False
1017 if exists and abssrc != abstarget:
1017 if exists and abssrc != abstarget:
1018 if (repo.dirstate.normalize(abssrc) ==
1018 if (repo.dirstate.normalize(abssrc) ==
1019 repo.dirstate.normalize(abstarget)):
1019 repo.dirstate.normalize(abstarget)):
1020 if not rename:
1020 if not rename:
1021 ui.warn(_("%s: can't copy - same file\n") % reltarget)
1021 ui.warn(_("%s: can't copy - same file\n") % reltarget)
1022 return
1022 return
1023 exists = False
1023 exists = False
1024 samefile = True
1024 samefile = True
1025
1025
1026 if not after and exists or after and state in 'mn':
1026 if not after and exists or after and state in 'mn':
1027 if not opts['force']:
1027 if not opts['force']:
1028 if state in 'mn':
1028 if state in 'mn':
1029 msg = _('%s: not overwriting - file already committed\n')
1029 msg = _('%s: not overwriting - file already committed\n')
1030 if after:
1030 if after:
1031 flags = '--after --force'
1031 flags = '--after --force'
1032 else:
1032 else:
1033 flags = '--force'
1033 flags = '--force'
1034 if rename:
1034 if rename:
1035 hint = _('(hg rename %s to replace the file by '
1035 hint = _('(hg rename %s to replace the file by '
1036 'recording a rename)\n') % flags
1036 'recording a rename)\n') % flags
1037 else:
1037 else:
1038 hint = _('(hg copy %s to replace the file by '
1038 hint = _('(hg copy %s to replace the file by '
1039 'recording a copy)\n') % flags
1039 'recording a copy)\n') % flags
1040 else:
1040 else:
1041 msg = _('%s: not overwriting - file exists\n')
1041 msg = _('%s: not overwriting - file exists\n')
1042 if rename:
1042 if rename:
1043 hint = _('(hg rename --after to record the rename)\n')
1043 hint = _('(hg rename --after to record the rename)\n')
1044 else:
1044 else:
1045 hint = _('(hg copy --after to record the copy)\n')
1045 hint = _('(hg copy --after to record the copy)\n')
1046 ui.warn(msg % reltarget)
1046 ui.warn(msg % reltarget)
1047 ui.warn(hint)
1047 ui.warn(hint)
1048 return
1048 return
1049
1049
1050 if after:
1050 if after:
1051 if not exists:
1051 if not exists:
1052 if rename:
1052 if rename:
1053 ui.warn(_('%s: not recording move - %s does not exist\n') %
1053 ui.warn(_('%s: not recording move - %s does not exist\n') %
1054 (relsrc, reltarget))
1054 (relsrc, reltarget))
1055 else:
1055 else:
1056 ui.warn(_('%s: not recording copy - %s does not exist\n') %
1056 ui.warn(_('%s: not recording copy - %s does not exist\n') %
1057 (relsrc, reltarget))
1057 (relsrc, reltarget))
1058 return
1058 return
1059 elif not dryrun:
1059 elif not dryrun:
1060 try:
1060 try:
1061 if exists:
1061 if exists:
1062 os.unlink(target)
1062 os.unlink(target)
1063 targetdir = os.path.dirname(target) or '.'
1063 targetdir = os.path.dirname(target) or '.'
1064 if not os.path.isdir(targetdir):
1064 if not os.path.isdir(targetdir):
1065 os.makedirs(targetdir)
1065 os.makedirs(targetdir)
1066 if samefile:
1066 if samefile:
1067 tmp = target + "~hgrename"
1067 tmp = target + "~hgrename"
1068 os.rename(src, tmp)
1068 os.rename(src, tmp)
1069 os.rename(tmp, target)
1069 os.rename(tmp, target)
1070 else:
1070 else:
1071 util.copyfile(src, target)
1071 util.copyfile(src, target)
1072 srcexists = True
1072 srcexists = True
1073 except IOError as inst:
1073 except IOError as inst:
1074 if inst.errno == errno.ENOENT:
1074 if inst.errno == errno.ENOENT:
1075 ui.warn(_('%s: deleted in working directory\n') % relsrc)
1075 ui.warn(_('%s: deleted in working directory\n') % relsrc)
1076 srcexists = False
1076 srcexists = False
1077 else:
1077 else:
1078 ui.warn(_('%s: cannot copy - %s\n') %
1078 ui.warn(_('%s: cannot copy - %s\n') %
1079 (relsrc, encoding.strtolocal(inst.strerror)))
1079 (relsrc, encoding.strtolocal(inst.strerror)))
1080 return True # report a failure
1080 return True # report a failure
1081
1081
1082 if ui.verbose or not exact:
1082 if ui.verbose or not exact:
1083 if rename:
1083 if rename:
1084 ui.status(_('moving %s to %s\n') % (relsrc, reltarget))
1084 ui.status(_('moving %s to %s\n') % (relsrc, reltarget))
1085 else:
1085 else:
1086 ui.status(_('copying %s to %s\n') % (relsrc, reltarget))
1086 ui.status(_('copying %s to %s\n') % (relsrc, reltarget))
1087
1087
1088 targets[abstarget] = abssrc
1088 targets[abstarget] = abssrc
1089
1089
1090 # fix up dirstate
1090 # fix up dirstate
1091 scmutil.dirstatecopy(ui, repo, wctx, abssrc, abstarget,
1091 scmutil.dirstatecopy(ui, repo, wctx, abssrc, abstarget,
1092 dryrun=dryrun, cwd=cwd)
1092 dryrun=dryrun, cwd=cwd)
1093 if rename and not dryrun:
1093 if rename and not dryrun:
1094 if not after and srcexists and not samefile:
1094 if not after and srcexists and not samefile:
1095 repo.wvfs.unlinkpath(abssrc)
1095 repo.wvfs.unlinkpath(abssrc)
1096 wctx.forget([abssrc])
1096 wctx.forget([abssrc])
1097
1097
1098 # pat: ossep
1098 # pat: ossep
1099 # dest ossep
1099 # dest ossep
1100 # srcs: list of (hgsep, hgsep, ossep, bool)
1100 # srcs: list of (hgsep, hgsep, ossep, bool)
1101 # return: function that takes hgsep and returns ossep
1101 # return: function that takes hgsep and returns ossep
1102 def targetpathfn(pat, dest, srcs):
1102 def targetpathfn(pat, dest, srcs):
1103 if os.path.isdir(pat):
1103 if os.path.isdir(pat):
1104 abspfx = pathutil.canonpath(repo.root, cwd, pat)
1104 abspfx = pathutil.canonpath(repo.root, cwd, pat)
1105 abspfx = util.localpath(abspfx)
1105 abspfx = util.localpath(abspfx)
1106 if destdirexists:
1106 if destdirexists:
1107 striplen = len(os.path.split(abspfx)[0])
1107 striplen = len(os.path.split(abspfx)[0])
1108 else:
1108 else:
1109 striplen = len(abspfx)
1109 striplen = len(abspfx)
1110 if striplen:
1110 if striplen:
1111 striplen += len(pycompat.ossep)
1111 striplen += len(pycompat.ossep)
1112 res = lambda p: os.path.join(dest, util.localpath(p)[striplen:])
1112 res = lambda p: os.path.join(dest, util.localpath(p)[striplen:])
1113 elif destdirexists:
1113 elif destdirexists:
1114 res = lambda p: os.path.join(dest,
1114 res = lambda p: os.path.join(dest,
1115 os.path.basename(util.localpath(p)))
1115 os.path.basename(util.localpath(p)))
1116 else:
1116 else:
1117 res = lambda p: dest
1117 res = lambda p: dest
1118 return res
1118 return res
1119
1119
1120 # pat: ossep
1120 # pat: ossep
1121 # dest ossep
1121 # dest ossep
1122 # srcs: list of (hgsep, hgsep, ossep, bool)
1122 # srcs: list of (hgsep, hgsep, ossep, bool)
1123 # return: function that takes hgsep and returns ossep
1123 # return: function that takes hgsep and returns ossep
1124 def targetpathafterfn(pat, dest, srcs):
1124 def targetpathafterfn(pat, dest, srcs):
1125 if matchmod.patkind(pat):
1125 if matchmod.patkind(pat):
1126 # a mercurial pattern
1126 # a mercurial pattern
1127 res = lambda p: os.path.join(dest,
1127 res = lambda p: os.path.join(dest,
1128 os.path.basename(util.localpath(p)))
1128 os.path.basename(util.localpath(p)))
1129 else:
1129 else:
1130 abspfx = pathutil.canonpath(repo.root, cwd, pat)
1130 abspfx = pathutil.canonpath(repo.root, cwd, pat)
1131 if len(abspfx) < len(srcs[0][0]):
1131 if len(abspfx) < len(srcs[0][0]):
1132 # A directory. Either the target path contains the last
1132 # A directory. Either the target path contains the last
1133 # component of the source path or it does not.
1133 # component of the source path or it does not.
1134 def evalpath(striplen):
1134 def evalpath(striplen):
1135 score = 0
1135 score = 0
1136 for s in srcs:
1136 for s in srcs:
1137 t = os.path.join(dest, util.localpath(s[0])[striplen:])
1137 t = os.path.join(dest, util.localpath(s[0])[striplen:])
1138 if os.path.lexists(t):
1138 if os.path.lexists(t):
1139 score += 1
1139 score += 1
1140 return score
1140 return score
1141
1141
1142 abspfx = util.localpath(abspfx)
1142 abspfx = util.localpath(abspfx)
1143 striplen = len(abspfx)
1143 striplen = len(abspfx)
1144 if striplen:
1144 if striplen:
1145 striplen += len(pycompat.ossep)
1145 striplen += len(pycompat.ossep)
1146 if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])):
1146 if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])):
1147 score = evalpath(striplen)
1147 score = evalpath(striplen)
1148 striplen1 = len(os.path.split(abspfx)[0])
1148 striplen1 = len(os.path.split(abspfx)[0])
1149 if striplen1:
1149 if striplen1:
1150 striplen1 += len(pycompat.ossep)
1150 striplen1 += len(pycompat.ossep)
1151 if evalpath(striplen1) > score:
1151 if evalpath(striplen1) > score:
1152 striplen = striplen1
1152 striplen = striplen1
1153 res = lambda p: os.path.join(dest,
1153 res = lambda p: os.path.join(dest,
1154 util.localpath(p)[striplen:])
1154 util.localpath(p)[striplen:])
1155 else:
1155 else:
1156 # a file
1156 # a file
1157 if destdirexists:
1157 if destdirexists:
1158 res = lambda p: os.path.join(dest,
1158 res = lambda p: os.path.join(dest,
1159 os.path.basename(util.localpath(p)))
1159 os.path.basename(util.localpath(p)))
1160 else:
1160 else:
1161 res = lambda p: dest
1161 res = lambda p: dest
1162 return res
1162 return res
1163
1163
1164 pats = scmutil.expandpats(pats)
1164 pats = scmutil.expandpats(pats)
1165 if not pats:
1165 if not pats:
1166 raise error.Abort(_('no source or destination specified'))
1166 raise error.Abort(_('no source or destination specified'))
1167 if len(pats) == 1:
1167 if len(pats) == 1:
1168 raise error.Abort(_('no destination specified'))
1168 raise error.Abort(_('no destination specified'))
1169 dest = pats.pop()
1169 dest = pats.pop()
1170 destdirexists = os.path.isdir(dest) and not os.path.islink(dest)
1170 destdirexists = os.path.isdir(dest) and not os.path.islink(dest)
1171 if not destdirexists:
1171 if not destdirexists:
1172 if len(pats) > 1 or matchmod.patkind(pats[0]):
1172 if len(pats) > 1 or matchmod.patkind(pats[0]):
1173 raise error.Abort(_('with multiple sources, destination must be an '
1173 raise error.Abort(_('with multiple sources, destination must be an '
1174 'existing directory'))
1174 'existing directory'))
1175 if util.endswithsep(dest):
1175 if util.endswithsep(dest):
1176 raise error.Abort(_('destination %s is not a directory') % dest)
1176 raise error.Abort(_('destination %s is not a directory') % dest)
1177
1177
1178 tfn = targetpathfn
1178 tfn = targetpathfn
1179 if after:
1179 if after:
1180 tfn = targetpathafterfn
1180 tfn = targetpathafterfn
1181 copylist = []
1181 copylist = []
1182 for pat in pats:
1182 for pat in pats:
1183 srcs = walkpat(pat)
1183 srcs = walkpat(pat)
1184 if not srcs:
1184 if not srcs:
1185 continue
1185 continue
1186 copylist.append((tfn(pat, dest, srcs), srcs))
1186 copylist.append((tfn(pat, dest, srcs), srcs))
1187 if not copylist:
1187 if not copylist:
1188 raise error.Abort(_('no files to copy'))
1188 raise error.Abort(_('no files to copy'))
1189
1189
1190 errors = 0
1190 errors = 0
1191 for targetpath, srcs in copylist:
1191 for targetpath, srcs in copylist:
1192 for abssrc, relsrc, exact in srcs:
1192 for abssrc, relsrc, exact in srcs:
1193 if copyfile(abssrc, relsrc, targetpath(abssrc), exact):
1193 if copyfile(abssrc, relsrc, targetpath(abssrc), exact):
1194 errors += 1
1194 errors += 1
1195
1195
1196 if errors:
1196 if errors:
1197 ui.warn(_('(consider using --after)\n'))
1197 ui.warn(_('(consider using --after)\n'))
1198
1198
1199 return errors != 0
1199 return errors != 0
1200
1200
1201 ## facility to let extension process additional data into an import patch
1201 ## facility to let extension process additional data into an import patch
1202 # list of identifier to be executed in order
1202 # list of identifier to be executed in order
1203 extrapreimport = [] # run before commit
1203 extrapreimport = [] # run before commit
1204 extrapostimport = [] # run after commit
1204 extrapostimport = [] # run after commit
1205 # mapping from identifier to actual import function
1205 # mapping from identifier to actual import function
1206 #
1206 #
1207 # 'preimport' are run before the commit is made and are provided the following
1207 # 'preimport' are run before the commit is made and are provided the following
1208 # arguments:
1208 # arguments:
1209 # - repo: the localrepository instance,
1209 # - repo: the localrepository instance,
1210 # - patchdata: data extracted from patch header (cf m.patch.patchheadermap),
1210 # - patchdata: data extracted from patch header (cf m.patch.patchheadermap),
1211 # - extra: the future extra dictionary of the changeset, please mutate it,
1211 # - extra: the future extra dictionary of the changeset, please mutate it,
1212 # - opts: the import options.
1212 # - opts: the import options.
1213 # XXX ideally, we would just pass an ctx ready to be computed, that would allow
1213 # XXX ideally, we would just pass an ctx ready to be computed, that would allow
1214 # mutation of in memory commit and more. Feel free to rework the code to get
1214 # mutation of in memory commit and more. Feel free to rework the code to get
1215 # there.
1215 # there.
1216 extrapreimportmap = {}
1216 extrapreimportmap = {}
1217 # 'postimport' are run after the commit is made and are provided the following
1217 # 'postimport' are run after the commit is made and are provided the following
1218 # argument:
1218 # argument:
1219 # - ctx: the changectx created by import.
1219 # - ctx: the changectx created by import.
1220 extrapostimportmap = {}
1220 extrapostimportmap = {}
1221
1221
1222 def tryimportone(ui, repo, hunk, parents, opts, msgs, updatefunc):
1222 def tryimportone(ui, repo, hunk, parents, opts, msgs, updatefunc):
1223 """Utility function used by commands.import to import a single patch
1223 """Utility function used by commands.import to import a single patch
1224
1224
1225 This function is explicitly defined here to help the evolve extension to
1225 This function is explicitly defined here to help the evolve extension to
1226 wrap this part of the import logic.
1226 wrap this part of the import logic.
1227
1227
1228 The API is currently a bit ugly because it a simple code translation from
1228 The API is currently a bit ugly because it a simple code translation from
1229 the import command. Feel free to make it better.
1229 the import command. Feel free to make it better.
1230
1230
1231 :hunk: a patch (as a binary string)
1231 :hunk: a patch (as a binary string)
1232 :parents: nodes that will be parent of the created commit
1232 :parents: nodes that will be parent of the created commit
1233 :opts: the full dict of option passed to the import command
1233 :opts: the full dict of option passed to the import command
1234 :msgs: list to save commit message to.
1234 :msgs: list to save commit message to.
1235 (used in case we need to save it when failing)
1235 (used in case we need to save it when failing)
1236 :updatefunc: a function that update a repo to a given node
1236 :updatefunc: a function that update a repo to a given node
1237 updatefunc(<repo>, <node>)
1237 updatefunc(<repo>, <node>)
1238 """
1238 """
1239 # avoid cycle context -> subrepo -> cmdutil
1239 # avoid cycle context -> subrepo -> cmdutil
1240 from . import context
1240 from . import context
1241 extractdata = patch.extract(ui, hunk)
1241 extractdata = patch.extract(ui, hunk)
1242 tmpname = extractdata.get('filename')
1242 tmpname = extractdata.get('filename')
1243 message = extractdata.get('message')
1243 message = extractdata.get('message')
1244 user = opts.get('user') or extractdata.get('user')
1244 user = opts.get('user') or extractdata.get('user')
1245 date = opts.get('date') or extractdata.get('date')
1245 date = opts.get('date') or extractdata.get('date')
1246 branch = extractdata.get('branch')
1246 branch = extractdata.get('branch')
1247 nodeid = extractdata.get('nodeid')
1247 nodeid = extractdata.get('nodeid')
1248 p1 = extractdata.get('p1')
1248 p1 = extractdata.get('p1')
1249 p2 = extractdata.get('p2')
1249 p2 = extractdata.get('p2')
1250
1250
1251 nocommit = opts.get('no_commit')
1251 nocommit = opts.get('no_commit')
1252 importbranch = opts.get('import_branch')
1252 importbranch = opts.get('import_branch')
1253 update = not opts.get('bypass')
1253 update = not opts.get('bypass')
1254 strip = opts["strip"]
1254 strip = opts["strip"]
1255 prefix = opts["prefix"]
1255 prefix = opts["prefix"]
1256 sim = float(opts.get('similarity') or 0)
1256 sim = float(opts.get('similarity') or 0)
1257 if not tmpname:
1257 if not tmpname:
1258 return (None, None, False)
1258 return (None, None, False)
1259
1259
1260 rejects = False
1260 rejects = False
1261
1261
1262 try:
1262 try:
1263 cmdline_message = logmessage(ui, opts)
1263 cmdline_message = logmessage(ui, opts)
1264 if cmdline_message:
1264 if cmdline_message:
1265 # pickup the cmdline msg
1265 # pickup the cmdline msg
1266 message = cmdline_message
1266 message = cmdline_message
1267 elif message:
1267 elif message:
1268 # pickup the patch msg
1268 # pickup the patch msg
1269 message = message.strip()
1269 message = message.strip()
1270 else:
1270 else:
1271 # launch the editor
1271 # launch the editor
1272 message = None
1272 message = None
1273 ui.debug('message:\n%s\n' % message)
1273 ui.debug('message:\n%s\n' % message)
1274
1274
1275 if len(parents) == 1:
1275 if len(parents) == 1:
1276 parents.append(repo[nullid])
1276 parents.append(repo[nullid])
1277 if opts.get('exact'):
1277 if opts.get('exact'):
1278 if not nodeid or not p1:
1278 if not nodeid or not p1:
1279 raise error.Abort(_('not a Mercurial patch'))
1279 raise error.Abort(_('not a Mercurial patch'))
1280 p1 = repo[p1]
1280 p1 = repo[p1]
1281 p2 = repo[p2 or nullid]
1281 p2 = repo[p2 or nullid]
1282 elif p2:
1282 elif p2:
1283 try:
1283 try:
1284 p1 = repo[p1]
1284 p1 = repo[p1]
1285 p2 = repo[p2]
1285 p2 = repo[p2]
1286 # Without any options, consider p2 only if the
1286 # Without any options, consider p2 only if the
1287 # patch is being applied on top of the recorded
1287 # patch is being applied on top of the recorded
1288 # first parent.
1288 # first parent.
1289 if p1 != parents[0]:
1289 if p1 != parents[0]:
1290 p1 = parents[0]
1290 p1 = parents[0]
1291 p2 = repo[nullid]
1291 p2 = repo[nullid]
1292 except error.RepoError:
1292 except error.RepoError:
1293 p1, p2 = parents
1293 p1, p2 = parents
1294 if p2.node() == nullid:
1294 if p2.node() == nullid:
1295 ui.warn(_("warning: import the patch as a normal revision\n"
1295 ui.warn(_("warning: import the patch as a normal revision\n"
1296 "(use --exact to import the patch as a merge)\n"))
1296 "(use --exact to import the patch as a merge)\n"))
1297 else:
1297 else:
1298 p1, p2 = parents
1298 p1, p2 = parents
1299
1299
1300 n = None
1300 n = None
1301 if update:
1301 if update:
1302 if p1 != parents[0]:
1302 if p1 != parents[0]:
1303 updatefunc(repo, p1.node())
1303 updatefunc(repo, p1.node())
1304 if p2 != parents[1]:
1304 if p2 != parents[1]:
1305 repo.setparents(p1.node(), p2.node())
1305 repo.setparents(p1.node(), p2.node())
1306
1306
1307 if opts.get('exact') or importbranch:
1307 if opts.get('exact') or importbranch:
1308 repo.dirstate.setbranch(branch or 'default')
1308 repo.dirstate.setbranch(branch or 'default')
1309
1309
1310 partial = opts.get('partial', False)
1310 partial = opts.get('partial', False)
1311 files = set()
1311 files = set()
1312 try:
1312 try:
1313 patch.patch(ui, repo, tmpname, strip=strip, prefix=prefix,
1313 patch.patch(ui, repo, tmpname, strip=strip, prefix=prefix,
1314 files=files, eolmode=None, similarity=sim / 100.0)
1314 files=files, eolmode=None, similarity=sim / 100.0)
1315 except error.PatchError as e:
1315 except error.PatchError as e:
1316 if not partial:
1316 if not partial:
1317 raise error.Abort(str(e))
1317 raise error.Abort(str(e))
1318 if partial:
1318 if partial:
1319 rejects = True
1319 rejects = True
1320
1320
1321 files = list(files)
1321 files = list(files)
1322 if nocommit:
1322 if nocommit:
1323 if message:
1323 if message:
1324 msgs.append(message)
1324 msgs.append(message)
1325 else:
1325 else:
1326 if opts.get('exact') or p2:
1326 if opts.get('exact') or p2:
1327 # If you got here, you either use --force and know what
1327 # If you got here, you either use --force and know what
1328 # you are doing or used --exact or a merge patch while
1328 # you are doing or used --exact or a merge patch while
1329 # being updated to its first parent.
1329 # being updated to its first parent.
1330 m = None
1330 m = None
1331 else:
1331 else:
1332 m = scmutil.matchfiles(repo, files or [])
1332 m = scmutil.matchfiles(repo, files or [])
1333 editform = mergeeditform(repo[None], 'import.normal')
1333 editform = mergeeditform(repo[None], 'import.normal')
1334 if opts.get('exact'):
1334 if opts.get('exact'):
1335 editor = None
1335 editor = None
1336 else:
1336 else:
1337 editor = getcommiteditor(editform=editform, **opts)
1337 editor = getcommiteditor(editform=editform, **opts)
1338 extra = {}
1338 extra = {}
1339 for idfunc in extrapreimport:
1339 for idfunc in extrapreimport:
1340 extrapreimportmap[idfunc](repo, extractdata, extra, opts)
1340 extrapreimportmap[idfunc](repo, extractdata, extra, opts)
1341 overrides = {}
1341 overrides = {}
1342 if partial:
1342 if partial:
1343 overrides[('ui', 'allowemptycommit')] = True
1343 overrides[('ui', 'allowemptycommit')] = True
1344 with repo.ui.configoverride(overrides, 'import'):
1344 with repo.ui.configoverride(overrides, 'import'):
1345 n = repo.commit(message, user,
1345 n = repo.commit(message, user,
1346 date, match=m,
1346 date, match=m,
1347 editor=editor, extra=extra)
1347 editor=editor, extra=extra)
1348 for idfunc in extrapostimport:
1348 for idfunc in extrapostimport:
1349 extrapostimportmap[idfunc](repo[n])
1349 extrapostimportmap[idfunc](repo[n])
1350 else:
1350 else:
1351 if opts.get('exact') or importbranch:
1351 if opts.get('exact') or importbranch:
1352 branch = branch or 'default'
1352 branch = branch or 'default'
1353 else:
1353 else:
1354 branch = p1.branch()
1354 branch = p1.branch()
1355 store = patch.filestore()
1355 store = patch.filestore()
1356 try:
1356 try:
1357 files = set()
1357 files = set()
1358 try:
1358 try:
1359 patch.patchrepo(ui, repo, p1, store, tmpname, strip, prefix,
1359 patch.patchrepo(ui, repo, p1, store, tmpname, strip, prefix,
1360 files, eolmode=None)
1360 files, eolmode=None)
1361 except error.PatchError as e:
1361 except error.PatchError as e:
1362 raise error.Abort(str(e))
1362 raise error.Abort(str(e))
1363 if opts.get('exact'):
1363 if opts.get('exact'):
1364 editor = None
1364 editor = None
1365 else:
1365 else:
1366 editor = getcommiteditor(editform='import.bypass')
1366 editor = getcommiteditor(editform='import.bypass')
1367 memctx = context.memctx(repo, (p1.node(), p2.node()),
1367 memctx = context.memctx(repo, (p1.node(), p2.node()),
1368 message,
1368 message,
1369 files=files,
1369 files=files,
1370 filectxfn=store,
1370 filectxfn=store,
1371 user=user,
1371 user=user,
1372 date=date,
1372 date=date,
1373 branch=branch,
1373 branch=branch,
1374 editor=editor)
1374 editor=editor)
1375 n = memctx.commit()
1375 n = memctx.commit()
1376 finally:
1376 finally:
1377 store.close()
1377 store.close()
1378 if opts.get('exact') and nocommit:
1378 if opts.get('exact') and nocommit:
1379 # --exact with --no-commit is still useful in that it does merge
1379 # --exact with --no-commit is still useful in that it does merge
1380 # and branch bits
1380 # and branch bits
1381 ui.warn(_("warning: can't check exact import with --no-commit\n"))
1381 ui.warn(_("warning: can't check exact import with --no-commit\n"))
1382 elif opts.get('exact') and hex(n) != nodeid:
1382 elif opts.get('exact') and hex(n) != nodeid:
1383 raise error.Abort(_('patch is damaged or loses information'))
1383 raise error.Abort(_('patch is damaged or loses information'))
1384 msg = _('applied to working directory')
1384 msg = _('applied to working directory')
1385 if n:
1385 if n:
1386 # i18n: refers to a short changeset id
1386 # i18n: refers to a short changeset id
1387 msg = _('created %s') % short(n)
1387 msg = _('created %s') % short(n)
1388 return (msg, n, rejects)
1388 return (msg, n, rejects)
1389 finally:
1389 finally:
1390 os.unlink(tmpname)
1390 os.unlink(tmpname)
1391
1391
1392 # facility to let extensions include additional data in an exported patch
1392 # facility to let extensions include additional data in an exported patch
1393 # list of identifiers to be executed in order
1393 # list of identifiers to be executed in order
1394 extraexport = []
1394 extraexport = []
1395 # mapping from identifier to actual export function
1395 # mapping from identifier to actual export function
1396 # function as to return a string to be added to the header or None
1396 # function as to return a string to be added to the header or None
1397 # it is given two arguments (sequencenumber, changectx)
1397 # it is given two arguments (sequencenumber, changectx)
1398 extraexportmap = {}
1398 extraexportmap = {}
1399
1399
1400 def _exportsingle(repo, ctx, match, switch_parent, rev, seqno, write, diffopts):
1400 def _exportsingle(repo, ctx, match, switch_parent, rev, seqno, write, diffopts):
1401 node = scmutil.binnode(ctx)
1401 node = scmutil.binnode(ctx)
1402 parents = [p.node() for p in ctx.parents() if p]
1402 parents = [p.node() for p in ctx.parents() if p]
1403 branch = ctx.branch()
1403 branch = ctx.branch()
1404 if switch_parent:
1404 if switch_parent:
1405 parents.reverse()
1405 parents.reverse()
1406
1406
1407 if parents:
1407 if parents:
1408 prev = parents[0]
1408 prev = parents[0]
1409 else:
1409 else:
1410 prev = nullid
1410 prev = nullid
1411
1411
1412 write("# HG changeset patch\n")
1412 write("# HG changeset patch\n")
1413 write("# User %s\n" % ctx.user())
1413 write("# User %s\n" % ctx.user())
1414 write("# Date %d %d\n" % ctx.date())
1414 write("# Date %d %d\n" % ctx.date())
1415 write("# %s\n" % util.datestr(ctx.date()))
1415 write("# %s\n" % util.datestr(ctx.date()))
1416 if branch and branch != 'default':
1416 if branch and branch != 'default':
1417 write("# Branch %s\n" % branch)
1417 write("# Branch %s\n" % branch)
1418 write("# Node ID %s\n" % hex(node))
1418 write("# Node ID %s\n" % hex(node))
1419 write("# Parent %s\n" % hex(prev))
1419 write("# Parent %s\n" % hex(prev))
1420 if len(parents) > 1:
1420 if len(parents) > 1:
1421 write("# Parent %s\n" % hex(parents[1]))
1421 write("# Parent %s\n" % hex(parents[1]))
1422
1422
1423 for headerid in extraexport:
1423 for headerid in extraexport:
1424 header = extraexportmap[headerid](seqno, ctx)
1424 header = extraexportmap[headerid](seqno, ctx)
1425 if header is not None:
1425 if header is not None:
1426 write('# %s\n' % header)
1426 write('# %s\n' % header)
1427 write(ctx.description().rstrip())
1427 write(ctx.description().rstrip())
1428 write("\n\n")
1428 write("\n\n")
1429
1429
1430 for chunk, label in patch.diffui(repo, prev, node, match, opts=diffopts):
1430 for chunk, label in patch.diffui(repo, prev, node, match, opts=diffopts):
1431 write(chunk, label=label)
1431 write(chunk, label=label)
1432
1432
1433 def export(repo, revs, fntemplate='hg-%h.patch', fp=None, switch_parent=False,
1433 def export(repo, revs, fntemplate='hg-%h.patch', fp=None, switch_parent=False,
1434 opts=None, match=None):
1434 opts=None, match=None):
1435 '''export changesets as hg patches
1435 '''export changesets as hg patches
1436
1436
1437 Args:
1437 Args:
1438 repo: The repository from which we're exporting revisions.
1438 repo: The repository from which we're exporting revisions.
1439 revs: A list of revisions to export as revision numbers.
1439 revs: A list of revisions to export as revision numbers.
1440 fntemplate: An optional string to use for generating patch file names.
1440 fntemplate: An optional string to use for generating patch file names.
1441 fp: An optional file-like object to which patches should be written.
1441 fp: An optional file-like object to which patches should be written.
1442 switch_parent: If True, show diffs against second parent when not nullid.
1442 switch_parent: If True, show diffs against second parent when not nullid.
1443 Default is false, which always shows diff against p1.
1443 Default is false, which always shows diff against p1.
1444 opts: diff options to use for generating the patch.
1444 opts: diff options to use for generating the patch.
1445 match: If specified, only export changes to files matching this matcher.
1445 match: If specified, only export changes to files matching this matcher.
1446
1446
1447 Returns:
1447 Returns:
1448 Nothing.
1448 Nothing.
1449
1449
1450 Side Effect:
1450 Side Effect:
1451 "HG Changeset Patch" data is emitted to one of the following
1451 "HG Changeset Patch" data is emitted to one of the following
1452 destinations:
1452 destinations:
1453 fp is specified: All revs are written to the specified
1453 fp is specified: All revs are written to the specified
1454 file-like object.
1454 file-like object.
1455 fntemplate specified: Each rev is written to a unique file named using
1455 fntemplate specified: Each rev is written to a unique file named using
1456 the given template.
1456 the given template.
1457 Neither fp nor template specified: All revs written to repo.ui.write()
1457 Neither fp nor template specified: All revs written to repo.ui.write()
1458 '''
1458 '''
1459
1459
1460 total = len(revs)
1460 total = len(revs)
1461 revwidth = max(len(str(rev)) for rev in revs)
1461 revwidth = max(len(str(rev)) for rev in revs)
1462 filemode = {}
1462 filemode = {}
1463
1463
1464 write = None
1464 write = None
1465 dest = '<unnamed>'
1465 dest = '<unnamed>'
1466 if fp:
1466 if fp:
1467 dest = getattr(fp, 'name', dest)
1467 dest = getattr(fp, 'name', dest)
1468 def write(s, **kw):
1468 def write(s, **kw):
1469 fp.write(s)
1469 fp.write(s)
1470 elif not fntemplate:
1470 elif not fntemplate:
1471 write = repo.ui.write
1471 write = repo.ui.write
1472
1472
1473 for seqno, rev in enumerate(revs, 1):
1473 for seqno, rev in enumerate(revs, 1):
1474 ctx = repo[rev]
1474 ctx = repo[rev]
1475 fo = None
1475 fo = None
1476 if not fp and fntemplate:
1476 if not fp and fntemplate:
1477 desc_lines = ctx.description().rstrip().split('\n')
1477 desc_lines = ctx.description().rstrip().split('\n')
1478 desc = desc_lines[0] #Commit always has a first line.
1478 desc = desc_lines[0] #Commit always has a first line.
1479 fo = makefileobj(repo, fntemplate, ctx.node(), desc=desc,
1479 fo = makefileobj(repo, fntemplate, ctx.node(), desc=desc,
1480 total=total, seqno=seqno, revwidth=revwidth,
1480 total=total, seqno=seqno, revwidth=revwidth,
1481 mode='wb', modemap=filemode)
1481 mode='wb', modemap=filemode)
1482 dest = fo.name
1482 dest = fo.name
1483 def write(s, **kw):
1483 def write(s, **kw):
1484 fo.write(s)
1484 fo.write(s)
1485 if not dest.startswith('<'):
1485 if not dest.startswith('<'):
1486 repo.ui.note("%s\n" % dest)
1486 repo.ui.note("%s\n" % dest)
1487 _exportsingle(
1487 _exportsingle(
1488 repo, ctx, match, switch_parent, rev, seqno, write, opts)
1488 repo, ctx, match, switch_parent, rev, seqno, write, opts)
1489 if fo is not None:
1489 if fo is not None:
1490 fo.close()
1490 fo.close()
1491
1491
1492 def diffordiffstat(ui, repo, diffopts, node1, node2, match,
1492 def diffordiffstat(ui, repo, diffopts, node1, node2, match,
1493 changes=None, stat=False, fp=None, prefix='',
1493 changes=None, stat=False, fp=None, prefix='',
1494 root='', listsubrepos=False, hunksfilterfn=None):
1494 root='', listsubrepos=False, hunksfilterfn=None):
1495 '''show diff or diffstat.'''
1495 '''show diff or diffstat.'''
1496 if fp is None:
1496 if fp is None:
1497 write = ui.write
1497 write = ui.write
1498 else:
1498 else:
1499 def write(s, **kw):
1499 def write(s, **kw):
1500 fp.write(s)
1500 fp.write(s)
1501
1501
1502 if root:
1502 if root:
1503 relroot = pathutil.canonpath(repo.root, repo.getcwd(), root)
1503 relroot = pathutil.canonpath(repo.root, repo.getcwd(), root)
1504 else:
1504 else:
1505 relroot = ''
1505 relroot = ''
1506 if relroot != '':
1506 if relroot != '':
1507 # XXX relative roots currently don't work if the root is within a
1507 # XXX relative roots currently don't work if the root is within a
1508 # subrepo
1508 # subrepo
1509 uirelroot = match.uipath(relroot)
1509 uirelroot = match.uipath(relroot)
1510 relroot += '/'
1510 relroot += '/'
1511 for matchroot in match.files():
1511 for matchroot in match.files():
1512 if not matchroot.startswith(relroot):
1512 if not matchroot.startswith(relroot):
1513 ui.warn(_('warning: %s not inside relative root %s\n') % (
1513 ui.warn(_('warning: %s not inside relative root %s\n') % (
1514 match.uipath(matchroot), uirelroot))
1514 match.uipath(matchroot), uirelroot))
1515
1515
1516 if stat:
1516 if stat:
1517 diffopts = diffopts.copy(context=0)
1517 diffopts = diffopts.copy(context=0)
1518 width = 80
1518 width = 80
1519 if not ui.plain():
1519 if not ui.plain():
1520 width = ui.termwidth()
1520 width = ui.termwidth()
1521 chunks = patch.diff(repo, node1, node2, match, changes, diffopts,
1521 chunks = patch.diff(repo, node1, node2, match, changes, diffopts,
1522 prefix=prefix, relroot=relroot,
1522 prefix=prefix, relroot=relroot,
1523 hunksfilterfn=hunksfilterfn)
1523 hunksfilterfn=hunksfilterfn)
1524 for chunk, label in patch.diffstatui(util.iterlines(chunks),
1524 for chunk, label in patch.diffstatui(util.iterlines(chunks),
1525 width=width):
1525 width=width):
1526 write(chunk, label=label)
1526 write(chunk, label=label)
1527 else:
1527 else:
1528 for chunk, label in patch.diffui(repo, node1, node2, match,
1528 for chunk, label in patch.diffui(repo, node1, node2, match,
1529 changes, diffopts, prefix=prefix,
1529 changes, diffopts, prefix=prefix,
1530 relroot=relroot,
1530 relroot=relroot,
1531 hunksfilterfn=hunksfilterfn):
1531 hunksfilterfn=hunksfilterfn):
1532 write(chunk, label=label)
1532 write(chunk, label=label)
1533
1533
1534 if listsubrepos:
1534 if listsubrepos:
1535 ctx1 = repo[node1]
1535 ctx1 = repo[node1]
1536 ctx2 = repo[node2]
1536 ctx2 = repo[node2]
1537 for subpath, sub in scmutil.itersubrepos(ctx1, ctx2):
1537 for subpath, sub in scmutil.itersubrepos(ctx1, ctx2):
1538 tempnode2 = node2
1538 tempnode2 = node2
1539 try:
1539 try:
1540 if node2 is not None:
1540 if node2 is not None:
1541 tempnode2 = ctx2.substate[subpath][1]
1541 tempnode2 = ctx2.substate[subpath][1]
1542 except KeyError:
1542 except KeyError:
1543 # A subrepo that existed in node1 was deleted between node1 and
1543 # A subrepo that existed in node1 was deleted between node1 and
1544 # node2 (inclusive). Thus, ctx2's substate won't contain that
1544 # node2 (inclusive). Thus, ctx2's substate won't contain that
1545 # subpath. The best we can do is to ignore it.
1545 # subpath. The best we can do is to ignore it.
1546 tempnode2 = None
1546 tempnode2 = None
1547 submatch = matchmod.subdirmatcher(subpath, match)
1547 submatch = matchmod.subdirmatcher(subpath, match)
1548 sub.diff(ui, diffopts, tempnode2, submatch, changes=changes,
1548 sub.diff(ui, diffopts, tempnode2, submatch, changes=changes,
1549 stat=stat, fp=fp, prefix=prefix)
1549 stat=stat, fp=fp, prefix=prefix)
1550
1550
1551 def _changesetlabels(ctx):
1551 def _changesetlabels(ctx):
1552 labels = ['log.changeset', 'changeset.%s' % ctx.phasestr()]
1552 labels = ['log.changeset', 'changeset.%s' % ctx.phasestr()]
1553 if ctx.obsolete():
1553 if ctx.obsolete():
1554 labels.append('changeset.obsolete')
1554 labels.append('changeset.obsolete')
1555 if ctx.isunstable():
1555 if ctx.isunstable():
1556 labels.append('changeset.unstable')
1556 labels.append('changeset.unstable')
1557 for instability in ctx.instabilities():
1557 for instability in ctx.instabilities():
1558 labels.append('instability.%s' % instability)
1558 labels.append('instability.%s' % instability)
1559 return ' '.join(labels)
1559 return ' '.join(labels)
1560
1560
1561 class changeset_printer(object):
1561 class changeset_printer(object):
1562 '''show changeset information when templating not requested.'''
1562 '''show changeset information when templating not requested.'''
1563
1563
1564 def __init__(self, ui, repo, matchfn, diffopts, buffered):
1564 def __init__(self, ui, repo, matchfn, diffopts, buffered):
1565 self.ui = ui
1565 self.ui = ui
1566 self.repo = repo
1566 self.repo = repo
1567 self.buffered = buffered
1567 self.buffered = buffered
1568 self.matchfn = matchfn
1568 self.matchfn = matchfn
1569 self.diffopts = diffopts
1569 self.diffopts = diffopts
1570 self.header = {}
1570 self.header = {}
1571 self.hunk = {}
1571 self.hunk = {}
1572 self.lastheader = None
1572 self.lastheader = None
1573 self.footer = None
1573 self.footer = None
1574
1574
1575 def flush(self, ctx):
1575 def flush(self, ctx):
1576 rev = ctx.rev()
1576 rev = ctx.rev()
1577 if rev in self.header:
1577 if rev in self.header:
1578 h = self.header[rev]
1578 h = self.header[rev]
1579 if h != self.lastheader:
1579 if h != self.lastheader:
1580 self.lastheader = h
1580 self.lastheader = h
1581 self.ui.write(h)
1581 self.ui.write(h)
1582 del self.header[rev]
1582 del self.header[rev]
1583 if rev in self.hunk:
1583 if rev in self.hunk:
1584 self.ui.write(self.hunk[rev])
1584 self.ui.write(self.hunk[rev])
1585 del self.hunk[rev]
1585 del self.hunk[rev]
1586 return 1
1586 return 1
1587 return 0
1587 return 0
1588
1588
1589 def close(self):
1589 def close(self):
1590 if self.footer:
1590 if self.footer:
1591 self.ui.write(self.footer)
1591 self.ui.write(self.footer)
1592
1592
1593 def show(self, ctx, copies=None, matchfn=None, hunksfilterfn=None,
1593 def show(self, ctx, copies=None, matchfn=None, hunksfilterfn=None,
1594 **props):
1594 **props):
1595 props = pycompat.byteskwargs(props)
1595 props = pycompat.byteskwargs(props)
1596 if self.buffered:
1596 if self.buffered:
1597 self.ui.pushbuffer(labeled=True)
1597 self.ui.pushbuffer(labeled=True)
1598 self._show(ctx, copies, matchfn, hunksfilterfn, props)
1598 self._show(ctx, copies, matchfn, hunksfilterfn, props)
1599 self.hunk[ctx.rev()] = self.ui.popbuffer()
1599 self.hunk[ctx.rev()] = self.ui.popbuffer()
1600 else:
1600 else:
1601 self._show(ctx, copies, matchfn, hunksfilterfn, props)
1601 self._show(ctx, copies, matchfn, hunksfilterfn, props)
1602
1602
1603 def _show(self, ctx, copies, matchfn, hunksfilterfn, props):
1603 def _show(self, ctx, copies, matchfn, hunksfilterfn, props):
1604 '''show a single changeset or file revision'''
1604 '''show a single changeset or file revision'''
1605 changenode = ctx.node()
1605 changenode = ctx.node()
1606 rev = ctx.rev()
1606 rev = ctx.rev()
1607
1607
1608 if self.ui.quiet:
1608 if self.ui.quiet:
1609 self.ui.write("%s\n" % scmutil.formatchangeid(ctx),
1609 self.ui.write("%s\n" % scmutil.formatchangeid(ctx),
1610 label='log.node')
1610 label='log.node')
1611 return
1611 return
1612
1612
1613 date = util.datestr(ctx.date())
1613 date = util.datestr(ctx.date())
1614
1614
1615 # i18n: column positioning for "hg log"
1615 # i18n: column positioning for "hg log"
1616 self.ui.write(_("changeset: %s\n") % scmutil.formatchangeid(ctx),
1616 self.ui.write(_("changeset: %s\n") % scmutil.formatchangeid(ctx),
1617 label=_changesetlabels(ctx))
1617 label=_changesetlabels(ctx))
1618
1618
1619 # branches are shown first before any other names due to backwards
1619 # branches are shown first before any other names due to backwards
1620 # compatibility
1620 # compatibility
1621 branch = ctx.branch()
1621 branch = ctx.branch()
1622 # don't show the default branch name
1622 # don't show the default branch name
1623 if branch != 'default':
1623 if branch != 'default':
1624 # i18n: column positioning for "hg log"
1624 # i18n: column positioning for "hg log"
1625 self.ui.write(_("branch: %s\n") % branch,
1625 self.ui.write(_("branch: %s\n") % branch,
1626 label='log.branch')
1626 label='log.branch')
1627
1627
1628 for nsname, ns in self.repo.names.iteritems():
1628 for nsname, ns in self.repo.names.iteritems():
1629 # branches has special logic already handled above, so here we just
1629 # branches has special logic already handled above, so here we just
1630 # skip it
1630 # skip it
1631 if nsname == 'branches':
1631 if nsname == 'branches':
1632 continue
1632 continue
1633 # we will use the templatename as the color name since those two
1633 # we will use the templatename as the color name since those two
1634 # should be the same
1634 # should be the same
1635 for name in ns.names(self.repo, changenode):
1635 for name in ns.names(self.repo, changenode):
1636 self.ui.write(ns.logfmt % name,
1636 self.ui.write(ns.logfmt % name,
1637 label='log.%s' % ns.colorname)
1637 label='log.%s' % ns.colorname)
1638 if self.ui.debugflag:
1638 if self.ui.debugflag:
1639 # i18n: column positioning for "hg log"
1639 # i18n: column positioning for "hg log"
1640 self.ui.write(_("phase: %s\n") % ctx.phasestr(),
1640 self.ui.write(_("phase: %s\n") % ctx.phasestr(),
1641 label='log.phase')
1641 label='log.phase')
1642 for pctx in scmutil.meaningfulparents(self.repo, ctx):
1642 for pctx in scmutil.meaningfulparents(self.repo, ctx):
1643 label = 'log.parent changeset.%s' % pctx.phasestr()
1643 label = 'log.parent changeset.%s' % pctx.phasestr()
1644 # i18n: column positioning for "hg log"
1644 # i18n: column positioning for "hg log"
1645 self.ui.write(_("parent: %s\n") % scmutil.formatchangeid(pctx),
1645 self.ui.write(_("parent: %s\n") % scmutil.formatchangeid(pctx),
1646 label=label)
1646 label=label)
1647
1647
1648 if self.ui.debugflag and rev is not None:
1648 if self.ui.debugflag and rev is not None:
1649 mnode = ctx.manifestnode()
1649 mnode = ctx.manifestnode()
1650 mrev = self.repo.manifestlog._revlog.rev(mnode)
1650 mrev = self.repo.manifestlog._revlog.rev(mnode)
1651 # i18n: column positioning for "hg log"
1651 # i18n: column positioning for "hg log"
1652 self.ui.write(_("manifest: %s\n")
1652 self.ui.write(_("manifest: %s\n")
1653 % scmutil.formatrevnode(self.ui, mrev, mnode),
1653 % scmutil.formatrevnode(self.ui, mrev, mnode),
1654 label='ui.debug log.manifest')
1654 label='ui.debug log.manifest')
1655 # i18n: column positioning for "hg log"
1655 # i18n: column positioning for "hg log"
1656 self.ui.write(_("user: %s\n") % ctx.user(),
1656 self.ui.write(_("user: %s\n") % ctx.user(),
1657 label='log.user')
1657 label='log.user')
1658 # i18n: column positioning for "hg log"
1658 # i18n: column positioning for "hg log"
1659 self.ui.write(_("date: %s\n") % date,
1659 self.ui.write(_("date: %s\n") % date,
1660 label='log.date')
1660 label='log.date')
1661
1661
1662 if ctx.isunstable():
1662 if ctx.isunstable():
1663 # i18n: column positioning for "hg log"
1663 # i18n: column positioning for "hg log"
1664 instabilities = ctx.instabilities()
1664 instabilities = ctx.instabilities()
1665 self.ui.write(_("instability: %s\n") % ', '.join(instabilities),
1665 self.ui.write(_("instability: %s\n") % ', '.join(instabilities),
1666 label='log.instability')
1666 label='log.instability')
1667
1667
1668 elif ctx.obsolete():
1668 elif ctx.obsolete():
1669 self._showobsfate(ctx)
1669 self._showobsfate(ctx)
1670
1670
1671 self._exthook(ctx)
1671 self._exthook(ctx)
1672
1672
1673 if self.ui.debugflag:
1673 if self.ui.debugflag:
1674 files = ctx.p1().status(ctx)[:3]
1674 files = ctx.p1().status(ctx)[:3]
1675 for key, value in zip([# i18n: column positioning for "hg log"
1675 for key, value in zip([# i18n: column positioning for "hg log"
1676 _("files:"),
1676 _("files:"),
1677 # i18n: column positioning for "hg log"
1677 # i18n: column positioning for "hg log"
1678 _("files+:"),
1678 _("files+:"),
1679 # i18n: column positioning for "hg log"
1679 # i18n: column positioning for "hg log"
1680 _("files-:")], files):
1680 _("files-:")], files):
1681 if value:
1681 if value:
1682 self.ui.write("%-12s %s\n" % (key, " ".join(value)),
1682 self.ui.write("%-12s %s\n" % (key, " ".join(value)),
1683 label='ui.debug log.files')
1683 label='ui.debug log.files')
1684 elif ctx.files() and self.ui.verbose:
1684 elif ctx.files() and self.ui.verbose:
1685 # i18n: column positioning for "hg log"
1685 # i18n: column positioning for "hg log"
1686 self.ui.write(_("files: %s\n") % " ".join(ctx.files()),
1686 self.ui.write(_("files: %s\n") % " ".join(ctx.files()),
1687 label='ui.note log.files')
1687 label='ui.note log.files')
1688 if copies and self.ui.verbose:
1688 if copies and self.ui.verbose:
1689 copies = ['%s (%s)' % c for c in copies]
1689 copies = ['%s (%s)' % c for c in copies]
1690 # i18n: column positioning for "hg log"
1690 # i18n: column positioning for "hg log"
1691 self.ui.write(_("copies: %s\n") % ' '.join(copies),
1691 self.ui.write(_("copies: %s\n") % ' '.join(copies),
1692 label='ui.note log.copies')
1692 label='ui.note log.copies')
1693
1693
1694 extra = ctx.extra()
1694 extra = ctx.extra()
1695 if extra and self.ui.debugflag:
1695 if extra and self.ui.debugflag:
1696 for key, value in sorted(extra.items()):
1696 for key, value in sorted(extra.items()):
1697 # i18n: column positioning for "hg log"
1697 # i18n: column positioning for "hg log"
1698 self.ui.write(_("extra: %s=%s\n")
1698 self.ui.write(_("extra: %s=%s\n")
1699 % (key, util.escapestr(value)),
1699 % (key, util.escapestr(value)),
1700 label='ui.debug log.extra')
1700 label='ui.debug log.extra')
1701
1701
1702 description = ctx.description().strip()
1702 description = ctx.description().strip()
1703 if description:
1703 if description:
1704 if self.ui.verbose:
1704 if self.ui.verbose:
1705 self.ui.write(_("description:\n"),
1705 self.ui.write(_("description:\n"),
1706 label='ui.note log.description')
1706 label='ui.note log.description')
1707 self.ui.write(description,
1707 self.ui.write(description,
1708 label='ui.note log.description')
1708 label='ui.note log.description')
1709 self.ui.write("\n\n")
1709 self.ui.write("\n\n")
1710 else:
1710 else:
1711 # i18n: column positioning for "hg log"
1711 # i18n: column positioning for "hg log"
1712 self.ui.write(_("summary: %s\n") %
1712 self.ui.write(_("summary: %s\n") %
1713 description.splitlines()[0],
1713 description.splitlines()[0],
1714 label='log.summary')
1714 label='log.summary')
1715 self.ui.write("\n")
1715 self.ui.write("\n")
1716
1716
1717 self.showpatch(ctx, matchfn, hunksfilterfn=hunksfilterfn)
1717 self.showpatch(ctx, matchfn, hunksfilterfn=hunksfilterfn)
1718
1718
1719 def _showobsfate(self, ctx):
1719 def _showobsfate(self, ctx):
1720 obsfate = templatekw.showobsfate(repo=self.repo, ctx=ctx, ui=self.ui)
1720 obsfate = templatekw.showobsfate(repo=self.repo, ctx=ctx, ui=self.ui)
1721
1721
1722 if obsfate:
1722 if obsfate:
1723 for obsfateline in obsfate:
1723 for obsfateline in obsfate:
1724 # i18n: column positioning for "hg log"
1724 # i18n: column positioning for "hg log"
1725 self.ui.write(_("obsolete: %s\n") % obsfateline,
1725 self.ui.write(_("obsolete: %s\n") % obsfateline,
1726 label='log.obsfate')
1726 label='log.obsfate')
1727
1727
1728 def _exthook(self, ctx):
1728 def _exthook(self, ctx):
1729 '''empty method used by extension as a hook point
1729 '''empty method used by extension as a hook point
1730 '''
1730 '''
1731
1731
1732 def showpatch(self, ctx, matchfn, hunksfilterfn=None):
1732 def showpatch(self, ctx, matchfn, hunksfilterfn=None):
1733 if not matchfn:
1733 if not matchfn:
1734 matchfn = self.matchfn
1734 matchfn = self.matchfn
1735 if matchfn:
1735 if matchfn:
1736 stat = self.diffopts.get('stat')
1736 stat = self.diffopts.get('stat')
1737 diff = self.diffopts.get('patch')
1737 diff = self.diffopts.get('patch')
1738 diffopts = patch.diffallopts(self.ui, self.diffopts)
1738 diffopts = patch.diffallopts(self.ui, self.diffopts)
1739 node = ctx.node()
1739 node = ctx.node()
1740 prev = ctx.p1().node()
1740 prev = ctx.p1().node()
1741 if stat:
1741 if stat:
1742 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1742 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1743 match=matchfn, stat=True,
1743 match=matchfn, stat=True,
1744 hunksfilterfn=hunksfilterfn)
1744 hunksfilterfn=hunksfilterfn)
1745 if diff:
1745 if diff:
1746 if stat:
1746 if stat:
1747 self.ui.write("\n")
1747 self.ui.write("\n")
1748 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1748 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1749 match=matchfn, stat=False,
1749 match=matchfn, stat=False,
1750 hunksfilterfn=hunksfilterfn)
1750 hunksfilterfn=hunksfilterfn)
1751 self.ui.write("\n")
1751 self.ui.write("\n")
1752
1752
1753 class jsonchangeset(changeset_printer):
1753 class jsonchangeset(changeset_printer):
1754 '''format changeset information.'''
1754 '''format changeset information.'''
1755
1755
1756 def __init__(self, ui, repo, matchfn, diffopts, buffered):
1756 def __init__(self, ui, repo, matchfn, diffopts, buffered):
1757 changeset_printer.__init__(self, ui, repo, matchfn, diffopts, buffered)
1757 changeset_printer.__init__(self, ui, repo, matchfn, diffopts, buffered)
1758 self.cache = {}
1758 self.cache = {}
1759 self._first = True
1759 self._first = True
1760
1760
1761 def close(self):
1761 def close(self):
1762 if not self._first:
1762 if not self._first:
1763 self.ui.write("\n]\n")
1763 self.ui.write("\n]\n")
1764 else:
1764 else:
1765 self.ui.write("[]\n")
1765 self.ui.write("[]\n")
1766
1766
1767 def _show(self, ctx, copies, matchfn, hunksfilterfn, props):
1767 def _show(self, ctx, copies, matchfn, hunksfilterfn, props):
1768 '''show a single changeset or file revision'''
1768 '''show a single changeset or file revision'''
1769 rev = ctx.rev()
1769 rev = ctx.rev()
1770 if rev is None:
1770 if rev is None:
1771 jrev = jnode = 'null'
1771 jrev = jnode = 'null'
1772 else:
1772 else:
1773 jrev = '%d' % rev
1773 jrev = '%d' % rev
1774 jnode = '"%s"' % hex(ctx.node())
1774 jnode = '"%s"' % hex(ctx.node())
1775 j = encoding.jsonescape
1775 j = encoding.jsonescape
1776
1776
1777 if self._first:
1777 if self._first:
1778 self.ui.write("[\n {")
1778 self.ui.write("[\n {")
1779 self._first = False
1779 self._first = False
1780 else:
1780 else:
1781 self.ui.write(",\n {")
1781 self.ui.write(",\n {")
1782
1782
1783 if self.ui.quiet:
1783 if self.ui.quiet:
1784 self.ui.write(('\n "rev": %s') % jrev)
1784 self.ui.write(('\n "rev": %s') % jrev)
1785 self.ui.write((',\n "node": %s') % jnode)
1785 self.ui.write((',\n "node": %s') % jnode)
1786 self.ui.write('\n }')
1786 self.ui.write('\n }')
1787 return
1787 return
1788
1788
1789 self.ui.write(('\n "rev": %s') % jrev)
1789 self.ui.write(('\n "rev": %s') % jrev)
1790 self.ui.write((',\n "node": %s') % jnode)
1790 self.ui.write((',\n "node": %s') % jnode)
1791 self.ui.write((',\n "branch": "%s"') % j(ctx.branch()))
1791 self.ui.write((',\n "branch": "%s"') % j(ctx.branch()))
1792 self.ui.write((',\n "phase": "%s"') % ctx.phasestr())
1792 self.ui.write((',\n "phase": "%s"') % ctx.phasestr())
1793 self.ui.write((',\n "user": "%s"') % j(ctx.user()))
1793 self.ui.write((',\n "user": "%s"') % j(ctx.user()))
1794 self.ui.write((',\n "date": [%d, %d]') % ctx.date())
1794 self.ui.write((',\n "date": [%d, %d]') % ctx.date())
1795 self.ui.write((',\n "desc": "%s"') % j(ctx.description()))
1795 self.ui.write((',\n "desc": "%s"') % j(ctx.description()))
1796
1796
1797 self.ui.write((',\n "bookmarks": [%s]') %
1797 self.ui.write((',\n "bookmarks": [%s]') %
1798 ", ".join('"%s"' % j(b) for b in ctx.bookmarks()))
1798 ", ".join('"%s"' % j(b) for b in ctx.bookmarks()))
1799 self.ui.write((',\n "tags": [%s]') %
1799 self.ui.write((',\n "tags": [%s]') %
1800 ", ".join('"%s"' % j(t) for t in ctx.tags()))
1800 ", ".join('"%s"' % j(t) for t in ctx.tags()))
1801 self.ui.write((',\n "parents": [%s]') %
1801 self.ui.write((',\n "parents": [%s]') %
1802 ", ".join('"%s"' % c.hex() for c in ctx.parents()))
1802 ", ".join('"%s"' % c.hex() for c in ctx.parents()))
1803
1803
1804 if self.ui.debugflag:
1804 if self.ui.debugflag:
1805 if rev is None:
1805 if rev is None:
1806 jmanifestnode = 'null'
1806 jmanifestnode = 'null'
1807 else:
1807 else:
1808 jmanifestnode = '"%s"' % hex(ctx.manifestnode())
1808 jmanifestnode = '"%s"' % hex(ctx.manifestnode())
1809 self.ui.write((',\n "manifest": %s') % jmanifestnode)
1809 self.ui.write((',\n "manifest": %s') % jmanifestnode)
1810
1810
1811 self.ui.write((',\n "extra": {%s}') %
1811 self.ui.write((',\n "extra": {%s}') %
1812 ", ".join('"%s": "%s"' % (j(k), j(v))
1812 ", ".join('"%s": "%s"' % (j(k), j(v))
1813 for k, v in ctx.extra().items()))
1813 for k, v in ctx.extra().items()))
1814
1814
1815 files = ctx.p1().status(ctx)
1815 files = ctx.p1().status(ctx)
1816 self.ui.write((',\n "modified": [%s]') %
1816 self.ui.write((',\n "modified": [%s]') %
1817 ", ".join('"%s"' % j(f) for f in files[0]))
1817 ", ".join('"%s"' % j(f) for f in files[0]))
1818 self.ui.write((',\n "added": [%s]') %
1818 self.ui.write((',\n "added": [%s]') %
1819 ", ".join('"%s"' % j(f) for f in files[1]))
1819 ", ".join('"%s"' % j(f) for f in files[1]))
1820 self.ui.write((',\n "removed": [%s]') %
1820 self.ui.write((',\n "removed": [%s]') %
1821 ", ".join('"%s"' % j(f) for f in files[2]))
1821 ", ".join('"%s"' % j(f) for f in files[2]))
1822
1822
1823 elif self.ui.verbose:
1823 elif self.ui.verbose:
1824 self.ui.write((',\n "files": [%s]') %
1824 self.ui.write((',\n "files": [%s]') %
1825 ", ".join('"%s"' % j(f) for f in ctx.files()))
1825 ", ".join('"%s"' % j(f) for f in ctx.files()))
1826
1826
1827 if copies:
1827 if copies:
1828 self.ui.write((',\n "copies": {%s}') %
1828 self.ui.write((',\n "copies": {%s}') %
1829 ", ".join('"%s": "%s"' % (j(k), j(v))
1829 ", ".join('"%s": "%s"' % (j(k), j(v))
1830 for k, v in copies))
1830 for k, v in copies))
1831
1831
1832 matchfn = self.matchfn
1832 matchfn = self.matchfn
1833 if matchfn:
1833 if matchfn:
1834 stat = self.diffopts.get('stat')
1834 stat = self.diffopts.get('stat')
1835 diff = self.diffopts.get('patch')
1835 diff = self.diffopts.get('patch')
1836 diffopts = patch.difffeatureopts(self.ui, self.diffopts, git=True)
1836 diffopts = patch.difffeatureopts(self.ui, self.diffopts, git=True)
1837 node, prev = ctx.node(), ctx.p1().node()
1837 node, prev = ctx.node(), ctx.p1().node()
1838 if stat:
1838 if stat:
1839 self.ui.pushbuffer()
1839 self.ui.pushbuffer()
1840 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1840 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1841 match=matchfn, stat=True)
1841 match=matchfn, stat=True)
1842 self.ui.write((',\n "diffstat": "%s"')
1842 self.ui.write((',\n "diffstat": "%s"')
1843 % j(self.ui.popbuffer()))
1843 % j(self.ui.popbuffer()))
1844 if diff:
1844 if diff:
1845 self.ui.pushbuffer()
1845 self.ui.pushbuffer()
1846 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1846 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1847 match=matchfn, stat=False)
1847 match=matchfn, stat=False)
1848 self.ui.write((',\n "diff": "%s"') % j(self.ui.popbuffer()))
1848 self.ui.write((',\n "diff": "%s"') % j(self.ui.popbuffer()))
1849
1849
1850 self.ui.write("\n }")
1850 self.ui.write("\n }")
1851
1851
1852 class changeset_templater(changeset_printer):
1852 class changeset_templater(changeset_printer):
1853 '''format changeset information.
1853 '''format changeset information.
1854
1854
1855 Note: there are a variety of convenience functions to build a
1855 Note: there are a variety of convenience functions to build a
1856 changeset_templater for common cases. See functions such as:
1856 changeset_templater for common cases. See functions such as:
1857 makelogtemplater, show_changeset, buildcommittemplate, or other
1857 makelogtemplater, show_changeset, buildcommittemplate, or other
1858 functions that use changesest_templater.
1858 functions that use changesest_templater.
1859 '''
1859 '''
1860
1860
1861 # Arguments before "buffered" used to be positional. Consider not
1861 # Arguments before "buffered" used to be positional. Consider not
1862 # adding/removing arguments before "buffered" to not break callers.
1862 # adding/removing arguments before "buffered" to not break callers.
1863 def __init__(self, ui, repo, tmplspec, matchfn=None, diffopts=None,
1863 def __init__(self, ui, repo, tmplspec, matchfn=None, diffopts=None,
1864 buffered=False):
1864 buffered=False):
1865 diffopts = diffopts or {}
1865 diffopts = diffopts or {}
1866
1866
1867 changeset_printer.__init__(self, ui, repo, matchfn, diffopts, buffered)
1867 changeset_printer.__init__(self, ui, repo, matchfn, diffopts, buffered)
1868 self.t = formatter.loadtemplater(ui, tmplspec,
1868 self.t = formatter.loadtemplater(ui, tmplspec,
1869 cache=templatekw.defaulttempl)
1869 cache=templatekw.defaulttempl)
1870 self._counter = itertools.count()
1870 self._counter = itertools.count()
1871 self.cache = {}
1871 self.cache = {}
1872
1872
1873 self._tref = tmplspec.ref
1873 self._tref = tmplspec.ref
1874 self._parts = {'header': '', 'footer': '',
1874 self._parts = {'header': '', 'footer': '',
1875 tmplspec.ref: tmplspec.ref,
1875 tmplspec.ref: tmplspec.ref,
1876 'docheader': '', 'docfooter': '',
1876 'docheader': '', 'docfooter': '',
1877 'separator': ''}
1877 'separator': ''}
1878 if tmplspec.mapfile:
1878 if tmplspec.mapfile:
1879 # find correct templates for current mode, for backward
1879 # find correct templates for current mode, for backward
1880 # compatibility with 'log -v/-q/--debug' using a mapfile
1880 # compatibility with 'log -v/-q/--debug' using a mapfile
1881 tmplmodes = [
1881 tmplmodes = [
1882 (True, ''),
1882 (True, ''),
1883 (self.ui.verbose, '_verbose'),
1883 (self.ui.verbose, '_verbose'),
1884 (self.ui.quiet, '_quiet'),
1884 (self.ui.quiet, '_quiet'),
1885 (self.ui.debugflag, '_debug'),
1885 (self.ui.debugflag, '_debug'),
1886 ]
1886 ]
1887 for mode, postfix in tmplmodes:
1887 for mode, postfix in tmplmodes:
1888 for t in self._parts:
1888 for t in self._parts:
1889 cur = t + postfix
1889 cur = t + postfix
1890 if mode and cur in self.t:
1890 if mode and cur in self.t:
1891 self._parts[t] = cur
1891 self._parts[t] = cur
1892 else:
1892 else:
1893 partnames = [p for p in self._parts.keys() if p != tmplspec.ref]
1893 partnames = [p for p in self._parts.keys() if p != tmplspec.ref]
1894 m = formatter.templatepartsmap(tmplspec, self.t, partnames)
1894 m = formatter.templatepartsmap(tmplspec, self.t, partnames)
1895 self._parts.update(m)
1895 self._parts.update(m)
1896
1896
1897 if self._parts['docheader']:
1897 if self._parts['docheader']:
1898 self.ui.write(templater.stringify(self.t(self._parts['docheader'])))
1898 self.ui.write(templater.stringify(self.t(self._parts['docheader'])))
1899
1899
1900 def close(self):
1900 def close(self):
1901 if self._parts['docfooter']:
1901 if self._parts['docfooter']:
1902 if not self.footer:
1902 if not self.footer:
1903 self.footer = ""
1903 self.footer = ""
1904 self.footer += templater.stringify(self.t(self._parts['docfooter']))
1904 self.footer += templater.stringify(self.t(self._parts['docfooter']))
1905 return super(changeset_templater, self).close()
1905 return super(changeset_templater, self).close()
1906
1906
1907 def _show(self, ctx, copies, matchfn, hunksfilterfn, props):
1907 def _show(self, ctx, copies, matchfn, hunksfilterfn, props):
1908 '''show a single changeset or file revision'''
1908 '''show a single changeset or file revision'''
1909 props = props.copy()
1909 props = props.copy()
1910 props.update(templatekw.keywords)
1910 props.update(templatekw.keywords)
1911 props['templ'] = self.t
1911 props['templ'] = self.t
1912 props['ctx'] = ctx
1912 props['ctx'] = ctx
1913 props['repo'] = self.repo
1913 props['repo'] = self.repo
1914 props['ui'] = self.repo.ui
1914 props['ui'] = self.repo.ui
1915 props['index'] = index = next(self._counter)
1915 props['index'] = index = next(self._counter)
1916 props['revcache'] = {'copies': copies}
1916 props['revcache'] = {'copies': copies}
1917 props['cache'] = self.cache
1917 props['cache'] = self.cache
1918 props = pycompat.strkwargs(props)
1918 props = pycompat.strkwargs(props)
1919
1919
1920 # write separator, which wouldn't work well with the header part below
1920 # write separator, which wouldn't work well with the header part below
1921 # since there's inherently a conflict between header (across items) and
1921 # since there's inherently a conflict between header (across items) and
1922 # separator (per item)
1922 # separator (per item)
1923 if self._parts['separator'] and index > 0:
1923 if self._parts['separator'] and index > 0:
1924 self.ui.write(templater.stringify(self.t(self._parts['separator'])))
1924 self.ui.write(templater.stringify(self.t(self._parts['separator'])))
1925
1925
1926 # write header
1926 # write header
1927 if self._parts['header']:
1927 if self._parts['header']:
1928 h = templater.stringify(self.t(self._parts['header'], **props))
1928 h = templater.stringify(self.t(self._parts['header'], **props))
1929 if self.buffered:
1929 if self.buffered:
1930 self.header[ctx.rev()] = h
1930 self.header[ctx.rev()] = h
1931 else:
1931 else:
1932 if self.lastheader != h:
1932 if self.lastheader != h:
1933 self.lastheader = h
1933 self.lastheader = h
1934 self.ui.write(h)
1934 self.ui.write(h)
1935
1935
1936 # write changeset metadata, then patch if requested
1936 # write changeset metadata, then patch if requested
1937 key = self._parts[self._tref]
1937 key = self._parts[self._tref]
1938 self.ui.write(templater.stringify(self.t(key, **props)))
1938 self.ui.write(templater.stringify(self.t(key, **props)))
1939 self.showpatch(ctx, matchfn, hunksfilterfn=hunksfilterfn)
1939 self.showpatch(ctx, matchfn, hunksfilterfn=hunksfilterfn)
1940
1940
1941 if self._parts['footer']:
1941 if self._parts['footer']:
1942 if not self.footer:
1942 if not self.footer:
1943 self.footer = templater.stringify(
1943 self.footer = templater.stringify(
1944 self.t(self._parts['footer'], **props))
1944 self.t(self._parts['footer'], **props))
1945
1945
1946 def logtemplatespec(tmpl, mapfile):
1946 def logtemplatespec(tmpl, mapfile):
1947 if mapfile:
1947 if mapfile:
1948 return formatter.templatespec('changeset', tmpl, mapfile)
1948 return formatter.templatespec('changeset', tmpl, mapfile)
1949 else:
1949 else:
1950 return formatter.templatespec('', tmpl, None)
1950 return formatter.templatespec('', tmpl, None)
1951
1951
1952 def _lookuplogtemplate(ui, tmpl, style):
1952 def _lookuplogtemplate(ui, tmpl, style):
1953 """Find the template matching the given template spec or style
1953 """Find the template matching the given template spec or style
1954
1954
1955 See formatter.lookuptemplate() for details.
1955 See formatter.lookuptemplate() for details.
1956 """
1956 """
1957
1957
1958 # ui settings
1958 # ui settings
1959 if not tmpl and not style: # template are stronger than style
1959 if not tmpl and not style: # template are stronger than style
1960 tmpl = ui.config('ui', 'logtemplate')
1960 tmpl = ui.config('ui', 'logtemplate')
1961 if tmpl:
1961 if tmpl:
1962 return logtemplatespec(templater.unquotestring(tmpl), None)
1962 return logtemplatespec(templater.unquotestring(tmpl), None)
1963 else:
1963 else:
1964 style = util.expandpath(ui.config('ui', 'style'))
1964 style = util.expandpath(ui.config('ui', 'style'))
1965
1965
1966 if not tmpl and style:
1966 if not tmpl and style:
1967 mapfile = style
1967 mapfile = style
1968 if not os.path.split(mapfile)[0]:
1968 if not os.path.split(mapfile)[0]:
1969 mapname = (templater.templatepath('map-cmdline.' + mapfile)
1969 mapname = (templater.templatepath('map-cmdline.' + mapfile)
1970 or templater.templatepath(mapfile))
1970 or templater.templatepath(mapfile))
1971 if mapname:
1971 if mapname:
1972 mapfile = mapname
1972 mapfile = mapname
1973 return logtemplatespec(None, mapfile)
1973 return logtemplatespec(None, mapfile)
1974
1974
1975 if not tmpl:
1975 if not tmpl:
1976 return logtemplatespec(None, None)
1976 return logtemplatespec(None, None)
1977
1977
1978 return formatter.lookuptemplate(ui, 'changeset', tmpl)
1978 return formatter.lookuptemplate(ui, 'changeset', tmpl)
1979
1979
1980 def makelogtemplater(ui, repo, tmpl, buffered=False):
1980 def makelogtemplater(ui, repo, tmpl, buffered=False):
1981 """Create a changeset_templater from a literal template 'tmpl'
1981 """Create a changeset_templater from a literal template 'tmpl'
1982 byte-string."""
1982 byte-string."""
1983 spec = logtemplatespec(tmpl, None)
1983 spec = logtemplatespec(tmpl, None)
1984 return changeset_templater(ui, repo, spec, buffered=buffered)
1984 return changeset_templater(ui, repo, spec, buffered=buffered)
1985
1985
1986 def show_changeset(ui, repo, opts, buffered=False):
1986 def show_changeset(ui, repo, opts, buffered=False):
1987 """show one changeset using template or regular display.
1987 """show one changeset using template or regular display.
1988
1988
1989 Display format will be the first non-empty hit of:
1989 Display format will be the first non-empty hit of:
1990 1. option 'template'
1990 1. option 'template'
1991 2. option 'style'
1991 2. option 'style'
1992 3. [ui] setting 'logtemplate'
1992 3. [ui] setting 'logtemplate'
1993 4. [ui] setting 'style'
1993 4. [ui] setting 'style'
1994 If all of these values are either the unset or the empty string,
1994 If all of these values are either the unset or the empty string,
1995 regular display via changeset_printer() is done.
1995 regular display via changeset_printer() is done.
1996 """
1996 """
1997 # options
1997 # options
1998 match = None
1998 match = None
1999 if opts.get('patch') or opts.get('stat'):
1999 if opts.get('patch') or opts.get('stat'):
2000 match = scmutil.matchall(repo)
2000 match = scmutil.matchall(repo)
2001
2001
2002 if opts.get('template') == 'json':
2002 if opts.get('template') == 'json':
2003 return jsonchangeset(ui, repo, match, opts, buffered)
2003 return jsonchangeset(ui, repo, match, opts, buffered)
2004
2004
2005 spec = _lookuplogtemplate(ui, opts.get('template'), opts.get('style'))
2005 spec = _lookuplogtemplate(ui, opts.get('template'), opts.get('style'))
2006
2006
2007 if not spec.ref and not spec.tmpl and not spec.mapfile:
2007 if not spec.ref and not spec.tmpl and not spec.mapfile:
2008 return changeset_printer(ui, repo, match, opts, buffered)
2008 return changeset_printer(ui, repo, match, opts, buffered)
2009
2009
2010 return changeset_templater(ui, repo, spec, match, opts, buffered)
2010 return changeset_templater(ui, repo, spec, match, opts, buffered)
2011
2011
2012 def showmarker(fm, marker, index=None):
2012 def showmarker(fm, marker, index=None):
2013 """utility function to display obsolescence marker in a readable way
2013 """utility function to display obsolescence marker in a readable way
2014
2014
2015 To be used by debug function."""
2015 To be used by debug function."""
2016 if index is not None:
2016 if index is not None:
2017 fm.write('index', '%i ', index)
2017 fm.write('index', '%i ', index)
2018 fm.write('prednode', '%s ', hex(marker.prednode()))
2018 fm.write('prednode', '%s ', hex(marker.prednode()))
2019 succs = marker.succnodes()
2019 succs = marker.succnodes()
2020 fm.condwrite(succs, 'succnodes', '%s ',
2020 fm.condwrite(succs, 'succnodes', '%s ',
2021 fm.formatlist(map(hex, succs), name='node'))
2021 fm.formatlist(map(hex, succs), name='node'))
2022 fm.write('flag', '%X ', marker.flags())
2022 fm.write('flag', '%X ', marker.flags())
2023 parents = marker.parentnodes()
2023 parents = marker.parentnodes()
2024 if parents is not None:
2024 if parents is not None:
2025 fm.write('parentnodes', '{%s} ',
2025 fm.write('parentnodes', '{%s} ',
2026 fm.formatlist(map(hex, parents), name='node', sep=', '))
2026 fm.formatlist(map(hex, parents), name='node', sep=', '))
2027 fm.write('date', '(%s) ', fm.formatdate(marker.date()))
2027 fm.write('date', '(%s) ', fm.formatdate(marker.date()))
2028 meta = marker.metadata().copy()
2028 meta = marker.metadata().copy()
2029 meta.pop('date', None)
2029 meta.pop('date', None)
2030 fm.write('metadata', '{%s}', fm.formatdict(meta, fmt='%r: %r', sep=', '))
2030 fm.write('metadata', '{%s}', fm.formatdict(meta, fmt='%r: %r', sep=', '))
2031 fm.plain('\n')
2031 fm.plain('\n')
2032
2032
2033 def finddate(ui, repo, date):
2033 def finddate(ui, repo, date):
2034 """Find the tipmost changeset that matches the given date spec"""
2034 """Find the tipmost changeset that matches the given date spec"""
2035
2035
2036 df = util.matchdate(date)
2036 df = util.matchdate(date)
2037 m = scmutil.matchall(repo)
2037 m = scmutil.matchall(repo)
2038 results = {}
2038 results = {}
2039
2039
2040 def prep(ctx, fns):
2040 def prep(ctx, fns):
2041 d = ctx.date()
2041 d = ctx.date()
2042 if df(d[0]):
2042 if df(d[0]):
2043 results[ctx.rev()] = d
2043 results[ctx.rev()] = d
2044
2044
2045 for ctx in walkchangerevs(repo, m, {'rev': None}, prep):
2045 for ctx in walkchangerevs(repo, m, {'rev': None}, prep):
2046 rev = ctx.rev()
2046 rev = ctx.rev()
2047 if rev in results:
2047 if rev in results:
2048 ui.status(_("found revision %s from %s\n") %
2048 ui.status(_("found revision %s from %s\n") %
2049 (rev, util.datestr(results[rev])))
2049 (rev, util.datestr(results[rev])))
2050 return '%d' % rev
2050 return '%d' % rev
2051
2051
2052 raise error.Abort(_("revision matching date not found"))
2052 raise error.Abort(_("revision matching date not found"))
2053
2053
2054 def increasingwindows(windowsize=8, sizelimit=512):
2054 def increasingwindows(windowsize=8, sizelimit=512):
2055 while True:
2055 while True:
2056 yield windowsize
2056 yield windowsize
2057 if windowsize < sizelimit:
2057 if windowsize < sizelimit:
2058 windowsize *= 2
2058 windowsize *= 2
2059
2059
2060 class FileWalkError(Exception):
2060 class FileWalkError(Exception):
2061 pass
2061 pass
2062
2062
2063 def walkfilerevs(repo, match, follow, revs, fncache):
2063 def walkfilerevs(repo, match, follow, revs, fncache):
2064 '''Walks the file history for the matched files.
2064 '''Walks the file history for the matched files.
2065
2065
2066 Returns the changeset revs that are involved in the file history.
2066 Returns the changeset revs that are involved in the file history.
2067
2067
2068 Throws FileWalkError if the file history can't be walked using
2068 Throws FileWalkError if the file history can't be walked using
2069 filelogs alone.
2069 filelogs alone.
2070 '''
2070 '''
2071 wanted = set()
2071 wanted = set()
2072 copies = []
2072 copies = []
2073 minrev, maxrev = min(revs), max(revs)
2073 minrev, maxrev = min(revs), max(revs)
2074 def filerevgen(filelog, last):
2074 def filerevgen(filelog, last):
2075 """
2075 """
2076 Only files, no patterns. Check the history of each file.
2076 Only files, no patterns. Check the history of each file.
2077
2077
2078 Examines filelog entries within minrev, maxrev linkrev range
2078 Examines filelog entries within minrev, maxrev linkrev range
2079 Returns an iterator yielding (linkrev, parentlinkrevs, copied)
2079 Returns an iterator yielding (linkrev, parentlinkrevs, copied)
2080 tuples in backwards order
2080 tuples in backwards order
2081 """
2081 """
2082 cl_count = len(repo)
2082 cl_count = len(repo)
2083 revs = []
2083 revs = []
2084 for j in xrange(0, last + 1):
2084 for j in xrange(0, last + 1):
2085 linkrev = filelog.linkrev(j)
2085 linkrev = filelog.linkrev(j)
2086 if linkrev < minrev:
2086 if linkrev < minrev:
2087 continue
2087 continue
2088 # only yield rev for which we have the changelog, it can
2088 # only yield rev for which we have the changelog, it can
2089 # happen while doing "hg log" during a pull or commit
2089 # happen while doing "hg log" during a pull or commit
2090 if linkrev >= cl_count:
2090 if linkrev >= cl_count:
2091 break
2091 break
2092
2092
2093 parentlinkrevs = []
2093 parentlinkrevs = []
2094 for p in filelog.parentrevs(j):
2094 for p in filelog.parentrevs(j):
2095 if p != nullrev:
2095 if p != nullrev:
2096 parentlinkrevs.append(filelog.linkrev(p))
2096 parentlinkrevs.append(filelog.linkrev(p))
2097 n = filelog.node(j)
2097 n = filelog.node(j)
2098 revs.append((linkrev, parentlinkrevs,
2098 revs.append((linkrev, parentlinkrevs,
2099 follow and filelog.renamed(n)))
2099 follow and filelog.renamed(n)))
2100
2100
2101 return reversed(revs)
2101 return reversed(revs)
2102 def iterfiles():
2102 def iterfiles():
2103 pctx = repo['.']
2103 pctx = repo['.']
2104 for filename in match.files():
2104 for filename in match.files():
2105 if follow:
2105 if follow:
2106 if filename not in pctx:
2106 if filename not in pctx:
2107 raise error.Abort(_('cannot follow file not in parent '
2107 raise error.Abort(_('cannot follow file not in parent '
2108 'revision: "%s"') % filename)
2108 'revision: "%s"') % filename)
2109 yield filename, pctx[filename].filenode()
2109 yield filename, pctx[filename].filenode()
2110 else:
2110 else:
2111 yield filename, None
2111 yield filename, None
2112 for filename_node in copies:
2112 for filename_node in copies:
2113 yield filename_node
2113 yield filename_node
2114
2114
2115 for file_, node in iterfiles():
2115 for file_, node in iterfiles():
2116 filelog = repo.file(file_)
2116 filelog = repo.file(file_)
2117 if not len(filelog):
2117 if not len(filelog):
2118 if node is None:
2118 if node is None:
2119 # A zero count may be a directory or deleted file, so
2119 # A zero count may be a directory or deleted file, so
2120 # try to find matching entries on the slow path.
2120 # try to find matching entries on the slow path.
2121 if follow:
2121 if follow:
2122 raise error.Abort(
2122 raise error.Abort(
2123 _('cannot follow nonexistent file: "%s"') % file_)
2123 _('cannot follow nonexistent file: "%s"') % file_)
2124 raise FileWalkError("Cannot walk via filelog")
2124 raise FileWalkError("Cannot walk via filelog")
2125 else:
2125 else:
2126 continue
2126 continue
2127
2127
2128 if node is None:
2128 if node is None:
2129 last = len(filelog) - 1
2129 last = len(filelog) - 1
2130 else:
2130 else:
2131 last = filelog.rev(node)
2131 last = filelog.rev(node)
2132
2132
2133 # keep track of all ancestors of the file
2133 # keep track of all ancestors of the file
2134 ancestors = {filelog.linkrev(last)}
2134 ancestors = {filelog.linkrev(last)}
2135
2135
2136 # iterate from latest to oldest revision
2136 # iterate from latest to oldest revision
2137 for rev, flparentlinkrevs, copied in filerevgen(filelog, last):
2137 for rev, flparentlinkrevs, copied in filerevgen(filelog, last):
2138 if not follow:
2138 if not follow:
2139 if rev > maxrev:
2139 if rev > maxrev:
2140 continue
2140 continue
2141 else:
2141 else:
2142 # Note that last might not be the first interesting
2142 # Note that last might not be the first interesting
2143 # rev to us:
2143 # rev to us:
2144 # if the file has been changed after maxrev, we'll
2144 # if the file has been changed after maxrev, we'll
2145 # have linkrev(last) > maxrev, and we still need
2145 # have linkrev(last) > maxrev, and we still need
2146 # to explore the file graph
2146 # to explore the file graph
2147 if rev not in ancestors:
2147 if rev not in ancestors:
2148 continue
2148 continue
2149 # XXX insert 1327 fix here
2149 # XXX insert 1327 fix here
2150 if flparentlinkrevs:
2150 if flparentlinkrevs:
2151 ancestors.update(flparentlinkrevs)
2151 ancestors.update(flparentlinkrevs)
2152
2152
2153 fncache.setdefault(rev, []).append(file_)
2153 fncache.setdefault(rev, []).append(file_)
2154 wanted.add(rev)
2154 wanted.add(rev)
2155 if copied:
2155 if copied:
2156 copies.append(copied)
2156 copies.append(copied)
2157
2157
2158 return wanted
2158 return wanted
2159
2159
2160 class _followfilter(object):
2160 class _followfilter(object):
2161 def __init__(self, repo, onlyfirst=False):
2161 def __init__(self, repo, onlyfirst=False):
2162 self.repo = repo
2162 self.repo = repo
2163 self.startrev = nullrev
2163 self.startrev = nullrev
2164 self.roots = set()
2164 self.roots = set()
2165 self.onlyfirst = onlyfirst
2165 self.onlyfirst = onlyfirst
2166
2166
2167 def match(self, rev):
2167 def match(self, rev):
2168 def realparents(rev):
2168 def realparents(rev):
2169 if self.onlyfirst:
2169 if self.onlyfirst:
2170 return self.repo.changelog.parentrevs(rev)[0:1]
2170 return self.repo.changelog.parentrevs(rev)[0:1]
2171 else:
2171 else:
2172 return filter(lambda x: x != nullrev,
2172 return filter(lambda x: x != nullrev,
2173 self.repo.changelog.parentrevs(rev))
2173 self.repo.changelog.parentrevs(rev))
2174
2174
2175 if self.startrev == nullrev:
2175 if self.startrev == nullrev:
2176 self.startrev = rev
2176 self.startrev = rev
2177 return True
2177 return True
2178
2178
2179 if rev > self.startrev:
2179 if rev > self.startrev:
2180 # forward: all descendants
2180 # forward: all descendants
2181 if not self.roots:
2181 if not self.roots:
2182 self.roots.add(self.startrev)
2182 self.roots.add(self.startrev)
2183 for parent in realparents(rev):
2183 for parent in realparents(rev):
2184 if parent in self.roots:
2184 if parent in self.roots:
2185 self.roots.add(rev)
2185 self.roots.add(rev)
2186 return True
2186 return True
2187 else:
2187 else:
2188 # backwards: all parents
2188 # backwards: all parents
2189 if not self.roots:
2189 if not self.roots:
2190 self.roots.update(realparents(self.startrev))
2190 self.roots.update(realparents(self.startrev))
2191 if rev in self.roots:
2191 if rev in self.roots:
2192 self.roots.remove(rev)
2192 self.roots.remove(rev)
2193 self.roots.update(realparents(rev))
2193 self.roots.update(realparents(rev))
2194 return True
2194 return True
2195
2195
2196 return False
2196 return False
2197
2197
2198 def walkchangerevs(repo, match, opts, prepare):
2198 def walkchangerevs(repo, match, opts, prepare):
2199 '''Iterate over files and the revs in which they changed.
2199 '''Iterate over files and the revs in which they changed.
2200
2200
2201 Callers most commonly need to iterate backwards over the history
2201 Callers most commonly need to iterate backwards over the history
2202 in which they are interested. Doing so has awful (quadratic-looking)
2202 in which they are interested. Doing so has awful (quadratic-looking)
2203 performance, so we use iterators in a "windowed" way.
2203 performance, so we use iterators in a "windowed" way.
2204
2204
2205 We walk a window of revisions in the desired order. Within the
2205 We walk a window of revisions in the desired order. Within the
2206 window, we first walk forwards to gather data, then in the desired
2206 window, we first walk forwards to gather data, then in the desired
2207 order (usually backwards) to display it.
2207 order (usually backwards) to display it.
2208
2208
2209 This function returns an iterator yielding contexts. Before
2209 This function returns an iterator yielding contexts. Before
2210 yielding each context, the iterator will first call the prepare
2210 yielding each context, the iterator will first call the prepare
2211 function on each context in the window in forward order.'''
2211 function on each context in the window in forward order.'''
2212
2212
2213 follow = opts.get('follow') or opts.get('follow_first')
2213 follow = opts.get('follow') or opts.get('follow_first')
2214 revs = _logrevs(repo, opts)
2214 revs = _logrevs(repo, opts)
2215 if not revs:
2215 if not revs:
2216 return []
2216 return []
2217 wanted = set()
2217 wanted = set()
2218 slowpath = match.anypats() or ((match.isexact() or match.prefix()) and
2218 slowpath = match.anypats() or ((match.isexact() or match.prefix()) and
2219 opts.get('removed'))
2219 opts.get('removed'))
2220 fncache = {}
2220 fncache = {}
2221 change = repo.changectx
2221 change = repo.changectx
2222
2222
2223 # First step is to fill wanted, the set of revisions that we want to yield.
2223 # First step is to fill wanted, the set of revisions that we want to yield.
2224 # When it does not induce extra cost, we also fill fncache for revisions in
2224 # When it does not induce extra cost, we also fill fncache for revisions in
2225 # wanted: a cache of filenames that were changed (ctx.files()) and that
2225 # wanted: a cache of filenames that were changed (ctx.files()) and that
2226 # match the file filtering conditions.
2226 # match the file filtering conditions.
2227
2227
2228 if match.always():
2228 if match.always():
2229 # No files, no patterns. Display all revs.
2229 # No files, no patterns. Display all revs.
2230 wanted = revs
2230 wanted = revs
2231 elif not slowpath:
2231 elif not slowpath:
2232 # We only have to read through the filelog to find wanted revisions
2232 # We only have to read through the filelog to find wanted revisions
2233
2233
2234 try:
2234 try:
2235 wanted = walkfilerevs(repo, match, follow, revs, fncache)
2235 wanted = walkfilerevs(repo, match, follow, revs, fncache)
2236 except FileWalkError:
2236 except FileWalkError:
2237 slowpath = True
2237 slowpath = True
2238
2238
2239 # We decided to fall back to the slowpath because at least one
2239 # We decided to fall back to the slowpath because at least one
2240 # of the paths was not a file. Check to see if at least one of them
2240 # of the paths was not a file. Check to see if at least one of them
2241 # existed in history, otherwise simply return
2241 # existed in history, otherwise simply return
2242 for path in match.files():
2242 for path in match.files():
2243 if path == '.' or path in repo.store:
2243 if path == '.' or path in repo.store:
2244 break
2244 break
2245 else:
2245 else:
2246 return []
2246 return []
2247
2247
2248 if slowpath:
2248 if slowpath:
2249 # We have to read the changelog to match filenames against
2249 # We have to read the changelog to match filenames against
2250 # changed files
2250 # changed files
2251
2251
2252 if follow:
2252 if follow:
2253 raise error.Abort(_('can only follow copies/renames for explicit '
2253 raise error.Abort(_('can only follow copies/renames for explicit '
2254 'filenames'))
2254 'filenames'))
2255
2255
2256 # The slow path checks files modified in every changeset.
2256 # The slow path checks files modified in every changeset.
2257 # This is really slow on large repos, so compute the set lazily.
2257 # This is really slow on large repos, so compute the set lazily.
2258 class lazywantedset(object):
2258 class lazywantedset(object):
2259 def __init__(self):
2259 def __init__(self):
2260 self.set = set()
2260 self.set = set()
2261 self.revs = set(revs)
2261 self.revs = set(revs)
2262
2262
2263 # No need to worry about locality here because it will be accessed
2263 # No need to worry about locality here because it will be accessed
2264 # in the same order as the increasing window below.
2264 # in the same order as the increasing window below.
2265 def __contains__(self, value):
2265 def __contains__(self, value):
2266 if value in self.set:
2266 if value in self.set:
2267 return True
2267 return True
2268 elif not value in self.revs:
2268 elif not value in self.revs:
2269 return False
2269 return False
2270 else:
2270 else:
2271 self.revs.discard(value)
2271 self.revs.discard(value)
2272 ctx = change(value)
2272 ctx = change(value)
2273 matches = filter(match, ctx.files())
2273 matches = filter(match, ctx.files())
2274 if matches:
2274 if matches:
2275 fncache[value] = matches
2275 fncache[value] = matches
2276 self.set.add(value)
2276 self.set.add(value)
2277 return True
2277 return True
2278 return False
2278 return False
2279
2279
2280 def discard(self, value):
2280 def discard(self, value):
2281 self.revs.discard(value)
2281 self.revs.discard(value)
2282 self.set.discard(value)
2282 self.set.discard(value)
2283
2283
2284 wanted = lazywantedset()
2284 wanted = lazywantedset()
2285
2285
2286 # it might be worthwhile to do this in the iterator if the rev range
2286 # it might be worthwhile to do this in the iterator if the rev range
2287 # is descending and the prune args are all within that range
2287 # is descending and the prune args are all within that range
2288 for rev in opts.get('prune', ()):
2288 for rev in opts.get('prune', ()):
2289 rev = repo[rev].rev()
2289 rev = repo[rev].rev()
2290 ff = _followfilter(repo)
2290 ff = _followfilter(repo)
2291 stop = min(revs[0], revs[-1])
2291 stop = min(revs[0], revs[-1])
2292 for x in xrange(rev, stop - 1, -1):
2292 for x in xrange(rev, stop - 1, -1):
2293 if ff.match(x):
2293 if ff.match(x):
2294 wanted = wanted - [x]
2294 wanted = wanted - [x]
2295
2295
2296 # Now that wanted is correctly initialized, we can iterate over the
2296 # Now that wanted is correctly initialized, we can iterate over the
2297 # revision range, yielding only revisions in wanted.
2297 # revision range, yielding only revisions in wanted.
2298 def iterate():
2298 def iterate():
2299 if follow and match.always():
2299 if follow and match.always():
2300 ff = _followfilter(repo, onlyfirst=opts.get('follow_first'))
2300 ff = _followfilter(repo, onlyfirst=opts.get('follow_first'))
2301 def want(rev):
2301 def want(rev):
2302 return ff.match(rev) and rev in wanted
2302 return ff.match(rev) and rev in wanted
2303 else:
2303 else:
2304 def want(rev):
2304 def want(rev):
2305 return rev in wanted
2305 return rev in wanted
2306
2306
2307 it = iter(revs)
2307 it = iter(revs)
2308 stopiteration = False
2308 stopiteration = False
2309 for windowsize in increasingwindows():
2309 for windowsize in increasingwindows():
2310 nrevs = []
2310 nrevs = []
2311 for i in xrange(windowsize):
2311 for i in xrange(windowsize):
2312 rev = next(it, None)
2312 rev = next(it, None)
2313 if rev is None:
2313 if rev is None:
2314 stopiteration = True
2314 stopiteration = True
2315 break
2315 break
2316 elif want(rev):
2316 elif want(rev):
2317 nrevs.append(rev)
2317 nrevs.append(rev)
2318 for rev in sorted(nrevs):
2318 for rev in sorted(nrevs):
2319 fns = fncache.get(rev)
2319 fns = fncache.get(rev)
2320 ctx = change(rev)
2320 ctx = change(rev)
2321 if not fns:
2321 if not fns:
2322 def fns_generator():
2322 def fns_generator():
2323 for f in ctx.files():
2323 for f in ctx.files():
2324 if match(f):
2324 if match(f):
2325 yield f
2325 yield f
2326 fns = fns_generator()
2326 fns = fns_generator()
2327 prepare(ctx, fns)
2327 prepare(ctx, fns)
2328 for rev in nrevs:
2328 for rev in nrevs:
2329 yield change(rev)
2329 yield change(rev)
2330
2330
2331 if stopiteration:
2331 if stopiteration:
2332 break
2332 break
2333
2333
2334 return iterate()
2334 return iterate()
2335
2335
2336 def _makefollowlogfilematcher(repo, files, followfirst):
2336 def _makefollowlogfilematcher(repo, files, followfirst):
2337 # When displaying a revision with --patch --follow FILE, we have
2337 # When displaying a revision with --patch --follow FILE, we have
2338 # to know which file of the revision must be diffed. With
2338 # to know which file of the revision must be diffed. With
2339 # --follow, we want the names of the ancestors of FILE in the
2339 # --follow, we want the names of the ancestors of FILE in the
2340 # revision, stored in "fcache". "fcache" is populated by
2340 # revision, stored in "fcache". "fcache" is populated by
2341 # reproducing the graph traversal already done by --follow revset
2341 # reproducing the graph traversal already done by --follow revset
2342 # and relating revs to file names (which is not "correct" but
2342 # and relating revs to file names (which is not "correct" but
2343 # good enough).
2343 # good enough).
2344 fcache = {}
2344 fcache = {}
2345 fcacheready = [False]
2345 fcacheready = [False]
2346 pctx = repo['.']
2346 pctx = repo['.']
2347
2347
2348 def populate():
2348 def populate():
2349 for fn in files:
2349 for fn in files:
2350 fctx = pctx[fn]
2350 fctx = pctx[fn]
2351 fcache.setdefault(fctx.introrev(), set()).add(fctx.path())
2351 fcache.setdefault(fctx.introrev(), set()).add(fctx.path())
2352 for c in fctx.ancestors(followfirst=followfirst):
2352 for c in fctx.ancestors(followfirst=followfirst):
2353 fcache.setdefault(c.rev(), set()).add(c.path())
2353 fcache.setdefault(c.rev(), set()).add(c.path())
2354
2354
2355 def filematcher(rev):
2355 def filematcher(rev):
2356 if not fcacheready[0]:
2356 if not fcacheready[0]:
2357 # Lazy initialization
2357 # Lazy initialization
2358 fcacheready[0] = True
2358 fcacheready[0] = True
2359 populate()
2359 populate()
2360 return scmutil.matchfiles(repo, fcache.get(rev, []))
2360 return scmutil.matchfiles(repo, fcache.get(rev, []))
2361
2361
2362 return filematcher
2362 return filematcher
2363
2363
2364 def _makenofollowlogfilematcher(repo, pats, opts):
2364 def _makenofollowlogfilematcher(repo, pats, opts):
2365 '''hook for extensions to override the filematcher for non-follow cases'''
2365 '''hook for extensions to override the filematcher for non-follow cases'''
2366 return None
2366 return None
2367
2367
2368 def _makelogrevset(repo, pats, opts, revs):
2368 def _makelogrevset(repo, pats, opts, revs):
2369 """Return (expr, filematcher) where expr is a revset string built
2369 """Return (expr, filematcher) where expr is a revset string built
2370 from log options and file patterns or None. If --stat or --patch
2370 from log options and file patterns or None. If --stat or --patch
2371 are not passed filematcher is None. Otherwise it is a callable
2371 are not passed filematcher is None. Otherwise it is a callable
2372 taking a revision number and returning a match objects filtering
2372 taking a revision number and returning a match objects filtering
2373 the files to be detailed when displaying the revision.
2373 the files to be detailed when displaying the revision.
2374 """
2374 """
2375 opt2revset = {
2375 opt2revset = {
2376 'no_merges': ('not merge()', None),
2376 'no_merges': ('not merge()', None),
2377 'only_merges': ('merge()', None),
2377 'only_merges': ('merge()', None),
2378 '_ancestors': ('ancestors(%(val)s)', None),
2378 '_ancestors': ('ancestors(%(val)s)', None),
2379 '_fancestors': ('_firstancestors(%(val)s)', None),
2379 '_fancestors': ('_firstancestors(%(val)s)', None),
2380 '_descendants': ('descendants(%(val)s)', None),
2380 '_descendants': ('descendants(%(val)s)', None),
2381 '_fdescendants': ('_firstdescendants(%(val)s)', None),
2381 '_fdescendants': ('_firstdescendants(%(val)s)', None),
2382 '_matchfiles': ('_matchfiles(%(val)s)', None),
2382 '_matchfiles': ('_matchfiles(%(val)s)', None),
2383 'date': ('date(%(val)r)', None),
2383 'date': ('date(%(val)r)', None),
2384 'branch': ('branch(%(val)r)', ' or '),
2384 'branch': ('branch(%(val)r)', ' or '),
2385 '_patslog': ('filelog(%(val)r)', ' or '),
2385 '_patslog': ('filelog(%(val)r)', ' or '),
2386 '_patsfollow': ('follow(%(val)r)', ' or '),
2386 '_patsfollow': ('follow(%(val)r)', ' or '),
2387 '_patsfollowfirst': ('_followfirst(%(val)r)', ' or '),
2387 '_patsfollowfirst': ('_followfirst(%(val)r)', ' or '),
2388 'keyword': ('keyword(%(val)r)', ' or '),
2388 'keyword': ('keyword(%(val)r)', ' or '),
2389 'prune': ('not (%(val)r or ancestors(%(val)r))', ' and '),
2389 'prune': ('not (%(val)r or ancestors(%(val)r))', ' and '),
2390 'user': ('user(%(val)r)', ' or '),
2390 'user': ('user(%(val)r)', ' or '),
2391 }
2391 }
2392
2392
2393 opts = dict(opts)
2393 opts = dict(opts)
2394 # follow or not follow?
2394 # follow or not follow?
2395 follow = opts.get('follow') or opts.get('follow_first')
2395 follow = opts.get('follow') or opts.get('follow_first')
2396 if opts.get('follow_first'):
2396 if opts.get('follow_first'):
2397 followfirst = 1
2397 followfirst = 1
2398 else:
2398 else:
2399 followfirst = 0
2399 followfirst = 0
2400 # --follow with FILE behavior depends on revs...
2400 # --follow with FILE behavior depends on revs...
2401 it = iter(revs)
2401 it = iter(revs)
2402 startrev = next(it)
2402 startrev = next(it)
2403 followdescendants = startrev < next(it, startrev)
2403 followdescendants = startrev < next(it, startrev)
2404
2404
2405 # branch and only_branch are really aliases and must be handled at
2405 # branch and only_branch are really aliases and must be handled at
2406 # the same time
2406 # the same time
2407 opts['branch'] = opts.get('branch', []) + opts.get('only_branch', [])
2407 opts['branch'] = opts.get('branch', []) + opts.get('only_branch', [])
2408 opts['branch'] = [repo.lookupbranch(b) for b in opts['branch']]
2408 opts['branch'] = [repo.lookupbranch(b) for b in opts['branch']]
2409 # pats/include/exclude are passed to match.match() directly in
2409 # pats/include/exclude are passed to match.match() directly in
2410 # _matchfiles() revset but walkchangerevs() builds its matcher with
2410 # _matchfiles() revset but walkchangerevs() builds its matcher with
2411 # scmutil.match(). The difference is input pats are globbed on
2411 # scmutil.match(). The difference is input pats are globbed on
2412 # platforms without shell expansion (windows).
2412 # platforms without shell expansion (windows).
2413 wctx = repo[None]
2413 wctx = repo[None]
2414 match, pats = scmutil.matchandpats(wctx, pats, opts)
2414 match, pats = scmutil.matchandpats(wctx, pats, opts)
2415 slowpath = match.anypats() or ((match.isexact() or match.prefix()) and
2415 slowpath = match.anypats() or ((match.isexact() or match.prefix()) and
2416 opts.get('removed'))
2416 opts.get('removed'))
2417 if not slowpath:
2417 if not slowpath:
2418 for f in match.files():
2418 for f in match.files():
2419 if follow and f not in wctx:
2419 if follow and f not in wctx:
2420 # If the file exists, it may be a directory, so let it
2420 # If the file exists, it may be a directory, so let it
2421 # take the slow path.
2421 # take the slow path.
2422 if os.path.exists(repo.wjoin(f)):
2422 if os.path.exists(repo.wjoin(f)):
2423 slowpath = True
2423 slowpath = True
2424 continue
2424 continue
2425 else:
2425 else:
2426 raise error.Abort(_('cannot follow file not in parent '
2426 raise error.Abort(_('cannot follow file not in parent '
2427 'revision: "%s"') % f)
2427 'revision: "%s"') % f)
2428 filelog = repo.file(f)
2428 filelog = repo.file(f)
2429 if not filelog:
2429 if not filelog:
2430 # A zero count may be a directory or deleted file, so
2430 # A zero count may be a directory or deleted file, so
2431 # try to find matching entries on the slow path.
2431 # try to find matching entries on the slow path.
2432 if follow:
2432 if follow:
2433 raise error.Abort(
2433 raise error.Abort(
2434 _('cannot follow nonexistent file: "%s"') % f)
2434 _('cannot follow nonexistent file: "%s"') % f)
2435 slowpath = True
2435 slowpath = True
2436
2436
2437 # We decided to fall back to the slowpath because at least one
2437 # We decided to fall back to the slowpath because at least one
2438 # of the paths was not a file. Check to see if at least one of them
2438 # of the paths was not a file. Check to see if at least one of them
2439 # existed in history - in that case, we'll continue down the
2439 # existed in history - in that case, we'll continue down the
2440 # slowpath; otherwise, we can turn off the slowpath
2440 # slowpath; otherwise, we can turn off the slowpath
2441 if slowpath:
2441 if slowpath:
2442 for path in match.files():
2442 for path in match.files():
2443 if path == '.' or path in repo.store:
2443 if path == '.' or path in repo.store:
2444 break
2444 break
2445 else:
2445 else:
2446 slowpath = False
2446 slowpath = False
2447
2447
2448 fpats = ('_patsfollow', '_patsfollowfirst')
2448 fpats = ('_patsfollow', '_patsfollowfirst')
2449 fnopats = (('_ancestors', '_fancestors'),
2449 fnopats = (('_ancestors', '_fancestors'),
2450 ('_descendants', '_fdescendants'))
2450 ('_descendants', '_fdescendants'))
2451 if slowpath:
2451 if slowpath:
2452 # See walkchangerevs() slow path.
2452 # See walkchangerevs() slow path.
2453 #
2453 #
2454 # pats/include/exclude cannot be represented as separate
2454 # pats/include/exclude cannot be represented as separate
2455 # revset expressions as their filtering logic applies at file
2455 # revset expressions as their filtering logic applies at file
2456 # level. For instance "-I a -X a" matches a revision touching
2456 # level. For instance "-I a -X a" matches a revision touching
2457 # "a" and "b" while "file(a) and not file(b)" does
2457 # "a" and "b" while "file(a) and not file(b)" does
2458 # not. Besides, filesets are evaluated against the working
2458 # not. Besides, filesets are evaluated against the working
2459 # directory.
2459 # directory.
2460 matchargs = ['r:', 'd:relpath']
2460 matchargs = ['r:', 'd:relpath']
2461 for p in pats:
2461 for p in pats:
2462 matchargs.append('p:' + p)
2462 matchargs.append('p:' + p)
2463 for p in opts.get('include', []):
2463 for p in opts.get('include', []):
2464 matchargs.append('i:' + p)
2464 matchargs.append('i:' + p)
2465 for p in opts.get('exclude', []):
2465 for p in opts.get('exclude', []):
2466 matchargs.append('x:' + p)
2466 matchargs.append('x:' + p)
2467 matchargs = ','.join(('%r' % p) for p in matchargs)
2467 matchargs = ','.join(('%r' % p) for p in matchargs)
2468 opts['_matchfiles'] = matchargs
2468 opts['_matchfiles'] = matchargs
2469 if follow:
2469 if follow:
2470 opts[fnopats[0][followfirst]] = '.'
2470 opts[fnopats[0][followfirst]] = '.'
2471 else:
2471 else:
2472 if follow:
2472 if follow:
2473 if pats:
2473 if pats:
2474 # follow() revset interprets its file argument as a
2474 # follow() revset interprets its file argument as a
2475 # manifest entry, so use match.files(), not pats.
2475 # manifest entry, so use match.files(), not pats.
2476 opts[fpats[followfirst]] = list(match.files())
2476 opts[fpats[followfirst]] = list(match.files())
2477 else:
2477 else:
2478 op = fnopats[followdescendants][followfirst]
2478 op = fnopats[followdescendants][followfirst]
2479 opts[op] = 'rev(%d)' % startrev
2479 opts[op] = 'rev(%d)' % startrev
2480 else:
2480 else:
2481 opts['_patslog'] = list(pats)
2481 opts['_patslog'] = list(pats)
2482
2482
2483 filematcher = None
2483 filematcher = None
2484 if opts.get('patch') or opts.get('stat'):
2484 if opts.get('patch') or opts.get('stat'):
2485 # When following files, track renames via a special matcher.
2485 # When following files, track renames via a special matcher.
2486 # If we're forced to take the slowpath it means we're following
2486 # If we're forced to take the slowpath it means we're following
2487 # at least one pattern/directory, so don't bother with rename tracking.
2487 # at least one pattern/directory, so don't bother with rename tracking.
2488 if follow and not match.always() and not slowpath:
2488 if follow and not match.always() and not slowpath:
2489 # _makefollowlogfilematcher expects its files argument to be
2489 # _makefollowlogfilematcher expects its files argument to be
2490 # relative to the repo root, so use match.files(), not pats.
2490 # relative to the repo root, so use match.files(), not pats.
2491 filematcher = _makefollowlogfilematcher(repo, match.files(),
2491 filematcher = _makefollowlogfilematcher(repo, match.files(),
2492 followfirst)
2492 followfirst)
2493 else:
2493 else:
2494 filematcher = _makenofollowlogfilematcher(repo, pats, opts)
2494 filematcher = _makenofollowlogfilematcher(repo, pats, opts)
2495 if filematcher is None:
2495 if filematcher is None:
2496 filematcher = lambda rev: match
2496 filematcher = lambda rev: match
2497
2497
2498 expr = []
2498 expr = []
2499 for op, val in sorted(opts.iteritems()):
2499 for op, val in sorted(opts.iteritems()):
2500 if not val:
2500 if not val:
2501 continue
2501 continue
2502 if op not in opt2revset:
2502 if op not in opt2revset:
2503 continue
2503 continue
2504 revop, andor = opt2revset[op]
2504 revop, andor = opt2revset[op]
2505 if '%(val)' not in revop:
2505 if '%(val)' not in revop:
2506 expr.append(revop)
2506 expr.append(revop)
2507 else:
2507 else:
2508 if not isinstance(val, list):
2508 if not isinstance(val, list):
2509 e = revop % {'val': val}
2509 e = revop % {'val': val}
2510 else:
2510 else:
2511 e = '(' + andor.join((revop % {'val': v}) for v in val) + ')'
2511 e = '(' + andor.join((revop % {'val': v}) for v in val) + ')'
2512 expr.append(e)
2512 expr.append(e)
2513
2513
2514 if expr:
2514 if expr:
2515 expr = '(' + ' and '.join(expr) + ')'
2515 expr = '(' + ' and '.join(expr) + ')'
2516 else:
2516 else:
2517 expr = None
2517 expr = None
2518 return expr, filematcher
2518 return expr, filematcher
2519
2519
2520 def _logrevs(repo, opts):
2520 def _logrevs(repo, opts):
2521 # Default --rev value depends on --follow but --follow behavior
2521 # Default --rev value depends on --follow but --follow behavior
2522 # depends on revisions resolved from --rev...
2522 # depends on revisions resolved from --rev...
2523 follow = opts.get('follow') or opts.get('follow_first')
2523 follow = opts.get('follow') or opts.get('follow_first')
2524 if opts.get('rev'):
2524 if opts.get('rev'):
2525 revs = scmutil.revrange(repo, opts['rev'])
2525 revs = scmutil.revrange(repo, opts['rev'])
2526 elif follow and repo.dirstate.p1() == nullid:
2526 elif follow and repo.dirstate.p1() == nullid:
2527 revs = smartset.baseset()
2527 revs = smartset.baseset()
2528 elif follow:
2528 elif follow:
2529 revs = repo.revs('reverse(:.)')
2529 revs = repo.revs('reverse(:.)')
2530 else:
2530 else:
2531 revs = smartset.spanset(repo)
2531 revs = smartset.spanset(repo)
2532 revs.reverse()
2532 revs.reverse()
2533 return revs
2533 return revs
2534
2534
2535 def getgraphlogrevs(repo, pats, opts):
2535 def getgraphlogrevs(repo, pats, opts):
2536 """Return (revs, expr, filematcher) where revs is an iterable of
2536 """Return (revs, expr, filematcher) where revs is an iterable of
2537 revision numbers, expr is a revset string built from log options
2537 revision numbers, expr is a revset string built from log options
2538 and file patterns or None, and used to filter 'revs'. If --stat or
2538 and file patterns or None, and used to filter 'revs'. If --stat or
2539 --patch are not passed filematcher is None. Otherwise it is a
2539 --patch are not passed filematcher is None. Otherwise it is a
2540 callable taking a revision number and returning a match objects
2540 callable taking a revision number and returning a match objects
2541 filtering the files to be detailed when displaying the revision.
2541 filtering the files to be detailed when displaying the revision.
2542 """
2542 """
2543 limit = loglimit(opts)
2543 limit = loglimit(opts)
2544 revs = _logrevs(repo, opts)
2544 revs = _logrevs(repo, opts)
2545 if not revs:
2545 if not revs:
2546 return smartset.baseset(), None, None
2546 return smartset.baseset(), None, None
2547 expr, filematcher = _makelogrevset(repo, pats, opts, revs)
2547 expr, filematcher = _makelogrevset(repo, pats, opts, revs)
2548 if opts.get('rev'):
2548 if opts.get('rev'):
2549 # User-specified revs might be unsorted, but don't sort before
2549 # User-specified revs might be unsorted, but don't sort before
2550 # _makelogrevset because it might depend on the order of revs
2550 # _makelogrevset because it might depend on the order of revs
2551 if not (revs.isdescending() or revs.istopo()):
2551 if not (revs.isdescending() or revs.istopo()):
2552 revs.sort(reverse=True)
2552 revs.sort(reverse=True)
2553 if expr:
2553 if expr:
2554 matcher = revset.match(repo.ui, expr)
2554 matcher = revset.match(repo.ui, expr)
2555 revs = matcher(repo, revs)
2555 revs = matcher(repo, revs)
2556 if limit is not None:
2556 if limit is not None:
2557 limitedrevs = []
2557 limitedrevs = []
2558 for idx, rev in enumerate(revs):
2558 for idx, rev in enumerate(revs):
2559 if idx >= limit:
2559 if idx >= limit:
2560 break
2560 break
2561 limitedrevs.append(rev)
2561 limitedrevs.append(rev)
2562 revs = smartset.baseset(limitedrevs)
2562 revs = smartset.baseset(limitedrevs)
2563
2563
2564 return revs, expr, filematcher
2564 return revs, expr, filematcher
2565
2565
2566 def getlogrevs(repo, pats, opts):
2566 def getlogrevs(repo, pats, opts):
2567 """Return (revs, expr, filematcher) where revs is an iterable of
2567 """Return (revs, expr, filematcher) where revs is an iterable of
2568 revision numbers, expr is a revset string built from log options
2568 revision numbers, expr is a revset string built from log options
2569 and file patterns or None, and used to filter 'revs'. If --stat or
2569 and file patterns or None, and used to filter 'revs'. If --stat or
2570 --patch are not passed filematcher is None. Otherwise it is a
2570 --patch are not passed filematcher is None. Otherwise it is a
2571 callable taking a revision number and returning a match objects
2571 callable taking a revision number and returning a match objects
2572 filtering the files to be detailed when displaying the revision.
2572 filtering the files to be detailed when displaying the revision.
2573 """
2573 """
2574 limit = loglimit(opts)
2574 limit = loglimit(opts)
2575 revs = _logrevs(repo, opts)
2575 revs = _logrevs(repo, opts)
2576 if not revs:
2576 if not revs:
2577 return smartset.baseset([]), None, None
2577 return smartset.baseset([]), None, None
2578 expr, filematcher = _makelogrevset(repo, pats, opts, revs)
2578 expr, filematcher = _makelogrevset(repo, pats, opts, revs)
2579 if expr:
2579 if expr:
2580 matcher = revset.match(repo.ui, expr)
2580 matcher = revset.match(repo.ui, expr)
2581 revs = matcher(repo, revs)
2581 revs = matcher(repo, revs)
2582 if limit is not None:
2582 if limit is not None:
2583 limitedrevs = []
2583 limitedrevs = []
2584 for idx, r in enumerate(revs):
2584 for idx, r in enumerate(revs):
2585 if limit <= idx:
2585 if limit <= idx:
2586 break
2586 break
2587 limitedrevs.append(r)
2587 limitedrevs.append(r)
2588 revs = smartset.baseset(limitedrevs)
2588 revs = smartset.baseset(limitedrevs)
2589
2589
2590 return revs, expr, filematcher
2590 return revs, expr, filematcher
2591
2591
2592 def _parselinerangelogopt(repo, opts):
2592 def _parselinerangelogopt(repo, opts):
2593 """Parse --line-range log option and return a list of tuples (filename,
2593 """Parse --line-range log option and return a list of tuples (filename,
2594 (fromline, toline)).
2594 (fromline, toline)).
2595 """
2595 """
2596 linerangebyfname = []
2596 linerangebyfname = []
2597 for pat in opts.get('line_range', []):
2597 for pat in opts.get('line_range', []):
2598 try:
2598 try:
2599 pat, linerange = pat.rsplit(',', 1)
2599 pat, linerange = pat.rsplit(',', 1)
2600 except ValueError:
2600 except ValueError:
2601 raise error.Abort(_('malformatted line-range pattern %s') % pat)
2601 raise error.Abort(_('malformatted line-range pattern %s') % pat)
2602 try:
2602 try:
2603 fromline, toline = map(int, linerange.split(':'))
2603 fromline, toline = map(int, linerange.split(':'))
2604 except ValueError:
2604 except ValueError:
2605 raise error.Abort(_("invalid line range for %s") % pat)
2605 raise error.Abort(_("invalid line range for %s") % pat)
2606 msg = _("line range pattern '%s' must match exactly one file") % pat
2606 msg = _("line range pattern '%s' must match exactly one file") % pat
2607 fname = scmutil.parsefollowlinespattern(repo, None, pat, msg)
2607 fname = scmutil.parsefollowlinespattern(repo, None, pat, msg)
2608 linerangebyfname.append(
2608 linerangebyfname.append(
2609 (fname, util.processlinerange(fromline, toline)))
2609 (fname, util.processlinerange(fromline, toline)))
2610 return linerangebyfname
2610 return linerangebyfname
2611
2611
2612 def getloglinerangerevs(repo, userrevs, opts):
2612 def getloglinerangerevs(repo, userrevs, opts):
2613 """Return (revs, filematcher, hunksfilter).
2613 """Return (revs, filematcher, hunksfilter).
2614
2614
2615 "revs" are revisions obtained by processing "line-range" log options and
2615 "revs" are revisions obtained by processing "line-range" log options and
2616 walking block ancestors of each specified file/line-range.
2616 walking block ancestors of each specified file/line-range.
2617
2617
2618 "filematcher(rev) -> match" is a factory function returning a match object
2618 "filematcher(rev) -> match" is a factory function returning a match object
2619 for a given revision for file patterns specified in --line-range option.
2619 for a given revision for file patterns specified in --line-range option.
2620 If neither --stat nor --patch options are passed, "filematcher" is None.
2620 If neither --stat nor --patch options are passed, "filematcher" is None.
2621
2621
2622 "hunksfilter(rev) -> filterfn(fctx, hunks)" is a factory function
2622 "hunksfilter(rev) -> filterfn(fctx, hunks)" is a factory function
2623 returning a hunks filtering function.
2623 returning a hunks filtering function.
2624 If neither --stat nor --patch options are passed, "filterhunks" is None.
2624 If neither --stat nor --patch options are passed, "filterhunks" is None.
2625 """
2625 """
2626 wctx = repo[None]
2626 wctx = repo[None]
2627
2627
2628 # Two-levels map of "rev -> file ctx -> [line range]".
2628 # Two-levels map of "rev -> file ctx -> [line range]".
2629 linerangesbyrev = {}
2629 linerangesbyrev = {}
2630 for fname, (fromline, toline) in _parselinerangelogopt(repo, opts):
2630 for fname, (fromline, toline) in _parselinerangelogopt(repo, opts):
2631 if fname not in wctx:
2631 if fname not in wctx:
2632 raise error.Abort(_('cannot follow file not in parent '
2632 raise error.Abort(_('cannot follow file not in parent '
2633 'revision: "%s"') % fname)
2633 'revision: "%s"') % fname)
2634 fctx = wctx.filectx(fname)
2634 fctx = wctx.filectx(fname)
2635 for fctx, linerange in dagop.blockancestors(fctx, fromline, toline):
2635 for fctx, linerange in dagop.blockancestors(fctx, fromline, toline):
2636 rev = fctx.introrev()
2636 rev = fctx.introrev()
2637 if rev not in userrevs:
2637 if rev not in userrevs:
2638 continue
2638 continue
2639 linerangesbyrev.setdefault(
2639 linerangesbyrev.setdefault(
2640 rev, {}).setdefault(
2640 rev, {}).setdefault(
2641 fctx.path(), []).append(linerange)
2641 fctx.path(), []).append(linerange)
2642
2642
2643 filematcher = None
2643 filematcher = None
2644 hunksfilter = None
2644 hunksfilter = None
2645 if opts.get('patch') or opts.get('stat'):
2645 if opts.get('patch') or opts.get('stat'):
2646
2646
2647 def nofilterhunksfn(fctx, hunks):
2647 def nofilterhunksfn(fctx, hunks):
2648 return hunks
2648 return hunks
2649
2649
2650 def hunksfilter(rev):
2650 def hunksfilter(rev):
2651 fctxlineranges = linerangesbyrev.get(rev)
2651 fctxlineranges = linerangesbyrev.get(rev)
2652 if fctxlineranges is None:
2652 if fctxlineranges is None:
2653 return nofilterhunksfn
2653 return nofilterhunksfn
2654
2654
2655 def filterfn(fctx, hunks):
2655 def filterfn(fctx, hunks):
2656 lineranges = fctxlineranges.get(fctx.path())
2656 lineranges = fctxlineranges.get(fctx.path())
2657 if lineranges is not None:
2657 if lineranges is not None:
2658 for hr, lines in hunks:
2658 for hr, lines in hunks:
2659 if hr is None: # binary
2659 if hr is None: # binary
2660 yield hr, lines
2660 yield hr, lines
2661 continue
2661 continue
2662 if any(mdiff.hunkinrange(hr[2:], lr)
2662 if any(mdiff.hunkinrange(hr[2:], lr)
2663 for lr in lineranges):
2663 for lr in lineranges):
2664 yield hr, lines
2664 yield hr, lines
2665 else:
2665 else:
2666 for hunk in hunks:
2666 for hunk in hunks:
2667 yield hunk
2667 yield hunk
2668
2668
2669 return filterfn
2669 return filterfn
2670
2670
2671 def filematcher(rev):
2671 def filematcher(rev):
2672 files = list(linerangesbyrev.get(rev, []))
2672 files = list(linerangesbyrev.get(rev, []))
2673 return scmutil.matchfiles(repo, files)
2673 return scmutil.matchfiles(repo, files)
2674
2674
2675 revs = sorted(linerangesbyrev, reverse=True)
2675 revs = sorted(linerangesbyrev, reverse=True)
2676
2676
2677 return revs, filematcher, hunksfilter
2677 return revs, filematcher, hunksfilter
2678
2678
2679 def _graphnodeformatter(ui, displayer):
2679 def _graphnodeformatter(ui, displayer):
2680 spec = ui.config('ui', 'graphnodetemplate')
2680 spec = ui.config('ui', 'graphnodetemplate')
2681 if not spec:
2681 if not spec:
2682 return templatekw.showgraphnode # fast path for "{graphnode}"
2682 return templatekw.showgraphnode # fast path for "{graphnode}"
2683
2683
2684 spec = templater.unquotestring(spec)
2684 spec = templater.unquotestring(spec)
2685 templ = formatter.maketemplater(ui, spec)
2685 templ = formatter.maketemplater(ui, spec)
2686 cache = {}
2686 cache = {}
2687 if isinstance(displayer, changeset_templater):
2687 if isinstance(displayer, changeset_templater):
2688 cache = displayer.cache # reuse cache of slow templates
2688 cache = displayer.cache # reuse cache of slow templates
2689 props = templatekw.keywords.copy()
2689 props = templatekw.keywords.copy()
2690 props['templ'] = templ
2690 props['templ'] = templ
2691 props['cache'] = cache
2691 props['cache'] = cache
2692 def formatnode(repo, ctx):
2692 def formatnode(repo, ctx):
2693 props['ctx'] = ctx
2693 props['ctx'] = ctx
2694 props['repo'] = repo
2694 props['repo'] = repo
2695 props['ui'] = repo.ui
2695 props['ui'] = repo.ui
2696 props['revcache'] = {}
2696 props['revcache'] = {}
2697 return templ.render(props)
2697 return templ.render(props)
2698 return formatnode
2698 return formatnode
2699
2699
2700 def displaygraph(ui, repo, dag, displayer, edgefn, getrenamed=None,
2700 def displaygraph(ui, repo, dag, displayer, edgefn, getrenamed=None,
2701 filematcher=None, props=None):
2701 filematcher=None, props=None):
2702 props = props or {}
2702 props = props or {}
2703 formatnode = _graphnodeformatter(ui, displayer)
2703 formatnode = _graphnodeformatter(ui, displayer)
2704 state = graphmod.asciistate()
2704 state = graphmod.asciistate()
2705 styles = state['styles']
2705 styles = state['styles']
2706
2706
2707 # only set graph styling if HGPLAIN is not set.
2707 # only set graph styling if HGPLAIN is not set.
2708 if ui.plain('graph'):
2708 if ui.plain('graph'):
2709 # set all edge styles to |, the default pre-3.8 behaviour
2709 # set all edge styles to |, the default pre-3.8 behaviour
2710 styles.update(dict.fromkeys(styles, '|'))
2710 styles.update(dict.fromkeys(styles, '|'))
2711 else:
2711 else:
2712 edgetypes = {
2712 edgetypes = {
2713 'parent': graphmod.PARENT,
2713 'parent': graphmod.PARENT,
2714 'grandparent': graphmod.GRANDPARENT,
2714 'grandparent': graphmod.GRANDPARENT,
2715 'missing': graphmod.MISSINGPARENT
2715 'missing': graphmod.MISSINGPARENT
2716 }
2716 }
2717 for name, key in edgetypes.items():
2717 for name, key in edgetypes.items():
2718 # experimental config: experimental.graphstyle.*
2718 # experimental config: experimental.graphstyle.*
2719 styles[key] = ui.config('experimental', 'graphstyle.%s' % name,
2719 styles[key] = ui.config('experimental', 'graphstyle.%s' % name,
2720 styles[key])
2720 styles[key])
2721 if not styles[key]:
2721 if not styles[key]:
2722 styles[key] = None
2722 styles[key] = None
2723
2723
2724 # experimental config: experimental.graphshorten
2724 # experimental config: experimental.graphshorten
2725 state['graphshorten'] = ui.configbool('experimental', 'graphshorten')
2725 state['graphshorten'] = ui.configbool('experimental', 'graphshorten')
2726
2726
2727 for rev, type, ctx, parents in dag:
2727 for rev, type, ctx, parents in dag:
2728 char = formatnode(repo, ctx)
2728 char = formatnode(repo, ctx)
2729 copies = None
2729 copies = None
2730 if getrenamed and ctx.rev():
2730 if getrenamed and ctx.rev():
2731 copies = []
2731 copies = []
2732 for fn in ctx.files():
2732 for fn in ctx.files():
2733 rename = getrenamed(fn, ctx.rev())
2733 rename = getrenamed(fn, ctx.rev())
2734 if rename:
2734 if rename:
2735 copies.append((fn, rename[0]))
2735 copies.append((fn, rename[0]))
2736 revmatchfn = None
2736 revmatchfn = None
2737 if filematcher is not None:
2737 if filematcher is not None:
2738 revmatchfn = filematcher(ctx.rev())
2738 revmatchfn = filematcher(ctx.rev())
2739 edges = edgefn(type, char, state, rev, parents)
2739 edges = edgefn(type, char, state, rev, parents)
2740 firstedge = next(edges)
2740 firstedge = next(edges)
2741 width = firstedge[2]
2741 width = firstedge[2]
2742 displayer.show(ctx, copies=copies, matchfn=revmatchfn,
2742 displayer.show(ctx, copies=copies, matchfn=revmatchfn,
2743 _graphwidth=width, **props)
2743 _graphwidth=width, **props)
2744 lines = displayer.hunk.pop(rev).split('\n')
2744 lines = displayer.hunk.pop(rev).split('\n')
2745 if not lines[-1]:
2745 if not lines[-1]:
2746 del lines[-1]
2746 del lines[-1]
2747 displayer.flush(ctx)
2747 displayer.flush(ctx)
2748 for type, char, width, coldata in itertools.chain([firstedge], edges):
2748 for type, char, width, coldata in itertools.chain([firstedge], edges):
2749 graphmod.ascii(ui, state, type, char, lines, coldata)
2749 graphmod.ascii(ui, state, type, char, lines, coldata)
2750 lines = []
2750 lines = []
2751 displayer.close()
2751 displayer.close()
2752
2752
2753 def graphlog(ui, repo, pats, opts):
2753 def graphlog(ui, repo, pats, opts):
2754 # Parameters are identical to log command ones
2754 # Parameters are identical to log command ones
2755 revs, expr, filematcher = getgraphlogrevs(repo, pats, opts)
2755 revs, expr, filematcher = getgraphlogrevs(repo, pats, opts)
2756 revdag = graphmod.dagwalker(repo, revs)
2756 revdag = graphmod.dagwalker(repo, revs)
2757
2757
2758 getrenamed = None
2758 getrenamed = None
2759 if opts.get('copies'):
2759 if opts.get('copies'):
2760 endrev = None
2760 endrev = None
2761 if opts.get('rev'):
2761 if opts.get('rev'):
2762 endrev = scmutil.revrange(repo, opts.get('rev')).max() + 1
2762 endrev = scmutil.revrange(repo, opts.get('rev')).max() + 1
2763 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
2763 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
2764
2764
2765 ui.pager('log')
2765 ui.pager('log')
2766 displayer = show_changeset(ui, repo, opts, buffered=True)
2766 displayer = show_changeset(ui, repo, opts, buffered=True)
2767 displaygraph(ui, repo, revdag, displayer, graphmod.asciiedges, getrenamed,
2767 displaygraph(ui, repo, revdag, displayer, graphmod.asciiedges, getrenamed,
2768 filematcher)
2768 filematcher)
2769
2769
2770 def checkunsupportedgraphflags(pats, opts):
2770 def checkunsupportedgraphflags(pats, opts):
2771 for op in ["newest_first"]:
2771 for op in ["newest_first"]:
2772 if op in opts and opts[op]:
2772 if op in opts and opts[op]:
2773 raise error.Abort(_("-G/--graph option is incompatible with --%s")
2773 raise error.Abort(_("-G/--graph option is incompatible with --%s")
2774 % op.replace("_", "-"))
2774 % op.replace("_", "-"))
2775
2775
2776 def graphrevs(repo, nodes, opts):
2776 def graphrevs(repo, nodes, opts):
2777 limit = loglimit(opts)
2777 limit = loglimit(opts)
2778 nodes.reverse()
2778 nodes.reverse()
2779 if limit is not None:
2779 if limit is not None:
2780 nodes = nodes[:limit]
2780 nodes = nodes[:limit]
2781 return graphmod.nodes(repo, nodes)
2781 return graphmod.nodes(repo, nodes)
2782
2782
2783 def add(ui, repo, match, prefix, explicitonly, **opts):
2783 def add(ui, repo, match, prefix, explicitonly, **opts):
2784 join = lambda f: os.path.join(prefix, f)
2784 join = lambda f: os.path.join(prefix, f)
2785 bad = []
2785 bad = []
2786
2786
2787 badfn = lambda x, y: bad.append(x) or match.bad(x, y)
2787 badfn = lambda x, y: bad.append(x) or match.bad(x, y)
2788 names = []
2788 names = []
2789 wctx = repo[None]
2789 wctx = repo[None]
2790 cca = None
2790 cca = None
2791 abort, warn = scmutil.checkportabilityalert(ui)
2791 abort, warn = scmutil.checkportabilityalert(ui)
2792 if abort or warn:
2792 if abort or warn:
2793 cca = scmutil.casecollisionauditor(ui, abort, repo.dirstate)
2793 cca = scmutil.casecollisionauditor(ui, abort, repo.dirstate)
2794
2794
2795 badmatch = matchmod.badmatch(match, badfn)
2795 badmatch = matchmod.badmatch(match, badfn)
2796 dirstate = repo.dirstate
2796 dirstate = repo.dirstate
2797 # We don't want to just call wctx.walk here, since it would return a lot of
2797 # We don't want to just call wctx.walk here, since it would return a lot of
2798 # clean files, which we aren't interested in and takes time.
2798 # clean files, which we aren't interested in and takes time.
2799 for f in sorted(dirstate.walk(badmatch, subrepos=sorted(wctx.substate),
2799 for f in sorted(dirstate.walk(badmatch, subrepos=sorted(wctx.substate),
2800 unknown=True, ignored=False, full=False)):
2800 unknown=True, ignored=False, full=False)):
2801 exact = match.exact(f)
2801 exact = match.exact(f)
2802 if exact or not explicitonly and f not in wctx and repo.wvfs.lexists(f):
2802 if exact or not explicitonly and f not in wctx and repo.wvfs.lexists(f):
2803 if cca:
2803 if cca:
2804 cca(f)
2804 cca(f)
2805 names.append(f)
2805 names.append(f)
2806 if ui.verbose or not exact:
2806 if ui.verbose or not exact:
2807 ui.status(_('adding %s\n') % match.rel(f))
2807 ui.status(_('adding %s\n') % match.rel(f))
2808
2808
2809 for subpath in sorted(wctx.substate):
2809 for subpath in sorted(wctx.substate):
2810 sub = wctx.sub(subpath)
2810 sub = wctx.sub(subpath)
2811 try:
2811 try:
2812 submatch = matchmod.subdirmatcher(subpath, match)
2812 submatch = matchmod.subdirmatcher(subpath, match)
2813 if opts.get(r'subrepos'):
2813 if opts.get(r'subrepos'):
2814 bad.extend(sub.add(ui, submatch, prefix, False, **opts))
2814 bad.extend(sub.add(ui, submatch, prefix, False, **opts))
2815 else:
2815 else:
2816 bad.extend(sub.add(ui, submatch, prefix, True, **opts))
2816 bad.extend(sub.add(ui, submatch, prefix, True, **opts))
2817 except error.LookupError:
2817 except error.LookupError:
2818 ui.status(_("skipping missing subrepository: %s\n")
2818 ui.status(_("skipping missing subrepository: %s\n")
2819 % join(subpath))
2819 % join(subpath))
2820
2820
2821 if not opts.get(r'dry_run'):
2821 if not opts.get(r'dry_run'):
2822 rejected = wctx.add(names, prefix)
2822 rejected = wctx.add(names, prefix)
2823 bad.extend(f for f in rejected if f in match.files())
2823 bad.extend(f for f in rejected if f in match.files())
2824 return bad
2824 return bad
2825
2825
2826 def addwebdirpath(repo, serverpath, webconf):
2826 def addwebdirpath(repo, serverpath, webconf):
2827 webconf[serverpath] = repo.root
2827 webconf[serverpath] = repo.root
2828 repo.ui.debug('adding %s = %s\n' % (serverpath, repo.root))
2828 repo.ui.debug('adding %s = %s\n' % (serverpath, repo.root))
2829
2829
2830 for r in repo.revs('filelog("path:.hgsub")'):
2830 for r in repo.revs('filelog("path:.hgsub")'):
2831 ctx = repo[r]
2831 ctx = repo[r]
2832 for subpath in ctx.substate:
2832 for subpath in ctx.substate:
2833 ctx.sub(subpath).addwebdirpath(serverpath, webconf)
2833 ctx.sub(subpath).addwebdirpath(serverpath, webconf)
2834
2834
2835 def forget(ui, repo, match, prefix, explicitonly):
2835 def forget(ui, repo, match, prefix, explicitonly):
2836 join = lambda f: os.path.join(prefix, f)
2836 join = lambda f: os.path.join(prefix, f)
2837 bad = []
2837 bad = []
2838 badfn = lambda x, y: bad.append(x) or match.bad(x, y)
2838 badfn = lambda x, y: bad.append(x) or match.bad(x, y)
2839 wctx = repo[None]
2839 wctx = repo[None]
2840 forgot = []
2840 forgot = []
2841
2841
2842 s = repo.status(match=matchmod.badmatch(match, badfn), clean=True)
2842 s = repo.status(match=matchmod.badmatch(match, badfn), clean=True)
2843 forget = sorted(s.modified + s.added + s.deleted + s.clean)
2843 forget = sorted(s.modified + s.added + s.deleted + s.clean)
2844 if explicitonly:
2844 if explicitonly:
2845 forget = [f for f in forget if match.exact(f)]
2845 forget = [f for f in forget if match.exact(f)]
2846
2846
2847 for subpath in sorted(wctx.substate):
2847 for subpath in sorted(wctx.substate):
2848 sub = wctx.sub(subpath)
2848 sub = wctx.sub(subpath)
2849 try:
2849 try:
2850 submatch = matchmod.subdirmatcher(subpath, match)
2850 submatch = matchmod.subdirmatcher(subpath, match)
2851 subbad, subforgot = sub.forget(submatch, prefix)
2851 subbad, subforgot = sub.forget(submatch, prefix)
2852 bad.extend([subpath + '/' + f for f in subbad])
2852 bad.extend([subpath + '/' + f for f in subbad])
2853 forgot.extend([subpath + '/' + f for f in subforgot])
2853 forgot.extend([subpath + '/' + f for f in subforgot])
2854 except error.LookupError:
2854 except error.LookupError:
2855 ui.status(_("skipping missing subrepository: %s\n")
2855 ui.status(_("skipping missing subrepository: %s\n")
2856 % join(subpath))
2856 % join(subpath))
2857
2857
2858 if not explicitonly:
2858 if not explicitonly:
2859 for f in match.files():
2859 for f in match.files():
2860 if f not in repo.dirstate and not repo.wvfs.isdir(f):
2860 if f not in repo.dirstate and not repo.wvfs.isdir(f):
2861 if f not in forgot:
2861 if f not in forgot:
2862 if repo.wvfs.exists(f):
2862 if repo.wvfs.exists(f):
2863 # Don't complain if the exact case match wasn't given.
2863 # Don't complain if the exact case match wasn't given.
2864 # But don't do this until after checking 'forgot', so
2864 # But don't do this until after checking 'forgot', so
2865 # that subrepo files aren't normalized, and this op is
2865 # that subrepo files aren't normalized, and this op is
2866 # purely from data cached by the status walk above.
2866 # purely from data cached by the status walk above.
2867 if repo.dirstate.normalize(f) in repo.dirstate:
2867 if repo.dirstate.normalize(f) in repo.dirstate:
2868 continue
2868 continue
2869 ui.warn(_('not removing %s: '
2869 ui.warn(_('not removing %s: '
2870 'file is already untracked\n')
2870 'file is already untracked\n')
2871 % match.rel(f))
2871 % match.rel(f))
2872 bad.append(f)
2872 bad.append(f)
2873
2873
2874 for f in forget:
2874 for f in forget:
2875 if ui.verbose or not match.exact(f):
2875 if ui.verbose or not match.exact(f):
2876 ui.status(_('removing %s\n') % match.rel(f))
2876 ui.status(_('removing %s\n') % match.rel(f))
2877
2877
2878 rejected = wctx.forget(forget, prefix)
2878 rejected = wctx.forget(forget, prefix)
2879 bad.extend(f for f in rejected if f in match.files())
2879 bad.extend(f for f in rejected if f in match.files())
2880 forgot.extend(f for f in forget if f not in rejected)
2880 forgot.extend(f for f in forget if f not in rejected)
2881 return bad, forgot
2881 return bad, forgot
2882
2882
2883 def files(ui, ctx, m, fm, fmt, subrepos):
2883 def files(ui, ctx, m, fm, fmt, subrepos):
2884 rev = ctx.rev()
2884 rev = ctx.rev()
2885 ret = 1
2885 ret = 1
2886 ds = ctx.repo().dirstate
2886 ds = ctx.repo().dirstate
2887
2887
2888 for f in ctx.matches(m):
2888 for f in ctx.matches(m):
2889 if rev is None and ds[f] == 'r':
2889 if rev is None and ds[f] == 'r':
2890 continue
2890 continue
2891 fm.startitem()
2891 fm.startitem()
2892 if ui.verbose:
2892 if ui.verbose:
2893 fc = ctx[f]
2893 fc = ctx[f]
2894 fm.write('size flags', '% 10d % 1s ', fc.size(), fc.flags())
2894 fm.write('size flags', '% 10d % 1s ', fc.size(), fc.flags())
2895 fm.data(abspath=f)
2895 fm.data(abspath=f)
2896 fm.write('path', fmt, m.rel(f))
2896 fm.write('path', fmt, m.rel(f))
2897 ret = 0
2897 ret = 0
2898
2898
2899 for subpath in sorted(ctx.substate):
2899 for subpath in sorted(ctx.substate):
2900 submatch = matchmod.subdirmatcher(subpath, m)
2900 submatch = matchmod.subdirmatcher(subpath, m)
2901 if (subrepos or m.exact(subpath) or any(submatch.files())):
2901 if (subrepos or m.exact(subpath) or any(submatch.files())):
2902 sub = ctx.sub(subpath)
2902 sub = ctx.sub(subpath)
2903 try:
2903 try:
2904 recurse = m.exact(subpath) or subrepos
2904 recurse = m.exact(subpath) or subrepos
2905 if sub.printfiles(ui, submatch, fm, fmt, recurse) == 0:
2905 if sub.printfiles(ui, submatch, fm, fmt, recurse) == 0:
2906 ret = 0
2906 ret = 0
2907 except error.LookupError:
2907 except error.LookupError:
2908 ui.status(_("skipping missing subrepository: %s\n")
2908 ui.status(_("skipping missing subrepository: %s\n")
2909 % m.abs(subpath))
2909 % m.abs(subpath))
2910
2910
2911 return ret
2911 return ret
2912
2912
2913 def remove(ui, repo, m, prefix, after, force, subrepos, warnings=None):
2913 def remove(ui, repo, m, prefix, after, force, subrepos, warnings=None):
2914 join = lambda f: os.path.join(prefix, f)
2914 join = lambda f: os.path.join(prefix, f)
2915 ret = 0
2915 ret = 0
2916 s = repo.status(match=m, clean=True)
2916 s = repo.status(match=m, clean=True)
2917 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
2917 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
2918
2918
2919 wctx = repo[None]
2919 wctx = repo[None]
2920
2920
2921 if warnings is None:
2921 if warnings is None:
2922 warnings = []
2922 warnings = []
2923 warn = True
2923 warn = True
2924 else:
2924 else:
2925 warn = False
2925 warn = False
2926
2926
2927 subs = sorted(wctx.substate)
2927 subs = sorted(wctx.substate)
2928 total = len(subs)
2928 total = len(subs)
2929 count = 0
2929 count = 0
2930 for subpath in subs:
2930 for subpath in subs:
2931 count += 1
2931 count += 1
2932 submatch = matchmod.subdirmatcher(subpath, m)
2932 submatch = matchmod.subdirmatcher(subpath, m)
2933 if subrepos or m.exact(subpath) or any(submatch.files()):
2933 if subrepos or m.exact(subpath) or any(submatch.files()):
2934 ui.progress(_('searching'), count, total=total, unit=_('subrepos'))
2934 ui.progress(_('searching'), count, total=total, unit=_('subrepos'))
2935 sub = wctx.sub(subpath)
2935 sub = wctx.sub(subpath)
2936 try:
2936 try:
2937 if sub.removefiles(submatch, prefix, after, force, subrepos,
2937 if sub.removefiles(submatch, prefix, after, force, subrepos,
2938 warnings):
2938 warnings):
2939 ret = 1
2939 ret = 1
2940 except error.LookupError:
2940 except error.LookupError:
2941 warnings.append(_("skipping missing subrepository: %s\n")
2941 warnings.append(_("skipping missing subrepository: %s\n")
2942 % join(subpath))
2942 % join(subpath))
2943 ui.progress(_('searching'), None)
2943 ui.progress(_('searching'), None)
2944
2944
2945 # warn about failure to delete explicit files/dirs
2945 # warn about failure to delete explicit files/dirs
2946 deleteddirs = util.dirs(deleted)
2946 deleteddirs = util.dirs(deleted)
2947 files = m.files()
2947 files = m.files()
2948 total = len(files)
2948 total = len(files)
2949 count = 0
2949 count = 0
2950 for f in files:
2950 for f in files:
2951 def insubrepo():
2951 def insubrepo():
2952 for subpath in wctx.substate:
2952 for subpath in wctx.substate:
2953 if f.startswith(subpath + '/'):
2953 if f.startswith(subpath + '/'):
2954 return True
2954 return True
2955 return False
2955 return False
2956
2956
2957 count += 1
2957 count += 1
2958 ui.progress(_('deleting'), count, total=total, unit=_('files'))
2958 ui.progress(_('deleting'), count, total=total, unit=_('files'))
2959 isdir = f in deleteddirs or wctx.hasdir(f)
2959 isdir = f in deleteddirs or wctx.hasdir(f)
2960 if (f in repo.dirstate or isdir or f == '.'
2960 if (f in repo.dirstate or isdir or f == '.'
2961 or insubrepo() or f in subs):
2961 or insubrepo() or f in subs):
2962 continue
2962 continue
2963
2963
2964 if repo.wvfs.exists(f):
2964 if repo.wvfs.exists(f):
2965 if repo.wvfs.isdir(f):
2965 if repo.wvfs.isdir(f):
2966 warnings.append(_('not removing %s: no tracked files\n')
2966 warnings.append(_('not removing %s: no tracked files\n')
2967 % m.rel(f))
2967 % m.rel(f))
2968 else:
2968 else:
2969 warnings.append(_('not removing %s: file is untracked\n')
2969 warnings.append(_('not removing %s: file is untracked\n')
2970 % m.rel(f))
2970 % m.rel(f))
2971 # missing files will generate a warning elsewhere
2971 # missing files will generate a warning elsewhere
2972 ret = 1
2972 ret = 1
2973 ui.progress(_('deleting'), None)
2973 ui.progress(_('deleting'), None)
2974
2974
2975 if force:
2975 if force:
2976 list = modified + deleted + clean + added
2976 list = modified + deleted + clean + added
2977 elif after:
2977 elif after:
2978 list = deleted
2978 list = deleted
2979 remaining = modified + added + clean
2979 remaining = modified + added + clean
2980 total = len(remaining)
2980 total = len(remaining)
2981 count = 0
2981 count = 0
2982 for f in remaining:
2982 for f in remaining:
2983 count += 1
2983 count += 1
2984 ui.progress(_('skipping'), count, total=total, unit=_('files'))
2984 ui.progress(_('skipping'), count, total=total, unit=_('files'))
2985 if ui.verbose or (f in files):
2985 if ui.verbose or (f in files):
2986 warnings.append(_('not removing %s: file still exists\n')
2986 warnings.append(_('not removing %s: file still exists\n')
2987 % m.rel(f))
2987 % m.rel(f))
2988 ret = 1
2988 ret = 1
2989 ui.progress(_('skipping'), None)
2989 ui.progress(_('skipping'), None)
2990 else:
2990 else:
2991 list = deleted + clean
2991 list = deleted + clean
2992 total = len(modified) + len(added)
2992 total = len(modified) + len(added)
2993 count = 0
2993 count = 0
2994 for f in modified:
2994 for f in modified:
2995 count += 1
2995 count += 1
2996 ui.progress(_('skipping'), count, total=total, unit=_('files'))
2996 ui.progress(_('skipping'), count, total=total, unit=_('files'))
2997 warnings.append(_('not removing %s: file is modified (use -f'
2997 warnings.append(_('not removing %s: file is modified (use -f'
2998 ' to force removal)\n') % m.rel(f))
2998 ' to force removal)\n') % m.rel(f))
2999 ret = 1
2999 ret = 1
3000 for f in added:
3000 for f in added:
3001 count += 1
3001 count += 1
3002 ui.progress(_('skipping'), count, total=total, unit=_('files'))
3002 ui.progress(_('skipping'), count, total=total, unit=_('files'))
3003 warnings.append(_("not removing %s: file has been marked for add"
3003 warnings.append(_("not removing %s: file has been marked for add"
3004 " (use 'hg forget' to undo add)\n") % m.rel(f))
3004 " (use 'hg forget' to undo add)\n") % m.rel(f))
3005 ret = 1
3005 ret = 1
3006 ui.progress(_('skipping'), None)
3006 ui.progress(_('skipping'), None)
3007
3007
3008 list = sorted(list)
3008 list = sorted(list)
3009 total = len(list)
3009 total = len(list)
3010 count = 0
3010 count = 0
3011 for f in list:
3011 for f in list:
3012 count += 1
3012 count += 1
3013 if ui.verbose or not m.exact(f):
3013 if ui.verbose or not m.exact(f):
3014 ui.progress(_('deleting'), count, total=total, unit=_('files'))
3014 ui.progress(_('deleting'), count, total=total, unit=_('files'))
3015 ui.status(_('removing %s\n') % m.rel(f))
3015 ui.status(_('removing %s\n') % m.rel(f))
3016 ui.progress(_('deleting'), None)
3016 ui.progress(_('deleting'), None)
3017
3017
3018 with repo.wlock():
3018 with repo.wlock():
3019 if not after:
3019 if not after:
3020 for f in list:
3020 for f in list:
3021 if f in added:
3021 if f in added:
3022 continue # we never unlink added files on remove
3022 continue # we never unlink added files on remove
3023 repo.wvfs.unlinkpath(f, ignoremissing=True)
3023 repo.wvfs.unlinkpath(f, ignoremissing=True)
3024 repo[None].forget(list)
3024 repo[None].forget(list)
3025
3025
3026 if warn:
3026 if warn:
3027 for warning in warnings:
3027 for warning in warnings:
3028 ui.warn(warning)
3028 ui.warn(warning)
3029
3029
3030 return ret
3030 return ret
3031
3031
3032 def cat(ui, repo, ctx, matcher, basefm, fntemplate, prefix, **opts):
3032 def cat(ui, repo, ctx, matcher, basefm, fntemplate, prefix, **opts):
3033 err = 1
3033 err = 1
3034
3034
3035 def write(path):
3035 def write(path):
3036 filename = None
3036 filename = None
3037 if fntemplate:
3037 if fntemplate:
3038 filename = makefilename(repo, fntemplate, ctx.node(),
3038 filename = makefilename(repo, fntemplate, ctx.node(),
3039 pathname=os.path.join(prefix, path))
3039 pathname=os.path.join(prefix, path))
3040 # attempt to create the directory if it does not already exist
3040 # attempt to create the directory if it does not already exist
3041 try:
3041 try:
3042 os.makedirs(os.path.dirname(filename))
3042 os.makedirs(os.path.dirname(filename))
3043 except OSError:
3043 except OSError:
3044 pass
3044 pass
3045 with formatter.maybereopen(basefm, filename, opts) as fm:
3045 with formatter.maybereopen(basefm, filename, opts) as fm:
3046 data = ctx[path].data()
3046 data = ctx[path].data()
3047 if opts.get('decode'):
3047 if opts.get('decode'):
3048 data = repo.wwritedata(path, data)
3048 data = repo.wwritedata(path, data)
3049 fm.startitem()
3049 fm.startitem()
3050 fm.write('data', '%s', data)
3050 fm.write('data', '%s', data)
3051 fm.data(abspath=path, path=matcher.rel(path))
3051 fm.data(abspath=path, path=matcher.rel(path))
3052
3052
3053 # Automation often uses hg cat on single files, so special case it
3053 # Automation often uses hg cat on single files, so special case it
3054 # for performance to avoid the cost of parsing the manifest.
3054 # for performance to avoid the cost of parsing the manifest.
3055 if len(matcher.files()) == 1 and not matcher.anypats():
3055 if len(matcher.files()) == 1 and not matcher.anypats():
3056 file = matcher.files()[0]
3056 file = matcher.files()[0]
3057 mfl = repo.manifestlog
3057 mfl = repo.manifestlog
3058 mfnode = ctx.manifestnode()
3058 mfnode = ctx.manifestnode()
3059 try:
3059 try:
3060 if mfnode and mfl[mfnode].find(file)[0]:
3060 if mfnode and mfl[mfnode].find(file)[0]:
3061 write(file)
3061 write(file)
3062 return 0
3062 return 0
3063 except KeyError:
3063 except KeyError:
3064 pass
3064 pass
3065
3065
3066 for abs in ctx.walk(matcher):
3066 for abs in ctx.walk(matcher):
3067 write(abs)
3067 write(abs)
3068 err = 0
3068 err = 0
3069
3069
3070 for subpath in sorted(ctx.substate):
3070 for subpath in sorted(ctx.substate):
3071 sub = ctx.sub(subpath)
3071 sub = ctx.sub(subpath)
3072 try:
3072 try:
3073 submatch = matchmod.subdirmatcher(subpath, matcher)
3073 submatch = matchmod.subdirmatcher(subpath, matcher)
3074
3074
3075 if not sub.cat(submatch, basefm, fntemplate,
3075 if not sub.cat(submatch, basefm, fntemplate,
3076 os.path.join(prefix, sub._path), **opts):
3076 os.path.join(prefix, sub._path), **opts):
3077 err = 0
3077 err = 0
3078 except error.RepoLookupError:
3078 except error.RepoLookupError:
3079 ui.status(_("skipping missing subrepository: %s\n")
3079 ui.status(_("skipping missing subrepository: %s\n")
3080 % os.path.join(prefix, subpath))
3080 % os.path.join(prefix, subpath))
3081
3081
3082 return err
3082 return err
3083
3083
3084 def commit(ui, repo, commitfunc, pats, opts):
3084 def commit(ui, repo, commitfunc, pats, opts):
3085 '''commit the specified files or all outstanding changes'''
3085 '''commit the specified files or all outstanding changes'''
3086 date = opts.get('date')
3086 date = opts.get('date')
3087 if date:
3087 if date:
3088 opts['date'] = util.parsedate(date)
3088 opts['date'] = util.parsedate(date)
3089 message = logmessage(ui, opts)
3089 message = logmessage(ui, opts)
3090 matcher = scmutil.match(repo[None], pats, opts)
3090 matcher = scmutil.match(repo[None], pats, opts)
3091
3091
3092 dsguard = None
3092 dsguard = None
3093 # extract addremove carefully -- this function can be called from a command
3093 # extract addremove carefully -- this function can be called from a command
3094 # that doesn't support addremove
3094 # that doesn't support addremove
3095 if opts.get('addremove'):
3095 if opts.get('addremove'):
3096 dsguard = dirstateguard.dirstateguard(repo, 'commit')
3096 dsguard = dirstateguard.dirstateguard(repo, 'commit')
3097 with dsguard or util.nullcontextmanager():
3097 with dsguard or util.nullcontextmanager():
3098 if dsguard:
3098 if dsguard:
3099 if scmutil.addremove(repo, matcher, "", opts) != 0:
3099 if scmutil.addremove(repo, matcher, "", opts) != 0:
3100 raise error.Abort(
3100 raise error.Abort(
3101 _("failed to mark all new/missing files as added/removed"))
3101 _("failed to mark all new/missing files as added/removed"))
3102
3102
3103 return commitfunc(ui, repo, message, matcher, opts)
3103 return commitfunc(ui, repo, message, matcher, opts)
3104
3104
3105 def samefile(f, ctx1, ctx2):
3105 def samefile(f, ctx1, ctx2):
3106 if f in ctx1.manifest():
3106 if f in ctx1.manifest():
3107 a = ctx1.filectx(f)
3107 a = ctx1.filectx(f)
3108 if f in ctx2.manifest():
3108 if f in ctx2.manifest():
3109 b = ctx2.filectx(f)
3109 b = ctx2.filectx(f)
3110 return (not a.cmp(b)
3110 return (not a.cmp(b)
3111 and a.flags() == b.flags())
3111 and a.flags() == b.flags())
3112 else:
3112 else:
3113 return False
3113 return False
3114 else:
3114 else:
3115 return f not in ctx2.manifest()
3115 return f not in ctx2.manifest()
3116
3116
3117 def amend(ui, repo, old, extra, pats, opts):
3117 def amend(ui, repo, old, extra, pats, opts):
3118 # avoid cycle context -> subrepo -> cmdutil
3118 # avoid cycle context -> subrepo -> cmdutil
3119 from . import context
3119 from . import context
3120
3120
3121 # amend will reuse the existing user if not specified, but the obsolete
3121 # amend will reuse the existing user if not specified, but the obsolete
3122 # marker creation requires that the current user's name is specified.
3122 # marker creation requires that the current user's name is specified.
3123 if obsolete.isenabled(repo, obsolete.createmarkersopt):
3123 if obsolete.isenabled(repo, obsolete.createmarkersopt):
3124 ui.username() # raise exception if username not set
3124 ui.username() # raise exception if username not set
3125
3125
3126 ui.note(_('amending changeset %s\n') % old)
3126 ui.note(_('amending changeset %s\n') % old)
3127 base = old.p1()
3127 base = old.p1()
3128
3128
3129 with repo.wlock(), repo.lock(), repo.transaction('amend'):
3129 with repo.wlock(), repo.lock(), repo.transaction('amend'):
3130 # Participating changesets:
3130 # Participating changesets:
3131 #
3131 #
3132 # wctx o - workingctx that contains changes from working copy
3132 # wctx o - workingctx that contains changes from working copy
3133 # | to go into amending commit
3133 # | to go into amending commit
3134 # |
3134 # |
3135 # old o - changeset to amend
3135 # old o - changeset to amend
3136 # |
3136 # |
3137 # base o - first parent of the changeset to amend
3137 # base o - first parent of the changeset to amend
3138 wctx = repo[None]
3138 wctx = repo[None]
3139
3139
3140 # Update extra dict from amended commit (e.g. to preserve graft
3140 # Update extra dict from amended commit (e.g. to preserve graft
3141 # source)
3141 # source)
3142 extra.update(old.extra())
3142 extra.update(old.extra())
3143
3143
3144 # Also update it from the from the wctx
3144 # Also update it from the from the wctx
3145 extra.update(wctx.extra())
3145 extra.update(wctx.extra())
3146
3146
3147 user = opts.get('user') or old.user()
3147 user = opts.get('user') or old.user()
3148 date = opts.get('date') or old.date()
3148 date = opts.get('date') or old.date()
3149
3149
3150 # Parse the date to allow comparison between date and old.date()
3150 # Parse the date to allow comparison between date and old.date()
3151 date = util.parsedate(date)
3151 date = util.parsedate(date)
3152
3152
3153 if len(old.parents()) > 1:
3153 if len(old.parents()) > 1:
3154 # ctx.files() isn't reliable for merges, so fall back to the
3154 # ctx.files() isn't reliable for merges, so fall back to the
3155 # slower repo.status() method
3155 # slower repo.status() method
3156 files = set([fn for st in repo.status(base, old)[:3]
3156 files = set([fn for st in repo.status(base, old)[:3]
3157 for fn in st])
3157 for fn in st])
3158 else:
3158 else:
3159 files = set(old.files())
3159 files = set(old.files())
3160
3160
3161 # add/remove the files to the working copy if the "addremove" option
3161 # add/remove the files to the working copy if the "addremove" option
3162 # was specified.
3162 # was specified.
3163 matcher = scmutil.match(wctx, pats, opts)
3163 matcher = scmutil.match(wctx, pats, opts)
3164 if (opts.get('addremove')
3164 if (opts.get('addremove')
3165 and scmutil.addremove(repo, matcher, "", opts)):
3165 and scmutil.addremove(repo, matcher, "", opts)):
3166 raise error.Abort(
3166 raise error.Abort(
3167 _("failed to mark all new/missing files as added/removed"))
3167 _("failed to mark all new/missing files as added/removed"))
3168
3168
3169 filestoamend = set(f for f in wctx.files() if matcher(f))
3169 filestoamend = set(f for f in wctx.files() if matcher(f))
3170
3170
3171 changes = (len(filestoamend) > 0)
3171 changes = (len(filestoamend) > 0)
3172 if changes:
3172 if changes:
3173 # Recompute copies (avoid recording a -> b -> a)
3173 # Recompute copies (avoid recording a -> b -> a)
3174 copied = copies.pathcopies(base, wctx, matcher)
3174 copied = copies.pathcopies(base, wctx, matcher)
3175 if old.p2:
3175 if old.p2:
3176 copied.update(copies.pathcopies(old.p2(), wctx, matcher))
3176 copied.update(copies.pathcopies(old.p2(), wctx, matcher))
3177
3177
3178 # Prune files which were reverted by the updates: if old
3178 # Prune files which were reverted by the updates: if old
3179 # introduced file X and the file was renamed in the working
3179 # introduced file X and the file was renamed in the working
3180 # copy, then those two files are the same and
3180 # copy, then those two files are the same and
3181 # we can discard X from our list of files. Likewise if X
3181 # we can discard X from our list of files. Likewise if X
3182 # was deleted, it's no longer relevant
3182 # was deleted, it's no longer relevant
3183 files.update(filestoamend)
3183 files.update(filestoamend)
3184 files = [f for f in files if not samefile(f, wctx, base)]
3184 files = [f for f in files if not samefile(f, wctx, base)]
3185
3185
3186 def filectxfn(repo, ctx_, path):
3186 def filectxfn(repo, ctx_, path):
3187 try:
3187 try:
3188 # If the file being considered is not amongst the files
3188 # If the file being considered is not amongst the files
3189 # to be amended, we should return the file context from the
3189 # to be amended, we should return the file context from the
3190 # old changeset. This avoids issues when only some files in
3190 # old changeset. This avoids issues when only some files in
3191 # the working copy are being amended but there are also
3191 # the working copy are being amended but there are also
3192 # changes to other files from the old changeset.
3192 # changes to other files from the old changeset.
3193 if path not in filestoamend:
3193 if path not in filestoamend:
3194 return old.filectx(path)
3194 return old.filectx(path)
3195
3195
3196 fctx = wctx[path]
3196 fctx = wctx[path]
3197
3197
3198 # Return None for removed files.
3198 # Return None for removed files.
3199 if not fctx.exists():
3199 if not fctx.exists():
3200 return None
3200 return None
3201
3201
3202 flags = fctx.flags()
3202 flags = fctx.flags()
3203 mctx = context.memfilectx(repo,
3203 mctx = context.memfilectx(repo,
3204 fctx.path(), fctx.data(),
3204 fctx.path(), fctx.data(),
3205 islink='l' in flags,
3205 islink='l' in flags,
3206 isexec='x' in flags,
3206 isexec='x' in flags,
3207 copied=copied.get(path))
3207 copied=copied.get(path))
3208 return mctx
3208 return mctx
3209 except KeyError:
3209 except KeyError:
3210 return None
3210 return None
3211 else:
3211 else:
3212 ui.note(_('copying changeset %s to %s\n') % (old, base))
3212 ui.note(_('copying changeset %s to %s\n') % (old, base))
3213
3213
3214 # Use version of files as in the old cset
3214 # Use version of files as in the old cset
3215 def filectxfn(repo, ctx_, path):
3215 def filectxfn(repo, ctx_, path):
3216 try:
3216 try:
3217 return old.filectx(path)
3217 return old.filectx(path)
3218 except KeyError:
3218 except KeyError:
3219 return None
3219 return None
3220
3220
3221 # See if we got a message from -m or -l, if not, open the editor with
3221 # See if we got a message from -m or -l, if not, open the editor with
3222 # the message of the changeset to amend.
3222 # the message of the changeset to amend.
3223 message = logmessage(ui, opts)
3223 message = logmessage(ui, opts)
3224
3224
3225 editform = mergeeditform(old, 'commit.amend')
3225 editform = mergeeditform(old, 'commit.amend')
3226 editor = getcommiteditor(editform=editform,
3226 editor = getcommiteditor(editform=editform,
3227 **pycompat.strkwargs(opts))
3227 **pycompat.strkwargs(opts))
3228
3228
3229 if not message:
3229 if not message:
3230 editor = getcommiteditor(edit=True, editform=editform)
3230 editor = getcommiteditor(edit=True, editform=editform)
3231 message = old.description()
3231 message = old.description()
3232
3232
3233 pureextra = extra.copy()
3233 pureextra = extra.copy()
3234 extra['amend_source'] = old.hex()
3234 extra['amend_source'] = old.hex()
3235
3235
3236 new = context.memctx(repo,
3236 new = context.memctx(repo,
3237 parents=[base.node(), old.p2().node()],
3237 parents=[base.node(), old.p2().node()],
3238 text=message,
3238 text=message,
3239 files=files,
3239 files=files,
3240 filectxfn=filectxfn,
3240 filectxfn=filectxfn,
3241 user=user,
3241 user=user,
3242 date=date,
3242 date=date,
3243 extra=extra,
3243 extra=extra,
3244 editor=editor)
3244 editor=editor)
3245
3245
3246 newdesc = changelog.stripdesc(new.description())
3246 newdesc = changelog.stripdesc(new.description())
3247 if ((not changes)
3247 if ((not changes)
3248 and newdesc == old.description()
3248 and newdesc == old.description()
3249 and user == old.user()
3249 and user == old.user()
3250 and date == old.date()
3250 and date == old.date()
3251 and pureextra == old.extra()):
3251 and pureextra == old.extra()):
3252 # nothing changed. continuing here would create a new node
3252 # nothing changed. continuing here would create a new node
3253 # anyway because of the amend_source noise.
3253 # anyway because of the amend_source noise.
3254 #
3254 #
3255 # This not what we expect from amend.
3255 # This not what we expect from amend.
3256 return old.node()
3256 return old.node()
3257
3257
3258 if opts.get('secret'):
3258 if opts.get('secret'):
3259 commitphase = 'secret'
3259 commitphase = 'secret'
3260 else:
3260 else:
3261 commitphase = old.phase()
3261 commitphase = old.phase()
3262 overrides = {('phases', 'new-commit'): commitphase}
3262 overrides = {('phases', 'new-commit'): commitphase}
3263 with ui.configoverride(overrides, 'amend'):
3263 with ui.configoverride(overrides, 'amend'):
3264 newid = repo.commitctx(new)
3264 newid = repo.commitctx(new)
3265
3265
3266 # Reroute the working copy parent to the new changeset
3266 # Reroute the working copy parent to the new changeset
3267 repo.setparents(newid, nullid)
3267 repo.setparents(newid, nullid)
3268 mapping = {old.node(): (newid,)}
3268 mapping = {old.node(): (newid,)}
3269 obsmetadata = None
3269 obsmetadata = None
3270 if opts.get('note'):
3270 if opts.get('note'):
3271 obsmetadata = {'note': opts['note']}
3271 obsmetadata = {'note': opts['note']}
3272 scmutil.cleanupnodes(repo, mapping, 'amend', metadata=obsmetadata)
3272 scmutil.cleanupnodes(repo, mapping, 'amend', metadata=obsmetadata)
3273
3273
3274 # Fixing the dirstate because localrepo.commitctx does not update
3274 # Fixing the dirstate because localrepo.commitctx does not update
3275 # it. This is rather convenient because we did not need to update
3275 # it. This is rather convenient because we did not need to update
3276 # the dirstate for all the files in the new commit which commitctx
3276 # the dirstate for all the files in the new commit which commitctx
3277 # could have done if it updated the dirstate. Now, we can
3277 # could have done if it updated the dirstate. Now, we can
3278 # selectively update the dirstate only for the amended files.
3278 # selectively update the dirstate only for the amended files.
3279 dirstate = repo.dirstate
3279 dirstate = repo.dirstate
3280
3280
3281 # Update the state of the files which were added and
3281 # Update the state of the files which were added and
3282 # and modified in the amend to "normal" in the dirstate.
3282 # and modified in the amend to "normal" in the dirstate.
3283 normalfiles = set(wctx.modified() + wctx.added()) & filestoamend
3283 normalfiles = set(wctx.modified() + wctx.added()) & filestoamend
3284 for f in normalfiles:
3284 for f in normalfiles:
3285 dirstate.normal(f)
3285 dirstate.normal(f)
3286
3286
3287 # Update the state of files which were removed in the amend
3287 # Update the state of files which were removed in the amend
3288 # to "removed" in the dirstate.
3288 # to "removed" in the dirstate.
3289 removedfiles = set(wctx.removed()) & filestoamend
3289 removedfiles = set(wctx.removed()) & filestoamend
3290 for f in removedfiles:
3290 for f in removedfiles:
3291 dirstate.drop(f)
3291 dirstate.drop(f)
3292
3292
3293 return newid
3293 return newid
3294
3294
3295 def commiteditor(repo, ctx, subs, editform=''):
3295 def commiteditor(repo, ctx, subs, editform=''):
3296 if ctx.description():
3296 if ctx.description():
3297 return ctx.description()
3297 return ctx.description()
3298 return commitforceeditor(repo, ctx, subs, editform=editform,
3298 return commitforceeditor(repo, ctx, subs, editform=editform,
3299 unchangedmessagedetection=True)
3299 unchangedmessagedetection=True)
3300
3300
3301 def commitforceeditor(repo, ctx, subs, finishdesc=None, extramsg=None,
3301 def commitforceeditor(repo, ctx, subs, finishdesc=None, extramsg=None,
3302 editform='', unchangedmessagedetection=False):
3302 editform='', unchangedmessagedetection=False):
3303 if not extramsg:
3303 if not extramsg:
3304 extramsg = _("Leave message empty to abort commit.")
3304 extramsg = _("Leave message empty to abort commit.")
3305
3305
3306 forms = [e for e in editform.split('.') if e]
3306 forms = [e for e in editform.split('.') if e]
3307 forms.insert(0, 'changeset')
3307 forms.insert(0, 'changeset')
3308 templatetext = None
3308 templatetext = None
3309 while forms:
3309 while forms:
3310 ref = '.'.join(forms)
3310 ref = '.'.join(forms)
3311 if repo.ui.config('committemplate', ref):
3311 if repo.ui.config('committemplate', ref):
3312 templatetext = committext = buildcommittemplate(
3312 templatetext = committext = buildcommittemplate(
3313 repo, ctx, subs, extramsg, ref)
3313 repo, ctx, subs, extramsg, ref)
3314 break
3314 break
3315 forms.pop()
3315 forms.pop()
3316 else:
3316 else:
3317 committext = buildcommittext(repo, ctx, subs, extramsg)
3317 committext = buildcommittext(repo, ctx, subs, extramsg)
3318
3318
3319 # run editor in the repository root
3319 # run editor in the repository root
3320 olddir = pycompat.getcwd()
3320 olddir = pycompat.getcwd()
3321 os.chdir(repo.root)
3321 os.chdir(repo.root)
3322
3322
3323 # make in-memory changes visible to external process
3323 # make in-memory changes visible to external process
3324 tr = repo.currenttransaction()
3324 tr = repo.currenttransaction()
3325 repo.dirstate.write(tr)
3325 repo.dirstate.write(tr)
3326 pending = tr and tr.writepending() and repo.root
3326 pending = tr and tr.writepending() and repo.root
3327
3327
3328 editortext = repo.ui.edit(committext, ctx.user(), ctx.extra(),
3328 editortext = repo.ui.edit(committext, ctx.user(), ctx.extra(),
3329 editform=editform, pending=pending,
3329 editform=editform, pending=pending,
3330 repopath=repo.path, action='commit')
3330 repopath=repo.path, action='commit')
3331 text = editortext
3331 text = editortext
3332
3332
3333 # strip away anything below this special string (used for editors that want
3333 # strip away anything below this special string (used for editors that want
3334 # to display the diff)
3334 # to display the diff)
3335 stripbelow = re.search(_linebelow, text, flags=re.MULTILINE)
3335 stripbelow = re.search(_linebelow, text, flags=re.MULTILINE)
3336 if stripbelow:
3336 if stripbelow:
3337 text = text[:stripbelow.start()]
3337 text = text[:stripbelow.start()]
3338
3338
3339 text = re.sub("(?m)^HG:.*(\n|$)", "", text)
3339 text = re.sub("(?m)^HG:.*(\n|$)", "", text)
3340 os.chdir(olddir)
3340 os.chdir(olddir)
3341
3341
3342 if finishdesc:
3342 if finishdesc:
3343 text = finishdesc(text)
3343 text = finishdesc(text)
3344 if not text.strip():
3344 if not text.strip():
3345 raise error.Abort(_("empty commit message"))
3345 raise error.Abort(_("empty commit message"))
3346 if unchangedmessagedetection and editortext == templatetext:
3346 if unchangedmessagedetection and editortext == templatetext:
3347 raise error.Abort(_("commit message unchanged"))
3347 raise error.Abort(_("commit message unchanged"))
3348
3348
3349 return text
3349 return text
3350
3350
3351 def buildcommittemplate(repo, ctx, subs, extramsg, ref):
3351 def buildcommittemplate(repo, ctx, subs, extramsg, ref):
3352 ui = repo.ui
3352 ui = repo.ui
3353 spec = formatter.templatespec(ref, None, None)
3353 spec = formatter.templatespec(ref, None, None)
3354 t = changeset_templater(ui, repo, spec, None, {}, False)
3354 t = changeset_templater(ui, repo, spec, None, {}, False)
3355 t.t.cache.update((k, templater.unquotestring(v))
3355 t.t.cache.update((k, templater.unquotestring(v))
3356 for k, v in repo.ui.configitems('committemplate'))
3356 for k, v in repo.ui.configitems('committemplate'))
3357
3357
3358 if not extramsg:
3358 if not extramsg:
3359 extramsg = '' # ensure that extramsg is string
3359 extramsg = '' # ensure that extramsg is string
3360
3360
3361 ui.pushbuffer()
3361 ui.pushbuffer()
3362 t.show(ctx, extramsg=extramsg)
3362 t.show(ctx, extramsg=extramsg)
3363 return ui.popbuffer()
3363 return ui.popbuffer()
3364
3364
3365 def hgprefix(msg):
3365 def hgprefix(msg):
3366 return "\n".join(["HG: %s" % a for a in msg.split("\n") if a])
3366 return "\n".join(["HG: %s" % a for a in msg.split("\n") if a])
3367
3367
3368 def buildcommittext(repo, ctx, subs, extramsg):
3368 def buildcommittext(repo, ctx, subs, extramsg):
3369 edittext = []
3369 edittext = []
3370 modified, added, removed = ctx.modified(), ctx.added(), ctx.removed()
3370 modified, added, removed = ctx.modified(), ctx.added(), ctx.removed()
3371 if ctx.description():
3371 if ctx.description():
3372 edittext.append(ctx.description())
3372 edittext.append(ctx.description())
3373 edittext.append("")
3373 edittext.append("")
3374 edittext.append("") # Empty line between message and comments.
3374 edittext.append("") # Empty line between message and comments.
3375 edittext.append(hgprefix(_("Enter commit message."
3375 edittext.append(hgprefix(_("Enter commit message."
3376 " Lines beginning with 'HG:' are removed.")))
3376 " Lines beginning with 'HG:' are removed.")))
3377 edittext.append(hgprefix(extramsg))
3377 edittext.append(hgprefix(extramsg))
3378 edittext.append("HG: --")
3378 edittext.append("HG: --")
3379 edittext.append(hgprefix(_("user: %s") % ctx.user()))
3379 edittext.append(hgprefix(_("user: %s") % ctx.user()))
3380 if ctx.p2():
3380 if ctx.p2():
3381 edittext.append(hgprefix(_("branch merge")))
3381 edittext.append(hgprefix(_("branch merge")))
3382 if ctx.branch():
3382 if ctx.branch():
3383 edittext.append(hgprefix(_("branch '%s'") % ctx.branch()))
3383 edittext.append(hgprefix(_("branch '%s'") % ctx.branch()))
3384 if bookmarks.isactivewdirparent(repo):
3384 if bookmarks.isactivewdirparent(repo):
3385 edittext.append(hgprefix(_("bookmark '%s'") % repo._activebookmark))
3385 edittext.append(hgprefix(_("bookmark '%s'") % repo._activebookmark))
3386 edittext.extend([hgprefix(_("subrepo %s") % s) for s in subs])
3386 edittext.extend([hgprefix(_("subrepo %s") % s) for s in subs])
3387 edittext.extend([hgprefix(_("added %s") % f) for f in added])
3387 edittext.extend([hgprefix(_("added %s") % f) for f in added])
3388 edittext.extend([hgprefix(_("changed %s") % f) for f in modified])
3388 edittext.extend([hgprefix(_("changed %s") % f) for f in modified])
3389 edittext.extend([hgprefix(_("removed %s") % f) for f in removed])
3389 edittext.extend([hgprefix(_("removed %s") % f) for f in removed])
3390 if not added and not modified and not removed:
3390 if not added and not modified and not removed:
3391 edittext.append(hgprefix(_("no files changed")))
3391 edittext.append(hgprefix(_("no files changed")))
3392 edittext.append("")
3392 edittext.append("")
3393
3393
3394 return "\n".join(edittext)
3394 return "\n".join(edittext)
3395
3395
3396 def commitstatus(repo, node, branch, bheads=None, opts=None):
3396 def commitstatus(repo, node, branch, bheads=None, opts=None):
3397 if opts is None:
3397 if opts is None:
3398 opts = {}
3398 opts = {}
3399 ctx = repo[node]
3399 ctx = repo[node]
3400 parents = ctx.parents()
3400 parents = ctx.parents()
3401
3401
3402 if (not opts.get('amend') and bheads and node not in bheads and not
3402 if (not opts.get('amend') and bheads and node not in bheads and not
3403 [x for x in parents if x.node() in bheads and x.branch() == branch]):
3403 [x for x in parents if x.node() in bheads and x.branch() == branch]):
3404 repo.ui.status(_('created new head\n'))
3404 repo.ui.status(_('created new head\n'))
3405 # The message is not printed for initial roots. For the other
3405 # The message is not printed for initial roots. For the other
3406 # changesets, it is printed in the following situations:
3406 # changesets, it is printed in the following situations:
3407 #
3407 #
3408 # Par column: for the 2 parents with ...
3408 # Par column: for the 2 parents with ...
3409 # N: null or no parent
3409 # N: null or no parent
3410 # B: parent is on another named branch
3410 # B: parent is on another named branch
3411 # C: parent is a regular non head changeset
3411 # C: parent is a regular non head changeset
3412 # H: parent was a branch head of the current branch
3412 # H: parent was a branch head of the current branch
3413 # Msg column: whether we print "created new head" message
3413 # Msg column: whether we print "created new head" message
3414 # In the following, it is assumed that there already exists some
3414 # In the following, it is assumed that there already exists some
3415 # initial branch heads of the current branch, otherwise nothing is
3415 # initial branch heads of the current branch, otherwise nothing is
3416 # printed anyway.
3416 # printed anyway.
3417 #
3417 #
3418 # Par Msg Comment
3418 # Par Msg Comment
3419 # N N y additional topo root
3419 # N N y additional topo root
3420 #
3420 #
3421 # B N y additional branch root
3421 # B N y additional branch root
3422 # C N y additional topo head
3422 # C N y additional topo head
3423 # H N n usual case
3423 # H N n usual case
3424 #
3424 #
3425 # B B y weird additional branch root
3425 # B B y weird additional branch root
3426 # C B y branch merge
3426 # C B y branch merge
3427 # H B n merge with named branch
3427 # H B n merge with named branch
3428 #
3428 #
3429 # C C y additional head from merge
3429 # C C y additional head from merge
3430 # C H n merge with a head
3430 # C H n merge with a head
3431 #
3431 #
3432 # H H n head merge: head count decreases
3432 # H H n head merge: head count decreases
3433
3433
3434 if not opts.get('close_branch'):
3434 if not opts.get('close_branch'):
3435 for r in parents:
3435 for r in parents:
3436 if r.closesbranch() and r.branch() == branch:
3436 if r.closesbranch() and r.branch() == branch:
3437 repo.ui.status(_('reopening closed branch head %d\n') % r)
3437 repo.ui.status(_('reopening closed branch head %d\n') % r)
3438
3438
3439 if repo.ui.debugflag:
3439 if repo.ui.debugflag:
3440 repo.ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
3440 repo.ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
3441 elif repo.ui.verbose:
3441 elif repo.ui.verbose:
3442 repo.ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
3442 repo.ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
3443
3443
3444 def postcommitstatus(repo, pats, opts):
3444 def postcommitstatus(repo, pats, opts):
3445 return repo.status(match=scmutil.match(repo[None], pats, opts))
3445 return repo.status(match=scmutil.match(repo[None], pats, opts))
3446
3446
3447 def revert(ui, repo, ctx, parents, *pats, **opts):
3447 def revert(ui, repo, ctx, parents, *pats, **opts):
3448 opts = pycompat.byteskwargs(opts)
3448 parent, p2 = parents
3449 parent, p2 = parents
3449 node = ctx.node()
3450 node = ctx.node()
3450
3451
3451 mf = ctx.manifest()
3452 mf = ctx.manifest()
3452 if node == p2:
3453 if node == p2:
3453 parent = p2
3454 parent = p2
3454
3455
3455 # need all matching names in dirstate and manifest of target rev,
3456 # need all matching names in dirstate and manifest of target rev,
3456 # so have to walk both. do not print errors if files exist in one
3457 # so have to walk both. do not print errors if files exist in one
3457 # but not other. in both cases, filesets should be evaluated against
3458 # but not other. in both cases, filesets should be evaluated against
3458 # workingctx to get consistent result (issue4497). this means 'set:**'
3459 # workingctx to get consistent result (issue4497). this means 'set:**'
3459 # cannot be used to select missing files from target rev.
3460 # cannot be used to select missing files from target rev.
3460
3461
3461 # `names` is a mapping for all elements in working copy and target revision
3462 # `names` is a mapping for all elements in working copy and target revision
3462 # The mapping is in the form:
3463 # The mapping is in the form:
3463 # <asb path in repo> -> (<path from CWD>, <exactly specified by matcher?>)
3464 # <asb path in repo> -> (<path from CWD>, <exactly specified by matcher?>)
3464 names = {}
3465 names = {}
3465
3466
3466 with repo.wlock():
3467 with repo.wlock():
3467 ## filling of the `names` mapping
3468 ## filling of the `names` mapping
3468 # walk dirstate to fill `names`
3469 # walk dirstate to fill `names`
3469
3470
3470 interactive = opts.get('interactive', False)
3471 interactive = opts.get('interactive', False)
3471 wctx = repo[None]
3472 wctx = repo[None]
3472 m = scmutil.match(wctx, pats, opts)
3473 m = scmutil.match(wctx, pats, opts)
3473
3474
3474 # we'll need this later
3475 # we'll need this later
3475 targetsubs = sorted(s for s in wctx.substate if m(s))
3476 targetsubs = sorted(s for s in wctx.substate if m(s))
3476
3477
3477 if not m.always():
3478 if not m.always():
3478 matcher = matchmod.badmatch(m, lambda x, y: False)
3479 matcher = matchmod.badmatch(m, lambda x, y: False)
3479 for abs in wctx.walk(matcher):
3480 for abs in wctx.walk(matcher):
3480 names[abs] = m.rel(abs), m.exact(abs)
3481 names[abs] = m.rel(abs), m.exact(abs)
3481
3482
3482 # walk target manifest to fill `names`
3483 # walk target manifest to fill `names`
3483
3484
3484 def badfn(path, msg):
3485 def badfn(path, msg):
3485 if path in names:
3486 if path in names:
3486 return
3487 return
3487 if path in ctx.substate:
3488 if path in ctx.substate:
3488 return
3489 return
3489 path_ = path + '/'
3490 path_ = path + '/'
3490 for f in names:
3491 for f in names:
3491 if f.startswith(path_):
3492 if f.startswith(path_):
3492 return
3493 return
3493 ui.warn("%s: %s\n" % (m.rel(path), msg))
3494 ui.warn("%s: %s\n" % (m.rel(path), msg))
3494
3495
3495 for abs in ctx.walk(matchmod.badmatch(m, badfn)):
3496 for abs in ctx.walk(matchmod.badmatch(m, badfn)):
3496 if abs not in names:
3497 if abs not in names:
3497 names[abs] = m.rel(abs), m.exact(abs)
3498 names[abs] = m.rel(abs), m.exact(abs)
3498
3499
3499 # Find status of all file in `names`.
3500 # Find status of all file in `names`.
3500 m = scmutil.matchfiles(repo, names)
3501 m = scmutil.matchfiles(repo, names)
3501
3502
3502 changes = repo.status(node1=node, match=m,
3503 changes = repo.status(node1=node, match=m,
3503 unknown=True, ignored=True, clean=True)
3504 unknown=True, ignored=True, clean=True)
3504 else:
3505 else:
3505 changes = repo.status(node1=node, match=m)
3506 changes = repo.status(node1=node, match=m)
3506 for kind in changes:
3507 for kind in changes:
3507 for abs in kind:
3508 for abs in kind:
3508 names[abs] = m.rel(abs), m.exact(abs)
3509 names[abs] = m.rel(abs), m.exact(abs)
3509
3510
3510 m = scmutil.matchfiles(repo, names)
3511 m = scmutil.matchfiles(repo, names)
3511
3512
3512 modified = set(changes.modified)
3513 modified = set(changes.modified)
3513 added = set(changes.added)
3514 added = set(changes.added)
3514 removed = set(changes.removed)
3515 removed = set(changes.removed)
3515 _deleted = set(changes.deleted)
3516 _deleted = set(changes.deleted)
3516 unknown = set(changes.unknown)
3517 unknown = set(changes.unknown)
3517 unknown.update(changes.ignored)
3518 unknown.update(changes.ignored)
3518 clean = set(changes.clean)
3519 clean = set(changes.clean)
3519 modadded = set()
3520 modadded = set()
3520
3521
3521 # We need to account for the state of the file in the dirstate,
3522 # We need to account for the state of the file in the dirstate,
3522 # even when we revert against something else than parent. This will
3523 # even when we revert against something else than parent. This will
3523 # slightly alter the behavior of revert (doing back up or not, delete
3524 # slightly alter the behavior of revert (doing back up or not, delete
3524 # or just forget etc).
3525 # or just forget etc).
3525 if parent == node:
3526 if parent == node:
3526 dsmodified = modified
3527 dsmodified = modified
3527 dsadded = added
3528 dsadded = added
3528 dsremoved = removed
3529 dsremoved = removed
3529 # store all local modifications, useful later for rename detection
3530 # store all local modifications, useful later for rename detection
3530 localchanges = dsmodified | dsadded
3531 localchanges = dsmodified | dsadded
3531 modified, added, removed = set(), set(), set()
3532 modified, added, removed = set(), set(), set()
3532 else:
3533 else:
3533 changes = repo.status(node1=parent, match=m)
3534 changes = repo.status(node1=parent, match=m)
3534 dsmodified = set(changes.modified)
3535 dsmodified = set(changes.modified)
3535 dsadded = set(changes.added)
3536 dsadded = set(changes.added)
3536 dsremoved = set(changes.removed)
3537 dsremoved = set(changes.removed)
3537 # store all local modifications, useful later for rename detection
3538 # store all local modifications, useful later for rename detection
3538 localchanges = dsmodified | dsadded
3539 localchanges = dsmodified | dsadded
3539
3540
3540 # only take into account for removes between wc and target
3541 # only take into account for removes between wc and target
3541 clean |= dsremoved - removed
3542 clean |= dsremoved - removed
3542 dsremoved &= removed
3543 dsremoved &= removed
3543 # distinct between dirstate remove and other
3544 # distinct between dirstate remove and other
3544 removed -= dsremoved
3545 removed -= dsremoved
3545
3546
3546 modadded = added & dsmodified
3547 modadded = added & dsmodified
3547 added -= modadded
3548 added -= modadded
3548
3549
3549 # tell newly modified apart.
3550 # tell newly modified apart.
3550 dsmodified &= modified
3551 dsmodified &= modified
3551 dsmodified |= modified & dsadded # dirstate added may need backup
3552 dsmodified |= modified & dsadded # dirstate added may need backup
3552 modified -= dsmodified
3553 modified -= dsmodified
3553
3554
3554 # We need to wait for some post-processing to update this set
3555 # We need to wait for some post-processing to update this set
3555 # before making the distinction. The dirstate will be used for
3556 # before making the distinction. The dirstate will be used for
3556 # that purpose.
3557 # that purpose.
3557 dsadded = added
3558 dsadded = added
3558
3559
3559 # in case of merge, files that are actually added can be reported as
3560 # in case of merge, files that are actually added can be reported as
3560 # modified, we need to post process the result
3561 # modified, we need to post process the result
3561 if p2 != nullid:
3562 if p2 != nullid:
3562 mergeadd = set(dsmodified)
3563 mergeadd = set(dsmodified)
3563 for path in dsmodified:
3564 for path in dsmodified:
3564 if path in mf:
3565 if path in mf:
3565 mergeadd.remove(path)
3566 mergeadd.remove(path)
3566 dsadded |= mergeadd
3567 dsadded |= mergeadd
3567 dsmodified -= mergeadd
3568 dsmodified -= mergeadd
3568
3569
3569 # if f is a rename, update `names` to also revert the source
3570 # if f is a rename, update `names` to also revert the source
3570 cwd = repo.getcwd()
3571 cwd = repo.getcwd()
3571 for f in localchanges:
3572 for f in localchanges:
3572 src = repo.dirstate.copied(f)
3573 src = repo.dirstate.copied(f)
3573 # XXX should we check for rename down to target node?
3574 # XXX should we check for rename down to target node?
3574 if src and src not in names and repo.dirstate[src] == 'r':
3575 if src and src not in names and repo.dirstate[src] == 'r':
3575 dsremoved.add(src)
3576 dsremoved.add(src)
3576 names[src] = (repo.pathto(src, cwd), True)
3577 names[src] = (repo.pathto(src, cwd), True)
3577
3578
3578 # determine the exact nature of the deleted changesets
3579 # determine the exact nature of the deleted changesets
3579 deladded = set(_deleted)
3580 deladded = set(_deleted)
3580 for path in _deleted:
3581 for path in _deleted:
3581 if path in mf:
3582 if path in mf:
3582 deladded.remove(path)
3583 deladded.remove(path)
3583 deleted = _deleted - deladded
3584 deleted = _deleted - deladded
3584
3585
3585 # distinguish between file to forget and the other
3586 # distinguish between file to forget and the other
3586 added = set()
3587 added = set()
3587 for abs in dsadded:
3588 for abs in dsadded:
3588 if repo.dirstate[abs] != 'a':
3589 if repo.dirstate[abs] != 'a':
3589 added.add(abs)
3590 added.add(abs)
3590 dsadded -= added
3591 dsadded -= added
3591
3592
3592 for abs in deladded:
3593 for abs in deladded:
3593 if repo.dirstate[abs] == 'a':
3594 if repo.dirstate[abs] == 'a':
3594 dsadded.add(abs)
3595 dsadded.add(abs)
3595 deladded -= dsadded
3596 deladded -= dsadded
3596
3597
3597 # For files marked as removed, we check if an unknown file is present at
3598 # For files marked as removed, we check if an unknown file is present at
3598 # the same path. If a such file exists it may need to be backed up.
3599 # the same path. If a such file exists it may need to be backed up.
3599 # Making the distinction at this stage helps have simpler backup
3600 # Making the distinction at this stage helps have simpler backup
3600 # logic.
3601 # logic.
3601 removunk = set()
3602 removunk = set()
3602 for abs in removed:
3603 for abs in removed:
3603 target = repo.wjoin(abs)
3604 target = repo.wjoin(abs)
3604 if os.path.lexists(target):
3605 if os.path.lexists(target):
3605 removunk.add(abs)
3606 removunk.add(abs)
3606 removed -= removunk
3607 removed -= removunk
3607
3608
3608 dsremovunk = set()
3609 dsremovunk = set()
3609 for abs in dsremoved:
3610 for abs in dsremoved:
3610 target = repo.wjoin(abs)
3611 target = repo.wjoin(abs)
3611 if os.path.lexists(target):
3612 if os.path.lexists(target):
3612 dsremovunk.add(abs)
3613 dsremovunk.add(abs)
3613 dsremoved -= dsremovunk
3614 dsremoved -= dsremovunk
3614
3615
3615 # action to be actually performed by revert
3616 # action to be actually performed by revert
3616 # (<list of file>, message>) tuple
3617 # (<list of file>, message>) tuple
3617 actions = {'revert': ([], _('reverting %s\n')),
3618 actions = {'revert': ([], _('reverting %s\n')),
3618 'add': ([], _('adding %s\n')),
3619 'add': ([], _('adding %s\n')),
3619 'remove': ([], _('removing %s\n')),
3620 'remove': ([], _('removing %s\n')),
3620 'drop': ([], _('removing %s\n')),
3621 'drop': ([], _('removing %s\n')),
3621 'forget': ([], _('forgetting %s\n')),
3622 'forget': ([], _('forgetting %s\n')),
3622 'undelete': ([], _('undeleting %s\n')),
3623 'undelete': ([], _('undeleting %s\n')),
3623 'noop': (None, _('no changes needed to %s\n')),
3624 'noop': (None, _('no changes needed to %s\n')),
3624 'unknown': (None, _('file not managed: %s\n')),
3625 'unknown': (None, _('file not managed: %s\n')),
3625 }
3626 }
3626
3627
3627 # "constant" that convey the backup strategy.
3628 # "constant" that convey the backup strategy.
3628 # All set to `discard` if `no-backup` is set do avoid checking
3629 # All set to `discard` if `no-backup` is set do avoid checking
3629 # no_backup lower in the code.
3630 # no_backup lower in the code.
3630 # These values are ordered for comparison purposes
3631 # These values are ordered for comparison purposes
3631 backupinteractive = 3 # do backup if interactively modified
3632 backupinteractive = 3 # do backup if interactively modified
3632 backup = 2 # unconditionally do backup
3633 backup = 2 # unconditionally do backup
3633 check = 1 # check if the existing file differs from target
3634 check = 1 # check if the existing file differs from target
3634 discard = 0 # never do backup
3635 discard = 0 # never do backup
3635 if opts.get('no_backup'):
3636 if opts.get('no_backup'):
3636 backupinteractive = backup = check = discard
3637 backupinteractive = backup = check = discard
3637 if interactive:
3638 if interactive:
3638 dsmodifiedbackup = backupinteractive
3639 dsmodifiedbackup = backupinteractive
3639 else:
3640 else:
3640 dsmodifiedbackup = backup
3641 dsmodifiedbackup = backup
3641 tobackup = set()
3642 tobackup = set()
3642
3643
3643 backupanddel = actions['remove']
3644 backupanddel = actions['remove']
3644 if not opts.get('no_backup'):
3645 if not opts.get('no_backup'):
3645 backupanddel = actions['drop']
3646 backupanddel = actions['drop']
3646
3647
3647 disptable = (
3648 disptable = (
3648 # dispatch table:
3649 # dispatch table:
3649 # file state
3650 # file state
3650 # action
3651 # action
3651 # make backup
3652 # make backup
3652
3653
3653 ## Sets that results that will change file on disk
3654 ## Sets that results that will change file on disk
3654 # Modified compared to target, no local change
3655 # Modified compared to target, no local change
3655 (modified, actions['revert'], discard),
3656 (modified, actions['revert'], discard),
3656 # Modified compared to target, but local file is deleted
3657 # Modified compared to target, but local file is deleted
3657 (deleted, actions['revert'], discard),
3658 (deleted, actions['revert'], discard),
3658 # Modified compared to target, local change
3659 # Modified compared to target, local change
3659 (dsmodified, actions['revert'], dsmodifiedbackup),
3660 (dsmodified, actions['revert'], dsmodifiedbackup),
3660 # Added since target
3661 # Added since target
3661 (added, actions['remove'], discard),
3662 (added, actions['remove'], discard),
3662 # Added in working directory
3663 # Added in working directory
3663 (dsadded, actions['forget'], discard),
3664 (dsadded, actions['forget'], discard),
3664 # Added since target, have local modification
3665 # Added since target, have local modification
3665 (modadded, backupanddel, backup),
3666 (modadded, backupanddel, backup),
3666 # Added since target but file is missing in working directory
3667 # Added since target but file is missing in working directory
3667 (deladded, actions['drop'], discard),
3668 (deladded, actions['drop'], discard),
3668 # Removed since target, before working copy parent
3669 # Removed since target, before working copy parent
3669 (removed, actions['add'], discard),
3670 (removed, actions['add'], discard),
3670 # Same as `removed` but an unknown file exists at the same path
3671 # Same as `removed` but an unknown file exists at the same path
3671 (removunk, actions['add'], check),
3672 (removunk, actions['add'], check),
3672 # Removed since targe, marked as such in working copy parent
3673 # Removed since targe, marked as such in working copy parent
3673 (dsremoved, actions['undelete'], discard),
3674 (dsremoved, actions['undelete'], discard),
3674 # Same as `dsremoved` but an unknown file exists at the same path
3675 # Same as `dsremoved` but an unknown file exists at the same path
3675 (dsremovunk, actions['undelete'], check),
3676 (dsremovunk, actions['undelete'], check),
3676 ## the following sets does not result in any file changes
3677 ## the following sets does not result in any file changes
3677 # File with no modification
3678 # File with no modification
3678 (clean, actions['noop'], discard),
3679 (clean, actions['noop'], discard),
3679 # Existing file, not tracked anywhere
3680 # Existing file, not tracked anywhere
3680 (unknown, actions['unknown'], discard),
3681 (unknown, actions['unknown'], discard),
3681 )
3682 )
3682
3683
3683 for abs, (rel, exact) in sorted(names.items()):
3684 for abs, (rel, exact) in sorted(names.items()):
3684 # target file to be touch on disk (relative to cwd)
3685 # target file to be touch on disk (relative to cwd)
3685 target = repo.wjoin(abs)
3686 target = repo.wjoin(abs)
3686 # search the entry in the dispatch table.
3687 # search the entry in the dispatch table.
3687 # if the file is in any of these sets, it was touched in the working
3688 # if the file is in any of these sets, it was touched in the working
3688 # directory parent and we are sure it needs to be reverted.
3689 # directory parent and we are sure it needs to be reverted.
3689 for table, (xlist, msg), dobackup in disptable:
3690 for table, (xlist, msg), dobackup in disptable:
3690 if abs not in table:
3691 if abs not in table:
3691 continue
3692 continue
3692 if xlist is not None:
3693 if xlist is not None:
3693 xlist.append(abs)
3694 xlist.append(abs)
3694 if dobackup:
3695 if dobackup:
3695 # If in interactive mode, don't automatically create
3696 # If in interactive mode, don't automatically create
3696 # .orig files (issue4793)
3697 # .orig files (issue4793)
3697 if dobackup == backupinteractive:
3698 if dobackup == backupinteractive:
3698 tobackup.add(abs)
3699 tobackup.add(abs)
3699 elif (backup <= dobackup or wctx[abs].cmp(ctx[abs])):
3700 elif (backup <= dobackup or wctx[abs].cmp(ctx[abs])):
3700 bakname = scmutil.origpath(ui, repo, rel)
3701 bakname = scmutil.origpath(ui, repo, rel)
3701 ui.note(_('saving current version of %s as %s\n') %
3702 ui.note(_('saving current version of %s as %s\n') %
3702 (rel, bakname))
3703 (rel, bakname))
3703 if not opts.get('dry_run'):
3704 if not opts.get('dry_run'):
3704 if interactive:
3705 if interactive:
3705 util.copyfile(target, bakname)
3706 util.copyfile(target, bakname)
3706 else:
3707 else:
3707 util.rename(target, bakname)
3708 util.rename(target, bakname)
3708 if ui.verbose or not exact:
3709 if ui.verbose or not exact:
3709 if not isinstance(msg, basestring):
3710 if not isinstance(msg, basestring):
3710 msg = msg(abs)
3711 msg = msg(abs)
3711 ui.status(msg % rel)
3712 ui.status(msg % rel)
3712 elif exact:
3713 elif exact:
3713 ui.warn(msg % rel)
3714 ui.warn(msg % rel)
3714 break
3715 break
3715
3716
3716 if not opts.get('dry_run'):
3717 if not opts.get('dry_run'):
3717 needdata = ('revert', 'add', 'undelete')
3718 needdata = ('revert', 'add', 'undelete')
3718 _revertprefetch(repo, ctx, *[actions[name][0] for name in needdata])
3719 _revertprefetch(repo, ctx, *[actions[name][0] for name in needdata])
3719 _performrevert(repo, parents, ctx, actions, interactive, tobackup)
3720 _performrevert(repo, parents, ctx, actions, interactive, tobackup)
3720
3721
3721 if targetsubs:
3722 if targetsubs:
3722 # Revert the subrepos on the revert list
3723 # Revert the subrepos on the revert list
3723 for sub in targetsubs:
3724 for sub in targetsubs:
3724 try:
3725 try:
3725 wctx.sub(sub).revert(ctx.substate[sub], *pats, **opts)
3726 wctx.sub(sub).revert(ctx.substate[sub], *pats,
3727 **pycompat.strkwargs(opts))
3726 except KeyError:
3728 except KeyError:
3727 raise error.Abort("subrepository '%s' does not exist in %s!"
3729 raise error.Abort("subrepository '%s' does not exist in %s!"
3728 % (sub, short(ctx.node())))
3730 % (sub, short(ctx.node())))
3729
3731
3730 def _revertprefetch(repo, ctx, *files):
3732 def _revertprefetch(repo, ctx, *files):
3731 """Let extension changing the storage layer prefetch content"""
3733 """Let extension changing the storage layer prefetch content"""
3732
3734
3733 def _performrevert(repo, parents, ctx, actions, interactive=False,
3735 def _performrevert(repo, parents, ctx, actions, interactive=False,
3734 tobackup=None):
3736 tobackup=None):
3735 """function that actually perform all the actions computed for revert
3737 """function that actually perform all the actions computed for revert
3736
3738
3737 This is an independent function to let extension to plug in and react to
3739 This is an independent function to let extension to plug in and react to
3738 the imminent revert.
3740 the imminent revert.
3739
3741
3740 Make sure you have the working directory locked when calling this function.
3742 Make sure you have the working directory locked when calling this function.
3741 """
3743 """
3742 parent, p2 = parents
3744 parent, p2 = parents
3743 node = ctx.node()
3745 node = ctx.node()
3744 excluded_files = []
3746 excluded_files = []
3745 matcher_opts = {"exclude": excluded_files}
3747 matcher_opts = {"exclude": excluded_files}
3746
3748
3747 def checkout(f):
3749 def checkout(f):
3748 fc = ctx[f]
3750 fc = ctx[f]
3749 repo.wwrite(f, fc.data(), fc.flags())
3751 repo.wwrite(f, fc.data(), fc.flags())
3750
3752
3751 def doremove(f):
3753 def doremove(f):
3752 try:
3754 try:
3753 repo.wvfs.unlinkpath(f)
3755 repo.wvfs.unlinkpath(f)
3754 except OSError:
3756 except OSError:
3755 pass
3757 pass
3756 repo.dirstate.remove(f)
3758 repo.dirstate.remove(f)
3757
3759
3758 audit_path = pathutil.pathauditor(repo.root, cached=True)
3760 audit_path = pathutil.pathauditor(repo.root, cached=True)
3759 for f in actions['forget'][0]:
3761 for f in actions['forget'][0]:
3760 if interactive:
3762 if interactive:
3761 choice = repo.ui.promptchoice(
3763 choice = repo.ui.promptchoice(
3762 _("forget added file %s (Yn)?$$ &Yes $$ &No") % f)
3764 _("forget added file %s (Yn)?$$ &Yes $$ &No") % f)
3763 if choice == 0:
3765 if choice == 0:
3764 repo.dirstate.drop(f)
3766 repo.dirstate.drop(f)
3765 else:
3767 else:
3766 excluded_files.append(repo.wjoin(f))
3768 excluded_files.append(repo.wjoin(f))
3767 else:
3769 else:
3768 repo.dirstate.drop(f)
3770 repo.dirstate.drop(f)
3769 for f in actions['remove'][0]:
3771 for f in actions['remove'][0]:
3770 audit_path(f)
3772 audit_path(f)
3771 if interactive:
3773 if interactive:
3772 choice = repo.ui.promptchoice(
3774 choice = repo.ui.promptchoice(
3773 _("remove added file %s (Yn)?$$ &Yes $$ &No") % f)
3775 _("remove added file %s (Yn)?$$ &Yes $$ &No") % f)
3774 if choice == 0:
3776 if choice == 0:
3775 doremove(f)
3777 doremove(f)
3776 else:
3778 else:
3777 excluded_files.append(repo.wjoin(f))
3779 excluded_files.append(repo.wjoin(f))
3778 else:
3780 else:
3779 doremove(f)
3781 doremove(f)
3780 for f in actions['drop'][0]:
3782 for f in actions['drop'][0]:
3781 audit_path(f)
3783 audit_path(f)
3782 repo.dirstate.remove(f)
3784 repo.dirstate.remove(f)
3783
3785
3784 normal = None
3786 normal = None
3785 if node == parent:
3787 if node == parent:
3786 # We're reverting to our parent. If possible, we'd like status
3788 # We're reverting to our parent. If possible, we'd like status
3787 # to report the file as clean. We have to use normallookup for
3789 # to report the file as clean. We have to use normallookup for
3788 # merges to avoid losing information about merged/dirty files.
3790 # merges to avoid losing information about merged/dirty files.
3789 if p2 != nullid:
3791 if p2 != nullid:
3790 normal = repo.dirstate.normallookup
3792 normal = repo.dirstate.normallookup
3791 else:
3793 else:
3792 normal = repo.dirstate.normal
3794 normal = repo.dirstate.normal
3793
3795
3794 newlyaddedandmodifiedfiles = set()
3796 newlyaddedandmodifiedfiles = set()
3795 if interactive:
3797 if interactive:
3796 # Prompt the user for changes to revert
3798 # Prompt the user for changes to revert
3797 torevert = [repo.wjoin(f) for f in actions['revert'][0]]
3799 torevert = [repo.wjoin(f) for f in actions['revert'][0]]
3798 m = scmutil.match(ctx, torevert, matcher_opts)
3800 m = scmutil.match(ctx, torevert, matcher_opts)
3799 diffopts = patch.difffeatureopts(repo.ui, whitespace=True)
3801 diffopts = patch.difffeatureopts(repo.ui, whitespace=True)
3800 diffopts.nodates = True
3802 diffopts.nodates = True
3801 diffopts.git = True
3803 diffopts.git = True
3802 operation = 'discard'
3804 operation = 'discard'
3803 reversehunks = True
3805 reversehunks = True
3804 if node != parent:
3806 if node != parent:
3805 operation = 'apply'
3807 operation = 'apply'
3806 reversehunks = False
3808 reversehunks = False
3807 if reversehunks:
3809 if reversehunks:
3808 diff = patch.diff(repo, ctx.node(), None, m, opts=diffopts)
3810 diff = patch.diff(repo, ctx.node(), None, m, opts=diffopts)
3809 else:
3811 else:
3810 diff = patch.diff(repo, None, ctx.node(), m, opts=diffopts)
3812 diff = patch.diff(repo, None, ctx.node(), m, opts=diffopts)
3811 originalchunks = patch.parsepatch(diff)
3813 originalchunks = patch.parsepatch(diff)
3812
3814
3813 try:
3815 try:
3814
3816
3815 chunks, opts = recordfilter(repo.ui, originalchunks,
3817 chunks, opts = recordfilter(repo.ui, originalchunks,
3816 operation=operation)
3818 operation=operation)
3817 if reversehunks:
3819 if reversehunks:
3818 chunks = patch.reversehunks(chunks)
3820 chunks = patch.reversehunks(chunks)
3819
3821
3820 except error.PatchError as err:
3822 except error.PatchError as err:
3821 raise error.Abort(_('error parsing patch: %s') % err)
3823 raise error.Abort(_('error parsing patch: %s') % err)
3822
3824
3823 newlyaddedandmodifiedfiles = newandmodified(chunks, originalchunks)
3825 newlyaddedandmodifiedfiles = newandmodified(chunks, originalchunks)
3824 if tobackup is None:
3826 if tobackup is None:
3825 tobackup = set()
3827 tobackup = set()
3826 # Apply changes
3828 # Apply changes
3827 fp = stringio()
3829 fp = stringio()
3828 for c in chunks:
3830 for c in chunks:
3829 # Create a backup file only if this hunk should be backed up
3831 # Create a backup file only if this hunk should be backed up
3830 if ishunk(c) and c.header.filename() in tobackup:
3832 if ishunk(c) and c.header.filename() in tobackup:
3831 abs = c.header.filename()
3833 abs = c.header.filename()
3832 target = repo.wjoin(abs)
3834 target = repo.wjoin(abs)
3833 bakname = scmutil.origpath(repo.ui, repo, m.rel(abs))
3835 bakname = scmutil.origpath(repo.ui, repo, m.rel(abs))
3834 util.copyfile(target, bakname)
3836 util.copyfile(target, bakname)
3835 tobackup.remove(abs)
3837 tobackup.remove(abs)
3836 c.write(fp)
3838 c.write(fp)
3837 dopatch = fp.tell()
3839 dopatch = fp.tell()
3838 fp.seek(0)
3840 fp.seek(0)
3839 if dopatch:
3841 if dopatch:
3840 try:
3842 try:
3841 patch.internalpatch(repo.ui, repo, fp, 1, eolmode=None)
3843 patch.internalpatch(repo.ui, repo, fp, 1, eolmode=None)
3842 except error.PatchError as err:
3844 except error.PatchError as err:
3843 raise error.Abort(str(err))
3845 raise error.Abort(str(err))
3844 del fp
3846 del fp
3845 else:
3847 else:
3846 for f in actions['revert'][0]:
3848 for f in actions['revert'][0]:
3847 checkout(f)
3849 checkout(f)
3848 if normal:
3850 if normal:
3849 normal(f)
3851 normal(f)
3850
3852
3851 for f in actions['add'][0]:
3853 for f in actions['add'][0]:
3852 # Don't checkout modified files, they are already created by the diff
3854 # Don't checkout modified files, they are already created by the diff
3853 if f not in newlyaddedandmodifiedfiles:
3855 if f not in newlyaddedandmodifiedfiles:
3854 checkout(f)
3856 checkout(f)
3855 repo.dirstate.add(f)
3857 repo.dirstate.add(f)
3856
3858
3857 normal = repo.dirstate.normallookup
3859 normal = repo.dirstate.normallookup
3858 if node == parent and p2 == nullid:
3860 if node == parent and p2 == nullid:
3859 normal = repo.dirstate.normal
3861 normal = repo.dirstate.normal
3860 for f in actions['undelete'][0]:
3862 for f in actions['undelete'][0]:
3861 checkout(f)
3863 checkout(f)
3862 normal(f)
3864 normal(f)
3863
3865
3864 copied = copies.pathcopies(repo[parent], ctx)
3866 copied = copies.pathcopies(repo[parent], ctx)
3865
3867
3866 for f in actions['add'][0] + actions['undelete'][0] + actions['revert'][0]:
3868 for f in actions['add'][0] + actions['undelete'][0] + actions['revert'][0]:
3867 if f in copied:
3869 if f in copied:
3868 repo.dirstate.copy(copied[f], f)
3870 repo.dirstate.copy(copied[f], f)
3869
3871
3870 class command(registrar.command):
3872 class command(registrar.command):
3871 """deprecated: used registrar.command instead"""
3873 """deprecated: used registrar.command instead"""
3872 def _doregister(self, func, name, *args, **kwargs):
3874 def _doregister(self, func, name, *args, **kwargs):
3873 func._deprecatedregistrar = True # flag for deprecwarn in extensions.py
3875 func._deprecatedregistrar = True # flag for deprecwarn in extensions.py
3874 return super(command, self)._doregister(func, name, *args, **kwargs)
3876 return super(command, self)._doregister(func, name, *args, **kwargs)
3875
3877
3876 # a list of (ui, repo, otherpeer, opts, missing) functions called by
3878 # a list of (ui, repo, otherpeer, opts, missing) functions called by
3877 # commands.outgoing. "missing" is "missing" of the result of
3879 # commands.outgoing. "missing" is "missing" of the result of
3878 # "findcommonoutgoing()"
3880 # "findcommonoutgoing()"
3879 outgoinghooks = util.hooks()
3881 outgoinghooks = util.hooks()
3880
3882
3881 # a list of (ui, repo) functions called by commands.summary
3883 # a list of (ui, repo) functions called by commands.summary
3882 summaryhooks = util.hooks()
3884 summaryhooks = util.hooks()
3883
3885
3884 # a list of (ui, repo, opts, changes) functions called by commands.summary.
3886 # a list of (ui, repo, opts, changes) functions called by commands.summary.
3885 #
3887 #
3886 # functions should return tuple of booleans below, if 'changes' is None:
3888 # functions should return tuple of booleans below, if 'changes' is None:
3887 # (whether-incomings-are-needed, whether-outgoings-are-needed)
3889 # (whether-incomings-are-needed, whether-outgoings-are-needed)
3888 #
3890 #
3889 # otherwise, 'changes' is a tuple of tuples below:
3891 # otherwise, 'changes' is a tuple of tuples below:
3890 # - (sourceurl, sourcebranch, sourcepeer, incoming)
3892 # - (sourceurl, sourcebranch, sourcepeer, incoming)
3891 # - (desturl, destbranch, destpeer, outgoing)
3893 # - (desturl, destbranch, destpeer, outgoing)
3892 summaryremotehooks = util.hooks()
3894 summaryremotehooks = util.hooks()
3893
3895
3894 # A list of state files kept by multistep operations like graft.
3896 # A list of state files kept by multistep operations like graft.
3895 # Since graft cannot be aborted, it is considered 'clearable' by update.
3897 # Since graft cannot be aborted, it is considered 'clearable' by update.
3896 # note: bisect is intentionally excluded
3898 # note: bisect is intentionally excluded
3897 # (state file, clearable, allowcommit, error, hint)
3899 # (state file, clearable, allowcommit, error, hint)
3898 unfinishedstates = [
3900 unfinishedstates = [
3899 ('graftstate', True, False, _('graft in progress'),
3901 ('graftstate', True, False, _('graft in progress'),
3900 _("use 'hg graft --continue' or 'hg update' to abort")),
3902 _("use 'hg graft --continue' or 'hg update' to abort")),
3901 ('updatestate', True, False, _('last update was interrupted'),
3903 ('updatestate', True, False, _('last update was interrupted'),
3902 _("use 'hg update' to get a consistent checkout"))
3904 _("use 'hg update' to get a consistent checkout"))
3903 ]
3905 ]
3904
3906
3905 def checkunfinished(repo, commit=False):
3907 def checkunfinished(repo, commit=False):
3906 '''Look for an unfinished multistep operation, like graft, and abort
3908 '''Look for an unfinished multistep operation, like graft, and abort
3907 if found. It's probably good to check this right before
3909 if found. It's probably good to check this right before
3908 bailifchanged().
3910 bailifchanged().
3909 '''
3911 '''
3910 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3912 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3911 if commit and allowcommit:
3913 if commit and allowcommit:
3912 continue
3914 continue
3913 if repo.vfs.exists(f):
3915 if repo.vfs.exists(f):
3914 raise error.Abort(msg, hint=hint)
3916 raise error.Abort(msg, hint=hint)
3915
3917
3916 def clearunfinished(repo):
3918 def clearunfinished(repo):
3917 '''Check for unfinished operations (as above), and clear the ones
3919 '''Check for unfinished operations (as above), and clear the ones
3918 that are clearable.
3920 that are clearable.
3919 '''
3921 '''
3920 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3922 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3921 if not clearable and repo.vfs.exists(f):
3923 if not clearable and repo.vfs.exists(f):
3922 raise error.Abort(msg, hint=hint)
3924 raise error.Abort(msg, hint=hint)
3923 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3925 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3924 if clearable and repo.vfs.exists(f):
3926 if clearable and repo.vfs.exists(f):
3925 util.unlink(repo.vfs.join(f))
3927 util.unlink(repo.vfs.join(f))
3926
3928
3927 afterresolvedstates = [
3929 afterresolvedstates = [
3928 ('graftstate',
3930 ('graftstate',
3929 _('hg graft --continue')),
3931 _('hg graft --continue')),
3930 ]
3932 ]
3931
3933
3932 def howtocontinue(repo):
3934 def howtocontinue(repo):
3933 '''Check for an unfinished operation and return the command to finish
3935 '''Check for an unfinished operation and return the command to finish
3934 it.
3936 it.
3935
3937
3936 afterresolvedstates tuples define a .hg/{file} and the corresponding
3938 afterresolvedstates tuples define a .hg/{file} and the corresponding
3937 command needed to finish it.
3939 command needed to finish it.
3938
3940
3939 Returns a (msg, warning) tuple. 'msg' is a string and 'warning' is
3941 Returns a (msg, warning) tuple. 'msg' is a string and 'warning' is
3940 a boolean.
3942 a boolean.
3941 '''
3943 '''
3942 contmsg = _("continue: %s")
3944 contmsg = _("continue: %s")
3943 for f, msg in afterresolvedstates:
3945 for f, msg in afterresolvedstates:
3944 if repo.vfs.exists(f):
3946 if repo.vfs.exists(f):
3945 return contmsg % msg, True
3947 return contmsg % msg, True
3946 if repo[None].dirty(missing=True, merge=False, branch=False):
3948 if repo[None].dirty(missing=True, merge=False, branch=False):
3947 return contmsg % _("hg commit"), False
3949 return contmsg % _("hg commit"), False
3948 return None, None
3950 return None, None
3949
3951
3950 def checkafterresolved(repo):
3952 def checkafterresolved(repo):
3951 '''Inform the user about the next action after completing hg resolve
3953 '''Inform the user about the next action after completing hg resolve
3952
3954
3953 If there's a matching afterresolvedstates, howtocontinue will yield
3955 If there's a matching afterresolvedstates, howtocontinue will yield
3954 repo.ui.warn as the reporter.
3956 repo.ui.warn as the reporter.
3955
3957
3956 Otherwise, it will yield repo.ui.note.
3958 Otherwise, it will yield repo.ui.note.
3957 '''
3959 '''
3958 msg, warning = howtocontinue(repo)
3960 msg, warning = howtocontinue(repo)
3959 if msg is not None:
3961 if msg is not None:
3960 if warning:
3962 if warning:
3961 repo.ui.warn("%s\n" % msg)
3963 repo.ui.warn("%s\n" % msg)
3962 else:
3964 else:
3963 repo.ui.note("%s\n" % msg)
3965 repo.ui.note("%s\n" % msg)
3964
3966
3965 def wrongtooltocontinue(repo, task):
3967 def wrongtooltocontinue(repo, task):
3966 '''Raise an abort suggesting how to properly continue if there is an
3968 '''Raise an abort suggesting how to properly continue if there is an
3967 active task.
3969 active task.
3968
3970
3969 Uses howtocontinue() to find the active task.
3971 Uses howtocontinue() to find the active task.
3970
3972
3971 If there's no task (repo.ui.note for 'hg commit'), it does not offer
3973 If there's no task (repo.ui.note for 'hg commit'), it does not offer
3972 a hint.
3974 a hint.
3973 '''
3975 '''
3974 after = howtocontinue(repo)
3976 after = howtocontinue(repo)
3975 hint = None
3977 hint = None
3976 if after[1]:
3978 if after[1]:
3977 hint = after[0]
3979 hint = after[0]
3978 raise error.Abort(_('no %s in progress') % task, hint=hint)
3980 raise error.Abort(_('no %s in progress') % task, hint=hint)
@@ -1,5590 +1,5592 b''
1 # commands.py - command processing for mercurial
1 # commands.py - command processing for 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 difflib
10 import difflib
11 import errno
11 import errno
12 import os
12 import os
13 import re
13 import re
14 import sys
14 import sys
15
15
16 from .i18n import _
16 from .i18n import _
17 from .node import (
17 from .node import (
18 hex,
18 hex,
19 nullid,
19 nullid,
20 nullrev,
20 nullrev,
21 short,
21 short,
22 )
22 )
23 from . import (
23 from . import (
24 archival,
24 archival,
25 bookmarks,
25 bookmarks,
26 bundle2,
26 bundle2,
27 changegroup,
27 changegroup,
28 cmdutil,
28 cmdutil,
29 copies,
29 copies,
30 debugcommands as debugcommandsmod,
30 debugcommands as debugcommandsmod,
31 destutil,
31 destutil,
32 dirstateguard,
32 dirstateguard,
33 discovery,
33 discovery,
34 encoding,
34 encoding,
35 error,
35 error,
36 exchange,
36 exchange,
37 extensions,
37 extensions,
38 formatter,
38 formatter,
39 graphmod,
39 graphmod,
40 hbisect,
40 hbisect,
41 help,
41 help,
42 hg,
42 hg,
43 lock as lockmod,
43 lock as lockmod,
44 merge as mergemod,
44 merge as mergemod,
45 obsolete,
45 obsolete,
46 patch,
46 patch,
47 phases,
47 phases,
48 pycompat,
48 pycompat,
49 rcutil,
49 rcutil,
50 registrar,
50 registrar,
51 revsetlang,
51 revsetlang,
52 scmutil,
52 scmutil,
53 server,
53 server,
54 sshserver,
54 sshserver,
55 streamclone,
55 streamclone,
56 tags as tagsmod,
56 tags as tagsmod,
57 templatekw,
57 templatekw,
58 ui as uimod,
58 ui as uimod,
59 util,
59 util,
60 )
60 )
61
61
62 release = lockmod.release
62 release = lockmod.release
63
63
64 table = {}
64 table = {}
65 table.update(debugcommandsmod.command._table)
65 table.update(debugcommandsmod.command._table)
66
66
67 command = registrar.command(table)
67 command = registrar.command(table)
68 readonly = registrar.command.readonly
68 readonly = registrar.command.readonly
69
69
70 # common command options
70 # common command options
71
71
72 globalopts = [
72 globalopts = [
73 ('R', 'repository', '',
73 ('R', 'repository', '',
74 _('repository root directory or name of overlay bundle file'),
74 _('repository root directory or name of overlay bundle file'),
75 _('REPO')),
75 _('REPO')),
76 ('', 'cwd', '',
76 ('', 'cwd', '',
77 _('change working directory'), _('DIR')),
77 _('change working directory'), _('DIR')),
78 ('y', 'noninteractive', None,
78 ('y', 'noninteractive', None,
79 _('do not prompt, automatically pick the first choice for all prompts')),
79 _('do not prompt, automatically pick the first choice for all prompts')),
80 ('q', 'quiet', None, _('suppress output')),
80 ('q', 'quiet', None, _('suppress output')),
81 ('v', 'verbose', None, _('enable additional output')),
81 ('v', 'verbose', None, _('enable additional output')),
82 ('', 'color', '',
82 ('', 'color', '',
83 # i18n: 'always', 'auto', 'never', and 'debug' are keywords
83 # i18n: 'always', 'auto', 'never', and 'debug' are keywords
84 # and should not be translated
84 # and should not be translated
85 _("when to colorize (boolean, always, auto, never, or debug)"),
85 _("when to colorize (boolean, always, auto, never, or debug)"),
86 _('TYPE')),
86 _('TYPE')),
87 ('', 'config', [],
87 ('', 'config', [],
88 _('set/override config option (use \'section.name=value\')'),
88 _('set/override config option (use \'section.name=value\')'),
89 _('CONFIG')),
89 _('CONFIG')),
90 ('', 'debug', None, _('enable debugging output')),
90 ('', 'debug', None, _('enable debugging output')),
91 ('', 'debugger', None, _('start debugger')),
91 ('', 'debugger', None, _('start debugger')),
92 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
92 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
93 _('ENCODE')),
93 _('ENCODE')),
94 ('', 'encodingmode', encoding.encodingmode,
94 ('', 'encodingmode', encoding.encodingmode,
95 _('set the charset encoding mode'), _('MODE')),
95 _('set the charset encoding mode'), _('MODE')),
96 ('', 'traceback', None, _('always print a traceback on exception')),
96 ('', 'traceback', None, _('always print a traceback on exception')),
97 ('', 'time', None, _('time how long the command takes')),
97 ('', 'time', None, _('time how long the command takes')),
98 ('', 'profile', None, _('print command execution profile')),
98 ('', 'profile', None, _('print command execution profile')),
99 ('', 'version', None, _('output version information and exit')),
99 ('', 'version', None, _('output version information and exit')),
100 ('h', 'help', None, _('display help and exit')),
100 ('h', 'help', None, _('display help and exit')),
101 ('', 'hidden', False, _('consider hidden changesets')),
101 ('', 'hidden', False, _('consider hidden changesets')),
102 ('', 'pager', 'auto',
102 ('', 'pager', 'auto',
103 _("when to paginate (boolean, always, auto, or never)"), _('TYPE')),
103 _("when to paginate (boolean, always, auto, or never)"), _('TYPE')),
104 ]
104 ]
105
105
106 dryrunopts = cmdutil.dryrunopts
106 dryrunopts = cmdutil.dryrunopts
107 remoteopts = cmdutil.remoteopts
107 remoteopts = cmdutil.remoteopts
108 walkopts = cmdutil.walkopts
108 walkopts = cmdutil.walkopts
109 commitopts = cmdutil.commitopts
109 commitopts = cmdutil.commitopts
110 commitopts2 = cmdutil.commitopts2
110 commitopts2 = cmdutil.commitopts2
111 formatteropts = cmdutil.formatteropts
111 formatteropts = cmdutil.formatteropts
112 templateopts = cmdutil.templateopts
112 templateopts = cmdutil.templateopts
113 logopts = cmdutil.logopts
113 logopts = cmdutil.logopts
114 diffopts = cmdutil.diffopts
114 diffopts = cmdutil.diffopts
115 diffwsopts = cmdutil.diffwsopts
115 diffwsopts = cmdutil.diffwsopts
116 diffopts2 = cmdutil.diffopts2
116 diffopts2 = cmdutil.diffopts2
117 mergetoolopts = cmdutil.mergetoolopts
117 mergetoolopts = cmdutil.mergetoolopts
118 similarityopts = cmdutil.similarityopts
118 similarityopts = cmdutil.similarityopts
119 subrepoopts = cmdutil.subrepoopts
119 subrepoopts = cmdutil.subrepoopts
120 debugrevlogopts = cmdutil.debugrevlogopts
120 debugrevlogopts = cmdutil.debugrevlogopts
121
121
122 # Commands start here, listed alphabetically
122 # Commands start here, listed alphabetically
123
123
124 @command('^add',
124 @command('^add',
125 walkopts + subrepoopts + dryrunopts,
125 walkopts + subrepoopts + dryrunopts,
126 _('[OPTION]... [FILE]...'),
126 _('[OPTION]... [FILE]...'),
127 inferrepo=True)
127 inferrepo=True)
128 def add(ui, repo, *pats, **opts):
128 def add(ui, repo, *pats, **opts):
129 """add the specified files on the next commit
129 """add the specified files on the next commit
130
130
131 Schedule files to be version controlled and added to the
131 Schedule files to be version controlled and added to the
132 repository.
132 repository.
133
133
134 The files will be added to the repository at the next commit. To
134 The files will be added to the repository at the next commit. To
135 undo an add before that, see :hg:`forget`.
135 undo an add before that, see :hg:`forget`.
136
136
137 If no names are given, add all files to the repository (except
137 If no names are given, add all files to the repository (except
138 files matching ``.hgignore``).
138 files matching ``.hgignore``).
139
139
140 .. container:: verbose
140 .. container:: verbose
141
141
142 Examples:
142 Examples:
143
143
144 - New (unknown) files are added
144 - New (unknown) files are added
145 automatically by :hg:`add`::
145 automatically by :hg:`add`::
146
146
147 $ ls
147 $ ls
148 foo.c
148 foo.c
149 $ hg status
149 $ hg status
150 ? foo.c
150 ? foo.c
151 $ hg add
151 $ hg add
152 adding foo.c
152 adding foo.c
153 $ hg status
153 $ hg status
154 A foo.c
154 A foo.c
155
155
156 - Specific files to be added can be specified::
156 - Specific files to be added can be specified::
157
157
158 $ ls
158 $ ls
159 bar.c foo.c
159 bar.c foo.c
160 $ hg status
160 $ hg status
161 ? bar.c
161 ? bar.c
162 ? foo.c
162 ? foo.c
163 $ hg add bar.c
163 $ hg add bar.c
164 $ hg status
164 $ hg status
165 A bar.c
165 A bar.c
166 ? foo.c
166 ? foo.c
167
167
168 Returns 0 if all files are successfully added.
168 Returns 0 if all files are successfully added.
169 """
169 """
170
170
171 m = scmutil.match(repo[None], pats, pycompat.byteskwargs(opts))
171 m = scmutil.match(repo[None], pats, pycompat.byteskwargs(opts))
172 rejected = cmdutil.add(ui, repo, m, "", False, **opts)
172 rejected = cmdutil.add(ui, repo, m, "", False, **opts)
173 return rejected and 1 or 0
173 return rejected and 1 or 0
174
174
175 @command('addremove',
175 @command('addremove',
176 similarityopts + subrepoopts + walkopts + dryrunopts,
176 similarityopts + subrepoopts + walkopts + dryrunopts,
177 _('[OPTION]... [FILE]...'),
177 _('[OPTION]... [FILE]...'),
178 inferrepo=True)
178 inferrepo=True)
179 def addremove(ui, repo, *pats, **opts):
179 def addremove(ui, repo, *pats, **opts):
180 """add all new files, delete all missing files
180 """add all new files, delete all missing files
181
181
182 Add all new files and remove all missing files from the
182 Add all new files and remove all missing files from the
183 repository.
183 repository.
184
184
185 Unless names are given, new files are ignored if they match any of
185 Unless names are given, new files are ignored if they match any of
186 the patterns in ``.hgignore``. As with add, these changes take
186 the patterns in ``.hgignore``. As with add, these changes take
187 effect at the next commit.
187 effect at the next commit.
188
188
189 Use the -s/--similarity option to detect renamed files. This
189 Use the -s/--similarity option to detect renamed files. This
190 option takes a percentage between 0 (disabled) and 100 (files must
190 option takes a percentage between 0 (disabled) and 100 (files must
191 be identical) as its parameter. With a parameter greater than 0,
191 be identical) as its parameter. With a parameter greater than 0,
192 this compares every removed file with every added file and records
192 this compares every removed file with every added file and records
193 those similar enough as renames. Detecting renamed files this way
193 those similar enough as renames. Detecting renamed files this way
194 can be expensive. After using this option, :hg:`status -C` can be
194 can be expensive. After using this option, :hg:`status -C` can be
195 used to check which files were identified as moved or renamed. If
195 used to check which files were identified as moved or renamed. If
196 not specified, -s/--similarity defaults to 100 and only renames of
196 not specified, -s/--similarity defaults to 100 and only renames of
197 identical files are detected.
197 identical files are detected.
198
198
199 .. container:: verbose
199 .. container:: verbose
200
200
201 Examples:
201 Examples:
202
202
203 - A number of files (bar.c and foo.c) are new,
203 - A number of files (bar.c and foo.c) are new,
204 while foobar.c has been removed (without using :hg:`remove`)
204 while foobar.c has been removed (without using :hg:`remove`)
205 from the repository::
205 from the repository::
206
206
207 $ ls
207 $ ls
208 bar.c foo.c
208 bar.c foo.c
209 $ hg status
209 $ hg status
210 ! foobar.c
210 ! foobar.c
211 ? bar.c
211 ? bar.c
212 ? foo.c
212 ? foo.c
213 $ hg addremove
213 $ hg addremove
214 adding bar.c
214 adding bar.c
215 adding foo.c
215 adding foo.c
216 removing foobar.c
216 removing foobar.c
217 $ hg status
217 $ hg status
218 A bar.c
218 A bar.c
219 A foo.c
219 A foo.c
220 R foobar.c
220 R foobar.c
221
221
222 - A file foobar.c was moved to foo.c without using :hg:`rename`.
222 - A file foobar.c was moved to foo.c without using :hg:`rename`.
223 Afterwards, it was edited slightly::
223 Afterwards, it was edited slightly::
224
224
225 $ ls
225 $ ls
226 foo.c
226 foo.c
227 $ hg status
227 $ hg status
228 ! foobar.c
228 ! foobar.c
229 ? foo.c
229 ? foo.c
230 $ hg addremove --similarity 90
230 $ hg addremove --similarity 90
231 removing foobar.c
231 removing foobar.c
232 adding foo.c
232 adding foo.c
233 recording removal of foobar.c as rename to foo.c (94% similar)
233 recording removal of foobar.c as rename to foo.c (94% similar)
234 $ hg status -C
234 $ hg status -C
235 A foo.c
235 A foo.c
236 foobar.c
236 foobar.c
237 R foobar.c
237 R foobar.c
238
238
239 Returns 0 if all files are successfully added.
239 Returns 0 if all files are successfully added.
240 """
240 """
241 opts = pycompat.byteskwargs(opts)
241 opts = pycompat.byteskwargs(opts)
242 try:
242 try:
243 sim = float(opts.get('similarity') or 100)
243 sim = float(opts.get('similarity') or 100)
244 except ValueError:
244 except ValueError:
245 raise error.Abort(_('similarity must be a number'))
245 raise error.Abort(_('similarity must be a number'))
246 if sim < 0 or sim > 100:
246 if sim < 0 or sim > 100:
247 raise error.Abort(_('similarity must be between 0 and 100'))
247 raise error.Abort(_('similarity must be between 0 and 100'))
248 matcher = scmutil.match(repo[None], pats, opts)
248 matcher = scmutil.match(repo[None], pats, opts)
249 return scmutil.addremove(repo, matcher, "", opts, similarity=sim / 100.0)
249 return scmutil.addremove(repo, matcher, "", opts, similarity=sim / 100.0)
250
250
251 @command('^annotate|blame',
251 @command('^annotate|blame',
252 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
252 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
253 ('', 'follow', None,
253 ('', 'follow', None,
254 _('follow copies/renames and list the filename (DEPRECATED)')),
254 _('follow copies/renames and list the filename (DEPRECATED)')),
255 ('', 'no-follow', None, _("don't follow copies and renames")),
255 ('', 'no-follow', None, _("don't follow copies and renames")),
256 ('a', 'text', None, _('treat all files as text')),
256 ('a', 'text', None, _('treat all files as text')),
257 ('u', 'user', None, _('list the author (long with -v)')),
257 ('u', 'user', None, _('list the author (long with -v)')),
258 ('f', 'file', None, _('list the filename')),
258 ('f', 'file', None, _('list the filename')),
259 ('d', 'date', None, _('list the date (short with -q)')),
259 ('d', 'date', None, _('list the date (short with -q)')),
260 ('n', 'number', None, _('list the revision number (default)')),
260 ('n', 'number', None, _('list the revision number (default)')),
261 ('c', 'changeset', None, _('list the changeset')),
261 ('c', 'changeset', None, _('list the changeset')),
262 ('l', 'line-number', None, _('show line number at the first appearance')),
262 ('l', 'line-number', None, _('show line number at the first appearance')),
263 ('', 'skip', [], _('revision to not display (EXPERIMENTAL)'), _('REV')),
263 ('', 'skip', [], _('revision to not display (EXPERIMENTAL)'), _('REV')),
264 ] + diffwsopts + walkopts + formatteropts,
264 ] + diffwsopts + walkopts + formatteropts,
265 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'),
265 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'),
266 inferrepo=True)
266 inferrepo=True)
267 def annotate(ui, repo, *pats, **opts):
267 def annotate(ui, repo, *pats, **opts):
268 """show changeset information by line for each file
268 """show changeset information by line for each file
269
269
270 List changes in files, showing the revision id responsible for
270 List changes in files, showing the revision id responsible for
271 each line.
271 each line.
272
272
273 This command is useful for discovering when a change was made and
273 This command is useful for discovering when a change was made and
274 by whom.
274 by whom.
275
275
276 If you include --file, --user, or --date, the revision number is
276 If you include --file, --user, or --date, the revision number is
277 suppressed unless you also include --number.
277 suppressed unless you also include --number.
278
278
279 Without the -a/--text option, annotate will avoid processing files
279 Without the -a/--text option, annotate will avoid processing files
280 it detects as binary. With -a, annotate will annotate the file
280 it detects as binary. With -a, annotate will annotate the file
281 anyway, although the results will probably be neither useful
281 anyway, although the results will probably be neither useful
282 nor desirable.
282 nor desirable.
283
283
284 Returns 0 on success.
284 Returns 0 on success.
285 """
285 """
286 opts = pycompat.byteskwargs(opts)
286 opts = pycompat.byteskwargs(opts)
287 if not pats:
287 if not pats:
288 raise error.Abort(_('at least one filename or pattern is required'))
288 raise error.Abort(_('at least one filename or pattern is required'))
289
289
290 if opts.get('follow'):
290 if opts.get('follow'):
291 # --follow is deprecated and now just an alias for -f/--file
291 # --follow is deprecated and now just an alias for -f/--file
292 # to mimic the behavior of Mercurial before version 1.5
292 # to mimic the behavior of Mercurial before version 1.5
293 opts['file'] = True
293 opts['file'] = True
294
294
295 ctx = scmutil.revsingle(repo, opts.get('rev'))
295 ctx = scmutil.revsingle(repo, opts.get('rev'))
296
296
297 rootfm = ui.formatter('annotate', opts)
297 rootfm = ui.formatter('annotate', opts)
298 if ui.quiet:
298 if ui.quiet:
299 datefunc = util.shortdate
299 datefunc = util.shortdate
300 else:
300 else:
301 datefunc = util.datestr
301 datefunc = util.datestr
302 if ctx.rev() is None:
302 if ctx.rev() is None:
303 def hexfn(node):
303 def hexfn(node):
304 if node is None:
304 if node is None:
305 return None
305 return None
306 else:
306 else:
307 return rootfm.hexfunc(node)
307 return rootfm.hexfunc(node)
308 if opts.get('changeset'):
308 if opts.get('changeset'):
309 # omit "+" suffix which is appended to node hex
309 # omit "+" suffix which is appended to node hex
310 def formatrev(rev):
310 def formatrev(rev):
311 if rev is None:
311 if rev is None:
312 return '%d' % ctx.p1().rev()
312 return '%d' % ctx.p1().rev()
313 else:
313 else:
314 return '%d' % rev
314 return '%d' % rev
315 else:
315 else:
316 def formatrev(rev):
316 def formatrev(rev):
317 if rev is None:
317 if rev is None:
318 return '%d+' % ctx.p1().rev()
318 return '%d+' % ctx.p1().rev()
319 else:
319 else:
320 return '%d ' % rev
320 return '%d ' % rev
321 def formathex(hex):
321 def formathex(hex):
322 if hex is None:
322 if hex is None:
323 return '%s+' % rootfm.hexfunc(ctx.p1().node())
323 return '%s+' % rootfm.hexfunc(ctx.p1().node())
324 else:
324 else:
325 return '%s ' % hex
325 return '%s ' % hex
326 else:
326 else:
327 hexfn = rootfm.hexfunc
327 hexfn = rootfm.hexfunc
328 formatrev = formathex = pycompat.bytestr
328 formatrev = formathex = pycompat.bytestr
329
329
330 opmap = [('user', ' ', lambda x: x.fctx.user(), ui.shortuser),
330 opmap = [('user', ' ', lambda x: x.fctx.user(), ui.shortuser),
331 ('number', ' ', lambda x: x.fctx.rev(), formatrev),
331 ('number', ' ', lambda x: x.fctx.rev(), formatrev),
332 ('changeset', ' ', lambda x: hexfn(x.fctx.node()), formathex),
332 ('changeset', ' ', lambda x: hexfn(x.fctx.node()), formathex),
333 ('date', ' ', lambda x: x.fctx.date(), util.cachefunc(datefunc)),
333 ('date', ' ', lambda x: x.fctx.date(), util.cachefunc(datefunc)),
334 ('file', ' ', lambda x: x.fctx.path(), str),
334 ('file', ' ', lambda x: x.fctx.path(), str),
335 ('line_number', ':', lambda x: x.lineno, str),
335 ('line_number', ':', lambda x: x.lineno, str),
336 ]
336 ]
337 fieldnamemap = {'number': 'rev', 'changeset': 'node'}
337 fieldnamemap = {'number': 'rev', 'changeset': 'node'}
338
338
339 if (not opts.get('user') and not opts.get('changeset')
339 if (not opts.get('user') and not opts.get('changeset')
340 and not opts.get('date') and not opts.get('file')):
340 and not opts.get('date') and not opts.get('file')):
341 opts['number'] = True
341 opts['number'] = True
342
342
343 linenumber = opts.get('line_number') is not None
343 linenumber = opts.get('line_number') is not None
344 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
344 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
345 raise error.Abort(_('at least one of -n/-c is required for -l'))
345 raise error.Abort(_('at least one of -n/-c is required for -l'))
346
346
347 ui.pager('annotate')
347 ui.pager('annotate')
348
348
349 if rootfm.isplain():
349 if rootfm.isplain():
350 def makefunc(get, fmt):
350 def makefunc(get, fmt):
351 return lambda x: fmt(get(x))
351 return lambda x: fmt(get(x))
352 else:
352 else:
353 def makefunc(get, fmt):
353 def makefunc(get, fmt):
354 return get
354 return get
355 funcmap = [(makefunc(get, fmt), sep) for op, sep, get, fmt in opmap
355 funcmap = [(makefunc(get, fmt), sep) for op, sep, get, fmt in opmap
356 if opts.get(op)]
356 if opts.get(op)]
357 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
357 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
358 fields = ' '.join(fieldnamemap.get(op, op) for op, sep, get, fmt in opmap
358 fields = ' '.join(fieldnamemap.get(op, op) for op, sep, get, fmt in opmap
359 if opts.get(op))
359 if opts.get(op))
360
360
361 def bad(x, y):
361 def bad(x, y):
362 raise error.Abort("%s: %s" % (x, y))
362 raise error.Abort("%s: %s" % (x, y))
363
363
364 m = scmutil.match(ctx, pats, opts, badfn=bad)
364 m = scmutil.match(ctx, pats, opts, badfn=bad)
365
365
366 follow = not opts.get('no_follow')
366 follow = not opts.get('no_follow')
367 diffopts = patch.difffeatureopts(ui, opts, section='annotate',
367 diffopts = patch.difffeatureopts(ui, opts, section='annotate',
368 whitespace=True)
368 whitespace=True)
369 skiprevs = opts.get('skip')
369 skiprevs = opts.get('skip')
370 if skiprevs:
370 if skiprevs:
371 skiprevs = scmutil.revrange(repo, skiprevs)
371 skiprevs = scmutil.revrange(repo, skiprevs)
372
372
373 for abs in ctx.walk(m):
373 for abs in ctx.walk(m):
374 fctx = ctx[abs]
374 fctx = ctx[abs]
375 rootfm.startitem()
375 rootfm.startitem()
376 rootfm.data(abspath=abs, path=m.rel(abs))
376 rootfm.data(abspath=abs, path=m.rel(abs))
377 if not opts.get('text') and fctx.isbinary():
377 if not opts.get('text') and fctx.isbinary():
378 rootfm.plain(_("%s: binary file\n")
378 rootfm.plain(_("%s: binary file\n")
379 % ((pats and m.rel(abs)) or abs))
379 % ((pats and m.rel(abs)) or abs))
380 continue
380 continue
381
381
382 fm = rootfm.nested('lines')
382 fm = rootfm.nested('lines')
383 lines = fctx.annotate(follow=follow, linenumber=linenumber,
383 lines = fctx.annotate(follow=follow, linenumber=linenumber,
384 skiprevs=skiprevs, diffopts=diffopts)
384 skiprevs=skiprevs, diffopts=diffopts)
385 if not lines:
385 if not lines:
386 fm.end()
386 fm.end()
387 continue
387 continue
388 formats = []
388 formats = []
389 pieces = []
389 pieces = []
390
390
391 for f, sep in funcmap:
391 for f, sep in funcmap:
392 l = [f(n) for n, dummy in lines]
392 l = [f(n) for n, dummy in lines]
393 if fm.isplain():
393 if fm.isplain():
394 sizes = [encoding.colwidth(x) for x in l]
394 sizes = [encoding.colwidth(x) for x in l]
395 ml = max(sizes)
395 ml = max(sizes)
396 formats.append([sep + ' ' * (ml - w) + '%s' for w in sizes])
396 formats.append([sep + ' ' * (ml - w) + '%s' for w in sizes])
397 else:
397 else:
398 formats.append(['%s' for x in l])
398 formats.append(['%s' for x in l])
399 pieces.append(l)
399 pieces.append(l)
400
400
401 for f, p, l in zip(zip(*formats), zip(*pieces), lines):
401 for f, p, l in zip(zip(*formats), zip(*pieces), lines):
402 fm.startitem()
402 fm.startitem()
403 fm.write(fields, "".join(f), *p)
403 fm.write(fields, "".join(f), *p)
404 if l[0].skip:
404 if l[0].skip:
405 fmt = "* %s"
405 fmt = "* %s"
406 else:
406 else:
407 fmt = ": %s"
407 fmt = ": %s"
408 fm.write('line', fmt, l[1])
408 fm.write('line', fmt, l[1])
409
409
410 if not lines[-1][1].endswith('\n'):
410 if not lines[-1][1].endswith('\n'):
411 fm.plain('\n')
411 fm.plain('\n')
412 fm.end()
412 fm.end()
413
413
414 rootfm.end()
414 rootfm.end()
415
415
416 @command('archive',
416 @command('archive',
417 [('', 'no-decode', None, _('do not pass files through decoders')),
417 [('', 'no-decode', None, _('do not pass files through decoders')),
418 ('p', 'prefix', '', _('directory prefix for files in archive'),
418 ('p', 'prefix', '', _('directory prefix for files in archive'),
419 _('PREFIX')),
419 _('PREFIX')),
420 ('r', 'rev', '', _('revision to distribute'), _('REV')),
420 ('r', 'rev', '', _('revision to distribute'), _('REV')),
421 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
421 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
422 ] + subrepoopts + walkopts,
422 ] + subrepoopts + walkopts,
423 _('[OPTION]... DEST'))
423 _('[OPTION]... DEST'))
424 def archive(ui, repo, dest, **opts):
424 def archive(ui, repo, dest, **opts):
425 '''create an unversioned archive of a repository revision
425 '''create an unversioned archive of a repository revision
426
426
427 By default, the revision used is the parent of the working
427 By default, the revision used is the parent of the working
428 directory; use -r/--rev to specify a different revision.
428 directory; use -r/--rev to specify a different revision.
429
429
430 The archive type is automatically detected based on file
430 The archive type is automatically detected based on file
431 extension (to override, use -t/--type).
431 extension (to override, use -t/--type).
432
432
433 .. container:: verbose
433 .. container:: verbose
434
434
435 Examples:
435 Examples:
436
436
437 - create a zip file containing the 1.0 release::
437 - create a zip file containing the 1.0 release::
438
438
439 hg archive -r 1.0 project-1.0.zip
439 hg archive -r 1.0 project-1.0.zip
440
440
441 - create a tarball excluding .hg files::
441 - create a tarball excluding .hg files::
442
442
443 hg archive project.tar.gz -X ".hg*"
443 hg archive project.tar.gz -X ".hg*"
444
444
445 Valid types are:
445 Valid types are:
446
446
447 :``files``: a directory full of files (default)
447 :``files``: a directory full of files (default)
448 :``tar``: tar archive, uncompressed
448 :``tar``: tar archive, uncompressed
449 :``tbz2``: tar archive, compressed using bzip2
449 :``tbz2``: tar archive, compressed using bzip2
450 :``tgz``: tar archive, compressed using gzip
450 :``tgz``: tar archive, compressed using gzip
451 :``uzip``: zip archive, uncompressed
451 :``uzip``: zip archive, uncompressed
452 :``zip``: zip archive, compressed using deflate
452 :``zip``: zip archive, compressed using deflate
453
453
454 The exact name of the destination archive or directory is given
454 The exact name of the destination archive or directory is given
455 using a format string; see :hg:`help export` for details.
455 using a format string; see :hg:`help export` for details.
456
456
457 Each member added to an archive file has a directory prefix
457 Each member added to an archive file has a directory prefix
458 prepended. Use -p/--prefix to specify a format string for the
458 prepended. Use -p/--prefix to specify a format string for the
459 prefix. The default is the basename of the archive, with suffixes
459 prefix. The default is the basename of the archive, with suffixes
460 removed.
460 removed.
461
461
462 Returns 0 on success.
462 Returns 0 on success.
463 '''
463 '''
464
464
465 opts = pycompat.byteskwargs(opts)
465 opts = pycompat.byteskwargs(opts)
466 ctx = scmutil.revsingle(repo, opts.get('rev'))
466 ctx = scmutil.revsingle(repo, opts.get('rev'))
467 if not ctx:
467 if not ctx:
468 raise error.Abort(_('no working directory: please specify a revision'))
468 raise error.Abort(_('no working directory: please specify a revision'))
469 node = ctx.node()
469 node = ctx.node()
470 dest = cmdutil.makefilename(repo, dest, node)
470 dest = cmdutil.makefilename(repo, dest, node)
471 if os.path.realpath(dest) == repo.root:
471 if os.path.realpath(dest) == repo.root:
472 raise error.Abort(_('repository root cannot be destination'))
472 raise error.Abort(_('repository root cannot be destination'))
473
473
474 kind = opts.get('type') or archival.guesskind(dest) or 'files'
474 kind = opts.get('type') or archival.guesskind(dest) or 'files'
475 prefix = opts.get('prefix')
475 prefix = opts.get('prefix')
476
476
477 if dest == '-':
477 if dest == '-':
478 if kind == 'files':
478 if kind == 'files':
479 raise error.Abort(_('cannot archive plain files to stdout'))
479 raise error.Abort(_('cannot archive plain files to stdout'))
480 dest = cmdutil.makefileobj(repo, dest)
480 dest = cmdutil.makefileobj(repo, dest)
481 if not prefix:
481 if not prefix:
482 prefix = os.path.basename(repo.root) + '-%h'
482 prefix = os.path.basename(repo.root) + '-%h'
483
483
484 prefix = cmdutil.makefilename(repo, prefix, node)
484 prefix = cmdutil.makefilename(repo, prefix, node)
485 match = scmutil.match(ctx, [], opts)
485 match = scmutil.match(ctx, [], opts)
486 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
486 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
487 match, prefix, subrepos=opts.get('subrepos'))
487 match, prefix, subrepos=opts.get('subrepos'))
488
488
489 @command('backout',
489 @command('backout',
490 [('', 'merge', None, _('merge with old dirstate parent after backout')),
490 [('', 'merge', None, _('merge with old dirstate parent after backout')),
491 ('', 'commit', None,
491 ('', 'commit', None,
492 _('commit if no conflicts were encountered (DEPRECATED)')),
492 _('commit if no conflicts were encountered (DEPRECATED)')),
493 ('', 'no-commit', None, _('do not commit')),
493 ('', 'no-commit', None, _('do not commit')),
494 ('', 'parent', '',
494 ('', 'parent', '',
495 _('parent to choose when backing out merge (DEPRECATED)'), _('REV')),
495 _('parent to choose when backing out merge (DEPRECATED)'), _('REV')),
496 ('r', 'rev', '', _('revision to backout'), _('REV')),
496 ('r', 'rev', '', _('revision to backout'), _('REV')),
497 ('e', 'edit', False, _('invoke editor on commit messages')),
497 ('e', 'edit', False, _('invoke editor on commit messages')),
498 ] + mergetoolopts + walkopts + commitopts + commitopts2,
498 ] + mergetoolopts + walkopts + commitopts + commitopts2,
499 _('[OPTION]... [-r] REV'))
499 _('[OPTION]... [-r] REV'))
500 def backout(ui, repo, node=None, rev=None, **opts):
500 def backout(ui, repo, node=None, rev=None, **opts):
501 '''reverse effect of earlier changeset
501 '''reverse effect of earlier changeset
502
502
503 Prepare a new changeset with the effect of REV undone in the
503 Prepare a new changeset with the effect of REV undone in the
504 current working directory. If no conflicts were encountered,
504 current working directory. If no conflicts were encountered,
505 it will be committed immediately.
505 it will be committed immediately.
506
506
507 If REV is the parent of the working directory, then this new changeset
507 If REV is the parent of the working directory, then this new changeset
508 is committed automatically (unless --no-commit is specified).
508 is committed automatically (unless --no-commit is specified).
509
509
510 .. note::
510 .. note::
511
511
512 :hg:`backout` cannot be used to fix either an unwanted or
512 :hg:`backout` cannot be used to fix either an unwanted or
513 incorrect merge.
513 incorrect merge.
514
514
515 .. container:: verbose
515 .. container:: verbose
516
516
517 Examples:
517 Examples:
518
518
519 - Reverse the effect of the parent of the working directory.
519 - Reverse the effect of the parent of the working directory.
520 This backout will be committed immediately::
520 This backout will be committed immediately::
521
521
522 hg backout -r .
522 hg backout -r .
523
523
524 - Reverse the effect of previous bad revision 23::
524 - Reverse the effect of previous bad revision 23::
525
525
526 hg backout -r 23
526 hg backout -r 23
527
527
528 - Reverse the effect of previous bad revision 23 and
528 - Reverse the effect of previous bad revision 23 and
529 leave changes uncommitted::
529 leave changes uncommitted::
530
530
531 hg backout -r 23 --no-commit
531 hg backout -r 23 --no-commit
532 hg commit -m "Backout revision 23"
532 hg commit -m "Backout revision 23"
533
533
534 By default, the pending changeset will have one parent,
534 By default, the pending changeset will have one parent,
535 maintaining a linear history. With --merge, the pending
535 maintaining a linear history. With --merge, the pending
536 changeset will instead have two parents: the old parent of the
536 changeset will instead have two parents: the old parent of the
537 working directory and a new child of REV that simply undoes REV.
537 working directory and a new child of REV that simply undoes REV.
538
538
539 Before version 1.7, the behavior without --merge was equivalent
539 Before version 1.7, the behavior without --merge was equivalent
540 to specifying --merge followed by :hg:`update --clean .` to
540 to specifying --merge followed by :hg:`update --clean .` to
541 cancel the merge and leave the child of REV as a head to be
541 cancel the merge and leave the child of REV as a head to be
542 merged separately.
542 merged separately.
543
543
544 See :hg:`help dates` for a list of formats valid for -d/--date.
544 See :hg:`help dates` for a list of formats valid for -d/--date.
545
545
546 See :hg:`help revert` for a way to restore files to the state
546 See :hg:`help revert` for a way to restore files to the state
547 of another revision.
547 of another revision.
548
548
549 Returns 0 on success, 1 if nothing to backout or there are unresolved
549 Returns 0 on success, 1 if nothing to backout or there are unresolved
550 files.
550 files.
551 '''
551 '''
552 wlock = lock = None
552 wlock = lock = None
553 try:
553 try:
554 wlock = repo.wlock()
554 wlock = repo.wlock()
555 lock = repo.lock()
555 lock = repo.lock()
556 return _dobackout(ui, repo, node, rev, **opts)
556 return _dobackout(ui, repo, node, rev, **opts)
557 finally:
557 finally:
558 release(lock, wlock)
558 release(lock, wlock)
559
559
560 def _dobackout(ui, repo, node=None, rev=None, **opts):
560 def _dobackout(ui, repo, node=None, rev=None, **opts):
561 opts = pycompat.byteskwargs(opts)
561 opts = pycompat.byteskwargs(opts)
562 if opts.get('commit') and opts.get('no_commit'):
562 if opts.get('commit') and opts.get('no_commit'):
563 raise error.Abort(_("cannot use --commit with --no-commit"))
563 raise error.Abort(_("cannot use --commit with --no-commit"))
564 if opts.get('merge') and opts.get('no_commit'):
564 if opts.get('merge') and opts.get('no_commit'):
565 raise error.Abort(_("cannot use --merge with --no-commit"))
565 raise error.Abort(_("cannot use --merge with --no-commit"))
566
566
567 if rev and node:
567 if rev and node:
568 raise error.Abort(_("please specify just one revision"))
568 raise error.Abort(_("please specify just one revision"))
569
569
570 if not rev:
570 if not rev:
571 rev = node
571 rev = node
572
572
573 if not rev:
573 if not rev:
574 raise error.Abort(_("please specify a revision to backout"))
574 raise error.Abort(_("please specify a revision to backout"))
575
575
576 date = opts.get('date')
576 date = opts.get('date')
577 if date:
577 if date:
578 opts['date'] = util.parsedate(date)
578 opts['date'] = util.parsedate(date)
579
579
580 cmdutil.checkunfinished(repo)
580 cmdutil.checkunfinished(repo)
581 cmdutil.bailifchanged(repo)
581 cmdutil.bailifchanged(repo)
582 node = scmutil.revsingle(repo, rev).node()
582 node = scmutil.revsingle(repo, rev).node()
583
583
584 op1, op2 = repo.dirstate.parents()
584 op1, op2 = repo.dirstate.parents()
585 if not repo.changelog.isancestor(node, op1):
585 if not repo.changelog.isancestor(node, op1):
586 raise error.Abort(_('cannot backout change that is not an ancestor'))
586 raise error.Abort(_('cannot backout change that is not an ancestor'))
587
587
588 p1, p2 = repo.changelog.parents(node)
588 p1, p2 = repo.changelog.parents(node)
589 if p1 == nullid:
589 if p1 == nullid:
590 raise error.Abort(_('cannot backout a change with no parents'))
590 raise error.Abort(_('cannot backout a change with no parents'))
591 if p2 != nullid:
591 if p2 != nullid:
592 if not opts.get('parent'):
592 if not opts.get('parent'):
593 raise error.Abort(_('cannot backout a merge changeset'))
593 raise error.Abort(_('cannot backout a merge changeset'))
594 p = repo.lookup(opts['parent'])
594 p = repo.lookup(opts['parent'])
595 if p not in (p1, p2):
595 if p not in (p1, p2):
596 raise error.Abort(_('%s is not a parent of %s') %
596 raise error.Abort(_('%s is not a parent of %s') %
597 (short(p), short(node)))
597 (short(p), short(node)))
598 parent = p
598 parent = p
599 else:
599 else:
600 if opts.get('parent'):
600 if opts.get('parent'):
601 raise error.Abort(_('cannot use --parent on non-merge changeset'))
601 raise error.Abort(_('cannot use --parent on non-merge changeset'))
602 parent = p1
602 parent = p1
603
603
604 # the backout should appear on the same branch
604 # the backout should appear on the same branch
605 branch = repo.dirstate.branch()
605 branch = repo.dirstate.branch()
606 bheads = repo.branchheads(branch)
606 bheads = repo.branchheads(branch)
607 rctx = scmutil.revsingle(repo, hex(parent))
607 rctx = scmutil.revsingle(repo, hex(parent))
608 if not opts.get('merge') and op1 != node:
608 if not opts.get('merge') and op1 != node:
609 dsguard = dirstateguard.dirstateguard(repo, 'backout')
609 dsguard = dirstateguard.dirstateguard(repo, 'backout')
610 try:
610 try:
611 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
611 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
612 'backout')
612 'backout')
613 stats = mergemod.update(repo, parent, True, True, node, False)
613 stats = mergemod.update(repo, parent, True, True, node, False)
614 repo.setparents(op1, op2)
614 repo.setparents(op1, op2)
615 dsguard.close()
615 dsguard.close()
616 hg._showstats(repo, stats)
616 hg._showstats(repo, stats)
617 if stats[3]:
617 if stats[3]:
618 repo.ui.status(_("use 'hg resolve' to retry unresolved "
618 repo.ui.status(_("use 'hg resolve' to retry unresolved "
619 "file merges\n"))
619 "file merges\n"))
620 return 1
620 return 1
621 finally:
621 finally:
622 ui.setconfig('ui', 'forcemerge', '', '')
622 ui.setconfig('ui', 'forcemerge', '', '')
623 lockmod.release(dsguard)
623 lockmod.release(dsguard)
624 else:
624 else:
625 hg.clean(repo, node, show_stats=False)
625 hg.clean(repo, node, show_stats=False)
626 repo.dirstate.setbranch(branch)
626 repo.dirstate.setbranch(branch)
627 cmdutil.revert(ui, repo, rctx, repo.dirstate.parents())
627 cmdutil.revert(ui, repo, rctx, repo.dirstate.parents())
628
628
629 if opts.get('no_commit'):
629 if opts.get('no_commit'):
630 msg = _("changeset %s backed out, "
630 msg = _("changeset %s backed out, "
631 "don't forget to commit.\n")
631 "don't forget to commit.\n")
632 ui.status(msg % short(node))
632 ui.status(msg % short(node))
633 return 0
633 return 0
634
634
635 def commitfunc(ui, repo, message, match, opts):
635 def commitfunc(ui, repo, message, match, opts):
636 editform = 'backout'
636 editform = 'backout'
637 e = cmdutil.getcommiteditor(editform=editform,
637 e = cmdutil.getcommiteditor(editform=editform,
638 **pycompat.strkwargs(opts))
638 **pycompat.strkwargs(opts))
639 if not message:
639 if not message:
640 # we don't translate commit messages
640 # we don't translate commit messages
641 message = "Backed out changeset %s" % short(node)
641 message = "Backed out changeset %s" % short(node)
642 e = cmdutil.getcommiteditor(edit=True, editform=editform)
642 e = cmdutil.getcommiteditor(edit=True, editform=editform)
643 return repo.commit(message, opts.get('user'), opts.get('date'),
643 return repo.commit(message, opts.get('user'), opts.get('date'),
644 match, editor=e)
644 match, editor=e)
645 newnode = cmdutil.commit(ui, repo, commitfunc, [], opts)
645 newnode = cmdutil.commit(ui, repo, commitfunc, [], opts)
646 if not newnode:
646 if not newnode:
647 ui.status(_("nothing changed\n"))
647 ui.status(_("nothing changed\n"))
648 return 1
648 return 1
649 cmdutil.commitstatus(repo, newnode, branch, bheads)
649 cmdutil.commitstatus(repo, newnode, branch, bheads)
650
650
651 def nice(node):
651 def nice(node):
652 return '%d:%s' % (repo.changelog.rev(node), short(node))
652 return '%d:%s' % (repo.changelog.rev(node), short(node))
653 ui.status(_('changeset %s backs out changeset %s\n') %
653 ui.status(_('changeset %s backs out changeset %s\n') %
654 (nice(repo.changelog.tip()), nice(node)))
654 (nice(repo.changelog.tip()), nice(node)))
655 if opts.get('merge') and op1 != node:
655 if opts.get('merge') and op1 != node:
656 hg.clean(repo, op1, show_stats=False)
656 hg.clean(repo, op1, show_stats=False)
657 ui.status(_('merging with changeset %s\n')
657 ui.status(_('merging with changeset %s\n')
658 % nice(repo.changelog.tip()))
658 % nice(repo.changelog.tip()))
659 try:
659 try:
660 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
660 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
661 'backout')
661 'backout')
662 return hg.merge(repo, hex(repo.changelog.tip()))
662 return hg.merge(repo, hex(repo.changelog.tip()))
663 finally:
663 finally:
664 ui.setconfig('ui', 'forcemerge', '', '')
664 ui.setconfig('ui', 'forcemerge', '', '')
665 return 0
665 return 0
666
666
667 @command('bisect',
667 @command('bisect',
668 [('r', 'reset', False, _('reset bisect state')),
668 [('r', 'reset', False, _('reset bisect state')),
669 ('g', 'good', False, _('mark changeset good')),
669 ('g', 'good', False, _('mark changeset good')),
670 ('b', 'bad', False, _('mark changeset bad')),
670 ('b', 'bad', False, _('mark changeset bad')),
671 ('s', 'skip', False, _('skip testing changeset')),
671 ('s', 'skip', False, _('skip testing changeset')),
672 ('e', 'extend', False, _('extend the bisect range')),
672 ('e', 'extend', False, _('extend the bisect range')),
673 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
673 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
674 ('U', 'noupdate', False, _('do not update to target'))],
674 ('U', 'noupdate', False, _('do not update to target'))],
675 _("[-gbsr] [-U] [-c CMD] [REV]"))
675 _("[-gbsr] [-U] [-c CMD] [REV]"))
676 def bisect(ui, repo, rev=None, extra=None, command=None,
676 def bisect(ui, repo, rev=None, extra=None, command=None,
677 reset=None, good=None, bad=None, skip=None, extend=None,
677 reset=None, good=None, bad=None, skip=None, extend=None,
678 noupdate=None):
678 noupdate=None):
679 """subdivision search of changesets
679 """subdivision search of changesets
680
680
681 This command helps to find changesets which introduce problems. To
681 This command helps to find changesets which introduce problems. To
682 use, mark the earliest changeset you know exhibits the problem as
682 use, mark the earliest changeset you know exhibits the problem as
683 bad, then mark the latest changeset which is free from the problem
683 bad, then mark the latest changeset which is free from the problem
684 as good. Bisect will update your working directory to a revision
684 as good. Bisect will update your working directory to a revision
685 for testing (unless the -U/--noupdate option is specified). Once
685 for testing (unless the -U/--noupdate option is specified). Once
686 you have performed tests, mark the working directory as good or
686 you have performed tests, mark the working directory as good or
687 bad, and bisect will either update to another candidate changeset
687 bad, and bisect will either update to another candidate changeset
688 or announce that it has found the bad revision.
688 or announce that it has found the bad revision.
689
689
690 As a shortcut, you can also use the revision argument to mark a
690 As a shortcut, you can also use the revision argument to mark a
691 revision as good or bad without checking it out first.
691 revision as good or bad without checking it out first.
692
692
693 If you supply a command, it will be used for automatic bisection.
693 If you supply a command, it will be used for automatic bisection.
694 The environment variable HG_NODE will contain the ID of the
694 The environment variable HG_NODE will contain the ID of the
695 changeset being tested. The exit status of the command will be
695 changeset being tested. The exit status of the command will be
696 used to mark revisions as good or bad: status 0 means good, 125
696 used to mark revisions as good or bad: status 0 means good, 125
697 means to skip the revision, 127 (command not found) will abort the
697 means to skip the revision, 127 (command not found) will abort the
698 bisection, and any other non-zero exit status means the revision
698 bisection, and any other non-zero exit status means the revision
699 is bad.
699 is bad.
700
700
701 .. container:: verbose
701 .. container:: verbose
702
702
703 Some examples:
703 Some examples:
704
704
705 - start a bisection with known bad revision 34, and good revision 12::
705 - start a bisection with known bad revision 34, and good revision 12::
706
706
707 hg bisect --bad 34
707 hg bisect --bad 34
708 hg bisect --good 12
708 hg bisect --good 12
709
709
710 - advance the current bisection by marking current revision as good or
710 - advance the current bisection by marking current revision as good or
711 bad::
711 bad::
712
712
713 hg bisect --good
713 hg bisect --good
714 hg bisect --bad
714 hg bisect --bad
715
715
716 - mark the current revision, or a known revision, to be skipped (e.g. if
716 - mark the current revision, or a known revision, to be skipped (e.g. if
717 that revision is not usable because of another issue)::
717 that revision is not usable because of another issue)::
718
718
719 hg bisect --skip
719 hg bisect --skip
720 hg bisect --skip 23
720 hg bisect --skip 23
721
721
722 - skip all revisions that do not touch directories ``foo`` or ``bar``::
722 - skip all revisions that do not touch directories ``foo`` or ``bar``::
723
723
724 hg bisect --skip "!( file('path:foo') & file('path:bar') )"
724 hg bisect --skip "!( file('path:foo') & file('path:bar') )"
725
725
726 - forget the current bisection::
726 - forget the current bisection::
727
727
728 hg bisect --reset
728 hg bisect --reset
729
729
730 - use 'make && make tests' to automatically find the first broken
730 - use 'make && make tests' to automatically find the first broken
731 revision::
731 revision::
732
732
733 hg bisect --reset
733 hg bisect --reset
734 hg bisect --bad 34
734 hg bisect --bad 34
735 hg bisect --good 12
735 hg bisect --good 12
736 hg bisect --command "make && make tests"
736 hg bisect --command "make && make tests"
737
737
738 - see all changesets whose states are already known in the current
738 - see all changesets whose states are already known in the current
739 bisection::
739 bisection::
740
740
741 hg log -r "bisect(pruned)"
741 hg log -r "bisect(pruned)"
742
742
743 - see the changeset currently being bisected (especially useful
743 - see the changeset currently being bisected (especially useful
744 if running with -U/--noupdate)::
744 if running with -U/--noupdate)::
745
745
746 hg log -r "bisect(current)"
746 hg log -r "bisect(current)"
747
747
748 - see all changesets that took part in the current bisection::
748 - see all changesets that took part in the current bisection::
749
749
750 hg log -r "bisect(range)"
750 hg log -r "bisect(range)"
751
751
752 - you can even get a nice graph::
752 - you can even get a nice graph::
753
753
754 hg log --graph -r "bisect(range)"
754 hg log --graph -r "bisect(range)"
755
755
756 See :hg:`help revisions.bisect` for more about the `bisect()` predicate.
756 See :hg:`help revisions.bisect` for more about the `bisect()` predicate.
757
757
758 Returns 0 on success.
758 Returns 0 on success.
759 """
759 """
760 # backward compatibility
760 # backward compatibility
761 if rev in "good bad reset init".split():
761 if rev in "good bad reset init".split():
762 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
762 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
763 cmd, rev, extra = rev, extra, None
763 cmd, rev, extra = rev, extra, None
764 if cmd == "good":
764 if cmd == "good":
765 good = True
765 good = True
766 elif cmd == "bad":
766 elif cmd == "bad":
767 bad = True
767 bad = True
768 else:
768 else:
769 reset = True
769 reset = True
770 elif extra:
770 elif extra:
771 raise error.Abort(_('incompatible arguments'))
771 raise error.Abort(_('incompatible arguments'))
772
772
773 incompatibles = {
773 incompatibles = {
774 '--bad': bad,
774 '--bad': bad,
775 '--command': bool(command),
775 '--command': bool(command),
776 '--extend': extend,
776 '--extend': extend,
777 '--good': good,
777 '--good': good,
778 '--reset': reset,
778 '--reset': reset,
779 '--skip': skip,
779 '--skip': skip,
780 }
780 }
781
781
782 enabled = [x for x in incompatibles if incompatibles[x]]
782 enabled = [x for x in incompatibles if incompatibles[x]]
783
783
784 if len(enabled) > 1:
784 if len(enabled) > 1:
785 raise error.Abort(_('%s and %s are incompatible') %
785 raise error.Abort(_('%s and %s are incompatible') %
786 tuple(sorted(enabled)[0:2]))
786 tuple(sorted(enabled)[0:2]))
787
787
788 if reset:
788 if reset:
789 hbisect.resetstate(repo)
789 hbisect.resetstate(repo)
790 return
790 return
791
791
792 state = hbisect.load_state(repo)
792 state = hbisect.load_state(repo)
793
793
794 # update state
794 # update state
795 if good or bad or skip:
795 if good or bad or skip:
796 if rev:
796 if rev:
797 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
797 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
798 else:
798 else:
799 nodes = [repo.lookup('.')]
799 nodes = [repo.lookup('.')]
800 if good:
800 if good:
801 state['good'] += nodes
801 state['good'] += nodes
802 elif bad:
802 elif bad:
803 state['bad'] += nodes
803 state['bad'] += nodes
804 elif skip:
804 elif skip:
805 state['skip'] += nodes
805 state['skip'] += nodes
806 hbisect.save_state(repo, state)
806 hbisect.save_state(repo, state)
807 if not (state['good'] and state['bad']):
807 if not (state['good'] and state['bad']):
808 return
808 return
809
809
810 def mayupdate(repo, node, show_stats=True):
810 def mayupdate(repo, node, show_stats=True):
811 """common used update sequence"""
811 """common used update sequence"""
812 if noupdate:
812 if noupdate:
813 return
813 return
814 cmdutil.checkunfinished(repo)
814 cmdutil.checkunfinished(repo)
815 cmdutil.bailifchanged(repo)
815 cmdutil.bailifchanged(repo)
816 return hg.clean(repo, node, show_stats=show_stats)
816 return hg.clean(repo, node, show_stats=show_stats)
817
817
818 displayer = cmdutil.show_changeset(ui, repo, {})
818 displayer = cmdutil.show_changeset(ui, repo, {})
819
819
820 if command:
820 if command:
821 changesets = 1
821 changesets = 1
822 if noupdate:
822 if noupdate:
823 try:
823 try:
824 node = state['current'][0]
824 node = state['current'][0]
825 except LookupError:
825 except LookupError:
826 raise error.Abort(_('current bisect revision is unknown - '
826 raise error.Abort(_('current bisect revision is unknown - '
827 'start a new bisect to fix'))
827 'start a new bisect to fix'))
828 else:
828 else:
829 node, p2 = repo.dirstate.parents()
829 node, p2 = repo.dirstate.parents()
830 if p2 != nullid:
830 if p2 != nullid:
831 raise error.Abort(_('current bisect revision is a merge'))
831 raise error.Abort(_('current bisect revision is a merge'))
832 if rev:
832 if rev:
833 node = repo[scmutil.revsingle(repo, rev, node)].node()
833 node = repo[scmutil.revsingle(repo, rev, node)].node()
834 try:
834 try:
835 while changesets:
835 while changesets:
836 # update state
836 # update state
837 state['current'] = [node]
837 state['current'] = [node]
838 hbisect.save_state(repo, state)
838 hbisect.save_state(repo, state)
839 status = ui.system(command, environ={'HG_NODE': hex(node)},
839 status = ui.system(command, environ={'HG_NODE': hex(node)},
840 blockedtag='bisect_check')
840 blockedtag='bisect_check')
841 if status == 125:
841 if status == 125:
842 transition = "skip"
842 transition = "skip"
843 elif status == 0:
843 elif status == 0:
844 transition = "good"
844 transition = "good"
845 # status < 0 means process was killed
845 # status < 0 means process was killed
846 elif status == 127:
846 elif status == 127:
847 raise error.Abort(_("failed to execute %s") % command)
847 raise error.Abort(_("failed to execute %s") % command)
848 elif status < 0:
848 elif status < 0:
849 raise error.Abort(_("%s killed") % command)
849 raise error.Abort(_("%s killed") % command)
850 else:
850 else:
851 transition = "bad"
851 transition = "bad"
852 state[transition].append(node)
852 state[transition].append(node)
853 ctx = repo[node]
853 ctx = repo[node]
854 ui.status(_('changeset %d:%s: %s\n') % (ctx, ctx, transition))
854 ui.status(_('changeset %d:%s: %s\n') % (ctx, ctx, transition))
855 hbisect.checkstate(state)
855 hbisect.checkstate(state)
856 # bisect
856 # bisect
857 nodes, changesets, bgood = hbisect.bisect(repo, state)
857 nodes, changesets, bgood = hbisect.bisect(repo, state)
858 # update to next check
858 # update to next check
859 node = nodes[0]
859 node = nodes[0]
860 mayupdate(repo, node, show_stats=False)
860 mayupdate(repo, node, show_stats=False)
861 finally:
861 finally:
862 state['current'] = [node]
862 state['current'] = [node]
863 hbisect.save_state(repo, state)
863 hbisect.save_state(repo, state)
864 hbisect.printresult(ui, repo, state, displayer, nodes, bgood)
864 hbisect.printresult(ui, repo, state, displayer, nodes, bgood)
865 return
865 return
866
866
867 hbisect.checkstate(state)
867 hbisect.checkstate(state)
868
868
869 # actually bisect
869 # actually bisect
870 nodes, changesets, good = hbisect.bisect(repo, state)
870 nodes, changesets, good = hbisect.bisect(repo, state)
871 if extend:
871 if extend:
872 if not changesets:
872 if not changesets:
873 extendnode = hbisect.extendrange(repo, state, nodes, good)
873 extendnode = hbisect.extendrange(repo, state, nodes, good)
874 if extendnode is not None:
874 if extendnode is not None:
875 ui.write(_("Extending search to changeset %d:%s\n")
875 ui.write(_("Extending search to changeset %d:%s\n")
876 % (extendnode.rev(), extendnode))
876 % (extendnode.rev(), extendnode))
877 state['current'] = [extendnode.node()]
877 state['current'] = [extendnode.node()]
878 hbisect.save_state(repo, state)
878 hbisect.save_state(repo, state)
879 return mayupdate(repo, extendnode.node())
879 return mayupdate(repo, extendnode.node())
880 raise error.Abort(_("nothing to extend"))
880 raise error.Abort(_("nothing to extend"))
881
881
882 if changesets == 0:
882 if changesets == 0:
883 hbisect.printresult(ui, repo, state, displayer, nodes, good)
883 hbisect.printresult(ui, repo, state, displayer, nodes, good)
884 else:
884 else:
885 assert len(nodes) == 1 # only a single node can be tested next
885 assert len(nodes) == 1 # only a single node can be tested next
886 node = nodes[0]
886 node = nodes[0]
887 # compute the approximate number of remaining tests
887 # compute the approximate number of remaining tests
888 tests, size = 0, 2
888 tests, size = 0, 2
889 while size <= changesets:
889 while size <= changesets:
890 tests, size = tests + 1, size * 2
890 tests, size = tests + 1, size * 2
891 rev = repo.changelog.rev(node)
891 rev = repo.changelog.rev(node)
892 ui.write(_("Testing changeset %d:%s "
892 ui.write(_("Testing changeset %d:%s "
893 "(%d changesets remaining, ~%d tests)\n")
893 "(%d changesets remaining, ~%d tests)\n")
894 % (rev, short(node), changesets, tests))
894 % (rev, short(node), changesets, tests))
895 state['current'] = [node]
895 state['current'] = [node]
896 hbisect.save_state(repo, state)
896 hbisect.save_state(repo, state)
897 return mayupdate(repo, node)
897 return mayupdate(repo, node)
898
898
899 @command('bookmarks|bookmark',
899 @command('bookmarks|bookmark',
900 [('f', 'force', False, _('force')),
900 [('f', 'force', False, _('force')),
901 ('r', 'rev', '', _('revision for bookmark action'), _('REV')),
901 ('r', 'rev', '', _('revision for bookmark action'), _('REV')),
902 ('d', 'delete', False, _('delete a given bookmark')),
902 ('d', 'delete', False, _('delete a given bookmark')),
903 ('m', 'rename', '', _('rename a given bookmark'), _('OLD')),
903 ('m', 'rename', '', _('rename a given bookmark'), _('OLD')),
904 ('i', 'inactive', False, _('mark a bookmark inactive')),
904 ('i', 'inactive', False, _('mark a bookmark inactive')),
905 ] + formatteropts,
905 ] + formatteropts,
906 _('hg bookmarks [OPTIONS]... [NAME]...'))
906 _('hg bookmarks [OPTIONS]... [NAME]...'))
907 def bookmark(ui, repo, *names, **opts):
907 def bookmark(ui, repo, *names, **opts):
908 '''create a new bookmark or list existing bookmarks
908 '''create a new bookmark or list existing bookmarks
909
909
910 Bookmarks are labels on changesets to help track lines of development.
910 Bookmarks are labels on changesets to help track lines of development.
911 Bookmarks are unversioned and can be moved, renamed and deleted.
911 Bookmarks are unversioned and can be moved, renamed and deleted.
912 Deleting or moving a bookmark has no effect on the associated changesets.
912 Deleting or moving a bookmark has no effect on the associated changesets.
913
913
914 Creating or updating to a bookmark causes it to be marked as 'active'.
914 Creating or updating to a bookmark causes it to be marked as 'active'.
915 The active bookmark is indicated with a '*'.
915 The active bookmark is indicated with a '*'.
916 When a commit is made, the active bookmark will advance to the new commit.
916 When a commit is made, the active bookmark will advance to the new commit.
917 A plain :hg:`update` will also advance an active bookmark, if possible.
917 A plain :hg:`update` will also advance an active bookmark, if possible.
918 Updating away from a bookmark will cause it to be deactivated.
918 Updating away from a bookmark will cause it to be deactivated.
919
919
920 Bookmarks can be pushed and pulled between repositories (see
920 Bookmarks can be pushed and pulled between repositories (see
921 :hg:`help push` and :hg:`help pull`). If a shared bookmark has
921 :hg:`help push` and :hg:`help pull`). If a shared bookmark has
922 diverged, a new 'divergent bookmark' of the form 'name@path' will
922 diverged, a new 'divergent bookmark' of the form 'name@path' will
923 be created. Using :hg:`merge` will resolve the divergence.
923 be created. Using :hg:`merge` will resolve the divergence.
924
924
925 Specifying bookmark as '.' to -m or -d options is equivalent to specifying
925 Specifying bookmark as '.' to -m or -d options is equivalent to specifying
926 the active bookmark's name.
926 the active bookmark's name.
927
927
928 A bookmark named '@' has the special property that :hg:`clone` will
928 A bookmark named '@' has the special property that :hg:`clone` will
929 check it out by default if it exists.
929 check it out by default if it exists.
930
930
931 .. container:: verbose
931 .. container:: verbose
932
932
933 Examples:
933 Examples:
934
934
935 - create an active bookmark for a new line of development::
935 - create an active bookmark for a new line of development::
936
936
937 hg book new-feature
937 hg book new-feature
938
938
939 - create an inactive bookmark as a place marker::
939 - create an inactive bookmark as a place marker::
940
940
941 hg book -i reviewed
941 hg book -i reviewed
942
942
943 - create an inactive bookmark on another changeset::
943 - create an inactive bookmark on another changeset::
944
944
945 hg book -r .^ tested
945 hg book -r .^ tested
946
946
947 - rename bookmark turkey to dinner::
947 - rename bookmark turkey to dinner::
948
948
949 hg book -m turkey dinner
949 hg book -m turkey dinner
950
950
951 - move the '@' bookmark from another branch::
951 - move the '@' bookmark from another branch::
952
952
953 hg book -f @
953 hg book -f @
954 '''
954 '''
955 force = opts.get(r'force')
955 force = opts.get(r'force')
956 rev = opts.get(r'rev')
956 rev = opts.get(r'rev')
957 delete = opts.get(r'delete')
957 delete = opts.get(r'delete')
958 rename = opts.get(r'rename')
958 rename = opts.get(r'rename')
959 inactive = opts.get(r'inactive')
959 inactive = opts.get(r'inactive')
960
960
961 if delete and rename:
961 if delete and rename:
962 raise error.Abort(_("--delete and --rename are incompatible"))
962 raise error.Abort(_("--delete and --rename are incompatible"))
963 if delete and rev:
963 if delete and rev:
964 raise error.Abort(_("--rev is incompatible with --delete"))
964 raise error.Abort(_("--rev is incompatible with --delete"))
965 if rename and rev:
965 if rename and rev:
966 raise error.Abort(_("--rev is incompatible with --rename"))
966 raise error.Abort(_("--rev is incompatible with --rename"))
967 if not names and (delete or rev):
967 if not names and (delete or rev):
968 raise error.Abort(_("bookmark name required"))
968 raise error.Abort(_("bookmark name required"))
969
969
970 if delete or rename or names or inactive:
970 if delete or rename or names or inactive:
971 with repo.wlock(), repo.lock(), repo.transaction('bookmark') as tr:
971 with repo.wlock(), repo.lock(), repo.transaction('bookmark') as tr:
972 if delete:
972 if delete:
973 names = pycompat.maplist(repo._bookmarks.expandname, names)
973 names = pycompat.maplist(repo._bookmarks.expandname, names)
974 bookmarks.delete(repo, tr, names)
974 bookmarks.delete(repo, tr, names)
975 elif rename:
975 elif rename:
976 if not names:
976 if not names:
977 raise error.Abort(_("new bookmark name required"))
977 raise error.Abort(_("new bookmark name required"))
978 elif len(names) > 1:
978 elif len(names) > 1:
979 raise error.Abort(_("only one new bookmark name allowed"))
979 raise error.Abort(_("only one new bookmark name allowed"))
980 rename = repo._bookmarks.expandname(rename)
980 rename = repo._bookmarks.expandname(rename)
981 bookmarks.rename(repo, tr, rename, names[0], force, inactive)
981 bookmarks.rename(repo, tr, rename, names[0], force, inactive)
982 elif names:
982 elif names:
983 bookmarks.addbookmarks(repo, tr, names, rev, force, inactive)
983 bookmarks.addbookmarks(repo, tr, names, rev, force, inactive)
984 elif inactive:
984 elif inactive:
985 if len(repo._bookmarks) == 0:
985 if len(repo._bookmarks) == 0:
986 ui.status(_("no bookmarks set\n"))
986 ui.status(_("no bookmarks set\n"))
987 elif not repo._activebookmark:
987 elif not repo._activebookmark:
988 ui.status(_("no active bookmark\n"))
988 ui.status(_("no active bookmark\n"))
989 else:
989 else:
990 bookmarks.deactivate(repo)
990 bookmarks.deactivate(repo)
991 else: # show bookmarks
991 else: # show bookmarks
992 bookmarks.printbookmarks(ui, repo, **opts)
992 bookmarks.printbookmarks(ui, repo, **opts)
993
993
994 @command('branch',
994 @command('branch',
995 [('f', 'force', None,
995 [('f', 'force', None,
996 _('set branch name even if it shadows an existing branch')),
996 _('set branch name even if it shadows an existing branch')),
997 ('C', 'clean', None, _('reset branch name to parent branch name'))],
997 ('C', 'clean', None, _('reset branch name to parent branch name'))],
998 _('[-fC] [NAME]'))
998 _('[-fC] [NAME]'))
999 def branch(ui, repo, label=None, **opts):
999 def branch(ui, repo, label=None, **opts):
1000 """set or show the current branch name
1000 """set or show the current branch name
1001
1001
1002 .. note::
1002 .. note::
1003
1003
1004 Branch names are permanent and global. Use :hg:`bookmark` to create a
1004 Branch names are permanent and global. Use :hg:`bookmark` to create a
1005 light-weight bookmark instead. See :hg:`help glossary` for more
1005 light-weight bookmark instead. See :hg:`help glossary` for more
1006 information about named branches and bookmarks.
1006 information about named branches and bookmarks.
1007
1007
1008 With no argument, show the current branch name. With one argument,
1008 With no argument, show the current branch name. With one argument,
1009 set the working directory branch name (the branch will not exist
1009 set the working directory branch name (the branch will not exist
1010 in the repository until the next commit). Standard practice
1010 in the repository until the next commit). Standard practice
1011 recommends that primary development take place on the 'default'
1011 recommends that primary development take place on the 'default'
1012 branch.
1012 branch.
1013
1013
1014 Unless -f/--force is specified, branch will not let you set a
1014 Unless -f/--force is specified, branch will not let you set a
1015 branch name that already exists.
1015 branch name that already exists.
1016
1016
1017 Use -C/--clean to reset the working directory branch to that of
1017 Use -C/--clean to reset the working directory branch to that of
1018 the parent of the working directory, negating a previous branch
1018 the parent of the working directory, negating a previous branch
1019 change.
1019 change.
1020
1020
1021 Use the command :hg:`update` to switch to an existing branch. Use
1021 Use the command :hg:`update` to switch to an existing branch. Use
1022 :hg:`commit --close-branch` to mark this branch head as closed.
1022 :hg:`commit --close-branch` to mark this branch head as closed.
1023 When all heads of a branch are closed, the branch will be
1023 When all heads of a branch are closed, the branch will be
1024 considered closed.
1024 considered closed.
1025
1025
1026 Returns 0 on success.
1026 Returns 0 on success.
1027 """
1027 """
1028 opts = pycompat.byteskwargs(opts)
1028 opts = pycompat.byteskwargs(opts)
1029 if label:
1029 if label:
1030 label = label.strip()
1030 label = label.strip()
1031
1031
1032 if not opts.get('clean') and not label:
1032 if not opts.get('clean') and not label:
1033 ui.write("%s\n" % repo.dirstate.branch())
1033 ui.write("%s\n" % repo.dirstate.branch())
1034 return
1034 return
1035
1035
1036 with repo.wlock():
1036 with repo.wlock():
1037 if opts.get('clean'):
1037 if opts.get('clean'):
1038 label = repo[None].p1().branch()
1038 label = repo[None].p1().branch()
1039 repo.dirstate.setbranch(label)
1039 repo.dirstate.setbranch(label)
1040 ui.status(_('reset working directory to branch %s\n') % label)
1040 ui.status(_('reset working directory to branch %s\n') % label)
1041 elif label:
1041 elif label:
1042 if not opts.get('force') and label in repo.branchmap():
1042 if not opts.get('force') and label in repo.branchmap():
1043 if label not in [p.branch() for p in repo[None].parents()]:
1043 if label not in [p.branch() for p in repo[None].parents()]:
1044 raise error.Abort(_('a branch of the same name already'
1044 raise error.Abort(_('a branch of the same name already'
1045 ' exists'),
1045 ' exists'),
1046 # i18n: "it" refers to an existing branch
1046 # i18n: "it" refers to an existing branch
1047 hint=_("use 'hg update' to switch to it"))
1047 hint=_("use 'hg update' to switch to it"))
1048 scmutil.checknewlabel(repo, label, 'branch')
1048 scmutil.checknewlabel(repo, label, 'branch')
1049 repo.dirstate.setbranch(label)
1049 repo.dirstate.setbranch(label)
1050 ui.status(_('marked working directory as branch %s\n') % label)
1050 ui.status(_('marked working directory as branch %s\n') % label)
1051
1051
1052 # find any open named branches aside from default
1052 # find any open named branches aside from default
1053 others = [n for n, h, t, c in repo.branchmap().iterbranches()
1053 others = [n for n, h, t, c in repo.branchmap().iterbranches()
1054 if n != "default" and not c]
1054 if n != "default" and not c]
1055 if not others:
1055 if not others:
1056 ui.status(_('(branches are permanent and global, '
1056 ui.status(_('(branches are permanent and global, '
1057 'did you want a bookmark?)\n'))
1057 'did you want a bookmark?)\n'))
1058
1058
1059 @command('branches',
1059 @command('branches',
1060 [('a', 'active', False,
1060 [('a', 'active', False,
1061 _('show only branches that have unmerged heads (DEPRECATED)')),
1061 _('show only branches that have unmerged heads (DEPRECATED)')),
1062 ('c', 'closed', False, _('show normal and closed branches')),
1062 ('c', 'closed', False, _('show normal and closed branches')),
1063 ] + formatteropts,
1063 ] + formatteropts,
1064 _('[-c]'), cmdtype=readonly)
1064 _('[-c]'), cmdtype=readonly)
1065 def branches(ui, repo, active=False, closed=False, **opts):
1065 def branches(ui, repo, active=False, closed=False, **opts):
1066 """list repository named branches
1066 """list repository named branches
1067
1067
1068 List the repository's named branches, indicating which ones are
1068 List the repository's named branches, indicating which ones are
1069 inactive. If -c/--closed is specified, also list branches which have
1069 inactive. If -c/--closed is specified, also list branches which have
1070 been marked closed (see :hg:`commit --close-branch`).
1070 been marked closed (see :hg:`commit --close-branch`).
1071
1071
1072 Use the command :hg:`update` to switch to an existing branch.
1072 Use the command :hg:`update` to switch to an existing branch.
1073
1073
1074 Returns 0.
1074 Returns 0.
1075 """
1075 """
1076
1076
1077 opts = pycompat.byteskwargs(opts)
1077 opts = pycompat.byteskwargs(opts)
1078 ui.pager('branches')
1078 ui.pager('branches')
1079 fm = ui.formatter('branches', opts)
1079 fm = ui.formatter('branches', opts)
1080 hexfunc = fm.hexfunc
1080 hexfunc = fm.hexfunc
1081
1081
1082 allheads = set(repo.heads())
1082 allheads = set(repo.heads())
1083 branches = []
1083 branches = []
1084 for tag, heads, tip, isclosed in repo.branchmap().iterbranches():
1084 for tag, heads, tip, isclosed in repo.branchmap().iterbranches():
1085 isactive = False
1085 isactive = False
1086 if not isclosed:
1086 if not isclosed:
1087 openheads = set(repo.branchmap().iteropen(heads))
1087 openheads = set(repo.branchmap().iteropen(heads))
1088 isactive = bool(openheads & allheads)
1088 isactive = bool(openheads & allheads)
1089 branches.append((tag, repo[tip], isactive, not isclosed))
1089 branches.append((tag, repo[tip], isactive, not isclosed))
1090 branches.sort(key=lambda i: (i[2], i[1].rev(), i[0], i[3]),
1090 branches.sort(key=lambda i: (i[2], i[1].rev(), i[0], i[3]),
1091 reverse=True)
1091 reverse=True)
1092
1092
1093 for tag, ctx, isactive, isopen in branches:
1093 for tag, ctx, isactive, isopen in branches:
1094 if active and not isactive:
1094 if active and not isactive:
1095 continue
1095 continue
1096 if isactive:
1096 if isactive:
1097 label = 'branches.active'
1097 label = 'branches.active'
1098 notice = ''
1098 notice = ''
1099 elif not isopen:
1099 elif not isopen:
1100 if not closed:
1100 if not closed:
1101 continue
1101 continue
1102 label = 'branches.closed'
1102 label = 'branches.closed'
1103 notice = _(' (closed)')
1103 notice = _(' (closed)')
1104 else:
1104 else:
1105 label = 'branches.inactive'
1105 label = 'branches.inactive'
1106 notice = _(' (inactive)')
1106 notice = _(' (inactive)')
1107 current = (tag == repo.dirstate.branch())
1107 current = (tag == repo.dirstate.branch())
1108 if current:
1108 if current:
1109 label = 'branches.current'
1109 label = 'branches.current'
1110
1110
1111 fm.startitem()
1111 fm.startitem()
1112 fm.write('branch', '%s', tag, label=label)
1112 fm.write('branch', '%s', tag, label=label)
1113 rev = ctx.rev()
1113 rev = ctx.rev()
1114 padsize = max(31 - len(str(rev)) - encoding.colwidth(tag), 0)
1114 padsize = max(31 - len(str(rev)) - encoding.colwidth(tag), 0)
1115 fmt = ' ' * padsize + ' %d:%s'
1115 fmt = ' ' * padsize + ' %d:%s'
1116 fm.condwrite(not ui.quiet, 'rev node', fmt, rev, hexfunc(ctx.node()),
1116 fm.condwrite(not ui.quiet, 'rev node', fmt, rev, hexfunc(ctx.node()),
1117 label='log.changeset changeset.%s' % ctx.phasestr())
1117 label='log.changeset changeset.%s' % ctx.phasestr())
1118 fm.context(ctx=ctx)
1118 fm.context(ctx=ctx)
1119 fm.data(active=isactive, closed=not isopen, current=current)
1119 fm.data(active=isactive, closed=not isopen, current=current)
1120 if not ui.quiet:
1120 if not ui.quiet:
1121 fm.plain(notice)
1121 fm.plain(notice)
1122 fm.plain('\n')
1122 fm.plain('\n')
1123 fm.end()
1123 fm.end()
1124
1124
1125 @command('bundle',
1125 @command('bundle',
1126 [('f', 'force', None, _('run even when the destination is unrelated')),
1126 [('f', 'force', None, _('run even when the destination is unrelated')),
1127 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
1127 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
1128 _('REV')),
1128 _('REV')),
1129 ('b', 'branch', [], _('a specific branch you would like to bundle'),
1129 ('b', 'branch', [], _('a specific branch you would like to bundle'),
1130 _('BRANCH')),
1130 _('BRANCH')),
1131 ('', 'base', [],
1131 ('', 'base', [],
1132 _('a base changeset assumed to be available at the destination'),
1132 _('a base changeset assumed to be available at the destination'),
1133 _('REV')),
1133 _('REV')),
1134 ('a', 'all', None, _('bundle all changesets in the repository')),
1134 ('a', 'all', None, _('bundle all changesets in the repository')),
1135 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
1135 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
1136 ] + remoteopts,
1136 ] + remoteopts,
1137 _('[-f] [-t BUNDLESPEC] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
1137 _('[-f] [-t BUNDLESPEC] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
1138 def bundle(ui, repo, fname, dest=None, **opts):
1138 def bundle(ui, repo, fname, dest=None, **opts):
1139 """create a bundle file
1139 """create a bundle file
1140
1140
1141 Generate a bundle file containing data to be added to a repository.
1141 Generate a bundle file containing data to be added to a repository.
1142
1142
1143 To create a bundle containing all changesets, use -a/--all
1143 To create a bundle containing all changesets, use -a/--all
1144 (or --base null). Otherwise, hg assumes the destination will have
1144 (or --base null). Otherwise, hg assumes the destination will have
1145 all the nodes you specify with --base parameters. Otherwise, hg
1145 all the nodes you specify with --base parameters. Otherwise, hg
1146 will assume the repository has all the nodes in destination, or
1146 will assume the repository has all the nodes in destination, or
1147 default-push/default if no destination is specified.
1147 default-push/default if no destination is specified.
1148
1148
1149 You can change bundle format with the -t/--type option. See
1149 You can change bundle format with the -t/--type option. See
1150 :hg:`help bundlespec` for documentation on this format. By default,
1150 :hg:`help bundlespec` for documentation on this format. By default,
1151 the most appropriate format is used and compression defaults to
1151 the most appropriate format is used and compression defaults to
1152 bzip2.
1152 bzip2.
1153
1153
1154 The bundle file can then be transferred using conventional means
1154 The bundle file can then be transferred using conventional means
1155 and applied to another repository with the unbundle or pull
1155 and applied to another repository with the unbundle or pull
1156 command. This is useful when direct push and pull are not
1156 command. This is useful when direct push and pull are not
1157 available or when exporting an entire repository is undesirable.
1157 available or when exporting an entire repository is undesirable.
1158
1158
1159 Applying bundles preserves all changeset contents including
1159 Applying bundles preserves all changeset contents including
1160 permissions, copy/rename information, and revision history.
1160 permissions, copy/rename information, and revision history.
1161
1161
1162 Returns 0 on success, 1 if no changes found.
1162 Returns 0 on success, 1 if no changes found.
1163 """
1163 """
1164 opts = pycompat.byteskwargs(opts)
1164 opts = pycompat.byteskwargs(opts)
1165 revs = None
1165 revs = None
1166 if 'rev' in opts:
1166 if 'rev' in opts:
1167 revstrings = opts['rev']
1167 revstrings = opts['rev']
1168 revs = scmutil.revrange(repo, revstrings)
1168 revs = scmutil.revrange(repo, revstrings)
1169 if revstrings and not revs:
1169 if revstrings and not revs:
1170 raise error.Abort(_('no commits to bundle'))
1170 raise error.Abort(_('no commits to bundle'))
1171
1171
1172 bundletype = opts.get('type', 'bzip2').lower()
1172 bundletype = opts.get('type', 'bzip2').lower()
1173 try:
1173 try:
1174 bcompression, cgversion, params = exchange.parsebundlespec(
1174 bcompression, cgversion, params = exchange.parsebundlespec(
1175 repo, bundletype, strict=False)
1175 repo, bundletype, strict=False)
1176 except error.UnsupportedBundleSpecification as e:
1176 except error.UnsupportedBundleSpecification as e:
1177 raise error.Abort(str(e),
1177 raise error.Abort(str(e),
1178 hint=_("see 'hg help bundlespec' for supported "
1178 hint=_("see 'hg help bundlespec' for supported "
1179 "values for --type"))
1179 "values for --type"))
1180
1180
1181 # Packed bundles are a pseudo bundle format for now.
1181 # Packed bundles are a pseudo bundle format for now.
1182 if cgversion == 's1':
1182 if cgversion == 's1':
1183 raise error.Abort(_('packed bundles cannot be produced by "hg bundle"'),
1183 raise error.Abort(_('packed bundles cannot be produced by "hg bundle"'),
1184 hint=_("use 'hg debugcreatestreamclonebundle'"))
1184 hint=_("use 'hg debugcreatestreamclonebundle'"))
1185
1185
1186 if opts.get('all'):
1186 if opts.get('all'):
1187 if dest:
1187 if dest:
1188 raise error.Abort(_("--all is incompatible with specifying "
1188 raise error.Abort(_("--all is incompatible with specifying "
1189 "a destination"))
1189 "a destination"))
1190 if opts.get('base'):
1190 if opts.get('base'):
1191 ui.warn(_("ignoring --base because --all was specified\n"))
1191 ui.warn(_("ignoring --base because --all was specified\n"))
1192 base = ['null']
1192 base = ['null']
1193 else:
1193 else:
1194 base = scmutil.revrange(repo, opts.get('base'))
1194 base = scmutil.revrange(repo, opts.get('base'))
1195 if cgversion not in changegroup.supportedoutgoingversions(repo):
1195 if cgversion not in changegroup.supportedoutgoingversions(repo):
1196 raise error.Abort(_("repository does not support bundle version %s") %
1196 raise error.Abort(_("repository does not support bundle version %s") %
1197 cgversion)
1197 cgversion)
1198
1198
1199 if base:
1199 if base:
1200 if dest:
1200 if dest:
1201 raise error.Abort(_("--base is incompatible with specifying "
1201 raise error.Abort(_("--base is incompatible with specifying "
1202 "a destination"))
1202 "a destination"))
1203 common = [repo.lookup(rev) for rev in base]
1203 common = [repo.lookup(rev) for rev in base]
1204 heads = revs and map(repo.lookup, revs) or None
1204 heads = revs and map(repo.lookup, revs) or None
1205 outgoing = discovery.outgoing(repo, common, heads)
1205 outgoing = discovery.outgoing(repo, common, heads)
1206 else:
1206 else:
1207 dest = ui.expandpath(dest or 'default-push', dest or 'default')
1207 dest = ui.expandpath(dest or 'default-push', dest or 'default')
1208 dest, branches = hg.parseurl(dest, opts.get('branch'))
1208 dest, branches = hg.parseurl(dest, opts.get('branch'))
1209 other = hg.peer(repo, opts, dest)
1209 other = hg.peer(repo, opts, dest)
1210 revs, checkout = hg.addbranchrevs(repo, repo, branches, revs)
1210 revs, checkout = hg.addbranchrevs(repo, repo, branches, revs)
1211 heads = revs and map(repo.lookup, revs) or revs
1211 heads = revs and map(repo.lookup, revs) or revs
1212 outgoing = discovery.findcommonoutgoing(repo, other,
1212 outgoing = discovery.findcommonoutgoing(repo, other,
1213 onlyheads=heads,
1213 onlyheads=heads,
1214 force=opts.get('force'),
1214 force=opts.get('force'),
1215 portable=True)
1215 portable=True)
1216
1216
1217 if not outgoing.missing:
1217 if not outgoing.missing:
1218 scmutil.nochangesfound(ui, repo, not base and outgoing.excluded)
1218 scmutil.nochangesfound(ui, repo, not base and outgoing.excluded)
1219 return 1
1219 return 1
1220
1220
1221 if cgversion == '01': #bundle1
1221 if cgversion == '01': #bundle1
1222 if bcompression is None:
1222 if bcompression is None:
1223 bcompression = 'UN'
1223 bcompression = 'UN'
1224 bversion = 'HG10' + bcompression
1224 bversion = 'HG10' + bcompression
1225 bcompression = None
1225 bcompression = None
1226 elif cgversion in ('02', '03'):
1226 elif cgversion in ('02', '03'):
1227 bversion = 'HG20'
1227 bversion = 'HG20'
1228 else:
1228 else:
1229 raise error.ProgrammingError(
1229 raise error.ProgrammingError(
1230 'bundle: unexpected changegroup version %s' % cgversion)
1230 'bundle: unexpected changegroup version %s' % cgversion)
1231
1231
1232 # TODO compression options should be derived from bundlespec parsing.
1232 # TODO compression options should be derived from bundlespec parsing.
1233 # This is a temporary hack to allow adjusting bundle compression
1233 # This is a temporary hack to allow adjusting bundle compression
1234 # level without a) formalizing the bundlespec changes to declare it
1234 # level without a) formalizing the bundlespec changes to declare it
1235 # b) introducing a command flag.
1235 # b) introducing a command flag.
1236 compopts = {}
1236 compopts = {}
1237 complevel = ui.configint('experimental', 'bundlecomplevel')
1237 complevel = ui.configint('experimental', 'bundlecomplevel')
1238 if complevel is not None:
1238 if complevel is not None:
1239 compopts['level'] = complevel
1239 compopts['level'] = complevel
1240
1240
1241
1241
1242 contentopts = {'cg.version': cgversion}
1242 contentopts = {'cg.version': cgversion}
1243 if repo.ui.configbool('experimental', 'evolution.bundle-obsmarker'):
1243 if repo.ui.configbool('experimental', 'evolution.bundle-obsmarker'):
1244 contentopts['obsolescence'] = True
1244 contentopts['obsolescence'] = True
1245 if repo.ui.configbool('experimental', 'bundle-phases'):
1245 if repo.ui.configbool('experimental', 'bundle-phases'):
1246 contentopts['phases'] = True
1246 contentopts['phases'] = True
1247 bundle2.writenewbundle(ui, repo, 'bundle', fname, bversion, outgoing,
1247 bundle2.writenewbundle(ui, repo, 'bundle', fname, bversion, outgoing,
1248 contentopts, compression=bcompression,
1248 contentopts, compression=bcompression,
1249 compopts=compopts)
1249 compopts=compopts)
1250
1250
1251 @command('cat',
1251 @command('cat',
1252 [('o', 'output', '',
1252 [('o', 'output', '',
1253 _('print output to file with formatted name'), _('FORMAT')),
1253 _('print output to file with formatted name'), _('FORMAT')),
1254 ('r', 'rev', '', _('print the given revision'), _('REV')),
1254 ('r', 'rev', '', _('print the given revision'), _('REV')),
1255 ('', 'decode', None, _('apply any matching decode filter')),
1255 ('', 'decode', None, _('apply any matching decode filter')),
1256 ] + walkopts + formatteropts,
1256 ] + walkopts + formatteropts,
1257 _('[OPTION]... FILE...'),
1257 _('[OPTION]... FILE...'),
1258 inferrepo=True, cmdtype=readonly)
1258 inferrepo=True, cmdtype=readonly)
1259 def cat(ui, repo, file1, *pats, **opts):
1259 def cat(ui, repo, file1, *pats, **opts):
1260 """output the current or given revision of files
1260 """output the current or given revision of files
1261
1261
1262 Print the specified files as they were at the given revision. If
1262 Print the specified files as they were at the given revision. If
1263 no revision is given, the parent of the working directory is used.
1263 no revision is given, the parent of the working directory is used.
1264
1264
1265 Output may be to a file, in which case the name of the file is
1265 Output may be to a file, in which case the name of the file is
1266 given using a format string. The formatting rules as follows:
1266 given using a format string. The formatting rules as follows:
1267
1267
1268 :``%%``: literal "%" character
1268 :``%%``: literal "%" character
1269 :``%s``: basename of file being printed
1269 :``%s``: basename of file being printed
1270 :``%d``: dirname of file being printed, or '.' if in repository root
1270 :``%d``: dirname of file being printed, or '.' if in repository root
1271 :``%p``: root-relative path name of file being printed
1271 :``%p``: root-relative path name of file being printed
1272 :``%H``: changeset hash (40 hexadecimal digits)
1272 :``%H``: changeset hash (40 hexadecimal digits)
1273 :``%R``: changeset revision number
1273 :``%R``: changeset revision number
1274 :``%h``: short-form changeset hash (12 hexadecimal digits)
1274 :``%h``: short-form changeset hash (12 hexadecimal digits)
1275 :``%r``: zero-padded changeset revision number
1275 :``%r``: zero-padded changeset revision number
1276 :``%b``: basename of the exporting repository
1276 :``%b``: basename of the exporting repository
1277
1277
1278 Returns 0 on success.
1278 Returns 0 on success.
1279 """
1279 """
1280 ctx = scmutil.revsingle(repo, opts.get('rev'))
1280 ctx = scmutil.revsingle(repo, opts.get('rev'))
1281 m = scmutil.match(ctx, (file1,) + pats, opts)
1281 m = scmutil.match(ctx, (file1,) + pats, opts)
1282 fntemplate = opts.pop('output', '')
1282 fntemplate = opts.pop('output', '')
1283 if cmdutil.isstdiofilename(fntemplate):
1283 if cmdutil.isstdiofilename(fntemplate):
1284 fntemplate = ''
1284 fntemplate = ''
1285
1285
1286 if fntemplate:
1286 if fntemplate:
1287 fm = formatter.nullformatter(ui, 'cat')
1287 fm = formatter.nullformatter(ui, 'cat')
1288 else:
1288 else:
1289 ui.pager('cat')
1289 ui.pager('cat')
1290 fm = ui.formatter('cat', opts)
1290 fm = ui.formatter('cat', opts)
1291 with fm:
1291 with fm:
1292 return cmdutil.cat(ui, repo, ctx, m, fm, fntemplate, '', **opts)
1292 return cmdutil.cat(ui, repo, ctx, m, fm, fntemplate, '', **opts)
1293
1293
1294 @command('^clone',
1294 @command('^clone',
1295 [('U', 'noupdate', None, _('the clone will include an empty working '
1295 [('U', 'noupdate', None, _('the clone will include an empty working '
1296 'directory (only a repository)')),
1296 'directory (only a repository)')),
1297 ('u', 'updaterev', '', _('revision, tag, or branch to check out'),
1297 ('u', 'updaterev', '', _('revision, tag, or branch to check out'),
1298 _('REV')),
1298 _('REV')),
1299 ('r', 'rev', [], _('include the specified changeset'), _('REV')),
1299 ('r', 'rev', [], _('include the specified changeset'), _('REV')),
1300 ('b', 'branch', [], _('clone only the specified branch'), _('BRANCH')),
1300 ('b', 'branch', [], _('clone only the specified branch'), _('BRANCH')),
1301 ('', 'pull', None, _('use pull protocol to copy metadata')),
1301 ('', 'pull', None, _('use pull protocol to copy metadata')),
1302 ('', 'uncompressed', None,
1302 ('', 'uncompressed', None,
1303 _('an alias to --stream (DEPRECATED)')),
1303 _('an alias to --stream (DEPRECATED)')),
1304 ('', 'stream', None,
1304 ('', 'stream', None,
1305 _('clone with minimal data processing')),
1305 _('clone with minimal data processing')),
1306 ] + remoteopts,
1306 ] + remoteopts,
1307 _('[OPTION]... SOURCE [DEST]'),
1307 _('[OPTION]... SOURCE [DEST]'),
1308 norepo=True)
1308 norepo=True)
1309 def clone(ui, source, dest=None, **opts):
1309 def clone(ui, source, dest=None, **opts):
1310 """make a copy of an existing repository
1310 """make a copy of an existing repository
1311
1311
1312 Create a copy of an existing repository in a new directory.
1312 Create a copy of an existing repository in a new directory.
1313
1313
1314 If no destination directory name is specified, it defaults to the
1314 If no destination directory name is specified, it defaults to the
1315 basename of the source.
1315 basename of the source.
1316
1316
1317 The location of the source is added to the new repository's
1317 The location of the source is added to the new repository's
1318 ``.hg/hgrc`` file, as the default to be used for future pulls.
1318 ``.hg/hgrc`` file, as the default to be used for future pulls.
1319
1319
1320 Only local paths and ``ssh://`` URLs are supported as
1320 Only local paths and ``ssh://`` URLs are supported as
1321 destinations. For ``ssh://`` destinations, no working directory or
1321 destinations. For ``ssh://`` destinations, no working directory or
1322 ``.hg/hgrc`` will be created on the remote side.
1322 ``.hg/hgrc`` will be created on the remote side.
1323
1323
1324 If the source repository has a bookmark called '@' set, that
1324 If the source repository has a bookmark called '@' set, that
1325 revision will be checked out in the new repository by default.
1325 revision will be checked out in the new repository by default.
1326
1326
1327 To check out a particular version, use -u/--update, or
1327 To check out a particular version, use -u/--update, or
1328 -U/--noupdate to create a clone with no working directory.
1328 -U/--noupdate to create a clone with no working directory.
1329
1329
1330 To pull only a subset of changesets, specify one or more revisions
1330 To pull only a subset of changesets, specify one or more revisions
1331 identifiers with -r/--rev or branches with -b/--branch. The
1331 identifiers with -r/--rev or branches with -b/--branch. The
1332 resulting clone will contain only the specified changesets and
1332 resulting clone will contain only the specified changesets and
1333 their ancestors. These options (or 'clone src#rev dest') imply
1333 their ancestors. These options (or 'clone src#rev dest') imply
1334 --pull, even for local source repositories.
1334 --pull, even for local source repositories.
1335
1335
1336 In normal clone mode, the remote normalizes repository data into a common
1336 In normal clone mode, the remote normalizes repository data into a common
1337 exchange format and the receiving end translates this data into its local
1337 exchange format and the receiving end translates this data into its local
1338 storage format. --stream activates a different clone mode that essentially
1338 storage format. --stream activates a different clone mode that essentially
1339 copies repository files from the remote with minimal data processing. This
1339 copies repository files from the remote with minimal data processing. This
1340 significantly reduces the CPU cost of a clone both remotely and locally.
1340 significantly reduces the CPU cost of a clone both remotely and locally.
1341 However, it often increases the transferred data size by 30-40%. This can
1341 However, it often increases the transferred data size by 30-40%. This can
1342 result in substantially faster clones where I/O throughput is plentiful,
1342 result in substantially faster clones where I/O throughput is plentiful,
1343 especially for larger repositories. A side-effect of --stream clones is
1343 especially for larger repositories. A side-effect of --stream clones is
1344 that storage settings and requirements on the remote are applied locally:
1344 that storage settings and requirements on the remote are applied locally:
1345 a modern client may inherit legacy or inefficient storage used by the
1345 a modern client may inherit legacy or inefficient storage used by the
1346 remote or a legacy Mercurial client may not be able to clone from a
1346 remote or a legacy Mercurial client may not be able to clone from a
1347 modern Mercurial remote.
1347 modern Mercurial remote.
1348
1348
1349 .. note::
1349 .. note::
1350
1350
1351 Specifying a tag will include the tagged changeset but not the
1351 Specifying a tag will include the tagged changeset but not the
1352 changeset containing the tag.
1352 changeset containing the tag.
1353
1353
1354 .. container:: verbose
1354 .. container:: verbose
1355
1355
1356 For efficiency, hardlinks are used for cloning whenever the
1356 For efficiency, hardlinks are used for cloning whenever the
1357 source and destination are on the same filesystem (note this
1357 source and destination are on the same filesystem (note this
1358 applies only to the repository data, not to the working
1358 applies only to the repository data, not to the working
1359 directory). Some filesystems, such as AFS, implement hardlinking
1359 directory). Some filesystems, such as AFS, implement hardlinking
1360 incorrectly, but do not report errors. In these cases, use the
1360 incorrectly, but do not report errors. In these cases, use the
1361 --pull option to avoid hardlinking.
1361 --pull option to avoid hardlinking.
1362
1362
1363 Mercurial will update the working directory to the first applicable
1363 Mercurial will update the working directory to the first applicable
1364 revision from this list:
1364 revision from this list:
1365
1365
1366 a) null if -U or the source repository has no changesets
1366 a) null if -U or the source repository has no changesets
1367 b) if -u . and the source repository is local, the first parent of
1367 b) if -u . and the source repository is local, the first parent of
1368 the source repository's working directory
1368 the source repository's working directory
1369 c) the changeset specified with -u (if a branch name, this means the
1369 c) the changeset specified with -u (if a branch name, this means the
1370 latest head of that branch)
1370 latest head of that branch)
1371 d) the changeset specified with -r
1371 d) the changeset specified with -r
1372 e) the tipmost head specified with -b
1372 e) the tipmost head specified with -b
1373 f) the tipmost head specified with the url#branch source syntax
1373 f) the tipmost head specified with the url#branch source syntax
1374 g) the revision marked with the '@' bookmark, if present
1374 g) the revision marked with the '@' bookmark, if present
1375 h) the tipmost head of the default branch
1375 h) the tipmost head of the default branch
1376 i) tip
1376 i) tip
1377
1377
1378 When cloning from servers that support it, Mercurial may fetch
1378 When cloning from servers that support it, Mercurial may fetch
1379 pre-generated data from a server-advertised URL. When this is done,
1379 pre-generated data from a server-advertised URL. When this is done,
1380 hooks operating on incoming changesets and changegroups may fire twice,
1380 hooks operating on incoming changesets and changegroups may fire twice,
1381 once for the bundle fetched from the URL and another for any additional
1381 once for the bundle fetched from the URL and another for any additional
1382 data not fetched from this URL. In addition, if an error occurs, the
1382 data not fetched from this URL. In addition, if an error occurs, the
1383 repository may be rolled back to a partial clone. This behavior may
1383 repository may be rolled back to a partial clone. This behavior may
1384 change in future releases. See :hg:`help -e clonebundles` for more.
1384 change in future releases. See :hg:`help -e clonebundles` for more.
1385
1385
1386 Examples:
1386 Examples:
1387
1387
1388 - clone a remote repository to a new directory named hg/::
1388 - clone a remote repository to a new directory named hg/::
1389
1389
1390 hg clone https://www.mercurial-scm.org/repo/hg/
1390 hg clone https://www.mercurial-scm.org/repo/hg/
1391
1391
1392 - create a lightweight local clone::
1392 - create a lightweight local clone::
1393
1393
1394 hg clone project/ project-feature/
1394 hg clone project/ project-feature/
1395
1395
1396 - clone from an absolute path on an ssh server (note double-slash)::
1396 - clone from an absolute path on an ssh server (note double-slash)::
1397
1397
1398 hg clone ssh://user@server//home/projects/alpha/
1398 hg clone ssh://user@server//home/projects/alpha/
1399
1399
1400 - do a streaming clone while checking out a specified version::
1400 - do a streaming clone while checking out a specified version::
1401
1401
1402 hg clone --stream http://server/repo -u 1.5
1402 hg clone --stream http://server/repo -u 1.5
1403
1403
1404 - create a repository without changesets after a particular revision::
1404 - create a repository without changesets after a particular revision::
1405
1405
1406 hg clone -r 04e544 experimental/ good/
1406 hg clone -r 04e544 experimental/ good/
1407
1407
1408 - clone (and track) a particular named branch::
1408 - clone (and track) a particular named branch::
1409
1409
1410 hg clone https://www.mercurial-scm.org/repo/hg/#stable
1410 hg clone https://www.mercurial-scm.org/repo/hg/#stable
1411
1411
1412 See :hg:`help urls` for details on specifying URLs.
1412 See :hg:`help urls` for details on specifying URLs.
1413
1413
1414 Returns 0 on success.
1414 Returns 0 on success.
1415 """
1415 """
1416 opts = pycompat.byteskwargs(opts)
1416 opts = pycompat.byteskwargs(opts)
1417 if opts.get('noupdate') and opts.get('updaterev'):
1417 if opts.get('noupdate') and opts.get('updaterev'):
1418 raise error.Abort(_("cannot specify both --noupdate and --updaterev"))
1418 raise error.Abort(_("cannot specify both --noupdate and --updaterev"))
1419
1419
1420 r = hg.clone(ui, opts, source, dest,
1420 r = hg.clone(ui, opts, source, dest,
1421 pull=opts.get('pull'),
1421 pull=opts.get('pull'),
1422 stream=opts.get('stream') or opts.get('uncompressed'),
1422 stream=opts.get('stream') or opts.get('uncompressed'),
1423 rev=opts.get('rev'),
1423 rev=opts.get('rev'),
1424 update=opts.get('updaterev') or not opts.get('noupdate'),
1424 update=opts.get('updaterev') or not opts.get('noupdate'),
1425 branch=opts.get('branch'),
1425 branch=opts.get('branch'),
1426 shareopts=opts.get('shareopts'))
1426 shareopts=opts.get('shareopts'))
1427
1427
1428 return r is None
1428 return r is None
1429
1429
1430 @command('^commit|ci',
1430 @command('^commit|ci',
1431 [('A', 'addremove', None,
1431 [('A', 'addremove', None,
1432 _('mark new/missing files as added/removed before committing')),
1432 _('mark new/missing files as added/removed before committing')),
1433 ('', 'close-branch', None,
1433 ('', 'close-branch', None,
1434 _('mark a branch head as closed')),
1434 _('mark a branch head as closed')),
1435 ('', 'amend', None, _('amend the parent of the working directory')),
1435 ('', 'amend', None, _('amend the parent of the working directory')),
1436 ('s', 'secret', None, _('use the secret phase for committing')),
1436 ('s', 'secret', None, _('use the secret phase for committing')),
1437 ('e', 'edit', None, _('invoke editor on commit messages')),
1437 ('e', 'edit', None, _('invoke editor on commit messages')),
1438 ('i', 'interactive', None, _('use interactive mode')),
1438 ('i', 'interactive', None, _('use interactive mode')),
1439 ] + walkopts + commitopts + commitopts2 + subrepoopts,
1439 ] + walkopts + commitopts + commitopts2 + subrepoopts,
1440 _('[OPTION]... [FILE]...'),
1440 _('[OPTION]... [FILE]...'),
1441 inferrepo=True)
1441 inferrepo=True)
1442 def commit(ui, repo, *pats, **opts):
1442 def commit(ui, repo, *pats, **opts):
1443 """commit the specified files or all outstanding changes
1443 """commit the specified files or all outstanding changes
1444
1444
1445 Commit changes to the given files into the repository. Unlike a
1445 Commit changes to the given files into the repository. Unlike a
1446 centralized SCM, this operation is a local operation. See
1446 centralized SCM, this operation is a local operation. See
1447 :hg:`push` for a way to actively distribute your changes.
1447 :hg:`push` for a way to actively distribute your changes.
1448
1448
1449 If a list of files is omitted, all changes reported by :hg:`status`
1449 If a list of files is omitted, all changes reported by :hg:`status`
1450 will be committed.
1450 will be committed.
1451
1451
1452 If you are committing the result of a merge, do not provide any
1452 If you are committing the result of a merge, do not provide any
1453 filenames or -I/-X filters.
1453 filenames or -I/-X filters.
1454
1454
1455 If no commit message is specified, Mercurial starts your
1455 If no commit message is specified, Mercurial starts your
1456 configured editor where you can enter a message. In case your
1456 configured editor where you can enter a message. In case your
1457 commit fails, you will find a backup of your message in
1457 commit fails, you will find a backup of your message in
1458 ``.hg/last-message.txt``.
1458 ``.hg/last-message.txt``.
1459
1459
1460 The --close-branch flag can be used to mark the current branch
1460 The --close-branch flag can be used to mark the current branch
1461 head closed. When all heads of a branch are closed, the branch
1461 head closed. When all heads of a branch are closed, the branch
1462 will be considered closed and no longer listed.
1462 will be considered closed and no longer listed.
1463
1463
1464 The --amend flag can be used to amend the parent of the
1464 The --amend flag can be used to amend the parent of the
1465 working directory with a new commit that contains the changes
1465 working directory with a new commit that contains the changes
1466 in the parent in addition to those currently reported by :hg:`status`,
1466 in the parent in addition to those currently reported by :hg:`status`,
1467 if there are any. The old commit is stored in a backup bundle in
1467 if there are any. The old commit is stored in a backup bundle in
1468 ``.hg/strip-backup`` (see :hg:`help bundle` and :hg:`help unbundle`
1468 ``.hg/strip-backup`` (see :hg:`help bundle` and :hg:`help unbundle`
1469 on how to restore it).
1469 on how to restore it).
1470
1470
1471 Message, user and date are taken from the amended commit unless
1471 Message, user and date are taken from the amended commit unless
1472 specified. When a message isn't specified on the command line,
1472 specified. When a message isn't specified on the command line,
1473 the editor will open with the message of the amended commit.
1473 the editor will open with the message of the amended commit.
1474
1474
1475 It is not possible to amend public changesets (see :hg:`help phases`)
1475 It is not possible to amend public changesets (see :hg:`help phases`)
1476 or changesets that have children.
1476 or changesets that have children.
1477
1477
1478 See :hg:`help dates` for a list of formats valid for -d/--date.
1478 See :hg:`help dates` for a list of formats valid for -d/--date.
1479
1479
1480 Returns 0 on success, 1 if nothing changed.
1480 Returns 0 on success, 1 if nothing changed.
1481
1481
1482 .. container:: verbose
1482 .. container:: verbose
1483
1483
1484 Examples:
1484 Examples:
1485
1485
1486 - commit all files ending in .py::
1486 - commit all files ending in .py::
1487
1487
1488 hg commit --include "set:**.py"
1488 hg commit --include "set:**.py"
1489
1489
1490 - commit all non-binary files::
1490 - commit all non-binary files::
1491
1491
1492 hg commit --exclude "set:binary()"
1492 hg commit --exclude "set:binary()"
1493
1493
1494 - amend the current commit and set the date to now::
1494 - amend the current commit and set the date to now::
1495
1495
1496 hg commit --amend --date now
1496 hg commit --amend --date now
1497 """
1497 """
1498 wlock = lock = None
1498 wlock = lock = None
1499 try:
1499 try:
1500 wlock = repo.wlock()
1500 wlock = repo.wlock()
1501 lock = repo.lock()
1501 lock = repo.lock()
1502 return _docommit(ui, repo, *pats, **opts)
1502 return _docommit(ui, repo, *pats, **opts)
1503 finally:
1503 finally:
1504 release(lock, wlock)
1504 release(lock, wlock)
1505
1505
1506 def _docommit(ui, repo, *pats, **opts):
1506 def _docommit(ui, repo, *pats, **opts):
1507 if opts.get(r'interactive'):
1507 if opts.get(r'interactive'):
1508 opts.pop(r'interactive')
1508 opts.pop(r'interactive')
1509 ret = cmdutil.dorecord(ui, repo, commit, None, False,
1509 ret = cmdutil.dorecord(ui, repo, commit, None, False,
1510 cmdutil.recordfilter, *pats,
1510 cmdutil.recordfilter, *pats,
1511 **opts)
1511 **opts)
1512 # ret can be 0 (no changes to record) or the value returned by
1512 # ret can be 0 (no changes to record) or the value returned by
1513 # commit(), 1 if nothing changed or None on success.
1513 # commit(), 1 if nothing changed or None on success.
1514 return 1 if ret == 0 else ret
1514 return 1 if ret == 0 else ret
1515
1515
1516 opts = pycompat.byteskwargs(opts)
1516 opts = pycompat.byteskwargs(opts)
1517 if opts.get('subrepos'):
1517 if opts.get('subrepos'):
1518 if opts.get('amend'):
1518 if opts.get('amend'):
1519 raise error.Abort(_('cannot amend with --subrepos'))
1519 raise error.Abort(_('cannot amend with --subrepos'))
1520 # Let --subrepos on the command line override config setting.
1520 # Let --subrepos on the command line override config setting.
1521 ui.setconfig('ui', 'commitsubrepos', True, 'commit')
1521 ui.setconfig('ui', 'commitsubrepos', True, 'commit')
1522
1522
1523 cmdutil.checkunfinished(repo, commit=True)
1523 cmdutil.checkunfinished(repo, commit=True)
1524
1524
1525 branch = repo[None].branch()
1525 branch = repo[None].branch()
1526 bheads = repo.branchheads(branch)
1526 bheads = repo.branchheads(branch)
1527
1527
1528 extra = {}
1528 extra = {}
1529 if opts.get('close_branch'):
1529 if opts.get('close_branch'):
1530 extra['close'] = 1
1530 extra['close'] = 1
1531
1531
1532 if not bheads:
1532 if not bheads:
1533 raise error.Abort(_('can only close branch heads'))
1533 raise error.Abort(_('can only close branch heads'))
1534 elif opts.get('amend'):
1534 elif opts.get('amend'):
1535 if repo[None].parents()[0].p1().branch() != branch and \
1535 if repo[None].parents()[0].p1().branch() != branch and \
1536 repo[None].parents()[0].p2().branch() != branch:
1536 repo[None].parents()[0].p2().branch() != branch:
1537 raise error.Abort(_('can only close branch heads'))
1537 raise error.Abort(_('can only close branch heads'))
1538
1538
1539 if opts.get('amend'):
1539 if opts.get('amend'):
1540 if ui.configbool('ui', 'commitsubrepos'):
1540 if ui.configbool('ui', 'commitsubrepos'):
1541 raise error.Abort(_('cannot amend with ui.commitsubrepos enabled'))
1541 raise error.Abort(_('cannot amend with ui.commitsubrepos enabled'))
1542
1542
1543 old = repo['.']
1543 old = repo['.']
1544 if not old.mutable():
1544 if not old.mutable():
1545 raise error.Abort(_('cannot amend public changesets'))
1545 raise error.Abort(_('cannot amend public changesets'))
1546 if len(repo[None].parents()) > 1:
1546 if len(repo[None].parents()) > 1:
1547 raise error.Abort(_('cannot amend while merging'))
1547 raise error.Abort(_('cannot amend while merging'))
1548 allowunstable = obsolete.isenabled(repo, obsolete.allowunstableopt)
1548 allowunstable = obsolete.isenabled(repo, obsolete.allowunstableopt)
1549 if not allowunstable and old.children():
1549 if not allowunstable and old.children():
1550 raise error.Abort(_('cannot amend changeset with children'))
1550 raise error.Abort(_('cannot amend changeset with children'))
1551
1551
1552 # Currently histedit gets confused if an amend happens while histedit
1552 # Currently histedit gets confused if an amend happens while histedit
1553 # is in progress. Since we have a checkunfinished command, we are
1553 # is in progress. Since we have a checkunfinished command, we are
1554 # temporarily honoring it.
1554 # temporarily honoring it.
1555 #
1555 #
1556 # Note: eventually this guard will be removed. Please do not expect
1556 # Note: eventually this guard will be removed. Please do not expect
1557 # this behavior to remain.
1557 # this behavior to remain.
1558 if not obsolete.isenabled(repo, obsolete.createmarkersopt):
1558 if not obsolete.isenabled(repo, obsolete.createmarkersopt):
1559 cmdutil.checkunfinished(repo)
1559 cmdutil.checkunfinished(repo)
1560
1560
1561 node = cmdutil.amend(ui, repo, old, extra, pats, opts)
1561 node = cmdutil.amend(ui, repo, old, extra, pats, opts)
1562 if node == old.node():
1562 if node == old.node():
1563 ui.status(_("nothing changed\n"))
1563 ui.status(_("nothing changed\n"))
1564 return 1
1564 return 1
1565 else:
1565 else:
1566 def commitfunc(ui, repo, message, match, opts):
1566 def commitfunc(ui, repo, message, match, opts):
1567 overrides = {}
1567 overrides = {}
1568 if opts.get('secret'):
1568 if opts.get('secret'):
1569 overrides[('phases', 'new-commit')] = 'secret'
1569 overrides[('phases', 'new-commit')] = 'secret'
1570
1570
1571 baseui = repo.baseui
1571 baseui = repo.baseui
1572 with baseui.configoverride(overrides, 'commit'):
1572 with baseui.configoverride(overrides, 'commit'):
1573 with ui.configoverride(overrides, 'commit'):
1573 with ui.configoverride(overrides, 'commit'):
1574 editform = cmdutil.mergeeditform(repo[None],
1574 editform = cmdutil.mergeeditform(repo[None],
1575 'commit.normal')
1575 'commit.normal')
1576 editor = cmdutil.getcommiteditor(
1576 editor = cmdutil.getcommiteditor(
1577 editform=editform, **pycompat.strkwargs(opts))
1577 editform=editform, **pycompat.strkwargs(opts))
1578 return repo.commit(message,
1578 return repo.commit(message,
1579 opts.get('user'),
1579 opts.get('user'),
1580 opts.get('date'),
1580 opts.get('date'),
1581 match,
1581 match,
1582 editor=editor,
1582 editor=editor,
1583 extra=extra)
1583 extra=extra)
1584
1584
1585 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1585 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1586
1586
1587 if not node:
1587 if not node:
1588 stat = cmdutil.postcommitstatus(repo, pats, opts)
1588 stat = cmdutil.postcommitstatus(repo, pats, opts)
1589 if stat[3]:
1589 if stat[3]:
1590 ui.status(_("nothing changed (%d missing files, see "
1590 ui.status(_("nothing changed (%d missing files, see "
1591 "'hg status')\n") % len(stat[3]))
1591 "'hg status')\n") % len(stat[3]))
1592 else:
1592 else:
1593 ui.status(_("nothing changed\n"))
1593 ui.status(_("nothing changed\n"))
1594 return 1
1594 return 1
1595
1595
1596 cmdutil.commitstatus(repo, node, branch, bheads, opts)
1596 cmdutil.commitstatus(repo, node, branch, bheads, opts)
1597
1597
1598 @command('config|showconfig|debugconfig',
1598 @command('config|showconfig|debugconfig',
1599 [('u', 'untrusted', None, _('show untrusted configuration options')),
1599 [('u', 'untrusted', None, _('show untrusted configuration options')),
1600 ('e', 'edit', None, _('edit user config')),
1600 ('e', 'edit', None, _('edit user config')),
1601 ('l', 'local', None, _('edit repository config')),
1601 ('l', 'local', None, _('edit repository config')),
1602 ('g', 'global', None, _('edit global config'))] + formatteropts,
1602 ('g', 'global', None, _('edit global config'))] + formatteropts,
1603 _('[-u] [NAME]...'),
1603 _('[-u] [NAME]...'),
1604 optionalrepo=True, cmdtype=readonly)
1604 optionalrepo=True, cmdtype=readonly)
1605 def config(ui, repo, *values, **opts):
1605 def config(ui, repo, *values, **opts):
1606 """show combined config settings from all hgrc files
1606 """show combined config settings from all hgrc files
1607
1607
1608 With no arguments, print names and values of all config items.
1608 With no arguments, print names and values of all config items.
1609
1609
1610 With one argument of the form section.name, print just the value
1610 With one argument of the form section.name, print just the value
1611 of that config item.
1611 of that config item.
1612
1612
1613 With multiple arguments, print names and values of all config
1613 With multiple arguments, print names and values of all config
1614 items with matching section names.
1614 items with matching section names.
1615
1615
1616 With --edit, start an editor on the user-level config file. With
1616 With --edit, start an editor on the user-level config file. With
1617 --global, edit the system-wide config file. With --local, edit the
1617 --global, edit the system-wide config file. With --local, edit the
1618 repository-level config file.
1618 repository-level config file.
1619
1619
1620 With --debug, the source (filename and line number) is printed
1620 With --debug, the source (filename and line number) is printed
1621 for each config item.
1621 for each config item.
1622
1622
1623 See :hg:`help config` for more information about config files.
1623 See :hg:`help config` for more information about config files.
1624
1624
1625 Returns 0 on success, 1 if NAME does not exist.
1625 Returns 0 on success, 1 if NAME does not exist.
1626
1626
1627 """
1627 """
1628
1628
1629 opts = pycompat.byteskwargs(opts)
1629 opts = pycompat.byteskwargs(opts)
1630 if opts.get('edit') or opts.get('local') or opts.get('global'):
1630 if opts.get('edit') or opts.get('local') or opts.get('global'):
1631 if opts.get('local') and opts.get('global'):
1631 if opts.get('local') and opts.get('global'):
1632 raise error.Abort(_("can't use --local and --global together"))
1632 raise error.Abort(_("can't use --local and --global together"))
1633
1633
1634 if opts.get('local'):
1634 if opts.get('local'):
1635 if not repo:
1635 if not repo:
1636 raise error.Abort(_("can't use --local outside a repository"))
1636 raise error.Abort(_("can't use --local outside a repository"))
1637 paths = [repo.vfs.join('hgrc')]
1637 paths = [repo.vfs.join('hgrc')]
1638 elif opts.get('global'):
1638 elif opts.get('global'):
1639 paths = rcutil.systemrcpath()
1639 paths = rcutil.systemrcpath()
1640 else:
1640 else:
1641 paths = rcutil.userrcpath()
1641 paths = rcutil.userrcpath()
1642
1642
1643 for f in paths:
1643 for f in paths:
1644 if os.path.exists(f):
1644 if os.path.exists(f):
1645 break
1645 break
1646 else:
1646 else:
1647 if opts.get('global'):
1647 if opts.get('global'):
1648 samplehgrc = uimod.samplehgrcs['global']
1648 samplehgrc = uimod.samplehgrcs['global']
1649 elif opts.get('local'):
1649 elif opts.get('local'):
1650 samplehgrc = uimod.samplehgrcs['local']
1650 samplehgrc = uimod.samplehgrcs['local']
1651 else:
1651 else:
1652 samplehgrc = uimod.samplehgrcs['user']
1652 samplehgrc = uimod.samplehgrcs['user']
1653
1653
1654 f = paths[0]
1654 f = paths[0]
1655 fp = open(f, "wb")
1655 fp = open(f, "wb")
1656 fp.write(util.tonativeeol(samplehgrc))
1656 fp.write(util.tonativeeol(samplehgrc))
1657 fp.close()
1657 fp.close()
1658
1658
1659 editor = ui.geteditor()
1659 editor = ui.geteditor()
1660 ui.system("%s \"%s\"" % (editor, f),
1660 ui.system("%s \"%s\"" % (editor, f),
1661 onerr=error.Abort, errprefix=_("edit failed"),
1661 onerr=error.Abort, errprefix=_("edit failed"),
1662 blockedtag='config_edit')
1662 blockedtag='config_edit')
1663 return
1663 return
1664 ui.pager('config')
1664 ui.pager('config')
1665 fm = ui.formatter('config', opts)
1665 fm = ui.formatter('config', opts)
1666 for t, f in rcutil.rccomponents():
1666 for t, f in rcutil.rccomponents():
1667 if t == 'path':
1667 if t == 'path':
1668 ui.debug('read config from: %s\n' % f)
1668 ui.debug('read config from: %s\n' % f)
1669 elif t == 'items':
1669 elif t == 'items':
1670 for section, name, value, source in f:
1670 for section, name, value, source in f:
1671 ui.debug('set config by: %s\n' % source)
1671 ui.debug('set config by: %s\n' % source)
1672 else:
1672 else:
1673 raise error.ProgrammingError('unknown rctype: %s' % t)
1673 raise error.ProgrammingError('unknown rctype: %s' % t)
1674 untrusted = bool(opts.get('untrusted'))
1674 untrusted = bool(opts.get('untrusted'))
1675 if values:
1675 if values:
1676 sections = [v for v in values if '.' not in v]
1676 sections = [v for v in values if '.' not in v]
1677 items = [v for v in values if '.' in v]
1677 items = [v for v in values if '.' in v]
1678 if len(items) > 1 or items and sections:
1678 if len(items) > 1 or items and sections:
1679 raise error.Abort(_('only one config item permitted'))
1679 raise error.Abort(_('only one config item permitted'))
1680 matched = False
1680 matched = False
1681 for section, name, value in ui.walkconfig(untrusted=untrusted):
1681 for section, name, value in ui.walkconfig(untrusted=untrusted):
1682 source = ui.configsource(section, name, untrusted)
1682 source = ui.configsource(section, name, untrusted)
1683 value = pycompat.bytestr(value)
1683 value = pycompat.bytestr(value)
1684 if fm.isplain():
1684 if fm.isplain():
1685 source = source or 'none'
1685 source = source or 'none'
1686 value = value.replace('\n', '\\n')
1686 value = value.replace('\n', '\\n')
1687 entryname = section + '.' + name
1687 entryname = section + '.' + name
1688 if values:
1688 if values:
1689 for v in values:
1689 for v in values:
1690 if v == section:
1690 if v == section:
1691 fm.startitem()
1691 fm.startitem()
1692 fm.condwrite(ui.debugflag, 'source', '%s: ', source)
1692 fm.condwrite(ui.debugflag, 'source', '%s: ', source)
1693 fm.write('name value', '%s=%s\n', entryname, value)
1693 fm.write('name value', '%s=%s\n', entryname, value)
1694 matched = True
1694 matched = True
1695 elif v == entryname:
1695 elif v == entryname:
1696 fm.startitem()
1696 fm.startitem()
1697 fm.condwrite(ui.debugflag, 'source', '%s: ', source)
1697 fm.condwrite(ui.debugflag, 'source', '%s: ', source)
1698 fm.write('value', '%s\n', value)
1698 fm.write('value', '%s\n', value)
1699 fm.data(name=entryname)
1699 fm.data(name=entryname)
1700 matched = True
1700 matched = True
1701 else:
1701 else:
1702 fm.startitem()
1702 fm.startitem()
1703 fm.condwrite(ui.debugflag, 'source', '%s: ', source)
1703 fm.condwrite(ui.debugflag, 'source', '%s: ', source)
1704 fm.write('name value', '%s=%s\n', entryname, value)
1704 fm.write('name value', '%s=%s\n', entryname, value)
1705 matched = True
1705 matched = True
1706 fm.end()
1706 fm.end()
1707 if matched:
1707 if matched:
1708 return 0
1708 return 0
1709 return 1
1709 return 1
1710
1710
1711 @command('copy|cp',
1711 @command('copy|cp',
1712 [('A', 'after', None, _('record a copy that has already occurred')),
1712 [('A', 'after', None, _('record a copy that has already occurred')),
1713 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1713 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1714 ] + walkopts + dryrunopts,
1714 ] + walkopts + dryrunopts,
1715 _('[OPTION]... [SOURCE]... DEST'))
1715 _('[OPTION]... [SOURCE]... DEST'))
1716 def copy(ui, repo, *pats, **opts):
1716 def copy(ui, repo, *pats, **opts):
1717 """mark files as copied for the next commit
1717 """mark files as copied for the next commit
1718
1718
1719 Mark dest as having copies of source files. If dest is a
1719 Mark dest as having copies of source files. If dest is a
1720 directory, copies are put in that directory. If dest is a file,
1720 directory, copies are put in that directory. If dest is a file,
1721 the source must be a single file.
1721 the source must be a single file.
1722
1722
1723 By default, this command copies the contents of files as they
1723 By default, this command copies the contents of files as they
1724 exist in the working directory. If invoked with -A/--after, the
1724 exist in the working directory. If invoked with -A/--after, the
1725 operation is recorded, but no copying is performed.
1725 operation is recorded, but no copying is performed.
1726
1726
1727 This command takes effect with the next commit. To undo a copy
1727 This command takes effect with the next commit. To undo a copy
1728 before that, see :hg:`revert`.
1728 before that, see :hg:`revert`.
1729
1729
1730 Returns 0 on success, 1 if errors are encountered.
1730 Returns 0 on success, 1 if errors are encountered.
1731 """
1731 """
1732 opts = pycompat.byteskwargs(opts)
1732 opts = pycompat.byteskwargs(opts)
1733 with repo.wlock(False):
1733 with repo.wlock(False):
1734 return cmdutil.copy(ui, repo, pats, opts)
1734 return cmdutil.copy(ui, repo, pats, opts)
1735
1735
1736 @command('debugcommands', [], _('[COMMAND]'), norepo=True)
1736 @command('debugcommands', [], _('[COMMAND]'), norepo=True)
1737 def debugcommands(ui, cmd='', *args):
1737 def debugcommands(ui, cmd='', *args):
1738 """list all available commands and options"""
1738 """list all available commands and options"""
1739 for cmd, vals in sorted(table.iteritems()):
1739 for cmd, vals in sorted(table.iteritems()):
1740 cmd = cmd.split('|')[0].strip('^')
1740 cmd = cmd.split('|')[0].strip('^')
1741 opts = ', '.join([i[1] for i in vals[1]])
1741 opts = ', '.join([i[1] for i in vals[1]])
1742 ui.write('%s: %s\n' % (cmd, opts))
1742 ui.write('%s: %s\n' % (cmd, opts))
1743
1743
1744 @command('debugcomplete',
1744 @command('debugcomplete',
1745 [('o', 'options', None, _('show the command options'))],
1745 [('o', 'options', None, _('show the command options'))],
1746 _('[-o] CMD'),
1746 _('[-o] CMD'),
1747 norepo=True)
1747 norepo=True)
1748 def debugcomplete(ui, cmd='', **opts):
1748 def debugcomplete(ui, cmd='', **opts):
1749 """returns the completion list associated with the given command"""
1749 """returns the completion list associated with the given command"""
1750
1750
1751 if opts.get('options'):
1751 if opts.get('options'):
1752 options = []
1752 options = []
1753 otables = [globalopts]
1753 otables = [globalopts]
1754 if cmd:
1754 if cmd:
1755 aliases, entry = cmdutil.findcmd(cmd, table, False)
1755 aliases, entry = cmdutil.findcmd(cmd, table, False)
1756 otables.append(entry[1])
1756 otables.append(entry[1])
1757 for t in otables:
1757 for t in otables:
1758 for o in t:
1758 for o in t:
1759 if "(DEPRECATED)" in o[3]:
1759 if "(DEPRECATED)" in o[3]:
1760 continue
1760 continue
1761 if o[0]:
1761 if o[0]:
1762 options.append('-%s' % o[0])
1762 options.append('-%s' % o[0])
1763 options.append('--%s' % o[1])
1763 options.append('--%s' % o[1])
1764 ui.write("%s\n" % "\n".join(options))
1764 ui.write("%s\n" % "\n".join(options))
1765 return
1765 return
1766
1766
1767 cmdlist, unused_allcmds = cmdutil.findpossible(cmd, table)
1767 cmdlist, unused_allcmds = cmdutil.findpossible(cmd, table)
1768 if ui.verbose:
1768 if ui.verbose:
1769 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1769 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1770 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1770 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1771
1771
1772 @command('^diff',
1772 @command('^diff',
1773 [('r', 'rev', [], _('revision'), _('REV')),
1773 [('r', 'rev', [], _('revision'), _('REV')),
1774 ('c', 'change', '', _('change made by revision'), _('REV'))
1774 ('c', 'change', '', _('change made by revision'), _('REV'))
1775 ] + diffopts + diffopts2 + walkopts + subrepoopts,
1775 ] + diffopts + diffopts2 + walkopts + subrepoopts,
1776 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'),
1776 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'),
1777 inferrepo=True, cmdtype=readonly)
1777 inferrepo=True, cmdtype=readonly)
1778 def diff(ui, repo, *pats, **opts):
1778 def diff(ui, repo, *pats, **opts):
1779 """diff repository (or selected files)
1779 """diff repository (or selected files)
1780
1780
1781 Show differences between revisions for the specified files.
1781 Show differences between revisions for the specified files.
1782
1782
1783 Differences between files are shown using the unified diff format.
1783 Differences between files are shown using the unified diff format.
1784
1784
1785 .. note::
1785 .. note::
1786
1786
1787 :hg:`diff` may generate unexpected results for merges, as it will
1787 :hg:`diff` may generate unexpected results for merges, as it will
1788 default to comparing against the working directory's first
1788 default to comparing against the working directory's first
1789 parent changeset if no revisions are specified.
1789 parent changeset if no revisions are specified.
1790
1790
1791 When two revision arguments are given, then changes are shown
1791 When two revision arguments are given, then changes are shown
1792 between those revisions. If only one revision is specified then
1792 between those revisions. If only one revision is specified then
1793 that revision is compared to the working directory, and, when no
1793 that revision is compared to the working directory, and, when no
1794 revisions are specified, the working directory files are compared
1794 revisions are specified, the working directory files are compared
1795 to its first parent.
1795 to its first parent.
1796
1796
1797 Alternatively you can specify -c/--change with a revision to see
1797 Alternatively you can specify -c/--change with a revision to see
1798 the changes in that changeset relative to its first parent.
1798 the changes in that changeset relative to its first parent.
1799
1799
1800 Without the -a/--text option, diff will avoid generating diffs of
1800 Without the -a/--text option, diff will avoid generating diffs of
1801 files it detects as binary. With -a, diff will generate a diff
1801 files it detects as binary. With -a, diff will generate a diff
1802 anyway, probably with undesirable results.
1802 anyway, probably with undesirable results.
1803
1803
1804 Use the -g/--git option to generate diffs in the git extended diff
1804 Use the -g/--git option to generate diffs in the git extended diff
1805 format. For more information, read :hg:`help diffs`.
1805 format. For more information, read :hg:`help diffs`.
1806
1806
1807 .. container:: verbose
1807 .. container:: verbose
1808
1808
1809 Examples:
1809 Examples:
1810
1810
1811 - compare a file in the current working directory to its parent::
1811 - compare a file in the current working directory to its parent::
1812
1812
1813 hg diff foo.c
1813 hg diff foo.c
1814
1814
1815 - compare two historical versions of a directory, with rename info::
1815 - compare two historical versions of a directory, with rename info::
1816
1816
1817 hg diff --git -r 1.0:1.2 lib/
1817 hg diff --git -r 1.0:1.2 lib/
1818
1818
1819 - get change stats relative to the last change on some date::
1819 - get change stats relative to the last change on some date::
1820
1820
1821 hg diff --stat -r "date('may 2')"
1821 hg diff --stat -r "date('may 2')"
1822
1822
1823 - diff all newly-added files that contain a keyword::
1823 - diff all newly-added files that contain a keyword::
1824
1824
1825 hg diff "set:added() and grep(GNU)"
1825 hg diff "set:added() and grep(GNU)"
1826
1826
1827 - compare a revision and its parents::
1827 - compare a revision and its parents::
1828
1828
1829 hg diff -c 9353 # compare against first parent
1829 hg diff -c 9353 # compare against first parent
1830 hg diff -r 9353^:9353 # same using revset syntax
1830 hg diff -r 9353^:9353 # same using revset syntax
1831 hg diff -r 9353^2:9353 # compare against the second parent
1831 hg diff -r 9353^2:9353 # compare against the second parent
1832
1832
1833 Returns 0 on success.
1833 Returns 0 on success.
1834 """
1834 """
1835
1835
1836 opts = pycompat.byteskwargs(opts)
1836 opts = pycompat.byteskwargs(opts)
1837 revs = opts.get('rev')
1837 revs = opts.get('rev')
1838 change = opts.get('change')
1838 change = opts.get('change')
1839 stat = opts.get('stat')
1839 stat = opts.get('stat')
1840 reverse = opts.get('reverse')
1840 reverse = opts.get('reverse')
1841
1841
1842 if revs and change:
1842 if revs and change:
1843 msg = _('cannot specify --rev and --change at the same time')
1843 msg = _('cannot specify --rev and --change at the same time')
1844 raise error.Abort(msg)
1844 raise error.Abort(msg)
1845 elif change:
1845 elif change:
1846 node2 = scmutil.revsingle(repo, change, None).node()
1846 node2 = scmutil.revsingle(repo, change, None).node()
1847 node1 = repo[node2].p1().node()
1847 node1 = repo[node2].p1().node()
1848 else:
1848 else:
1849 node1, node2 = scmutil.revpair(repo, revs)
1849 node1, node2 = scmutil.revpair(repo, revs)
1850
1850
1851 if reverse:
1851 if reverse:
1852 node1, node2 = node2, node1
1852 node1, node2 = node2, node1
1853
1853
1854 diffopts = patch.diffallopts(ui, opts)
1854 diffopts = patch.diffallopts(ui, opts)
1855 m = scmutil.match(repo[node2], pats, opts)
1855 m = scmutil.match(repo[node2], pats, opts)
1856 ui.pager('diff')
1856 ui.pager('diff')
1857 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
1857 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
1858 listsubrepos=opts.get('subrepos'),
1858 listsubrepos=opts.get('subrepos'),
1859 root=opts.get('root'))
1859 root=opts.get('root'))
1860
1860
1861 @command('^export',
1861 @command('^export',
1862 [('o', 'output', '',
1862 [('o', 'output', '',
1863 _('print output to file with formatted name'), _('FORMAT')),
1863 _('print output to file with formatted name'), _('FORMAT')),
1864 ('', 'switch-parent', None, _('diff against the second parent')),
1864 ('', 'switch-parent', None, _('diff against the second parent')),
1865 ('r', 'rev', [], _('revisions to export'), _('REV')),
1865 ('r', 'rev', [], _('revisions to export'), _('REV')),
1866 ] + diffopts,
1866 ] + diffopts,
1867 _('[OPTION]... [-o OUTFILESPEC] [-r] [REV]...'), cmdtype=readonly)
1867 _('[OPTION]... [-o OUTFILESPEC] [-r] [REV]...'), cmdtype=readonly)
1868 def export(ui, repo, *changesets, **opts):
1868 def export(ui, repo, *changesets, **opts):
1869 """dump the header and diffs for one or more changesets
1869 """dump the header and diffs for one or more changesets
1870
1870
1871 Print the changeset header and diffs for one or more revisions.
1871 Print the changeset header and diffs for one or more revisions.
1872 If no revision is given, the parent of the working directory is used.
1872 If no revision is given, the parent of the working directory is used.
1873
1873
1874 The information shown in the changeset header is: author, date,
1874 The information shown in the changeset header is: author, date,
1875 branch name (if non-default), changeset hash, parent(s) and commit
1875 branch name (if non-default), changeset hash, parent(s) and commit
1876 comment.
1876 comment.
1877
1877
1878 .. note::
1878 .. note::
1879
1879
1880 :hg:`export` may generate unexpected diff output for merge
1880 :hg:`export` may generate unexpected diff output for merge
1881 changesets, as it will compare the merge changeset against its
1881 changesets, as it will compare the merge changeset against its
1882 first parent only.
1882 first parent only.
1883
1883
1884 Output may be to a file, in which case the name of the file is
1884 Output may be to a file, in which case the name of the file is
1885 given using a format string. The formatting rules are as follows:
1885 given using a format string. The formatting rules are as follows:
1886
1886
1887 :``%%``: literal "%" character
1887 :``%%``: literal "%" character
1888 :``%H``: changeset hash (40 hexadecimal digits)
1888 :``%H``: changeset hash (40 hexadecimal digits)
1889 :``%N``: number of patches being generated
1889 :``%N``: number of patches being generated
1890 :``%R``: changeset revision number
1890 :``%R``: changeset revision number
1891 :``%b``: basename of the exporting repository
1891 :``%b``: basename of the exporting repository
1892 :``%h``: short-form changeset hash (12 hexadecimal digits)
1892 :``%h``: short-form changeset hash (12 hexadecimal digits)
1893 :``%m``: first line of the commit message (only alphanumeric characters)
1893 :``%m``: first line of the commit message (only alphanumeric characters)
1894 :``%n``: zero-padded sequence number, starting at 1
1894 :``%n``: zero-padded sequence number, starting at 1
1895 :``%r``: zero-padded changeset revision number
1895 :``%r``: zero-padded changeset revision number
1896
1896
1897 Without the -a/--text option, export will avoid generating diffs
1897 Without the -a/--text option, export will avoid generating diffs
1898 of files it detects as binary. With -a, export will generate a
1898 of files it detects as binary. With -a, export will generate a
1899 diff anyway, probably with undesirable results.
1899 diff anyway, probably with undesirable results.
1900
1900
1901 Use the -g/--git option to generate diffs in the git extended diff
1901 Use the -g/--git option to generate diffs in the git extended diff
1902 format. See :hg:`help diffs` for more information.
1902 format. See :hg:`help diffs` for more information.
1903
1903
1904 With the --switch-parent option, the diff will be against the
1904 With the --switch-parent option, the diff will be against the
1905 second parent. It can be useful to review a merge.
1905 second parent. It can be useful to review a merge.
1906
1906
1907 .. container:: verbose
1907 .. container:: verbose
1908
1908
1909 Examples:
1909 Examples:
1910
1910
1911 - use export and import to transplant a bugfix to the current
1911 - use export and import to transplant a bugfix to the current
1912 branch::
1912 branch::
1913
1913
1914 hg export -r 9353 | hg import -
1914 hg export -r 9353 | hg import -
1915
1915
1916 - export all the changesets between two revisions to a file with
1916 - export all the changesets between two revisions to a file with
1917 rename information::
1917 rename information::
1918
1918
1919 hg export --git -r 123:150 > changes.txt
1919 hg export --git -r 123:150 > changes.txt
1920
1920
1921 - split outgoing changes into a series of patches with
1921 - split outgoing changes into a series of patches with
1922 descriptive names::
1922 descriptive names::
1923
1923
1924 hg export -r "outgoing()" -o "%n-%m.patch"
1924 hg export -r "outgoing()" -o "%n-%m.patch"
1925
1925
1926 Returns 0 on success.
1926 Returns 0 on success.
1927 """
1927 """
1928 opts = pycompat.byteskwargs(opts)
1928 opts = pycompat.byteskwargs(opts)
1929 changesets += tuple(opts.get('rev', []))
1929 changesets += tuple(opts.get('rev', []))
1930 if not changesets:
1930 if not changesets:
1931 changesets = ['.']
1931 changesets = ['.']
1932 revs = scmutil.revrange(repo, changesets)
1932 revs = scmutil.revrange(repo, changesets)
1933 if not revs:
1933 if not revs:
1934 raise error.Abort(_("export requires at least one changeset"))
1934 raise error.Abort(_("export requires at least one changeset"))
1935 if len(revs) > 1:
1935 if len(revs) > 1:
1936 ui.note(_('exporting patches:\n'))
1936 ui.note(_('exporting patches:\n'))
1937 else:
1937 else:
1938 ui.note(_('exporting patch:\n'))
1938 ui.note(_('exporting patch:\n'))
1939 ui.pager('export')
1939 ui.pager('export')
1940 cmdutil.export(repo, revs, fntemplate=opts.get('output'),
1940 cmdutil.export(repo, revs, fntemplate=opts.get('output'),
1941 switch_parent=opts.get('switch_parent'),
1941 switch_parent=opts.get('switch_parent'),
1942 opts=patch.diffallopts(ui, opts))
1942 opts=patch.diffallopts(ui, opts))
1943
1943
1944 @command('files',
1944 @command('files',
1945 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
1945 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
1946 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
1946 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
1947 ] + walkopts + formatteropts + subrepoopts,
1947 ] + walkopts + formatteropts + subrepoopts,
1948 _('[OPTION]... [FILE]...'), cmdtype=readonly)
1948 _('[OPTION]... [FILE]...'), cmdtype=readonly)
1949 def files(ui, repo, *pats, **opts):
1949 def files(ui, repo, *pats, **opts):
1950 """list tracked files
1950 """list tracked files
1951
1951
1952 Print files under Mercurial control in the working directory or
1952 Print files under Mercurial control in the working directory or
1953 specified revision for given files (excluding removed files).
1953 specified revision for given files (excluding removed files).
1954 Files can be specified as filenames or filesets.
1954 Files can be specified as filenames or filesets.
1955
1955
1956 If no files are given to match, this command prints the names
1956 If no files are given to match, this command prints the names
1957 of all files under Mercurial control.
1957 of all files under Mercurial control.
1958
1958
1959 .. container:: verbose
1959 .. container:: verbose
1960
1960
1961 Examples:
1961 Examples:
1962
1962
1963 - list all files under the current directory::
1963 - list all files under the current directory::
1964
1964
1965 hg files .
1965 hg files .
1966
1966
1967 - shows sizes and flags for current revision::
1967 - shows sizes and flags for current revision::
1968
1968
1969 hg files -vr .
1969 hg files -vr .
1970
1970
1971 - list all files named README::
1971 - list all files named README::
1972
1972
1973 hg files -I "**/README"
1973 hg files -I "**/README"
1974
1974
1975 - list all binary files::
1975 - list all binary files::
1976
1976
1977 hg files "set:binary()"
1977 hg files "set:binary()"
1978
1978
1979 - find files containing a regular expression::
1979 - find files containing a regular expression::
1980
1980
1981 hg files "set:grep('bob')"
1981 hg files "set:grep('bob')"
1982
1982
1983 - search tracked file contents with xargs and grep::
1983 - search tracked file contents with xargs and grep::
1984
1984
1985 hg files -0 | xargs -0 grep foo
1985 hg files -0 | xargs -0 grep foo
1986
1986
1987 See :hg:`help patterns` and :hg:`help filesets` for more information
1987 See :hg:`help patterns` and :hg:`help filesets` for more information
1988 on specifying file patterns.
1988 on specifying file patterns.
1989
1989
1990 Returns 0 if a match is found, 1 otherwise.
1990 Returns 0 if a match is found, 1 otherwise.
1991
1991
1992 """
1992 """
1993
1993
1994 opts = pycompat.byteskwargs(opts)
1994 opts = pycompat.byteskwargs(opts)
1995 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
1995 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
1996
1996
1997 end = '\n'
1997 end = '\n'
1998 if opts.get('print0'):
1998 if opts.get('print0'):
1999 end = '\0'
1999 end = '\0'
2000 fmt = '%s' + end
2000 fmt = '%s' + end
2001
2001
2002 m = scmutil.match(ctx, pats, opts)
2002 m = scmutil.match(ctx, pats, opts)
2003 ui.pager('files')
2003 ui.pager('files')
2004 with ui.formatter('files', opts) as fm:
2004 with ui.formatter('files', opts) as fm:
2005 return cmdutil.files(ui, ctx, m, fm, fmt, opts.get('subrepos'))
2005 return cmdutil.files(ui, ctx, m, fm, fmt, opts.get('subrepos'))
2006
2006
2007 @command('^forget', walkopts, _('[OPTION]... FILE...'), inferrepo=True)
2007 @command('^forget', walkopts, _('[OPTION]... FILE...'), inferrepo=True)
2008 def forget(ui, repo, *pats, **opts):
2008 def forget(ui, repo, *pats, **opts):
2009 """forget the specified files on the next commit
2009 """forget the specified files on the next commit
2010
2010
2011 Mark the specified files so they will no longer be tracked
2011 Mark the specified files so they will no longer be tracked
2012 after the next commit.
2012 after the next commit.
2013
2013
2014 This only removes files from the current branch, not from the
2014 This only removes files from the current branch, not from the
2015 entire project history, and it does not delete them from the
2015 entire project history, and it does not delete them from the
2016 working directory.
2016 working directory.
2017
2017
2018 To delete the file from the working directory, see :hg:`remove`.
2018 To delete the file from the working directory, see :hg:`remove`.
2019
2019
2020 To undo a forget before the next commit, see :hg:`add`.
2020 To undo a forget before the next commit, see :hg:`add`.
2021
2021
2022 .. container:: verbose
2022 .. container:: verbose
2023
2023
2024 Examples:
2024 Examples:
2025
2025
2026 - forget newly-added binary files::
2026 - forget newly-added binary files::
2027
2027
2028 hg forget "set:added() and binary()"
2028 hg forget "set:added() and binary()"
2029
2029
2030 - forget files that would be excluded by .hgignore::
2030 - forget files that would be excluded by .hgignore::
2031
2031
2032 hg forget "set:hgignore()"
2032 hg forget "set:hgignore()"
2033
2033
2034 Returns 0 on success.
2034 Returns 0 on success.
2035 """
2035 """
2036
2036
2037 opts = pycompat.byteskwargs(opts)
2037 opts = pycompat.byteskwargs(opts)
2038 if not pats:
2038 if not pats:
2039 raise error.Abort(_('no files specified'))
2039 raise error.Abort(_('no files specified'))
2040
2040
2041 m = scmutil.match(repo[None], pats, opts)
2041 m = scmutil.match(repo[None], pats, opts)
2042 rejected = cmdutil.forget(ui, repo, m, prefix="", explicitonly=False)[0]
2042 rejected = cmdutil.forget(ui, repo, m, prefix="", explicitonly=False)[0]
2043 return rejected and 1 or 0
2043 return rejected and 1 or 0
2044
2044
2045 @command(
2045 @command(
2046 'graft',
2046 'graft',
2047 [('r', 'rev', [], _('revisions to graft'), _('REV')),
2047 [('r', 'rev', [], _('revisions to graft'), _('REV')),
2048 ('c', 'continue', False, _('resume interrupted graft')),
2048 ('c', 'continue', False, _('resume interrupted graft')),
2049 ('e', 'edit', False, _('invoke editor on commit messages')),
2049 ('e', 'edit', False, _('invoke editor on commit messages')),
2050 ('', 'log', None, _('append graft info to log message')),
2050 ('', 'log', None, _('append graft info to log message')),
2051 ('f', 'force', False, _('force graft')),
2051 ('f', 'force', False, _('force graft')),
2052 ('D', 'currentdate', False,
2052 ('D', 'currentdate', False,
2053 _('record the current date as commit date')),
2053 _('record the current date as commit date')),
2054 ('U', 'currentuser', False,
2054 ('U', 'currentuser', False,
2055 _('record the current user as committer'), _('DATE'))]
2055 _('record the current user as committer'), _('DATE'))]
2056 + commitopts2 + mergetoolopts + dryrunopts,
2056 + commitopts2 + mergetoolopts + dryrunopts,
2057 _('[OPTION]... [-r REV]... REV...'))
2057 _('[OPTION]... [-r REV]... REV...'))
2058 def graft(ui, repo, *revs, **opts):
2058 def graft(ui, repo, *revs, **opts):
2059 '''copy changes from other branches onto the current branch
2059 '''copy changes from other branches onto the current branch
2060
2060
2061 This command uses Mercurial's merge logic to copy individual
2061 This command uses Mercurial's merge logic to copy individual
2062 changes from other branches without merging branches in the
2062 changes from other branches without merging branches in the
2063 history graph. This is sometimes known as 'backporting' or
2063 history graph. This is sometimes known as 'backporting' or
2064 'cherry-picking'. By default, graft will copy user, date, and
2064 'cherry-picking'. By default, graft will copy user, date, and
2065 description from the source changesets.
2065 description from the source changesets.
2066
2066
2067 Changesets that are ancestors of the current revision, that have
2067 Changesets that are ancestors of the current revision, that have
2068 already been grafted, or that are merges will be skipped.
2068 already been grafted, or that are merges will be skipped.
2069
2069
2070 If --log is specified, log messages will have a comment appended
2070 If --log is specified, log messages will have a comment appended
2071 of the form::
2071 of the form::
2072
2072
2073 (grafted from CHANGESETHASH)
2073 (grafted from CHANGESETHASH)
2074
2074
2075 If --force is specified, revisions will be grafted even if they
2075 If --force is specified, revisions will be grafted even if they
2076 are already ancestors of, or have been grafted to, the destination.
2076 are already ancestors of, or have been grafted to, the destination.
2077 This is useful when the revisions have since been backed out.
2077 This is useful when the revisions have since been backed out.
2078
2078
2079 If a graft merge results in conflicts, the graft process is
2079 If a graft merge results in conflicts, the graft process is
2080 interrupted so that the current merge can be manually resolved.
2080 interrupted so that the current merge can be manually resolved.
2081 Once all conflicts are addressed, the graft process can be
2081 Once all conflicts are addressed, the graft process can be
2082 continued with the -c/--continue option.
2082 continued with the -c/--continue option.
2083
2083
2084 .. note::
2084 .. note::
2085
2085
2086 The -c/--continue option does not reapply earlier options, except
2086 The -c/--continue option does not reapply earlier options, except
2087 for --force.
2087 for --force.
2088
2088
2089 .. container:: verbose
2089 .. container:: verbose
2090
2090
2091 Examples:
2091 Examples:
2092
2092
2093 - copy a single change to the stable branch and edit its description::
2093 - copy a single change to the stable branch and edit its description::
2094
2094
2095 hg update stable
2095 hg update stable
2096 hg graft --edit 9393
2096 hg graft --edit 9393
2097
2097
2098 - graft a range of changesets with one exception, updating dates::
2098 - graft a range of changesets with one exception, updating dates::
2099
2099
2100 hg graft -D "2085::2093 and not 2091"
2100 hg graft -D "2085::2093 and not 2091"
2101
2101
2102 - continue a graft after resolving conflicts::
2102 - continue a graft after resolving conflicts::
2103
2103
2104 hg graft -c
2104 hg graft -c
2105
2105
2106 - show the source of a grafted changeset::
2106 - show the source of a grafted changeset::
2107
2107
2108 hg log --debug -r .
2108 hg log --debug -r .
2109
2109
2110 - show revisions sorted by date::
2110 - show revisions sorted by date::
2111
2111
2112 hg log -r "sort(all(), date)"
2112 hg log -r "sort(all(), date)"
2113
2113
2114 See :hg:`help revisions` for more about specifying revisions.
2114 See :hg:`help revisions` for more about specifying revisions.
2115
2115
2116 Returns 0 on successful completion.
2116 Returns 0 on successful completion.
2117 '''
2117 '''
2118 with repo.wlock():
2118 with repo.wlock():
2119 return _dograft(ui, repo, *revs, **opts)
2119 return _dograft(ui, repo, *revs, **opts)
2120
2120
2121 def _dograft(ui, repo, *revs, **opts):
2121 def _dograft(ui, repo, *revs, **opts):
2122 opts = pycompat.byteskwargs(opts)
2122 opts = pycompat.byteskwargs(opts)
2123 if revs and opts.get('rev'):
2123 if revs and opts.get('rev'):
2124 ui.warn(_('warning: inconsistent use of --rev might give unexpected '
2124 ui.warn(_('warning: inconsistent use of --rev might give unexpected '
2125 'revision ordering!\n'))
2125 'revision ordering!\n'))
2126
2126
2127 revs = list(revs)
2127 revs = list(revs)
2128 revs.extend(opts.get('rev'))
2128 revs.extend(opts.get('rev'))
2129
2129
2130 if not opts.get('user') and opts.get('currentuser'):
2130 if not opts.get('user') and opts.get('currentuser'):
2131 opts['user'] = ui.username()
2131 opts['user'] = ui.username()
2132 if not opts.get('date') and opts.get('currentdate'):
2132 if not opts.get('date') and opts.get('currentdate'):
2133 opts['date'] = "%d %d" % util.makedate()
2133 opts['date'] = "%d %d" % util.makedate()
2134
2134
2135 editor = cmdutil.getcommiteditor(editform='graft',
2135 editor = cmdutil.getcommiteditor(editform='graft',
2136 **pycompat.strkwargs(opts))
2136 **pycompat.strkwargs(opts))
2137
2137
2138 cont = False
2138 cont = False
2139 if opts.get('continue'):
2139 if opts.get('continue'):
2140 cont = True
2140 cont = True
2141 if revs:
2141 if revs:
2142 raise error.Abort(_("can't specify --continue and revisions"))
2142 raise error.Abort(_("can't specify --continue and revisions"))
2143 # read in unfinished revisions
2143 # read in unfinished revisions
2144 try:
2144 try:
2145 nodes = repo.vfs.read('graftstate').splitlines()
2145 nodes = repo.vfs.read('graftstate').splitlines()
2146 revs = [repo[node].rev() for node in nodes]
2146 revs = [repo[node].rev() for node in nodes]
2147 except IOError as inst:
2147 except IOError as inst:
2148 if inst.errno != errno.ENOENT:
2148 if inst.errno != errno.ENOENT:
2149 raise
2149 raise
2150 cmdutil.wrongtooltocontinue(repo, _('graft'))
2150 cmdutil.wrongtooltocontinue(repo, _('graft'))
2151 else:
2151 else:
2152 cmdutil.checkunfinished(repo)
2152 cmdutil.checkunfinished(repo)
2153 cmdutil.bailifchanged(repo)
2153 cmdutil.bailifchanged(repo)
2154 if not revs:
2154 if not revs:
2155 raise error.Abort(_('no revisions specified'))
2155 raise error.Abort(_('no revisions specified'))
2156 revs = scmutil.revrange(repo, revs)
2156 revs = scmutil.revrange(repo, revs)
2157
2157
2158 skipped = set()
2158 skipped = set()
2159 # check for merges
2159 # check for merges
2160 for rev in repo.revs('%ld and merge()', revs):
2160 for rev in repo.revs('%ld and merge()', revs):
2161 ui.warn(_('skipping ungraftable merge revision %d\n') % rev)
2161 ui.warn(_('skipping ungraftable merge revision %d\n') % rev)
2162 skipped.add(rev)
2162 skipped.add(rev)
2163 revs = [r for r in revs if r not in skipped]
2163 revs = [r for r in revs if r not in skipped]
2164 if not revs:
2164 if not revs:
2165 return -1
2165 return -1
2166
2166
2167 # Don't check in the --continue case, in effect retaining --force across
2167 # Don't check in the --continue case, in effect retaining --force across
2168 # --continues. That's because without --force, any revisions we decided to
2168 # --continues. That's because without --force, any revisions we decided to
2169 # skip would have been filtered out here, so they wouldn't have made their
2169 # skip would have been filtered out here, so they wouldn't have made their
2170 # way to the graftstate. With --force, any revisions we would have otherwise
2170 # way to the graftstate. With --force, any revisions we would have otherwise
2171 # skipped would not have been filtered out, and if they hadn't been applied
2171 # skipped would not have been filtered out, and if they hadn't been applied
2172 # already, they'd have been in the graftstate.
2172 # already, they'd have been in the graftstate.
2173 if not (cont or opts.get('force')):
2173 if not (cont or opts.get('force')):
2174 # check for ancestors of dest branch
2174 # check for ancestors of dest branch
2175 crev = repo['.'].rev()
2175 crev = repo['.'].rev()
2176 ancestors = repo.changelog.ancestors([crev], inclusive=True)
2176 ancestors = repo.changelog.ancestors([crev], inclusive=True)
2177 # XXX make this lazy in the future
2177 # XXX make this lazy in the future
2178 # don't mutate while iterating, create a copy
2178 # don't mutate while iterating, create a copy
2179 for rev in list(revs):
2179 for rev in list(revs):
2180 if rev in ancestors:
2180 if rev in ancestors:
2181 ui.warn(_('skipping ancestor revision %d:%s\n') %
2181 ui.warn(_('skipping ancestor revision %d:%s\n') %
2182 (rev, repo[rev]))
2182 (rev, repo[rev]))
2183 # XXX remove on list is slow
2183 # XXX remove on list is slow
2184 revs.remove(rev)
2184 revs.remove(rev)
2185 if not revs:
2185 if not revs:
2186 return -1
2186 return -1
2187
2187
2188 # analyze revs for earlier grafts
2188 # analyze revs for earlier grafts
2189 ids = {}
2189 ids = {}
2190 for ctx in repo.set("%ld", revs):
2190 for ctx in repo.set("%ld", revs):
2191 ids[ctx.hex()] = ctx.rev()
2191 ids[ctx.hex()] = ctx.rev()
2192 n = ctx.extra().get('source')
2192 n = ctx.extra().get('source')
2193 if n:
2193 if n:
2194 ids[n] = ctx.rev()
2194 ids[n] = ctx.rev()
2195
2195
2196 # check ancestors for earlier grafts
2196 # check ancestors for earlier grafts
2197 ui.debug('scanning for duplicate grafts\n')
2197 ui.debug('scanning for duplicate grafts\n')
2198
2198
2199 # The only changesets we can be sure doesn't contain grafts of any
2199 # The only changesets we can be sure doesn't contain grafts of any
2200 # revs, are the ones that are common ancestors of *all* revs:
2200 # revs, are the ones that are common ancestors of *all* revs:
2201 for rev in repo.revs('only(%d,ancestor(%ld))', crev, revs):
2201 for rev in repo.revs('only(%d,ancestor(%ld))', crev, revs):
2202 ctx = repo[rev]
2202 ctx = repo[rev]
2203 n = ctx.extra().get('source')
2203 n = ctx.extra().get('source')
2204 if n in ids:
2204 if n in ids:
2205 try:
2205 try:
2206 r = repo[n].rev()
2206 r = repo[n].rev()
2207 except error.RepoLookupError:
2207 except error.RepoLookupError:
2208 r = None
2208 r = None
2209 if r in revs:
2209 if r in revs:
2210 ui.warn(_('skipping revision %d:%s '
2210 ui.warn(_('skipping revision %d:%s '
2211 '(already grafted to %d:%s)\n')
2211 '(already grafted to %d:%s)\n')
2212 % (r, repo[r], rev, ctx))
2212 % (r, repo[r], rev, ctx))
2213 revs.remove(r)
2213 revs.remove(r)
2214 elif ids[n] in revs:
2214 elif ids[n] in revs:
2215 if r is None:
2215 if r is None:
2216 ui.warn(_('skipping already grafted revision %d:%s '
2216 ui.warn(_('skipping already grafted revision %d:%s '
2217 '(%d:%s also has unknown origin %s)\n')
2217 '(%d:%s also has unknown origin %s)\n')
2218 % (ids[n], repo[ids[n]], rev, ctx, n[:12]))
2218 % (ids[n], repo[ids[n]], rev, ctx, n[:12]))
2219 else:
2219 else:
2220 ui.warn(_('skipping already grafted revision %d:%s '
2220 ui.warn(_('skipping already grafted revision %d:%s '
2221 '(%d:%s also has origin %d:%s)\n')
2221 '(%d:%s also has origin %d:%s)\n')
2222 % (ids[n], repo[ids[n]], rev, ctx, r, n[:12]))
2222 % (ids[n], repo[ids[n]], rev, ctx, r, n[:12]))
2223 revs.remove(ids[n])
2223 revs.remove(ids[n])
2224 elif ctx.hex() in ids:
2224 elif ctx.hex() in ids:
2225 r = ids[ctx.hex()]
2225 r = ids[ctx.hex()]
2226 ui.warn(_('skipping already grafted revision %d:%s '
2226 ui.warn(_('skipping already grafted revision %d:%s '
2227 '(was grafted from %d:%s)\n') %
2227 '(was grafted from %d:%s)\n') %
2228 (r, repo[r], rev, ctx))
2228 (r, repo[r], rev, ctx))
2229 revs.remove(r)
2229 revs.remove(r)
2230 if not revs:
2230 if not revs:
2231 return -1
2231 return -1
2232
2232
2233 for pos, ctx in enumerate(repo.set("%ld", revs)):
2233 for pos, ctx in enumerate(repo.set("%ld", revs)):
2234 desc = '%d:%s "%s"' % (ctx.rev(), ctx,
2234 desc = '%d:%s "%s"' % (ctx.rev(), ctx,
2235 ctx.description().split('\n', 1)[0])
2235 ctx.description().split('\n', 1)[0])
2236 names = repo.nodetags(ctx.node()) + repo.nodebookmarks(ctx.node())
2236 names = repo.nodetags(ctx.node()) + repo.nodebookmarks(ctx.node())
2237 if names:
2237 if names:
2238 desc += ' (%s)' % ' '.join(names)
2238 desc += ' (%s)' % ' '.join(names)
2239 ui.status(_('grafting %s\n') % desc)
2239 ui.status(_('grafting %s\n') % desc)
2240 if opts.get('dry_run'):
2240 if opts.get('dry_run'):
2241 continue
2241 continue
2242
2242
2243 source = ctx.extra().get('source')
2243 source = ctx.extra().get('source')
2244 extra = {}
2244 extra = {}
2245 if source:
2245 if source:
2246 extra['source'] = source
2246 extra['source'] = source
2247 extra['intermediate-source'] = ctx.hex()
2247 extra['intermediate-source'] = ctx.hex()
2248 else:
2248 else:
2249 extra['source'] = ctx.hex()
2249 extra['source'] = ctx.hex()
2250 user = ctx.user()
2250 user = ctx.user()
2251 if opts.get('user'):
2251 if opts.get('user'):
2252 user = opts['user']
2252 user = opts['user']
2253 date = ctx.date()
2253 date = ctx.date()
2254 if opts.get('date'):
2254 if opts.get('date'):
2255 date = opts['date']
2255 date = opts['date']
2256 message = ctx.description()
2256 message = ctx.description()
2257 if opts.get('log'):
2257 if opts.get('log'):
2258 message += '\n(grafted from %s)' % ctx.hex()
2258 message += '\n(grafted from %s)' % ctx.hex()
2259
2259
2260 # we don't merge the first commit when continuing
2260 # we don't merge the first commit when continuing
2261 if not cont:
2261 if not cont:
2262 # perform the graft merge with p1(rev) as 'ancestor'
2262 # perform the graft merge with p1(rev) as 'ancestor'
2263 try:
2263 try:
2264 # ui.forcemerge is an internal variable, do not document
2264 # ui.forcemerge is an internal variable, do not document
2265 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
2265 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
2266 'graft')
2266 'graft')
2267 stats = mergemod.graft(repo, ctx, ctx.p1(),
2267 stats = mergemod.graft(repo, ctx, ctx.p1(),
2268 ['local', 'graft'])
2268 ['local', 'graft'])
2269 finally:
2269 finally:
2270 repo.ui.setconfig('ui', 'forcemerge', '', 'graft')
2270 repo.ui.setconfig('ui', 'forcemerge', '', 'graft')
2271 # report any conflicts
2271 # report any conflicts
2272 if stats and stats[3] > 0:
2272 if stats and stats[3] > 0:
2273 # write out state for --continue
2273 # write out state for --continue
2274 nodelines = [repo[rev].hex() + "\n" for rev in revs[pos:]]
2274 nodelines = [repo[rev].hex() + "\n" for rev in revs[pos:]]
2275 repo.vfs.write('graftstate', ''.join(nodelines))
2275 repo.vfs.write('graftstate', ''.join(nodelines))
2276 extra = ''
2276 extra = ''
2277 if opts.get('user'):
2277 if opts.get('user'):
2278 extra += ' --user %s' % util.shellquote(opts['user'])
2278 extra += ' --user %s' % util.shellquote(opts['user'])
2279 if opts.get('date'):
2279 if opts.get('date'):
2280 extra += ' --date %s' % util.shellquote(opts['date'])
2280 extra += ' --date %s' % util.shellquote(opts['date'])
2281 if opts.get('log'):
2281 if opts.get('log'):
2282 extra += ' --log'
2282 extra += ' --log'
2283 hint=_("use 'hg resolve' and 'hg graft --continue%s'") % extra
2283 hint=_("use 'hg resolve' and 'hg graft --continue%s'") % extra
2284 raise error.Abort(
2284 raise error.Abort(
2285 _("unresolved conflicts, can't continue"),
2285 _("unresolved conflicts, can't continue"),
2286 hint=hint)
2286 hint=hint)
2287 else:
2287 else:
2288 cont = False
2288 cont = False
2289
2289
2290 # commit
2290 # commit
2291 node = repo.commit(text=message, user=user,
2291 node = repo.commit(text=message, user=user,
2292 date=date, extra=extra, editor=editor)
2292 date=date, extra=extra, editor=editor)
2293 if node is None:
2293 if node is None:
2294 ui.warn(
2294 ui.warn(
2295 _('note: graft of %d:%s created no changes to commit\n') %
2295 _('note: graft of %d:%s created no changes to commit\n') %
2296 (ctx.rev(), ctx))
2296 (ctx.rev(), ctx))
2297
2297
2298 # remove state when we complete successfully
2298 # remove state when we complete successfully
2299 if not opts.get('dry_run'):
2299 if not opts.get('dry_run'):
2300 repo.vfs.unlinkpath('graftstate', ignoremissing=True)
2300 repo.vfs.unlinkpath('graftstate', ignoremissing=True)
2301
2301
2302 return 0
2302 return 0
2303
2303
2304 @command('grep',
2304 @command('grep',
2305 [('0', 'print0', None, _('end fields with NUL')),
2305 [('0', 'print0', None, _('end fields with NUL')),
2306 ('', 'all', None, _('print all revisions that match')),
2306 ('', 'all', None, _('print all revisions that match')),
2307 ('a', 'text', None, _('treat all files as text')),
2307 ('a', 'text', None, _('treat all files as text')),
2308 ('f', 'follow', None,
2308 ('f', 'follow', None,
2309 _('follow changeset history,'
2309 _('follow changeset history,'
2310 ' or file history across copies and renames')),
2310 ' or file history across copies and renames')),
2311 ('i', 'ignore-case', None, _('ignore case when matching')),
2311 ('i', 'ignore-case', None, _('ignore case when matching')),
2312 ('l', 'files-with-matches', None,
2312 ('l', 'files-with-matches', None,
2313 _('print only filenames and revisions that match')),
2313 _('print only filenames and revisions that match')),
2314 ('n', 'line-number', None, _('print matching line numbers')),
2314 ('n', 'line-number', None, _('print matching line numbers')),
2315 ('r', 'rev', [],
2315 ('r', 'rev', [],
2316 _('only search files changed within revision range'), _('REV')),
2316 _('only search files changed within revision range'), _('REV')),
2317 ('u', 'user', None, _('list the author (long with -v)')),
2317 ('u', 'user', None, _('list the author (long with -v)')),
2318 ('d', 'date', None, _('list the date (short with -q)')),
2318 ('d', 'date', None, _('list the date (short with -q)')),
2319 ] + formatteropts + walkopts,
2319 ] + formatteropts + walkopts,
2320 _('[OPTION]... PATTERN [FILE]...'),
2320 _('[OPTION]... PATTERN [FILE]...'),
2321 inferrepo=True, cmdtype=readonly)
2321 inferrepo=True, cmdtype=readonly)
2322 def grep(ui, repo, pattern, *pats, **opts):
2322 def grep(ui, repo, pattern, *pats, **opts):
2323 """search revision history for a pattern in specified files
2323 """search revision history for a pattern in specified files
2324
2324
2325 Search revision history for a regular expression in the specified
2325 Search revision history for a regular expression in the specified
2326 files or the entire project.
2326 files or the entire project.
2327
2327
2328 By default, grep prints the most recent revision number for each
2328 By default, grep prints the most recent revision number for each
2329 file in which it finds a match. To get it to print every revision
2329 file in which it finds a match. To get it to print every revision
2330 that contains a change in match status ("-" for a match that becomes
2330 that contains a change in match status ("-" for a match that becomes
2331 a non-match, or "+" for a non-match that becomes a match), use the
2331 a non-match, or "+" for a non-match that becomes a match), use the
2332 --all flag.
2332 --all flag.
2333
2333
2334 PATTERN can be any Python (roughly Perl-compatible) regular
2334 PATTERN can be any Python (roughly Perl-compatible) regular
2335 expression.
2335 expression.
2336
2336
2337 If no FILEs are specified (and -f/--follow isn't set), all files in
2337 If no FILEs are specified (and -f/--follow isn't set), all files in
2338 the repository are searched, including those that don't exist in the
2338 the repository are searched, including those that don't exist in the
2339 current branch or have been deleted in a prior changeset.
2339 current branch or have been deleted in a prior changeset.
2340
2340
2341 Returns 0 if a match is found, 1 otherwise.
2341 Returns 0 if a match is found, 1 otherwise.
2342 """
2342 """
2343 opts = pycompat.byteskwargs(opts)
2343 opts = pycompat.byteskwargs(opts)
2344 reflags = re.M
2344 reflags = re.M
2345 if opts.get('ignore_case'):
2345 if opts.get('ignore_case'):
2346 reflags |= re.I
2346 reflags |= re.I
2347 try:
2347 try:
2348 regexp = util.re.compile(pattern, reflags)
2348 regexp = util.re.compile(pattern, reflags)
2349 except re.error as inst:
2349 except re.error as inst:
2350 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
2350 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
2351 return 1
2351 return 1
2352 sep, eol = ':', '\n'
2352 sep, eol = ':', '\n'
2353 if opts.get('print0'):
2353 if opts.get('print0'):
2354 sep = eol = '\0'
2354 sep = eol = '\0'
2355
2355
2356 getfile = util.lrucachefunc(repo.file)
2356 getfile = util.lrucachefunc(repo.file)
2357
2357
2358 def matchlines(body):
2358 def matchlines(body):
2359 begin = 0
2359 begin = 0
2360 linenum = 0
2360 linenum = 0
2361 while begin < len(body):
2361 while begin < len(body):
2362 match = regexp.search(body, begin)
2362 match = regexp.search(body, begin)
2363 if not match:
2363 if not match:
2364 break
2364 break
2365 mstart, mend = match.span()
2365 mstart, mend = match.span()
2366 linenum += body.count('\n', begin, mstart) + 1
2366 linenum += body.count('\n', begin, mstart) + 1
2367 lstart = body.rfind('\n', begin, mstart) + 1 or begin
2367 lstart = body.rfind('\n', begin, mstart) + 1 or begin
2368 begin = body.find('\n', mend) + 1 or len(body) + 1
2368 begin = body.find('\n', mend) + 1 or len(body) + 1
2369 lend = begin - 1
2369 lend = begin - 1
2370 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
2370 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
2371
2371
2372 class linestate(object):
2372 class linestate(object):
2373 def __init__(self, line, linenum, colstart, colend):
2373 def __init__(self, line, linenum, colstart, colend):
2374 self.line = line
2374 self.line = line
2375 self.linenum = linenum
2375 self.linenum = linenum
2376 self.colstart = colstart
2376 self.colstart = colstart
2377 self.colend = colend
2377 self.colend = colend
2378
2378
2379 def __hash__(self):
2379 def __hash__(self):
2380 return hash((self.linenum, self.line))
2380 return hash((self.linenum, self.line))
2381
2381
2382 def __eq__(self, other):
2382 def __eq__(self, other):
2383 return self.line == other.line
2383 return self.line == other.line
2384
2384
2385 def findpos(self):
2385 def findpos(self):
2386 """Iterate all (start, end) indices of matches"""
2386 """Iterate all (start, end) indices of matches"""
2387 yield self.colstart, self.colend
2387 yield self.colstart, self.colend
2388 p = self.colend
2388 p = self.colend
2389 while p < len(self.line):
2389 while p < len(self.line):
2390 m = regexp.search(self.line, p)
2390 m = regexp.search(self.line, p)
2391 if not m:
2391 if not m:
2392 break
2392 break
2393 yield m.span()
2393 yield m.span()
2394 p = m.end()
2394 p = m.end()
2395
2395
2396 matches = {}
2396 matches = {}
2397 copies = {}
2397 copies = {}
2398 def grepbody(fn, rev, body):
2398 def grepbody(fn, rev, body):
2399 matches[rev].setdefault(fn, [])
2399 matches[rev].setdefault(fn, [])
2400 m = matches[rev][fn]
2400 m = matches[rev][fn]
2401 for lnum, cstart, cend, line in matchlines(body):
2401 for lnum, cstart, cend, line in matchlines(body):
2402 s = linestate(line, lnum, cstart, cend)
2402 s = linestate(line, lnum, cstart, cend)
2403 m.append(s)
2403 m.append(s)
2404
2404
2405 def difflinestates(a, b):
2405 def difflinestates(a, b):
2406 sm = difflib.SequenceMatcher(None, a, b)
2406 sm = difflib.SequenceMatcher(None, a, b)
2407 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
2407 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
2408 if tag == 'insert':
2408 if tag == 'insert':
2409 for i in xrange(blo, bhi):
2409 for i in xrange(blo, bhi):
2410 yield ('+', b[i])
2410 yield ('+', b[i])
2411 elif tag == 'delete':
2411 elif tag == 'delete':
2412 for i in xrange(alo, ahi):
2412 for i in xrange(alo, ahi):
2413 yield ('-', a[i])
2413 yield ('-', a[i])
2414 elif tag == 'replace':
2414 elif tag == 'replace':
2415 for i in xrange(alo, ahi):
2415 for i in xrange(alo, ahi):
2416 yield ('-', a[i])
2416 yield ('-', a[i])
2417 for i in xrange(blo, bhi):
2417 for i in xrange(blo, bhi):
2418 yield ('+', b[i])
2418 yield ('+', b[i])
2419
2419
2420 def display(fm, fn, ctx, pstates, states):
2420 def display(fm, fn, ctx, pstates, states):
2421 rev = ctx.rev()
2421 rev = ctx.rev()
2422 if fm.isplain():
2422 if fm.isplain():
2423 formatuser = ui.shortuser
2423 formatuser = ui.shortuser
2424 else:
2424 else:
2425 formatuser = str
2425 formatuser = str
2426 if ui.quiet:
2426 if ui.quiet:
2427 datefmt = '%Y-%m-%d'
2427 datefmt = '%Y-%m-%d'
2428 else:
2428 else:
2429 datefmt = '%a %b %d %H:%M:%S %Y %1%2'
2429 datefmt = '%a %b %d %H:%M:%S %Y %1%2'
2430 found = False
2430 found = False
2431 @util.cachefunc
2431 @util.cachefunc
2432 def binary():
2432 def binary():
2433 flog = getfile(fn)
2433 flog = getfile(fn)
2434 return util.binary(flog.read(ctx.filenode(fn)))
2434 return util.binary(flog.read(ctx.filenode(fn)))
2435
2435
2436 fieldnamemap = {'filename': 'file', 'linenumber': 'line_number'}
2436 fieldnamemap = {'filename': 'file', 'linenumber': 'line_number'}
2437 if opts.get('all'):
2437 if opts.get('all'):
2438 iter = difflinestates(pstates, states)
2438 iter = difflinestates(pstates, states)
2439 else:
2439 else:
2440 iter = [('', l) for l in states]
2440 iter = [('', l) for l in states]
2441 for change, l in iter:
2441 for change, l in iter:
2442 fm.startitem()
2442 fm.startitem()
2443 fm.data(node=fm.hexfunc(ctx.node()))
2443 fm.data(node=fm.hexfunc(ctx.node()))
2444 cols = [
2444 cols = [
2445 ('filename', fn, True),
2445 ('filename', fn, True),
2446 ('rev', rev, True),
2446 ('rev', rev, True),
2447 ('linenumber', l.linenum, opts.get('line_number')),
2447 ('linenumber', l.linenum, opts.get('line_number')),
2448 ]
2448 ]
2449 if opts.get('all'):
2449 if opts.get('all'):
2450 cols.append(('change', change, True))
2450 cols.append(('change', change, True))
2451 cols.extend([
2451 cols.extend([
2452 ('user', formatuser(ctx.user()), opts.get('user')),
2452 ('user', formatuser(ctx.user()), opts.get('user')),
2453 ('date', fm.formatdate(ctx.date(), datefmt), opts.get('date')),
2453 ('date', fm.formatdate(ctx.date(), datefmt), opts.get('date')),
2454 ])
2454 ])
2455 lastcol = next(name for name, data, cond in reversed(cols) if cond)
2455 lastcol = next(name for name, data, cond in reversed(cols) if cond)
2456 for name, data, cond in cols:
2456 for name, data, cond in cols:
2457 field = fieldnamemap.get(name, name)
2457 field = fieldnamemap.get(name, name)
2458 fm.condwrite(cond, field, '%s', data, label='grep.%s' % name)
2458 fm.condwrite(cond, field, '%s', data, label='grep.%s' % name)
2459 if cond and name != lastcol:
2459 if cond and name != lastcol:
2460 fm.plain(sep, label='grep.sep')
2460 fm.plain(sep, label='grep.sep')
2461 if not opts.get('files_with_matches'):
2461 if not opts.get('files_with_matches'):
2462 fm.plain(sep, label='grep.sep')
2462 fm.plain(sep, label='grep.sep')
2463 if not opts.get('text') and binary():
2463 if not opts.get('text') and binary():
2464 fm.plain(_(" Binary file matches"))
2464 fm.plain(_(" Binary file matches"))
2465 else:
2465 else:
2466 displaymatches(fm.nested('texts'), l)
2466 displaymatches(fm.nested('texts'), l)
2467 fm.plain(eol)
2467 fm.plain(eol)
2468 found = True
2468 found = True
2469 if opts.get('files_with_matches'):
2469 if opts.get('files_with_matches'):
2470 break
2470 break
2471 return found
2471 return found
2472
2472
2473 def displaymatches(fm, l):
2473 def displaymatches(fm, l):
2474 p = 0
2474 p = 0
2475 for s, e in l.findpos():
2475 for s, e in l.findpos():
2476 if p < s:
2476 if p < s:
2477 fm.startitem()
2477 fm.startitem()
2478 fm.write('text', '%s', l.line[p:s])
2478 fm.write('text', '%s', l.line[p:s])
2479 fm.data(matched=False)
2479 fm.data(matched=False)
2480 fm.startitem()
2480 fm.startitem()
2481 fm.write('text', '%s', l.line[s:e], label='grep.match')
2481 fm.write('text', '%s', l.line[s:e], label='grep.match')
2482 fm.data(matched=True)
2482 fm.data(matched=True)
2483 p = e
2483 p = e
2484 if p < len(l.line):
2484 if p < len(l.line):
2485 fm.startitem()
2485 fm.startitem()
2486 fm.write('text', '%s', l.line[p:])
2486 fm.write('text', '%s', l.line[p:])
2487 fm.data(matched=False)
2487 fm.data(matched=False)
2488 fm.end()
2488 fm.end()
2489
2489
2490 skip = {}
2490 skip = {}
2491 revfiles = {}
2491 revfiles = {}
2492 match = scmutil.match(repo[None], pats, opts)
2492 match = scmutil.match(repo[None], pats, opts)
2493 found = False
2493 found = False
2494 follow = opts.get('follow')
2494 follow = opts.get('follow')
2495
2495
2496 def prep(ctx, fns):
2496 def prep(ctx, fns):
2497 rev = ctx.rev()
2497 rev = ctx.rev()
2498 pctx = ctx.p1()
2498 pctx = ctx.p1()
2499 parent = pctx.rev()
2499 parent = pctx.rev()
2500 matches.setdefault(rev, {})
2500 matches.setdefault(rev, {})
2501 matches.setdefault(parent, {})
2501 matches.setdefault(parent, {})
2502 files = revfiles.setdefault(rev, [])
2502 files = revfiles.setdefault(rev, [])
2503 for fn in fns:
2503 for fn in fns:
2504 flog = getfile(fn)
2504 flog = getfile(fn)
2505 try:
2505 try:
2506 fnode = ctx.filenode(fn)
2506 fnode = ctx.filenode(fn)
2507 except error.LookupError:
2507 except error.LookupError:
2508 continue
2508 continue
2509
2509
2510 copied = flog.renamed(fnode)
2510 copied = flog.renamed(fnode)
2511 copy = follow and copied and copied[0]
2511 copy = follow and copied and copied[0]
2512 if copy:
2512 if copy:
2513 copies.setdefault(rev, {})[fn] = copy
2513 copies.setdefault(rev, {})[fn] = copy
2514 if fn in skip:
2514 if fn in skip:
2515 if copy:
2515 if copy:
2516 skip[copy] = True
2516 skip[copy] = True
2517 continue
2517 continue
2518 files.append(fn)
2518 files.append(fn)
2519
2519
2520 if fn not in matches[rev]:
2520 if fn not in matches[rev]:
2521 grepbody(fn, rev, flog.read(fnode))
2521 grepbody(fn, rev, flog.read(fnode))
2522
2522
2523 pfn = copy or fn
2523 pfn = copy or fn
2524 if pfn not in matches[parent]:
2524 if pfn not in matches[parent]:
2525 try:
2525 try:
2526 fnode = pctx.filenode(pfn)
2526 fnode = pctx.filenode(pfn)
2527 grepbody(pfn, parent, flog.read(fnode))
2527 grepbody(pfn, parent, flog.read(fnode))
2528 except error.LookupError:
2528 except error.LookupError:
2529 pass
2529 pass
2530
2530
2531 ui.pager('grep')
2531 ui.pager('grep')
2532 fm = ui.formatter('grep', opts)
2532 fm = ui.formatter('grep', opts)
2533 for ctx in cmdutil.walkchangerevs(repo, match, opts, prep):
2533 for ctx in cmdutil.walkchangerevs(repo, match, opts, prep):
2534 rev = ctx.rev()
2534 rev = ctx.rev()
2535 parent = ctx.p1().rev()
2535 parent = ctx.p1().rev()
2536 for fn in sorted(revfiles.get(rev, [])):
2536 for fn in sorted(revfiles.get(rev, [])):
2537 states = matches[rev][fn]
2537 states = matches[rev][fn]
2538 copy = copies.get(rev, {}).get(fn)
2538 copy = copies.get(rev, {}).get(fn)
2539 if fn in skip:
2539 if fn in skip:
2540 if copy:
2540 if copy:
2541 skip[copy] = True
2541 skip[copy] = True
2542 continue
2542 continue
2543 pstates = matches.get(parent, {}).get(copy or fn, [])
2543 pstates = matches.get(parent, {}).get(copy or fn, [])
2544 if pstates or states:
2544 if pstates or states:
2545 r = display(fm, fn, ctx, pstates, states)
2545 r = display(fm, fn, ctx, pstates, states)
2546 found = found or r
2546 found = found or r
2547 if r and not opts.get('all'):
2547 if r and not opts.get('all'):
2548 skip[fn] = True
2548 skip[fn] = True
2549 if copy:
2549 if copy:
2550 skip[copy] = True
2550 skip[copy] = True
2551 del matches[rev]
2551 del matches[rev]
2552 del revfiles[rev]
2552 del revfiles[rev]
2553 fm.end()
2553 fm.end()
2554
2554
2555 return not found
2555 return not found
2556
2556
2557 @command('heads',
2557 @command('heads',
2558 [('r', 'rev', '',
2558 [('r', 'rev', '',
2559 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
2559 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
2560 ('t', 'topo', False, _('show topological heads only')),
2560 ('t', 'topo', False, _('show topological heads only')),
2561 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
2561 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
2562 ('c', 'closed', False, _('show normal and closed branch heads')),
2562 ('c', 'closed', False, _('show normal and closed branch heads')),
2563 ] + templateopts,
2563 ] + templateopts,
2564 _('[-ct] [-r STARTREV] [REV]...'), cmdtype=readonly)
2564 _('[-ct] [-r STARTREV] [REV]...'), cmdtype=readonly)
2565 def heads(ui, repo, *branchrevs, **opts):
2565 def heads(ui, repo, *branchrevs, **opts):
2566 """show branch heads
2566 """show branch heads
2567
2567
2568 With no arguments, show all open branch heads in the repository.
2568 With no arguments, show all open branch heads in the repository.
2569 Branch heads are changesets that have no descendants on the
2569 Branch heads are changesets that have no descendants on the
2570 same branch. They are where development generally takes place and
2570 same branch. They are where development generally takes place and
2571 are the usual targets for update and merge operations.
2571 are the usual targets for update and merge operations.
2572
2572
2573 If one or more REVs are given, only open branch heads on the
2573 If one or more REVs are given, only open branch heads on the
2574 branches associated with the specified changesets are shown. This
2574 branches associated with the specified changesets are shown. This
2575 means that you can use :hg:`heads .` to see the heads on the
2575 means that you can use :hg:`heads .` to see the heads on the
2576 currently checked-out branch.
2576 currently checked-out branch.
2577
2577
2578 If -c/--closed is specified, also show branch heads marked closed
2578 If -c/--closed is specified, also show branch heads marked closed
2579 (see :hg:`commit --close-branch`).
2579 (see :hg:`commit --close-branch`).
2580
2580
2581 If STARTREV is specified, only those heads that are descendants of
2581 If STARTREV is specified, only those heads that are descendants of
2582 STARTREV will be displayed.
2582 STARTREV will be displayed.
2583
2583
2584 If -t/--topo is specified, named branch mechanics will be ignored and only
2584 If -t/--topo is specified, named branch mechanics will be ignored and only
2585 topological heads (changesets with no children) will be shown.
2585 topological heads (changesets with no children) will be shown.
2586
2586
2587 Returns 0 if matching heads are found, 1 if not.
2587 Returns 0 if matching heads are found, 1 if not.
2588 """
2588 """
2589
2589
2590 opts = pycompat.byteskwargs(opts)
2590 opts = pycompat.byteskwargs(opts)
2591 start = None
2591 start = None
2592 if 'rev' in opts:
2592 if 'rev' in opts:
2593 start = scmutil.revsingle(repo, opts['rev'], None).node()
2593 start = scmutil.revsingle(repo, opts['rev'], None).node()
2594
2594
2595 if opts.get('topo'):
2595 if opts.get('topo'):
2596 heads = [repo[h] for h in repo.heads(start)]
2596 heads = [repo[h] for h in repo.heads(start)]
2597 else:
2597 else:
2598 heads = []
2598 heads = []
2599 for branch in repo.branchmap():
2599 for branch in repo.branchmap():
2600 heads += repo.branchheads(branch, start, opts.get('closed'))
2600 heads += repo.branchheads(branch, start, opts.get('closed'))
2601 heads = [repo[h] for h in heads]
2601 heads = [repo[h] for h in heads]
2602
2602
2603 if branchrevs:
2603 if branchrevs:
2604 branches = set(repo[br].branch() for br in branchrevs)
2604 branches = set(repo[br].branch() for br in branchrevs)
2605 heads = [h for h in heads if h.branch() in branches]
2605 heads = [h for h in heads if h.branch() in branches]
2606
2606
2607 if opts.get('active') and branchrevs:
2607 if opts.get('active') and branchrevs:
2608 dagheads = repo.heads(start)
2608 dagheads = repo.heads(start)
2609 heads = [h for h in heads if h.node() in dagheads]
2609 heads = [h for h in heads if h.node() in dagheads]
2610
2610
2611 if branchrevs:
2611 if branchrevs:
2612 haveheads = set(h.branch() for h in heads)
2612 haveheads = set(h.branch() for h in heads)
2613 if branches - haveheads:
2613 if branches - haveheads:
2614 headless = ', '.join(b for b in branches - haveheads)
2614 headless = ', '.join(b for b in branches - haveheads)
2615 msg = _('no open branch heads found on branches %s')
2615 msg = _('no open branch heads found on branches %s')
2616 if opts.get('rev'):
2616 if opts.get('rev'):
2617 msg += _(' (started at %s)') % opts['rev']
2617 msg += _(' (started at %s)') % opts['rev']
2618 ui.warn((msg + '\n') % headless)
2618 ui.warn((msg + '\n') % headless)
2619
2619
2620 if not heads:
2620 if not heads:
2621 return 1
2621 return 1
2622
2622
2623 ui.pager('heads')
2623 ui.pager('heads')
2624 heads = sorted(heads, key=lambda x: -x.rev())
2624 heads = sorted(heads, key=lambda x: -x.rev())
2625 displayer = cmdutil.show_changeset(ui, repo, opts)
2625 displayer = cmdutil.show_changeset(ui, repo, opts)
2626 for ctx in heads:
2626 for ctx in heads:
2627 displayer.show(ctx)
2627 displayer.show(ctx)
2628 displayer.close()
2628 displayer.close()
2629
2629
2630 @command('help',
2630 @command('help',
2631 [('e', 'extension', None, _('show only help for extensions')),
2631 [('e', 'extension', None, _('show only help for extensions')),
2632 ('c', 'command', None, _('show only help for commands')),
2632 ('c', 'command', None, _('show only help for commands')),
2633 ('k', 'keyword', None, _('show topics matching keyword')),
2633 ('k', 'keyword', None, _('show topics matching keyword')),
2634 ('s', 'system', [], _('show help for specific platform(s)')),
2634 ('s', 'system', [], _('show help for specific platform(s)')),
2635 ],
2635 ],
2636 _('[-ecks] [TOPIC]'),
2636 _('[-ecks] [TOPIC]'),
2637 norepo=True, cmdtype=readonly)
2637 norepo=True, cmdtype=readonly)
2638 def help_(ui, name=None, **opts):
2638 def help_(ui, name=None, **opts):
2639 """show help for a given topic or a help overview
2639 """show help for a given topic or a help overview
2640
2640
2641 With no arguments, print a list of commands with short help messages.
2641 With no arguments, print a list of commands with short help messages.
2642
2642
2643 Given a topic, extension, or command name, print help for that
2643 Given a topic, extension, or command name, print help for that
2644 topic.
2644 topic.
2645
2645
2646 Returns 0 if successful.
2646 Returns 0 if successful.
2647 """
2647 """
2648
2648
2649 keep = opts.get(r'system') or []
2649 keep = opts.get(r'system') or []
2650 if len(keep) == 0:
2650 if len(keep) == 0:
2651 if pycompat.sysplatform.startswith('win'):
2651 if pycompat.sysplatform.startswith('win'):
2652 keep.append('windows')
2652 keep.append('windows')
2653 elif pycompat.sysplatform == 'OpenVMS':
2653 elif pycompat.sysplatform == 'OpenVMS':
2654 keep.append('vms')
2654 keep.append('vms')
2655 elif pycompat.sysplatform == 'plan9':
2655 elif pycompat.sysplatform == 'plan9':
2656 keep.append('plan9')
2656 keep.append('plan9')
2657 else:
2657 else:
2658 keep.append('unix')
2658 keep.append('unix')
2659 keep.append(pycompat.sysplatform.lower())
2659 keep.append(pycompat.sysplatform.lower())
2660 if ui.verbose:
2660 if ui.verbose:
2661 keep.append('verbose')
2661 keep.append('verbose')
2662
2662
2663 commands = sys.modules[__name__]
2663 commands = sys.modules[__name__]
2664 formatted = help.formattedhelp(ui, commands, name, keep=keep, **opts)
2664 formatted = help.formattedhelp(ui, commands, name, keep=keep, **opts)
2665 ui.pager('help')
2665 ui.pager('help')
2666 ui.write(formatted)
2666 ui.write(formatted)
2667
2667
2668
2668
2669 @command('identify|id',
2669 @command('identify|id',
2670 [('r', 'rev', '',
2670 [('r', 'rev', '',
2671 _('identify the specified revision'), _('REV')),
2671 _('identify the specified revision'), _('REV')),
2672 ('n', 'num', None, _('show local revision number')),
2672 ('n', 'num', None, _('show local revision number')),
2673 ('i', 'id', None, _('show global revision id')),
2673 ('i', 'id', None, _('show global revision id')),
2674 ('b', 'branch', None, _('show branch')),
2674 ('b', 'branch', None, _('show branch')),
2675 ('t', 'tags', None, _('show tags')),
2675 ('t', 'tags', None, _('show tags')),
2676 ('B', 'bookmarks', None, _('show bookmarks')),
2676 ('B', 'bookmarks', None, _('show bookmarks')),
2677 ] + remoteopts + formatteropts,
2677 ] + remoteopts + formatteropts,
2678 _('[-nibtB] [-r REV] [SOURCE]'),
2678 _('[-nibtB] [-r REV] [SOURCE]'),
2679 optionalrepo=True, cmdtype=readonly)
2679 optionalrepo=True, cmdtype=readonly)
2680 def identify(ui, repo, source=None, rev=None,
2680 def identify(ui, repo, source=None, rev=None,
2681 num=None, id=None, branch=None, tags=None, bookmarks=None, **opts):
2681 num=None, id=None, branch=None, tags=None, bookmarks=None, **opts):
2682 """identify the working directory or specified revision
2682 """identify the working directory or specified revision
2683
2683
2684 Print a summary identifying the repository state at REV using one or
2684 Print a summary identifying the repository state at REV using one or
2685 two parent hash identifiers, followed by a "+" if the working
2685 two parent hash identifiers, followed by a "+" if the working
2686 directory has uncommitted changes, the branch name (if not default),
2686 directory has uncommitted changes, the branch name (if not default),
2687 a list of tags, and a list of bookmarks.
2687 a list of tags, and a list of bookmarks.
2688
2688
2689 When REV is not given, print a summary of the current state of the
2689 When REV is not given, print a summary of the current state of the
2690 repository.
2690 repository.
2691
2691
2692 Specifying a path to a repository root or Mercurial bundle will
2692 Specifying a path to a repository root or Mercurial bundle will
2693 cause lookup to operate on that repository/bundle.
2693 cause lookup to operate on that repository/bundle.
2694
2694
2695 .. container:: verbose
2695 .. container:: verbose
2696
2696
2697 Examples:
2697 Examples:
2698
2698
2699 - generate a build identifier for the working directory::
2699 - generate a build identifier for the working directory::
2700
2700
2701 hg id --id > build-id.dat
2701 hg id --id > build-id.dat
2702
2702
2703 - find the revision corresponding to a tag::
2703 - find the revision corresponding to a tag::
2704
2704
2705 hg id -n -r 1.3
2705 hg id -n -r 1.3
2706
2706
2707 - check the most recent revision of a remote repository::
2707 - check the most recent revision of a remote repository::
2708
2708
2709 hg id -r tip https://www.mercurial-scm.org/repo/hg/
2709 hg id -r tip https://www.mercurial-scm.org/repo/hg/
2710
2710
2711 See :hg:`log` for generating more information about specific revisions,
2711 See :hg:`log` for generating more information about specific revisions,
2712 including full hash identifiers.
2712 including full hash identifiers.
2713
2713
2714 Returns 0 if successful.
2714 Returns 0 if successful.
2715 """
2715 """
2716
2716
2717 opts = pycompat.byteskwargs(opts)
2717 opts = pycompat.byteskwargs(opts)
2718 if not repo and not source:
2718 if not repo and not source:
2719 raise error.Abort(_("there is no Mercurial repository here "
2719 raise error.Abort(_("there is no Mercurial repository here "
2720 "(.hg not found)"))
2720 "(.hg not found)"))
2721
2721
2722 if ui.debugflag:
2722 if ui.debugflag:
2723 hexfunc = hex
2723 hexfunc = hex
2724 else:
2724 else:
2725 hexfunc = short
2725 hexfunc = short
2726 default = not (num or id or branch or tags or bookmarks)
2726 default = not (num or id or branch or tags or bookmarks)
2727 output = []
2727 output = []
2728 revs = []
2728 revs = []
2729
2729
2730 if source:
2730 if source:
2731 source, branches = hg.parseurl(ui.expandpath(source))
2731 source, branches = hg.parseurl(ui.expandpath(source))
2732 peer = hg.peer(repo or ui, opts, source) # only pass ui when no repo
2732 peer = hg.peer(repo or ui, opts, source) # only pass ui when no repo
2733 repo = peer.local()
2733 repo = peer.local()
2734 revs, checkout = hg.addbranchrevs(repo, peer, branches, None)
2734 revs, checkout = hg.addbranchrevs(repo, peer, branches, None)
2735
2735
2736 fm = ui.formatter('identify', opts)
2736 fm = ui.formatter('identify', opts)
2737 fm.startitem()
2737 fm.startitem()
2738
2738
2739 if not repo:
2739 if not repo:
2740 if num or branch or tags:
2740 if num or branch or tags:
2741 raise error.Abort(
2741 raise error.Abort(
2742 _("can't query remote revision number, branch, or tags"))
2742 _("can't query remote revision number, branch, or tags"))
2743 if not rev and revs:
2743 if not rev and revs:
2744 rev = revs[0]
2744 rev = revs[0]
2745 if not rev:
2745 if not rev:
2746 rev = "tip"
2746 rev = "tip"
2747
2747
2748 remoterev = peer.lookup(rev)
2748 remoterev = peer.lookup(rev)
2749 hexrev = hexfunc(remoterev)
2749 hexrev = hexfunc(remoterev)
2750 if default or id:
2750 if default or id:
2751 output = [hexrev]
2751 output = [hexrev]
2752 fm.data(id=hexrev)
2752 fm.data(id=hexrev)
2753
2753
2754 def getbms():
2754 def getbms():
2755 bms = []
2755 bms = []
2756
2756
2757 if 'bookmarks' in peer.listkeys('namespaces'):
2757 if 'bookmarks' in peer.listkeys('namespaces'):
2758 hexremoterev = hex(remoterev)
2758 hexremoterev = hex(remoterev)
2759 bms = [bm for bm, bmr in peer.listkeys('bookmarks').iteritems()
2759 bms = [bm for bm, bmr in peer.listkeys('bookmarks').iteritems()
2760 if bmr == hexremoterev]
2760 if bmr == hexremoterev]
2761
2761
2762 return sorted(bms)
2762 return sorted(bms)
2763
2763
2764 bms = getbms()
2764 bms = getbms()
2765 if bookmarks:
2765 if bookmarks:
2766 output.extend(bms)
2766 output.extend(bms)
2767 elif default and not ui.quiet:
2767 elif default and not ui.quiet:
2768 # multiple bookmarks for a single parent separated by '/'
2768 # multiple bookmarks for a single parent separated by '/'
2769 bm = '/'.join(bms)
2769 bm = '/'.join(bms)
2770 if bm:
2770 if bm:
2771 output.append(bm)
2771 output.append(bm)
2772
2772
2773 fm.data(node=hex(remoterev))
2773 fm.data(node=hex(remoterev))
2774 fm.data(bookmarks=fm.formatlist(bms, name='bookmark'))
2774 fm.data(bookmarks=fm.formatlist(bms, name='bookmark'))
2775 else:
2775 else:
2776 ctx = scmutil.revsingle(repo, rev, None)
2776 ctx = scmutil.revsingle(repo, rev, None)
2777
2777
2778 if ctx.rev() is None:
2778 if ctx.rev() is None:
2779 ctx = repo[None]
2779 ctx = repo[None]
2780 parents = ctx.parents()
2780 parents = ctx.parents()
2781 taglist = []
2781 taglist = []
2782 for p in parents:
2782 for p in parents:
2783 taglist.extend(p.tags())
2783 taglist.extend(p.tags())
2784
2784
2785 dirty = ""
2785 dirty = ""
2786 if ctx.dirty(missing=True, merge=False, branch=False):
2786 if ctx.dirty(missing=True, merge=False, branch=False):
2787 dirty = '+'
2787 dirty = '+'
2788 fm.data(dirty=dirty)
2788 fm.data(dirty=dirty)
2789
2789
2790 hexoutput = [hexfunc(p.node()) for p in parents]
2790 hexoutput = [hexfunc(p.node()) for p in parents]
2791 if default or id:
2791 if default or id:
2792 output = ["%s%s" % ('+'.join(hexoutput), dirty)]
2792 output = ["%s%s" % ('+'.join(hexoutput), dirty)]
2793 fm.data(id="%s%s" % ('+'.join(hexoutput), dirty))
2793 fm.data(id="%s%s" % ('+'.join(hexoutput), dirty))
2794
2794
2795 if num:
2795 if num:
2796 numoutput = ["%d" % p.rev() for p in parents]
2796 numoutput = ["%d" % p.rev() for p in parents]
2797 output.append("%s%s" % ('+'.join(numoutput), dirty))
2797 output.append("%s%s" % ('+'.join(numoutput), dirty))
2798
2798
2799 fn = fm.nested('parents')
2799 fn = fm.nested('parents')
2800 for p in parents:
2800 for p in parents:
2801 fn.startitem()
2801 fn.startitem()
2802 fn.data(rev=p.rev())
2802 fn.data(rev=p.rev())
2803 fn.data(node=p.hex())
2803 fn.data(node=p.hex())
2804 fn.context(ctx=p)
2804 fn.context(ctx=p)
2805 fn.end()
2805 fn.end()
2806 else:
2806 else:
2807 hexoutput = hexfunc(ctx.node())
2807 hexoutput = hexfunc(ctx.node())
2808 if default or id:
2808 if default or id:
2809 output = [hexoutput]
2809 output = [hexoutput]
2810 fm.data(id=hexoutput)
2810 fm.data(id=hexoutput)
2811
2811
2812 if num:
2812 if num:
2813 output.append(pycompat.bytestr(ctx.rev()))
2813 output.append(pycompat.bytestr(ctx.rev()))
2814 taglist = ctx.tags()
2814 taglist = ctx.tags()
2815
2815
2816 if default and not ui.quiet:
2816 if default and not ui.quiet:
2817 b = ctx.branch()
2817 b = ctx.branch()
2818 if b != 'default':
2818 if b != 'default':
2819 output.append("(%s)" % b)
2819 output.append("(%s)" % b)
2820
2820
2821 # multiple tags for a single parent separated by '/'
2821 # multiple tags for a single parent separated by '/'
2822 t = '/'.join(taglist)
2822 t = '/'.join(taglist)
2823 if t:
2823 if t:
2824 output.append(t)
2824 output.append(t)
2825
2825
2826 # multiple bookmarks for a single parent separated by '/'
2826 # multiple bookmarks for a single parent separated by '/'
2827 bm = '/'.join(ctx.bookmarks())
2827 bm = '/'.join(ctx.bookmarks())
2828 if bm:
2828 if bm:
2829 output.append(bm)
2829 output.append(bm)
2830 else:
2830 else:
2831 if branch:
2831 if branch:
2832 output.append(ctx.branch())
2832 output.append(ctx.branch())
2833
2833
2834 if tags:
2834 if tags:
2835 output.extend(taglist)
2835 output.extend(taglist)
2836
2836
2837 if bookmarks:
2837 if bookmarks:
2838 output.extend(ctx.bookmarks())
2838 output.extend(ctx.bookmarks())
2839
2839
2840 fm.data(node=ctx.hex())
2840 fm.data(node=ctx.hex())
2841 fm.data(branch=ctx.branch())
2841 fm.data(branch=ctx.branch())
2842 fm.data(tags=fm.formatlist(taglist, name='tag', sep=':'))
2842 fm.data(tags=fm.formatlist(taglist, name='tag', sep=':'))
2843 fm.data(bookmarks=fm.formatlist(ctx.bookmarks(), name='bookmark'))
2843 fm.data(bookmarks=fm.formatlist(ctx.bookmarks(), name='bookmark'))
2844 fm.context(ctx=ctx)
2844 fm.context(ctx=ctx)
2845
2845
2846 fm.plain("%s\n" % ' '.join(output))
2846 fm.plain("%s\n" % ' '.join(output))
2847 fm.end()
2847 fm.end()
2848
2848
2849 @command('import|patch',
2849 @command('import|patch',
2850 [('p', 'strip', 1,
2850 [('p', 'strip', 1,
2851 _('directory strip option for patch. This has the same '
2851 _('directory strip option for patch. This has the same '
2852 'meaning as the corresponding patch option'), _('NUM')),
2852 'meaning as the corresponding patch option'), _('NUM')),
2853 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
2853 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
2854 ('e', 'edit', False, _('invoke editor on commit messages')),
2854 ('e', 'edit', False, _('invoke editor on commit messages')),
2855 ('f', 'force', None,
2855 ('f', 'force', None,
2856 _('skip check for outstanding uncommitted changes (DEPRECATED)')),
2856 _('skip check for outstanding uncommitted changes (DEPRECATED)')),
2857 ('', 'no-commit', None,
2857 ('', 'no-commit', None,
2858 _("don't commit, just update the working directory")),
2858 _("don't commit, just update the working directory")),
2859 ('', 'bypass', None,
2859 ('', 'bypass', None,
2860 _("apply patch without touching the working directory")),
2860 _("apply patch without touching the working directory")),
2861 ('', 'partial', None,
2861 ('', 'partial', None,
2862 _('commit even if some hunks fail')),
2862 _('commit even if some hunks fail')),
2863 ('', 'exact', None,
2863 ('', 'exact', None,
2864 _('abort if patch would apply lossily')),
2864 _('abort if patch would apply lossily')),
2865 ('', 'prefix', '',
2865 ('', 'prefix', '',
2866 _('apply patch to subdirectory'), _('DIR')),
2866 _('apply patch to subdirectory'), _('DIR')),
2867 ('', 'import-branch', None,
2867 ('', 'import-branch', None,
2868 _('use any branch information in patch (implied by --exact)'))] +
2868 _('use any branch information in patch (implied by --exact)'))] +
2869 commitopts + commitopts2 + similarityopts,
2869 commitopts + commitopts2 + similarityopts,
2870 _('[OPTION]... PATCH...'))
2870 _('[OPTION]... PATCH...'))
2871 def import_(ui, repo, patch1=None, *patches, **opts):
2871 def import_(ui, repo, patch1=None, *patches, **opts):
2872 """import an ordered set of patches
2872 """import an ordered set of patches
2873
2873
2874 Import a list of patches and commit them individually (unless
2874 Import a list of patches and commit them individually (unless
2875 --no-commit is specified).
2875 --no-commit is specified).
2876
2876
2877 To read a patch from standard input (stdin), use "-" as the patch
2877 To read a patch from standard input (stdin), use "-" as the patch
2878 name. If a URL is specified, the patch will be downloaded from
2878 name. If a URL is specified, the patch will be downloaded from
2879 there.
2879 there.
2880
2880
2881 Import first applies changes to the working directory (unless
2881 Import first applies changes to the working directory (unless
2882 --bypass is specified), import will abort if there are outstanding
2882 --bypass is specified), import will abort if there are outstanding
2883 changes.
2883 changes.
2884
2884
2885 Use --bypass to apply and commit patches directly to the
2885 Use --bypass to apply and commit patches directly to the
2886 repository, without affecting the working directory. Without
2886 repository, without affecting the working directory. Without
2887 --exact, patches will be applied on top of the working directory
2887 --exact, patches will be applied on top of the working directory
2888 parent revision.
2888 parent revision.
2889
2889
2890 You can import a patch straight from a mail message. Even patches
2890 You can import a patch straight from a mail message. Even patches
2891 as attachments work (to use the body part, it must have type
2891 as attachments work (to use the body part, it must have type
2892 text/plain or text/x-patch). From and Subject headers of email
2892 text/plain or text/x-patch). From and Subject headers of email
2893 message are used as default committer and commit message. All
2893 message are used as default committer and commit message. All
2894 text/plain body parts before first diff are added to the commit
2894 text/plain body parts before first diff are added to the commit
2895 message.
2895 message.
2896
2896
2897 If the imported patch was generated by :hg:`export`, user and
2897 If the imported patch was generated by :hg:`export`, user and
2898 description from patch override values from message headers and
2898 description from patch override values from message headers and
2899 body. Values given on command line with -m/--message and -u/--user
2899 body. Values given on command line with -m/--message and -u/--user
2900 override these.
2900 override these.
2901
2901
2902 If --exact is specified, import will set the working directory to
2902 If --exact is specified, import will set the working directory to
2903 the parent of each patch before applying it, and will abort if the
2903 the parent of each patch before applying it, and will abort if the
2904 resulting changeset has a different ID than the one recorded in
2904 resulting changeset has a different ID than the one recorded in
2905 the patch. This will guard against various ways that portable
2905 the patch. This will guard against various ways that portable
2906 patch formats and mail systems might fail to transfer Mercurial
2906 patch formats and mail systems might fail to transfer Mercurial
2907 data or metadata. See :hg:`bundle` for lossless transmission.
2907 data or metadata. See :hg:`bundle` for lossless transmission.
2908
2908
2909 Use --partial to ensure a changeset will be created from the patch
2909 Use --partial to ensure a changeset will be created from the patch
2910 even if some hunks fail to apply. Hunks that fail to apply will be
2910 even if some hunks fail to apply. Hunks that fail to apply will be
2911 written to a <target-file>.rej file. Conflicts can then be resolved
2911 written to a <target-file>.rej file. Conflicts can then be resolved
2912 by hand before :hg:`commit --amend` is run to update the created
2912 by hand before :hg:`commit --amend` is run to update the created
2913 changeset. This flag exists to let people import patches that
2913 changeset. This flag exists to let people import patches that
2914 partially apply without losing the associated metadata (author,
2914 partially apply without losing the associated metadata (author,
2915 date, description, ...).
2915 date, description, ...).
2916
2916
2917 .. note::
2917 .. note::
2918
2918
2919 When no hunks apply cleanly, :hg:`import --partial` will create
2919 When no hunks apply cleanly, :hg:`import --partial` will create
2920 an empty changeset, importing only the patch metadata.
2920 an empty changeset, importing only the patch metadata.
2921
2921
2922 With -s/--similarity, hg will attempt to discover renames and
2922 With -s/--similarity, hg will attempt to discover renames and
2923 copies in the patch in the same way as :hg:`addremove`.
2923 copies in the patch in the same way as :hg:`addremove`.
2924
2924
2925 It is possible to use external patch programs to perform the patch
2925 It is possible to use external patch programs to perform the patch
2926 by setting the ``ui.patch`` configuration option. For the default
2926 by setting the ``ui.patch`` configuration option. For the default
2927 internal tool, the fuzz can also be configured via ``patch.fuzz``.
2927 internal tool, the fuzz can also be configured via ``patch.fuzz``.
2928 See :hg:`help config` for more information about configuration
2928 See :hg:`help config` for more information about configuration
2929 files and how to use these options.
2929 files and how to use these options.
2930
2930
2931 See :hg:`help dates` for a list of formats valid for -d/--date.
2931 See :hg:`help dates` for a list of formats valid for -d/--date.
2932
2932
2933 .. container:: verbose
2933 .. container:: verbose
2934
2934
2935 Examples:
2935 Examples:
2936
2936
2937 - import a traditional patch from a website and detect renames::
2937 - import a traditional patch from a website and detect renames::
2938
2938
2939 hg import -s 80 http://example.com/bugfix.patch
2939 hg import -s 80 http://example.com/bugfix.patch
2940
2940
2941 - import a changeset from an hgweb server::
2941 - import a changeset from an hgweb server::
2942
2942
2943 hg import https://www.mercurial-scm.org/repo/hg/rev/5ca8c111e9aa
2943 hg import https://www.mercurial-scm.org/repo/hg/rev/5ca8c111e9aa
2944
2944
2945 - import all the patches in an Unix-style mbox::
2945 - import all the patches in an Unix-style mbox::
2946
2946
2947 hg import incoming-patches.mbox
2947 hg import incoming-patches.mbox
2948
2948
2949 - import patches from stdin::
2949 - import patches from stdin::
2950
2950
2951 hg import -
2951 hg import -
2952
2952
2953 - attempt to exactly restore an exported changeset (not always
2953 - attempt to exactly restore an exported changeset (not always
2954 possible)::
2954 possible)::
2955
2955
2956 hg import --exact proposed-fix.patch
2956 hg import --exact proposed-fix.patch
2957
2957
2958 - use an external tool to apply a patch which is too fuzzy for
2958 - use an external tool to apply a patch which is too fuzzy for
2959 the default internal tool.
2959 the default internal tool.
2960
2960
2961 hg import --config ui.patch="patch --merge" fuzzy.patch
2961 hg import --config ui.patch="patch --merge" fuzzy.patch
2962
2962
2963 - change the default fuzzing from 2 to a less strict 7
2963 - change the default fuzzing from 2 to a less strict 7
2964
2964
2965 hg import --config ui.fuzz=7 fuzz.patch
2965 hg import --config ui.fuzz=7 fuzz.patch
2966
2966
2967 Returns 0 on success, 1 on partial success (see --partial).
2967 Returns 0 on success, 1 on partial success (see --partial).
2968 """
2968 """
2969
2969
2970 opts = pycompat.byteskwargs(opts)
2970 opts = pycompat.byteskwargs(opts)
2971 if not patch1:
2971 if not patch1:
2972 raise error.Abort(_('need at least one patch to import'))
2972 raise error.Abort(_('need at least one patch to import'))
2973
2973
2974 patches = (patch1,) + patches
2974 patches = (patch1,) + patches
2975
2975
2976 date = opts.get('date')
2976 date = opts.get('date')
2977 if date:
2977 if date:
2978 opts['date'] = util.parsedate(date)
2978 opts['date'] = util.parsedate(date)
2979
2979
2980 exact = opts.get('exact')
2980 exact = opts.get('exact')
2981 update = not opts.get('bypass')
2981 update = not opts.get('bypass')
2982 if not update and opts.get('no_commit'):
2982 if not update and opts.get('no_commit'):
2983 raise error.Abort(_('cannot use --no-commit with --bypass'))
2983 raise error.Abort(_('cannot use --no-commit with --bypass'))
2984 try:
2984 try:
2985 sim = float(opts.get('similarity') or 0)
2985 sim = float(opts.get('similarity') or 0)
2986 except ValueError:
2986 except ValueError:
2987 raise error.Abort(_('similarity must be a number'))
2987 raise error.Abort(_('similarity must be a number'))
2988 if sim < 0 or sim > 100:
2988 if sim < 0 or sim > 100:
2989 raise error.Abort(_('similarity must be between 0 and 100'))
2989 raise error.Abort(_('similarity must be between 0 and 100'))
2990 if sim and not update:
2990 if sim and not update:
2991 raise error.Abort(_('cannot use --similarity with --bypass'))
2991 raise error.Abort(_('cannot use --similarity with --bypass'))
2992 if exact:
2992 if exact:
2993 if opts.get('edit'):
2993 if opts.get('edit'):
2994 raise error.Abort(_('cannot use --exact with --edit'))
2994 raise error.Abort(_('cannot use --exact with --edit'))
2995 if opts.get('prefix'):
2995 if opts.get('prefix'):
2996 raise error.Abort(_('cannot use --exact with --prefix'))
2996 raise error.Abort(_('cannot use --exact with --prefix'))
2997
2997
2998 base = opts["base"]
2998 base = opts["base"]
2999 wlock = dsguard = lock = tr = None
2999 wlock = dsguard = lock = tr = None
3000 msgs = []
3000 msgs = []
3001 ret = 0
3001 ret = 0
3002
3002
3003
3003
3004 try:
3004 try:
3005 wlock = repo.wlock()
3005 wlock = repo.wlock()
3006
3006
3007 if update:
3007 if update:
3008 cmdutil.checkunfinished(repo)
3008 cmdutil.checkunfinished(repo)
3009 if (exact or not opts.get('force')):
3009 if (exact or not opts.get('force')):
3010 cmdutil.bailifchanged(repo)
3010 cmdutil.bailifchanged(repo)
3011
3011
3012 if not opts.get('no_commit'):
3012 if not opts.get('no_commit'):
3013 lock = repo.lock()
3013 lock = repo.lock()
3014 tr = repo.transaction('import')
3014 tr = repo.transaction('import')
3015 else:
3015 else:
3016 dsguard = dirstateguard.dirstateguard(repo, 'import')
3016 dsguard = dirstateguard.dirstateguard(repo, 'import')
3017 parents = repo[None].parents()
3017 parents = repo[None].parents()
3018 for patchurl in patches:
3018 for patchurl in patches:
3019 if patchurl == '-':
3019 if patchurl == '-':
3020 ui.status(_('applying patch from stdin\n'))
3020 ui.status(_('applying patch from stdin\n'))
3021 patchfile = ui.fin
3021 patchfile = ui.fin
3022 patchurl = 'stdin' # for error message
3022 patchurl = 'stdin' # for error message
3023 else:
3023 else:
3024 patchurl = os.path.join(base, patchurl)
3024 patchurl = os.path.join(base, patchurl)
3025 ui.status(_('applying %s\n') % patchurl)
3025 ui.status(_('applying %s\n') % patchurl)
3026 patchfile = hg.openpath(ui, patchurl)
3026 patchfile = hg.openpath(ui, patchurl)
3027
3027
3028 haspatch = False
3028 haspatch = False
3029 for hunk in patch.split(patchfile):
3029 for hunk in patch.split(patchfile):
3030 (msg, node, rej) = cmdutil.tryimportone(ui, repo, hunk,
3030 (msg, node, rej) = cmdutil.tryimportone(ui, repo, hunk,
3031 parents, opts,
3031 parents, opts,
3032 msgs, hg.clean)
3032 msgs, hg.clean)
3033 if msg:
3033 if msg:
3034 haspatch = True
3034 haspatch = True
3035 ui.note(msg + '\n')
3035 ui.note(msg + '\n')
3036 if update or exact:
3036 if update or exact:
3037 parents = repo[None].parents()
3037 parents = repo[None].parents()
3038 else:
3038 else:
3039 parents = [repo[node]]
3039 parents = [repo[node]]
3040 if rej:
3040 if rej:
3041 ui.write_err(_("patch applied partially\n"))
3041 ui.write_err(_("patch applied partially\n"))
3042 ui.write_err(_("(fix the .rej files and run "
3042 ui.write_err(_("(fix the .rej files and run "
3043 "`hg commit --amend`)\n"))
3043 "`hg commit --amend`)\n"))
3044 ret = 1
3044 ret = 1
3045 break
3045 break
3046
3046
3047 if not haspatch:
3047 if not haspatch:
3048 raise error.Abort(_('%s: no diffs found') % patchurl)
3048 raise error.Abort(_('%s: no diffs found') % patchurl)
3049
3049
3050 if tr:
3050 if tr:
3051 tr.close()
3051 tr.close()
3052 if msgs:
3052 if msgs:
3053 repo.savecommitmessage('\n* * *\n'.join(msgs))
3053 repo.savecommitmessage('\n* * *\n'.join(msgs))
3054 if dsguard:
3054 if dsguard:
3055 dsguard.close()
3055 dsguard.close()
3056 return ret
3056 return ret
3057 finally:
3057 finally:
3058 if tr:
3058 if tr:
3059 tr.release()
3059 tr.release()
3060 release(lock, dsguard, wlock)
3060 release(lock, dsguard, wlock)
3061
3061
3062 @command('incoming|in',
3062 @command('incoming|in',
3063 [('f', 'force', None,
3063 [('f', 'force', None,
3064 _('run even if remote repository is unrelated')),
3064 _('run even if remote repository is unrelated')),
3065 ('n', 'newest-first', None, _('show newest record first')),
3065 ('n', 'newest-first', None, _('show newest record first')),
3066 ('', 'bundle', '',
3066 ('', 'bundle', '',
3067 _('file to store the bundles into'), _('FILE')),
3067 _('file to store the bundles into'), _('FILE')),
3068 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3068 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3069 ('B', 'bookmarks', False, _("compare bookmarks")),
3069 ('B', 'bookmarks', False, _("compare bookmarks")),
3070 ('b', 'branch', [],
3070 ('b', 'branch', [],
3071 _('a specific branch you would like to pull'), _('BRANCH')),
3071 _('a specific branch you would like to pull'), _('BRANCH')),
3072 ] + logopts + remoteopts + subrepoopts,
3072 ] + logopts + remoteopts + subrepoopts,
3073 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
3073 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
3074 def incoming(ui, repo, source="default", **opts):
3074 def incoming(ui, repo, source="default", **opts):
3075 """show new changesets found in source
3075 """show new changesets found in source
3076
3076
3077 Show new changesets found in the specified path/URL or the default
3077 Show new changesets found in the specified path/URL or the default
3078 pull location. These are the changesets that would have been pulled
3078 pull location. These are the changesets that would have been pulled
3079 by :hg:`pull` at the time you issued this command.
3079 by :hg:`pull` at the time you issued this command.
3080
3080
3081 See pull for valid source format details.
3081 See pull for valid source format details.
3082
3082
3083 .. container:: verbose
3083 .. container:: verbose
3084
3084
3085 With -B/--bookmarks, the result of bookmark comparison between
3085 With -B/--bookmarks, the result of bookmark comparison between
3086 local and remote repositories is displayed. With -v/--verbose,
3086 local and remote repositories is displayed. With -v/--verbose,
3087 status is also displayed for each bookmark like below::
3087 status is also displayed for each bookmark like below::
3088
3088
3089 BM1 01234567890a added
3089 BM1 01234567890a added
3090 BM2 1234567890ab advanced
3090 BM2 1234567890ab advanced
3091 BM3 234567890abc diverged
3091 BM3 234567890abc diverged
3092 BM4 34567890abcd changed
3092 BM4 34567890abcd changed
3093
3093
3094 The action taken locally when pulling depends on the
3094 The action taken locally when pulling depends on the
3095 status of each bookmark:
3095 status of each bookmark:
3096
3096
3097 :``added``: pull will create it
3097 :``added``: pull will create it
3098 :``advanced``: pull will update it
3098 :``advanced``: pull will update it
3099 :``diverged``: pull will create a divergent bookmark
3099 :``diverged``: pull will create a divergent bookmark
3100 :``changed``: result depends on remote changesets
3100 :``changed``: result depends on remote changesets
3101
3101
3102 From the point of view of pulling behavior, bookmark
3102 From the point of view of pulling behavior, bookmark
3103 existing only in the remote repository are treated as ``added``,
3103 existing only in the remote repository are treated as ``added``,
3104 even if it is in fact locally deleted.
3104 even if it is in fact locally deleted.
3105
3105
3106 .. container:: verbose
3106 .. container:: verbose
3107
3107
3108 For remote repository, using --bundle avoids downloading the
3108 For remote repository, using --bundle avoids downloading the
3109 changesets twice if the incoming is followed by a pull.
3109 changesets twice if the incoming is followed by a pull.
3110
3110
3111 Examples:
3111 Examples:
3112
3112
3113 - show incoming changes with patches and full description::
3113 - show incoming changes with patches and full description::
3114
3114
3115 hg incoming -vp
3115 hg incoming -vp
3116
3116
3117 - show incoming changes excluding merges, store a bundle::
3117 - show incoming changes excluding merges, store a bundle::
3118
3118
3119 hg in -vpM --bundle incoming.hg
3119 hg in -vpM --bundle incoming.hg
3120 hg pull incoming.hg
3120 hg pull incoming.hg
3121
3121
3122 - briefly list changes inside a bundle::
3122 - briefly list changes inside a bundle::
3123
3123
3124 hg in changes.hg -T "{desc|firstline}\\n"
3124 hg in changes.hg -T "{desc|firstline}\\n"
3125
3125
3126 Returns 0 if there are incoming changes, 1 otherwise.
3126 Returns 0 if there are incoming changes, 1 otherwise.
3127 """
3127 """
3128 opts = pycompat.byteskwargs(opts)
3128 opts = pycompat.byteskwargs(opts)
3129 if opts.get('graph'):
3129 if opts.get('graph'):
3130 cmdutil.checkunsupportedgraphflags([], opts)
3130 cmdutil.checkunsupportedgraphflags([], opts)
3131 def display(other, chlist, displayer):
3131 def display(other, chlist, displayer):
3132 revdag = cmdutil.graphrevs(other, chlist, opts)
3132 revdag = cmdutil.graphrevs(other, chlist, opts)
3133 cmdutil.displaygraph(ui, repo, revdag, displayer,
3133 cmdutil.displaygraph(ui, repo, revdag, displayer,
3134 graphmod.asciiedges)
3134 graphmod.asciiedges)
3135
3135
3136 hg._incoming(display, lambda: 1, ui, repo, source, opts, buffered=True)
3136 hg._incoming(display, lambda: 1, ui, repo, source, opts, buffered=True)
3137 return 0
3137 return 0
3138
3138
3139 if opts.get('bundle') and opts.get('subrepos'):
3139 if opts.get('bundle') and opts.get('subrepos'):
3140 raise error.Abort(_('cannot combine --bundle and --subrepos'))
3140 raise error.Abort(_('cannot combine --bundle and --subrepos'))
3141
3141
3142 if opts.get('bookmarks'):
3142 if opts.get('bookmarks'):
3143 source, branches = hg.parseurl(ui.expandpath(source),
3143 source, branches = hg.parseurl(ui.expandpath(source),
3144 opts.get('branch'))
3144 opts.get('branch'))
3145 other = hg.peer(repo, opts, source)
3145 other = hg.peer(repo, opts, source)
3146 if 'bookmarks' not in other.listkeys('namespaces'):
3146 if 'bookmarks' not in other.listkeys('namespaces'):
3147 ui.warn(_("remote doesn't support bookmarks\n"))
3147 ui.warn(_("remote doesn't support bookmarks\n"))
3148 return 0
3148 return 0
3149 ui.pager('incoming')
3149 ui.pager('incoming')
3150 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3150 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3151 return bookmarks.incoming(ui, repo, other)
3151 return bookmarks.incoming(ui, repo, other)
3152
3152
3153 repo._subtoppath = ui.expandpath(source)
3153 repo._subtoppath = ui.expandpath(source)
3154 try:
3154 try:
3155 return hg.incoming(ui, repo, source, opts)
3155 return hg.incoming(ui, repo, source, opts)
3156 finally:
3156 finally:
3157 del repo._subtoppath
3157 del repo._subtoppath
3158
3158
3159
3159
3160 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'),
3160 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'),
3161 norepo=True)
3161 norepo=True)
3162 def init(ui, dest=".", **opts):
3162 def init(ui, dest=".", **opts):
3163 """create a new repository in the given directory
3163 """create a new repository in the given directory
3164
3164
3165 Initialize a new repository in the given directory. If the given
3165 Initialize a new repository in the given directory. If the given
3166 directory does not exist, it will be created.
3166 directory does not exist, it will be created.
3167
3167
3168 If no directory is given, the current directory is used.
3168 If no directory is given, the current directory is used.
3169
3169
3170 It is possible to specify an ``ssh://`` URL as the destination.
3170 It is possible to specify an ``ssh://`` URL as the destination.
3171 See :hg:`help urls` for more information.
3171 See :hg:`help urls` for more information.
3172
3172
3173 Returns 0 on success.
3173 Returns 0 on success.
3174 """
3174 """
3175 opts = pycompat.byteskwargs(opts)
3175 opts = pycompat.byteskwargs(opts)
3176 hg.peer(ui, opts, ui.expandpath(dest), create=True)
3176 hg.peer(ui, opts, ui.expandpath(dest), create=True)
3177
3177
3178 @command('locate',
3178 @command('locate',
3179 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3179 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3180 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3180 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3181 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3181 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3182 ] + walkopts,
3182 ] + walkopts,
3183 _('[OPTION]... [PATTERN]...'))
3183 _('[OPTION]... [PATTERN]...'))
3184 def locate(ui, repo, *pats, **opts):
3184 def locate(ui, repo, *pats, **opts):
3185 """locate files matching specific patterns (DEPRECATED)
3185 """locate files matching specific patterns (DEPRECATED)
3186
3186
3187 Print files under Mercurial control in the working directory whose
3187 Print files under Mercurial control in the working directory whose
3188 names match the given patterns.
3188 names match the given patterns.
3189
3189
3190 By default, this command searches all directories in the working
3190 By default, this command searches all directories in the working
3191 directory. To search just the current directory and its
3191 directory. To search just the current directory and its
3192 subdirectories, use "--include .".
3192 subdirectories, use "--include .".
3193
3193
3194 If no patterns are given to match, this command prints the names
3194 If no patterns are given to match, this command prints the names
3195 of all files under Mercurial control in the working directory.
3195 of all files under Mercurial control in the working directory.
3196
3196
3197 If you want to feed the output of this command into the "xargs"
3197 If you want to feed the output of this command into the "xargs"
3198 command, use the -0 option to both this command and "xargs". This
3198 command, use the -0 option to both this command and "xargs". This
3199 will avoid the problem of "xargs" treating single filenames that
3199 will avoid the problem of "xargs" treating single filenames that
3200 contain whitespace as multiple filenames.
3200 contain whitespace as multiple filenames.
3201
3201
3202 See :hg:`help files` for a more versatile command.
3202 See :hg:`help files` for a more versatile command.
3203
3203
3204 Returns 0 if a match is found, 1 otherwise.
3204 Returns 0 if a match is found, 1 otherwise.
3205 """
3205 """
3206 opts = pycompat.byteskwargs(opts)
3206 opts = pycompat.byteskwargs(opts)
3207 if opts.get('print0'):
3207 if opts.get('print0'):
3208 end = '\0'
3208 end = '\0'
3209 else:
3209 else:
3210 end = '\n'
3210 end = '\n'
3211 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
3211 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
3212
3212
3213 ret = 1
3213 ret = 1
3214 ctx = repo[rev]
3214 ctx = repo[rev]
3215 m = scmutil.match(ctx, pats, opts, default='relglob',
3215 m = scmutil.match(ctx, pats, opts, default='relglob',
3216 badfn=lambda x, y: False)
3216 badfn=lambda x, y: False)
3217
3217
3218 ui.pager('locate')
3218 ui.pager('locate')
3219 for abs in ctx.matches(m):
3219 for abs in ctx.matches(m):
3220 if opts.get('fullpath'):
3220 if opts.get('fullpath'):
3221 ui.write(repo.wjoin(abs), end)
3221 ui.write(repo.wjoin(abs), end)
3222 else:
3222 else:
3223 ui.write(((pats and m.rel(abs)) or abs), end)
3223 ui.write(((pats and m.rel(abs)) or abs), end)
3224 ret = 0
3224 ret = 0
3225
3225
3226 return ret
3226 return ret
3227
3227
3228 @command('^log|history',
3228 @command('^log|history',
3229 [('f', 'follow', None,
3229 [('f', 'follow', None,
3230 _('follow changeset history, or file history across copies and renames')),
3230 _('follow changeset history, or file history across copies and renames')),
3231 ('', 'follow-first', None,
3231 ('', 'follow-first', None,
3232 _('only follow the first parent of merge changesets (DEPRECATED)')),
3232 _('only follow the first parent of merge changesets (DEPRECATED)')),
3233 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
3233 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
3234 ('C', 'copies', None, _('show copied files')),
3234 ('C', 'copies', None, _('show copied files')),
3235 ('k', 'keyword', [],
3235 ('k', 'keyword', [],
3236 _('do case-insensitive search for a given text'), _('TEXT')),
3236 _('do case-insensitive search for a given text'), _('TEXT')),
3237 ('r', 'rev', [], _('show the specified revision or revset'), _('REV')),
3237 ('r', 'rev', [], _('show the specified revision or revset'), _('REV')),
3238 ('L', 'line-range', [],
3238 ('L', 'line-range', [],
3239 _('follow line range of specified file (EXPERIMENTAL)'),
3239 _('follow line range of specified file (EXPERIMENTAL)'),
3240 _('FILE,RANGE')),
3240 _('FILE,RANGE')),
3241 ('', 'removed', None, _('include revisions where files were removed')),
3241 ('', 'removed', None, _('include revisions where files were removed')),
3242 ('m', 'only-merges', None, _('show only merges (DEPRECATED)')),
3242 ('m', 'only-merges', None, _('show only merges (DEPRECATED)')),
3243 ('u', 'user', [], _('revisions committed by user'), _('USER')),
3243 ('u', 'user', [], _('revisions committed by user'), _('USER')),
3244 ('', 'only-branch', [],
3244 ('', 'only-branch', [],
3245 _('show only changesets within the given named branch (DEPRECATED)'),
3245 _('show only changesets within the given named branch (DEPRECATED)'),
3246 _('BRANCH')),
3246 _('BRANCH')),
3247 ('b', 'branch', [],
3247 ('b', 'branch', [],
3248 _('show changesets within the given named branch'), _('BRANCH')),
3248 _('show changesets within the given named branch'), _('BRANCH')),
3249 ('P', 'prune', [],
3249 ('P', 'prune', [],
3250 _('do not display revision or any of its ancestors'), _('REV')),
3250 _('do not display revision or any of its ancestors'), _('REV')),
3251 ] + logopts + walkopts,
3251 ] + logopts + walkopts,
3252 _('[OPTION]... [FILE]'),
3252 _('[OPTION]... [FILE]'),
3253 inferrepo=True, cmdtype=readonly)
3253 inferrepo=True, cmdtype=readonly)
3254 def log(ui, repo, *pats, **opts):
3254 def log(ui, repo, *pats, **opts):
3255 """show revision history of entire repository or files
3255 """show revision history of entire repository or files
3256
3256
3257 Print the revision history of the specified files or the entire
3257 Print the revision history of the specified files or the entire
3258 project.
3258 project.
3259
3259
3260 If no revision range is specified, the default is ``tip:0`` unless
3260 If no revision range is specified, the default is ``tip:0`` unless
3261 --follow is set, in which case the working directory parent is
3261 --follow is set, in which case the working directory parent is
3262 used as the starting revision.
3262 used as the starting revision.
3263
3263
3264 File history is shown without following rename or copy history of
3264 File history is shown without following rename or copy history of
3265 files. Use -f/--follow with a filename to follow history across
3265 files. Use -f/--follow with a filename to follow history across
3266 renames and copies. --follow without a filename will only show
3266 renames and copies. --follow without a filename will only show
3267 ancestors or descendants of the starting revision.
3267 ancestors or descendants of the starting revision.
3268
3268
3269 By default this command prints revision number and changeset id,
3269 By default this command prints revision number and changeset id,
3270 tags, non-trivial parents, user, date and time, and a summary for
3270 tags, non-trivial parents, user, date and time, and a summary for
3271 each commit. When the -v/--verbose switch is used, the list of
3271 each commit. When the -v/--verbose switch is used, the list of
3272 changed files and full commit message are shown.
3272 changed files and full commit message are shown.
3273
3273
3274 With --graph the revisions are shown as an ASCII art DAG with the most
3274 With --graph the revisions are shown as an ASCII art DAG with the most
3275 recent changeset at the top.
3275 recent changeset at the top.
3276 'o' is a changeset, '@' is a working directory parent, 'x' is obsolete,
3276 'o' is a changeset, '@' is a working directory parent, 'x' is obsolete,
3277 and '+' represents a fork where the changeset from the lines below is a
3277 and '+' represents a fork where the changeset from the lines below is a
3278 parent of the 'o' merge on the same line.
3278 parent of the 'o' merge on the same line.
3279 Paths in the DAG are represented with '|', '/' and so forth. ':' in place
3279 Paths in the DAG are represented with '|', '/' and so forth. ':' in place
3280 of a '|' indicates one or more revisions in a path are omitted.
3280 of a '|' indicates one or more revisions in a path are omitted.
3281
3281
3282 .. container:: verbose
3282 .. container:: verbose
3283
3283
3284 Use -L/--line-range FILE,M:N options to follow the history of lines
3284 Use -L/--line-range FILE,M:N options to follow the history of lines
3285 from M to N in FILE. With -p/--patch only diff hunks affecting
3285 from M to N in FILE. With -p/--patch only diff hunks affecting
3286 specified line range will be shown. This option requires --follow;
3286 specified line range will be shown. This option requires --follow;
3287 it can be specified multiple times. Currently, this option is not
3287 it can be specified multiple times. Currently, this option is not
3288 compatible with --graph. This option is experimental.
3288 compatible with --graph. This option is experimental.
3289
3289
3290 .. note::
3290 .. note::
3291
3291
3292 :hg:`log --patch` may generate unexpected diff output for merge
3292 :hg:`log --patch` may generate unexpected diff output for merge
3293 changesets, as it will only compare the merge changeset against
3293 changesets, as it will only compare the merge changeset against
3294 its first parent. Also, only files different from BOTH parents
3294 its first parent. Also, only files different from BOTH parents
3295 will appear in files:.
3295 will appear in files:.
3296
3296
3297 .. note::
3297 .. note::
3298
3298
3299 For performance reasons, :hg:`log FILE` may omit duplicate changes
3299 For performance reasons, :hg:`log FILE` may omit duplicate changes
3300 made on branches and will not show removals or mode changes. To
3300 made on branches and will not show removals or mode changes. To
3301 see all such changes, use the --removed switch.
3301 see all such changes, use the --removed switch.
3302
3302
3303 .. container:: verbose
3303 .. container:: verbose
3304
3304
3305 .. note::
3305 .. note::
3306
3306
3307 The history resulting from -L/--line-range options depends on diff
3307 The history resulting from -L/--line-range options depends on diff
3308 options; for instance if white-spaces are ignored, respective changes
3308 options; for instance if white-spaces are ignored, respective changes
3309 with only white-spaces in specified line range will not be listed.
3309 with only white-spaces in specified line range will not be listed.
3310
3310
3311 .. container:: verbose
3311 .. container:: verbose
3312
3312
3313 Some examples:
3313 Some examples:
3314
3314
3315 - changesets with full descriptions and file lists::
3315 - changesets with full descriptions and file lists::
3316
3316
3317 hg log -v
3317 hg log -v
3318
3318
3319 - changesets ancestral to the working directory::
3319 - changesets ancestral to the working directory::
3320
3320
3321 hg log -f
3321 hg log -f
3322
3322
3323 - last 10 commits on the current branch::
3323 - last 10 commits on the current branch::
3324
3324
3325 hg log -l 10 -b .
3325 hg log -l 10 -b .
3326
3326
3327 - changesets showing all modifications of a file, including removals::
3327 - changesets showing all modifications of a file, including removals::
3328
3328
3329 hg log --removed file.c
3329 hg log --removed file.c
3330
3330
3331 - all changesets that touch a directory, with diffs, excluding merges::
3331 - all changesets that touch a directory, with diffs, excluding merges::
3332
3332
3333 hg log -Mp lib/
3333 hg log -Mp lib/
3334
3334
3335 - all revision numbers that match a keyword::
3335 - all revision numbers that match a keyword::
3336
3336
3337 hg log -k bug --template "{rev}\\n"
3337 hg log -k bug --template "{rev}\\n"
3338
3338
3339 - the full hash identifier of the working directory parent::
3339 - the full hash identifier of the working directory parent::
3340
3340
3341 hg log -r . --template "{node}\\n"
3341 hg log -r . --template "{node}\\n"
3342
3342
3343 - list available log templates::
3343 - list available log templates::
3344
3344
3345 hg log -T list
3345 hg log -T list
3346
3346
3347 - check if a given changeset is included in a tagged release::
3347 - check if a given changeset is included in a tagged release::
3348
3348
3349 hg log -r "a21ccf and ancestor(1.9)"
3349 hg log -r "a21ccf and ancestor(1.9)"
3350
3350
3351 - find all changesets by some user in a date range::
3351 - find all changesets by some user in a date range::
3352
3352
3353 hg log -k alice -d "may 2008 to jul 2008"
3353 hg log -k alice -d "may 2008 to jul 2008"
3354
3354
3355 - summary of all changesets after the last tag::
3355 - summary of all changesets after the last tag::
3356
3356
3357 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
3357 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
3358
3358
3359 - changesets touching lines 13 to 23 for file.c::
3359 - changesets touching lines 13 to 23 for file.c::
3360
3360
3361 hg log -L file.c,13:23
3361 hg log -L file.c,13:23
3362
3362
3363 - changesets touching lines 13 to 23 for file.c and lines 2 to 6 of
3363 - changesets touching lines 13 to 23 for file.c and lines 2 to 6 of
3364 main.c with patch::
3364 main.c with patch::
3365
3365
3366 hg log -L file.c,13:23 -L main.c,2:6 -p
3366 hg log -L file.c,13:23 -L main.c,2:6 -p
3367
3367
3368 See :hg:`help dates` for a list of formats valid for -d/--date.
3368 See :hg:`help dates` for a list of formats valid for -d/--date.
3369
3369
3370 See :hg:`help revisions` for more about specifying and ordering
3370 See :hg:`help revisions` for more about specifying and ordering
3371 revisions.
3371 revisions.
3372
3372
3373 See :hg:`help templates` for more about pre-packaged styles and
3373 See :hg:`help templates` for more about pre-packaged styles and
3374 specifying custom templates. The default template used by the log
3374 specifying custom templates. The default template used by the log
3375 command can be customized via the ``ui.logtemplate`` configuration
3375 command can be customized via the ``ui.logtemplate`` configuration
3376 setting.
3376 setting.
3377
3377
3378 Returns 0 on success.
3378 Returns 0 on success.
3379
3379
3380 """
3380 """
3381 opts = pycompat.byteskwargs(opts)
3381 opts = pycompat.byteskwargs(opts)
3382 linerange = opts.get('line_range')
3382 linerange = opts.get('line_range')
3383
3383
3384 if linerange and not opts.get('follow'):
3384 if linerange and not opts.get('follow'):
3385 raise error.Abort(_('--line-range requires --follow'))
3385 raise error.Abort(_('--line-range requires --follow'))
3386
3386
3387 if linerange and pats:
3387 if linerange and pats:
3388 raise error.Abort(
3388 raise error.Abort(
3389 _('FILE arguments are not compatible with --line-range option')
3389 _('FILE arguments are not compatible with --line-range option')
3390 )
3390 )
3391
3391
3392 if opts.get('follow') and opts.get('rev'):
3392 if opts.get('follow') and opts.get('rev'):
3393 opts['rev'] = [revsetlang.formatspec('reverse(::%lr)', opts.get('rev'))]
3393 opts['rev'] = [revsetlang.formatspec('reverse(::%lr)', opts.get('rev'))]
3394 del opts['follow']
3394 del opts['follow']
3395
3395
3396 if opts.get('graph'):
3396 if opts.get('graph'):
3397 if linerange:
3397 if linerange:
3398 raise error.Abort(_('graph not supported with line range patterns'))
3398 raise error.Abort(_('graph not supported with line range patterns'))
3399 return cmdutil.graphlog(ui, repo, pats, opts)
3399 return cmdutil.graphlog(ui, repo, pats, opts)
3400
3400
3401 revs, expr, filematcher = cmdutil.getlogrevs(repo, pats, opts)
3401 revs, expr, filematcher = cmdutil.getlogrevs(repo, pats, opts)
3402 hunksfilter = None
3402 hunksfilter = None
3403
3403
3404 if linerange:
3404 if linerange:
3405 revs, lrfilematcher, hunksfilter = cmdutil.getloglinerangerevs(
3405 revs, lrfilematcher, hunksfilter = cmdutil.getloglinerangerevs(
3406 repo, revs, opts)
3406 repo, revs, opts)
3407
3407
3408 if filematcher is not None and lrfilematcher is not None:
3408 if filematcher is not None and lrfilematcher is not None:
3409 basefilematcher = filematcher
3409 basefilematcher = filematcher
3410
3410
3411 def filematcher(rev):
3411 def filematcher(rev):
3412 files = (basefilematcher(rev).files()
3412 files = (basefilematcher(rev).files()
3413 + lrfilematcher(rev).files())
3413 + lrfilematcher(rev).files())
3414 return scmutil.matchfiles(repo, files)
3414 return scmutil.matchfiles(repo, files)
3415
3415
3416 elif filematcher is None:
3416 elif filematcher is None:
3417 filematcher = lrfilematcher
3417 filematcher = lrfilematcher
3418
3418
3419 limit = cmdutil.loglimit(opts)
3419 limit = cmdutil.loglimit(opts)
3420 count = 0
3420 count = 0
3421
3421
3422 getrenamed = None
3422 getrenamed = None
3423 if opts.get('copies'):
3423 if opts.get('copies'):
3424 endrev = None
3424 endrev = None
3425 if opts.get('rev'):
3425 if opts.get('rev'):
3426 endrev = scmutil.revrange(repo, opts.get('rev')).max() + 1
3426 endrev = scmutil.revrange(repo, opts.get('rev')).max() + 1
3427 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
3427 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
3428
3428
3429 ui.pager('log')
3429 ui.pager('log')
3430 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
3430 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
3431 for rev in revs:
3431 for rev in revs:
3432 if count == limit:
3432 if count == limit:
3433 break
3433 break
3434 ctx = repo[rev]
3434 ctx = repo[rev]
3435 copies = None
3435 copies = None
3436 if getrenamed is not None and rev:
3436 if getrenamed is not None and rev:
3437 copies = []
3437 copies = []
3438 for fn in ctx.files():
3438 for fn in ctx.files():
3439 rename = getrenamed(fn, rev)
3439 rename = getrenamed(fn, rev)
3440 if rename:
3440 if rename:
3441 copies.append((fn, rename[0]))
3441 copies.append((fn, rename[0]))
3442 if filematcher:
3442 if filematcher:
3443 revmatchfn = filematcher(ctx.rev())
3443 revmatchfn = filematcher(ctx.rev())
3444 else:
3444 else:
3445 revmatchfn = None
3445 revmatchfn = None
3446 if hunksfilter:
3446 if hunksfilter:
3447 revhunksfilter = hunksfilter(rev)
3447 revhunksfilter = hunksfilter(rev)
3448 else:
3448 else:
3449 revhunksfilter = None
3449 revhunksfilter = None
3450 displayer.show(ctx, copies=copies, matchfn=revmatchfn,
3450 displayer.show(ctx, copies=copies, matchfn=revmatchfn,
3451 hunksfilterfn=revhunksfilter)
3451 hunksfilterfn=revhunksfilter)
3452 if displayer.flush(ctx):
3452 if displayer.flush(ctx):
3453 count += 1
3453 count += 1
3454
3454
3455 displayer.close()
3455 displayer.close()
3456
3456
3457 @command('manifest',
3457 @command('manifest',
3458 [('r', 'rev', '', _('revision to display'), _('REV')),
3458 [('r', 'rev', '', _('revision to display'), _('REV')),
3459 ('', 'all', False, _("list files from all revisions"))]
3459 ('', 'all', False, _("list files from all revisions"))]
3460 + formatteropts,
3460 + formatteropts,
3461 _('[-r REV]'), cmdtype=readonly)
3461 _('[-r REV]'), cmdtype=readonly)
3462 def manifest(ui, repo, node=None, rev=None, **opts):
3462 def manifest(ui, repo, node=None, rev=None, **opts):
3463 """output the current or given revision of the project manifest
3463 """output the current or given revision of the project manifest
3464
3464
3465 Print a list of version controlled files for the given revision.
3465 Print a list of version controlled files for the given revision.
3466 If no revision is given, the first parent of the working directory
3466 If no revision is given, the first parent of the working directory
3467 is used, or the null revision if no revision is checked out.
3467 is used, or the null revision if no revision is checked out.
3468
3468
3469 With -v, print file permissions, symlink and executable bits.
3469 With -v, print file permissions, symlink and executable bits.
3470 With --debug, print file revision hashes.
3470 With --debug, print file revision hashes.
3471
3471
3472 If option --all is specified, the list of all files from all revisions
3472 If option --all is specified, the list of all files from all revisions
3473 is printed. This includes deleted and renamed files.
3473 is printed. This includes deleted and renamed files.
3474
3474
3475 Returns 0 on success.
3475 Returns 0 on success.
3476 """
3476 """
3477 opts = pycompat.byteskwargs(opts)
3477 opts = pycompat.byteskwargs(opts)
3478 fm = ui.formatter('manifest', opts)
3478 fm = ui.formatter('manifest', opts)
3479
3479
3480 if opts.get('all'):
3480 if opts.get('all'):
3481 if rev or node:
3481 if rev or node:
3482 raise error.Abort(_("can't specify a revision with --all"))
3482 raise error.Abort(_("can't specify a revision with --all"))
3483
3483
3484 res = []
3484 res = []
3485 prefix = "data/"
3485 prefix = "data/"
3486 suffix = ".i"
3486 suffix = ".i"
3487 plen = len(prefix)
3487 plen = len(prefix)
3488 slen = len(suffix)
3488 slen = len(suffix)
3489 with repo.lock():
3489 with repo.lock():
3490 for fn, b, size in repo.store.datafiles():
3490 for fn, b, size in repo.store.datafiles():
3491 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
3491 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
3492 res.append(fn[plen:-slen])
3492 res.append(fn[plen:-slen])
3493 ui.pager('manifest')
3493 ui.pager('manifest')
3494 for f in res:
3494 for f in res:
3495 fm.startitem()
3495 fm.startitem()
3496 fm.write("path", '%s\n', f)
3496 fm.write("path", '%s\n', f)
3497 fm.end()
3497 fm.end()
3498 return
3498 return
3499
3499
3500 if rev and node:
3500 if rev and node:
3501 raise error.Abort(_("please specify just one revision"))
3501 raise error.Abort(_("please specify just one revision"))
3502
3502
3503 if not node:
3503 if not node:
3504 node = rev
3504 node = rev
3505
3505
3506 char = {'l': '@', 'x': '*', '': ''}
3506 char = {'l': '@', 'x': '*', '': ''}
3507 mode = {'l': '644', 'x': '755', '': '644'}
3507 mode = {'l': '644', 'x': '755', '': '644'}
3508 ctx = scmutil.revsingle(repo, node)
3508 ctx = scmutil.revsingle(repo, node)
3509 mf = ctx.manifest()
3509 mf = ctx.manifest()
3510 ui.pager('manifest')
3510 ui.pager('manifest')
3511 for f in ctx:
3511 for f in ctx:
3512 fm.startitem()
3512 fm.startitem()
3513 fl = ctx[f].flags()
3513 fl = ctx[f].flags()
3514 fm.condwrite(ui.debugflag, 'hash', '%s ', hex(mf[f]))
3514 fm.condwrite(ui.debugflag, 'hash', '%s ', hex(mf[f]))
3515 fm.condwrite(ui.verbose, 'mode type', '%s %1s ', mode[fl], char[fl])
3515 fm.condwrite(ui.verbose, 'mode type', '%s %1s ', mode[fl], char[fl])
3516 fm.write('path', '%s\n', f)
3516 fm.write('path', '%s\n', f)
3517 fm.end()
3517 fm.end()
3518
3518
3519 @command('^merge',
3519 @command('^merge',
3520 [('f', 'force', None,
3520 [('f', 'force', None,
3521 _('force a merge including outstanding changes (DEPRECATED)')),
3521 _('force a merge including outstanding changes (DEPRECATED)')),
3522 ('r', 'rev', '', _('revision to merge'), _('REV')),
3522 ('r', 'rev', '', _('revision to merge'), _('REV')),
3523 ('P', 'preview', None,
3523 ('P', 'preview', None,
3524 _('review revisions to merge (no merge is performed)'))
3524 _('review revisions to merge (no merge is performed)'))
3525 ] + mergetoolopts,
3525 ] + mergetoolopts,
3526 _('[-P] [[-r] REV]'))
3526 _('[-P] [[-r] REV]'))
3527 def merge(ui, repo, node=None, **opts):
3527 def merge(ui, repo, node=None, **opts):
3528 """merge another revision into working directory
3528 """merge another revision into working directory
3529
3529
3530 The current working directory is updated with all changes made in
3530 The current working directory is updated with all changes made in
3531 the requested revision since the last common predecessor revision.
3531 the requested revision since the last common predecessor revision.
3532
3532
3533 Files that changed between either parent are marked as changed for
3533 Files that changed between either parent are marked as changed for
3534 the next commit and a commit must be performed before any further
3534 the next commit and a commit must be performed before any further
3535 updates to the repository are allowed. The next commit will have
3535 updates to the repository are allowed. The next commit will have
3536 two parents.
3536 two parents.
3537
3537
3538 ``--tool`` can be used to specify the merge tool used for file
3538 ``--tool`` can be used to specify the merge tool used for file
3539 merges. It overrides the HGMERGE environment variable and your
3539 merges. It overrides the HGMERGE environment variable and your
3540 configuration files. See :hg:`help merge-tools` for options.
3540 configuration files. See :hg:`help merge-tools` for options.
3541
3541
3542 If no revision is specified, the working directory's parent is a
3542 If no revision is specified, the working directory's parent is a
3543 head revision, and the current branch contains exactly one other
3543 head revision, and the current branch contains exactly one other
3544 head, the other head is merged with by default. Otherwise, an
3544 head, the other head is merged with by default. Otherwise, an
3545 explicit revision with which to merge with must be provided.
3545 explicit revision with which to merge with must be provided.
3546
3546
3547 See :hg:`help resolve` for information on handling file conflicts.
3547 See :hg:`help resolve` for information on handling file conflicts.
3548
3548
3549 To undo an uncommitted merge, use :hg:`update --clean .` which
3549 To undo an uncommitted merge, use :hg:`update --clean .` which
3550 will check out a clean copy of the original merge parent, losing
3550 will check out a clean copy of the original merge parent, losing
3551 all changes.
3551 all changes.
3552
3552
3553 Returns 0 on success, 1 if there are unresolved files.
3553 Returns 0 on success, 1 if there are unresolved files.
3554 """
3554 """
3555
3555
3556 opts = pycompat.byteskwargs(opts)
3556 opts = pycompat.byteskwargs(opts)
3557 if opts.get('rev') and node:
3557 if opts.get('rev') and node:
3558 raise error.Abort(_("please specify just one revision"))
3558 raise error.Abort(_("please specify just one revision"))
3559 if not node:
3559 if not node:
3560 node = opts.get('rev')
3560 node = opts.get('rev')
3561
3561
3562 if node:
3562 if node:
3563 node = scmutil.revsingle(repo, node).node()
3563 node = scmutil.revsingle(repo, node).node()
3564
3564
3565 if not node:
3565 if not node:
3566 node = repo[destutil.destmerge(repo)].node()
3566 node = repo[destutil.destmerge(repo)].node()
3567
3567
3568 if opts.get('preview'):
3568 if opts.get('preview'):
3569 # find nodes that are ancestors of p2 but not of p1
3569 # find nodes that are ancestors of p2 but not of p1
3570 p1 = repo.lookup('.')
3570 p1 = repo.lookup('.')
3571 p2 = repo.lookup(node)
3571 p2 = repo.lookup(node)
3572 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
3572 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
3573
3573
3574 displayer = cmdutil.show_changeset(ui, repo, opts)
3574 displayer = cmdutil.show_changeset(ui, repo, opts)
3575 for node in nodes:
3575 for node in nodes:
3576 displayer.show(repo[node])
3576 displayer.show(repo[node])
3577 displayer.close()
3577 displayer.close()
3578 return 0
3578 return 0
3579
3579
3580 try:
3580 try:
3581 # ui.forcemerge is an internal variable, do not document
3581 # ui.forcemerge is an internal variable, do not document
3582 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''), 'merge')
3582 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''), 'merge')
3583 force = opts.get('force')
3583 force = opts.get('force')
3584 labels = ['working copy', 'merge rev']
3584 labels = ['working copy', 'merge rev']
3585 return hg.merge(repo, node, force=force, mergeforce=force,
3585 return hg.merge(repo, node, force=force, mergeforce=force,
3586 labels=labels)
3586 labels=labels)
3587 finally:
3587 finally:
3588 ui.setconfig('ui', 'forcemerge', '', 'merge')
3588 ui.setconfig('ui', 'forcemerge', '', 'merge')
3589
3589
3590 @command('outgoing|out',
3590 @command('outgoing|out',
3591 [('f', 'force', None, _('run even when the destination is unrelated')),
3591 [('f', 'force', None, _('run even when the destination is unrelated')),
3592 ('r', 'rev', [],
3592 ('r', 'rev', [],
3593 _('a changeset intended to be included in the destination'), _('REV')),
3593 _('a changeset intended to be included in the destination'), _('REV')),
3594 ('n', 'newest-first', None, _('show newest record first')),
3594 ('n', 'newest-first', None, _('show newest record first')),
3595 ('B', 'bookmarks', False, _('compare bookmarks')),
3595 ('B', 'bookmarks', False, _('compare bookmarks')),
3596 ('b', 'branch', [], _('a specific branch you would like to push'),
3596 ('b', 'branch', [], _('a specific branch you would like to push'),
3597 _('BRANCH')),
3597 _('BRANCH')),
3598 ] + logopts + remoteopts + subrepoopts,
3598 ] + logopts + remoteopts + subrepoopts,
3599 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
3599 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
3600 def outgoing(ui, repo, dest=None, **opts):
3600 def outgoing(ui, repo, dest=None, **opts):
3601 """show changesets not found in the destination
3601 """show changesets not found in the destination
3602
3602
3603 Show changesets not found in the specified destination repository
3603 Show changesets not found in the specified destination repository
3604 or the default push location. These are the changesets that would
3604 or the default push location. These are the changesets that would
3605 be pushed if a push was requested.
3605 be pushed if a push was requested.
3606
3606
3607 See pull for details of valid destination formats.
3607 See pull for details of valid destination formats.
3608
3608
3609 .. container:: verbose
3609 .. container:: verbose
3610
3610
3611 With -B/--bookmarks, the result of bookmark comparison between
3611 With -B/--bookmarks, the result of bookmark comparison between
3612 local and remote repositories is displayed. With -v/--verbose,
3612 local and remote repositories is displayed. With -v/--verbose,
3613 status is also displayed for each bookmark like below::
3613 status is also displayed for each bookmark like below::
3614
3614
3615 BM1 01234567890a added
3615 BM1 01234567890a added
3616 BM2 deleted
3616 BM2 deleted
3617 BM3 234567890abc advanced
3617 BM3 234567890abc advanced
3618 BM4 34567890abcd diverged
3618 BM4 34567890abcd diverged
3619 BM5 4567890abcde changed
3619 BM5 4567890abcde changed
3620
3620
3621 The action taken when pushing depends on the
3621 The action taken when pushing depends on the
3622 status of each bookmark:
3622 status of each bookmark:
3623
3623
3624 :``added``: push with ``-B`` will create it
3624 :``added``: push with ``-B`` will create it
3625 :``deleted``: push with ``-B`` will delete it
3625 :``deleted``: push with ``-B`` will delete it
3626 :``advanced``: push will update it
3626 :``advanced``: push will update it
3627 :``diverged``: push with ``-B`` will update it
3627 :``diverged``: push with ``-B`` will update it
3628 :``changed``: push with ``-B`` will update it
3628 :``changed``: push with ``-B`` will update it
3629
3629
3630 From the point of view of pushing behavior, bookmarks
3630 From the point of view of pushing behavior, bookmarks
3631 existing only in the remote repository are treated as
3631 existing only in the remote repository are treated as
3632 ``deleted``, even if it is in fact added remotely.
3632 ``deleted``, even if it is in fact added remotely.
3633
3633
3634 Returns 0 if there are outgoing changes, 1 otherwise.
3634 Returns 0 if there are outgoing changes, 1 otherwise.
3635 """
3635 """
3636 opts = pycompat.byteskwargs(opts)
3636 opts = pycompat.byteskwargs(opts)
3637 if opts.get('graph'):
3637 if opts.get('graph'):
3638 cmdutil.checkunsupportedgraphflags([], opts)
3638 cmdutil.checkunsupportedgraphflags([], opts)
3639 o, other = hg._outgoing(ui, repo, dest, opts)
3639 o, other = hg._outgoing(ui, repo, dest, opts)
3640 if not o:
3640 if not o:
3641 cmdutil.outgoinghooks(ui, repo, other, opts, o)
3641 cmdutil.outgoinghooks(ui, repo, other, opts, o)
3642 return
3642 return
3643
3643
3644 revdag = cmdutil.graphrevs(repo, o, opts)
3644 revdag = cmdutil.graphrevs(repo, o, opts)
3645 ui.pager('outgoing')
3645 ui.pager('outgoing')
3646 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
3646 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
3647 cmdutil.displaygraph(ui, repo, revdag, displayer, graphmod.asciiedges)
3647 cmdutil.displaygraph(ui, repo, revdag, displayer, graphmod.asciiedges)
3648 cmdutil.outgoinghooks(ui, repo, other, opts, o)
3648 cmdutil.outgoinghooks(ui, repo, other, opts, o)
3649 return 0
3649 return 0
3650
3650
3651 if opts.get('bookmarks'):
3651 if opts.get('bookmarks'):
3652 dest = ui.expandpath(dest or 'default-push', dest or 'default')
3652 dest = ui.expandpath(dest or 'default-push', dest or 'default')
3653 dest, branches = hg.parseurl(dest, opts.get('branch'))
3653 dest, branches = hg.parseurl(dest, opts.get('branch'))
3654 other = hg.peer(repo, opts, dest)
3654 other = hg.peer(repo, opts, dest)
3655 if 'bookmarks' not in other.listkeys('namespaces'):
3655 if 'bookmarks' not in other.listkeys('namespaces'):
3656 ui.warn(_("remote doesn't support bookmarks\n"))
3656 ui.warn(_("remote doesn't support bookmarks\n"))
3657 return 0
3657 return 0
3658 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
3658 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
3659 ui.pager('outgoing')
3659 ui.pager('outgoing')
3660 return bookmarks.outgoing(ui, repo, other)
3660 return bookmarks.outgoing(ui, repo, other)
3661
3661
3662 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
3662 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
3663 try:
3663 try:
3664 return hg.outgoing(ui, repo, dest, opts)
3664 return hg.outgoing(ui, repo, dest, opts)
3665 finally:
3665 finally:
3666 del repo._subtoppath
3666 del repo._subtoppath
3667
3667
3668 @command('parents',
3668 @command('parents',
3669 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
3669 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
3670 ] + templateopts,
3670 ] + templateopts,
3671 _('[-r REV] [FILE]'),
3671 _('[-r REV] [FILE]'),
3672 inferrepo=True)
3672 inferrepo=True)
3673 def parents(ui, repo, file_=None, **opts):
3673 def parents(ui, repo, file_=None, **opts):
3674 """show the parents of the working directory or revision (DEPRECATED)
3674 """show the parents of the working directory or revision (DEPRECATED)
3675
3675
3676 Print the working directory's parent revisions. If a revision is
3676 Print the working directory's parent revisions. If a revision is
3677 given via -r/--rev, the parent of that revision will be printed.
3677 given via -r/--rev, the parent of that revision will be printed.
3678 If a file argument is given, the revision in which the file was
3678 If a file argument is given, the revision in which the file was
3679 last changed (before the working directory revision or the
3679 last changed (before the working directory revision or the
3680 argument to --rev if given) is printed.
3680 argument to --rev if given) is printed.
3681
3681
3682 This command is equivalent to::
3682 This command is equivalent to::
3683
3683
3684 hg log -r "p1()+p2()" or
3684 hg log -r "p1()+p2()" or
3685 hg log -r "p1(REV)+p2(REV)" or
3685 hg log -r "p1(REV)+p2(REV)" or
3686 hg log -r "max(::p1() and file(FILE))+max(::p2() and file(FILE))" or
3686 hg log -r "max(::p1() and file(FILE))+max(::p2() and file(FILE))" or
3687 hg log -r "max(::p1(REV) and file(FILE))+max(::p2(REV) and file(FILE))"
3687 hg log -r "max(::p1(REV) and file(FILE))+max(::p2(REV) and file(FILE))"
3688
3688
3689 See :hg:`summary` and :hg:`help revsets` for related information.
3689 See :hg:`summary` and :hg:`help revsets` for related information.
3690
3690
3691 Returns 0 on success.
3691 Returns 0 on success.
3692 """
3692 """
3693
3693
3694 opts = pycompat.byteskwargs(opts)
3694 opts = pycompat.byteskwargs(opts)
3695 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
3695 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
3696
3696
3697 if file_:
3697 if file_:
3698 m = scmutil.match(ctx, (file_,), opts)
3698 m = scmutil.match(ctx, (file_,), opts)
3699 if m.anypats() or len(m.files()) != 1:
3699 if m.anypats() or len(m.files()) != 1:
3700 raise error.Abort(_('can only specify an explicit filename'))
3700 raise error.Abort(_('can only specify an explicit filename'))
3701 file_ = m.files()[0]
3701 file_ = m.files()[0]
3702 filenodes = []
3702 filenodes = []
3703 for cp in ctx.parents():
3703 for cp in ctx.parents():
3704 if not cp:
3704 if not cp:
3705 continue
3705 continue
3706 try:
3706 try:
3707 filenodes.append(cp.filenode(file_))
3707 filenodes.append(cp.filenode(file_))
3708 except error.LookupError:
3708 except error.LookupError:
3709 pass
3709 pass
3710 if not filenodes:
3710 if not filenodes:
3711 raise error.Abort(_("'%s' not found in manifest!") % file_)
3711 raise error.Abort(_("'%s' not found in manifest!") % file_)
3712 p = []
3712 p = []
3713 for fn in filenodes:
3713 for fn in filenodes:
3714 fctx = repo.filectx(file_, fileid=fn)
3714 fctx = repo.filectx(file_, fileid=fn)
3715 p.append(fctx.node())
3715 p.append(fctx.node())
3716 else:
3716 else:
3717 p = [cp.node() for cp in ctx.parents()]
3717 p = [cp.node() for cp in ctx.parents()]
3718
3718
3719 displayer = cmdutil.show_changeset(ui, repo, opts)
3719 displayer = cmdutil.show_changeset(ui, repo, opts)
3720 for n in p:
3720 for n in p:
3721 if n != nullid:
3721 if n != nullid:
3722 displayer.show(repo[n])
3722 displayer.show(repo[n])
3723 displayer.close()
3723 displayer.close()
3724
3724
3725 @command('paths', formatteropts, _('[NAME]'), optionalrepo=True,
3725 @command('paths', formatteropts, _('[NAME]'), optionalrepo=True,
3726 cmdtype=readonly)
3726 cmdtype=readonly)
3727 def paths(ui, repo, search=None, **opts):
3727 def paths(ui, repo, search=None, **opts):
3728 """show aliases for remote repositories
3728 """show aliases for remote repositories
3729
3729
3730 Show definition of symbolic path name NAME. If no name is given,
3730 Show definition of symbolic path name NAME. If no name is given,
3731 show definition of all available names.
3731 show definition of all available names.
3732
3732
3733 Option -q/--quiet suppresses all output when searching for NAME
3733 Option -q/--quiet suppresses all output when searching for NAME
3734 and shows only the path names when listing all definitions.
3734 and shows only the path names when listing all definitions.
3735
3735
3736 Path names are defined in the [paths] section of your
3736 Path names are defined in the [paths] section of your
3737 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
3737 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
3738 repository, ``.hg/hgrc`` is used, too.
3738 repository, ``.hg/hgrc`` is used, too.
3739
3739
3740 The path names ``default`` and ``default-push`` have a special
3740 The path names ``default`` and ``default-push`` have a special
3741 meaning. When performing a push or pull operation, they are used
3741 meaning. When performing a push or pull operation, they are used
3742 as fallbacks if no location is specified on the command-line.
3742 as fallbacks if no location is specified on the command-line.
3743 When ``default-push`` is set, it will be used for push and
3743 When ``default-push`` is set, it will be used for push and
3744 ``default`` will be used for pull; otherwise ``default`` is used
3744 ``default`` will be used for pull; otherwise ``default`` is used
3745 as the fallback for both. When cloning a repository, the clone
3745 as the fallback for both. When cloning a repository, the clone
3746 source is written as ``default`` in ``.hg/hgrc``.
3746 source is written as ``default`` in ``.hg/hgrc``.
3747
3747
3748 .. note::
3748 .. note::
3749
3749
3750 ``default`` and ``default-push`` apply to all inbound (e.g.
3750 ``default`` and ``default-push`` apply to all inbound (e.g.
3751 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email`
3751 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email`
3752 and :hg:`bundle`) operations.
3752 and :hg:`bundle`) operations.
3753
3753
3754 See :hg:`help urls` for more information.
3754 See :hg:`help urls` for more information.
3755
3755
3756 Returns 0 on success.
3756 Returns 0 on success.
3757 """
3757 """
3758
3758
3759 opts = pycompat.byteskwargs(opts)
3759 opts = pycompat.byteskwargs(opts)
3760 ui.pager('paths')
3760 ui.pager('paths')
3761 if search:
3761 if search:
3762 pathitems = [(name, path) for name, path in ui.paths.iteritems()
3762 pathitems = [(name, path) for name, path in ui.paths.iteritems()
3763 if name == search]
3763 if name == search]
3764 else:
3764 else:
3765 pathitems = sorted(ui.paths.iteritems())
3765 pathitems = sorted(ui.paths.iteritems())
3766
3766
3767 fm = ui.formatter('paths', opts)
3767 fm = ui.formatter('paths', opts)
3768 if fm.isplain():
3768 if fm.isplain():
3769 hidepassword = util.hidepassword
3769 hidepassword = util.hidepassword
3770 else:
3770 else:
3771 hidepassword = str
3771 hidepassword = str
3772 if ui.quiet:
3772 if ui.quiet:
3773 namefmt = '%s\n'
3773 namefmt = '%s\n'
3774 else:
3774 else:
3775 namefmt = '%s = '
3775 namefmt = '%s = '
3776 showsubopts = not search and not ui.quiet
3776 showsubopts = not search and not ui.quiet
3777
3777
3778 for name, path in pathitems:
3778 for name, path in pathitems:
3779 fm.startitem()
3779 fm.startitem()
3780 fm.condwrite(not search, 'name', namefmt, name)
3780 fm.condwrite(not search, 'name', namefmt, name)
3781 fm.condwrite(not ui.quiet, 'url', '%s\n', hidepassword(path.rawloc))
3781 fm.condwrite(not ui.quiet, 'url', '%s\n', hidepassword(path.rawloc))
3782 for subopt, value in sorted(path.suboptions.items()):
3782 for subopt, value in sorted(path.suboptions.items()):
3783 assert subopt not in ('name', 'url')
3783 assert subopt not in ('name', 'url')
3784 if showsubopts:
3784 if showsubopts:
3785 fm.plain('%s:%s = ' % (name, subopt))
3785 fm.plain('%s:%s = ' % (name, subopt))
3786 fm.condwrite(showsubopts, subopt, '%s\n', value)
3786 fm.condwrite(showsubopts, subopt, '%s\n', value)
3787
3787
3788 fm.end()
3788 fm.end()
3789
3789
3790 if search and not pathitems:
3790 if search and not pathitems:
3791 if not ui.quiet:
3791 if not ui.quiet:
3792 ui.warn(_("not found!\n"))
3792 ui.warn(_("not found!\n"))
3793 return 1
3793 return 1
3794 else:
3794 else:
3795 return 0
3795 return 0
3796
3796
3797 @command('phase',
3797 @command('phase',
3798 [('p', 'public', False, _('set changeset phase to public')),
3798 [('p', 'public', False, _('set changeset phase to public')),
3799 ('d', 'draft', False, _('set changeset phase to draft')),
3799 ('d', 'draft', False, _('set changeset phase to draft')),
3800 ('s', 'secret', False, _('set changeset phase to secret')),
3800 ('s', 'secret', False, _('set changeset phase to secret')),
3801 ('f', 'force', False, _('allow to move boundary backward')),
3801 ('f', 'force', False, _('allow to move boundary backward')),
3802 ('r', 'rev', [], _('target revision'), _('REV')),
3802 ('r', 'rev', [], _('target revision'), _('REV')),
3803 ],
3803 ],
3804 _('[-p|-d|-s] [-f] [-r] [REV...]'))
3804 _('[-p|-d|-s] [-f] [-r] [REV...]'))
3805 def phase(ui, repo, *revs, **opts):
3805 def phase(ui, repo, *revs, **opts):
3806 """set or show the current phase name
3806 """set or show the current phase name
3807
3807
3808 With no argument, show the phase name of the current revision(s).
3808 With no argument, show the phase name of the current revision(s).
3809
3809
3810 With one of -p/--public, -d/--draft or -s/--secret, change the
3810 With one of -p/--public, -d/--draft or -s/--secret, change the
3811 phase value of the specified revisions.
3811 phase value of the specified revisions.
3812
3812
3813 Unless -f/--force is specified, :hg:`phase` won't move changesets from a
3813 Unless -f/--force is specified, :hg:`phase` won't move changesets from a
3814 lower phase to a higher phase. Phases are ordered as follows::
3814 lower phase to a higher phase. Phases are ordered as follows::
3815
3815
3816 public < draft < secret
3816 public < draft < secret
3817
3817
3818 Returns 0 on success, 1 if some phases could not be changed.
3818 Returns 0 on success, 1 if some phases could not be changed.
3819
3819
3820 (For more information about the phases concept, see :hg:`help phases`.)
3820 (For more information about the phases concept, see :hg:`help phases`.)
3821 """
3821 """
3822 opts = pycompat.byteskwargs(opts)
3822 opts = pycompat.byteskwargs(opts)
3823 # search for a unique phase argument
3823 # search for a unique phase argument
3824 targetphase = None
3824 targetphase = None
3825 for idx, name in enumerate(phases.phasenames):
3825 for idx, name in enumerate(phases.phasenames):
3826 if opts[name]:
3826 if opts[name]:
3827 if targetphase is not None:
3827 if targetphase is not None:
3828 raise error.Abort(_('only one phase can be specified'))
3828 raise error.Abort(_('only one phase can be specified'))
3829 targetphase = idx
3829 targetphase = idx
3830
3830
3831 # look for specified revision
3831 # look for specified revision
3832 revs = list(revs)
3832 revs = list(revs)
3833 revs.extend(opts['rev'])
3833 revs.extend(opts['rev'])
3834 if not revs:
3834 if not revs:
3835 # display both parents as the second parent phase can influence
3835 # display both parents as the second parent phase can influence
3836 # the phase of a merge commit
3836 # the phase of a merge commit
3837 revs = [c.rev() for c in repo[None].parents()]
3837 revs = [c.rev() for c in repo[None].parents()]
3838
3838
3839 revs = scmutil.revrange(repo, revs)
3839 revs = scmutil.revrange(repo, revs)
3840
3840
3841 lock = None
3841 lock = None
3842 ret = 0
3842 ret = 0
3843 if targetphase is None:
3843 if targetphase is None:
3844 # display
3844 # display
3845 for r in revs:
3845 for r in revs:
3846 ctx = repo[r]
3846 ctx = repo[r]
3847 ui.write('%i: %s\n' % (ctx.rev(), ctx.phasestr()))
3847 ui.write('%i: %s\n' % (ctx.rev(), ctx.phasestr()))
3848 else:
3848 else:
3849 tr = None
3849 tr = None
3850 lock = repo.lock()
3850 lock = repo.lock()
3851 try:
3851 try:
3852 tr = repo.transaction("phase")
3852 tr = repo.transaction("phase")
3853 # set phase
3853 # set phase
3854 if not revs:
3854 if not revs:
3855 raise error.Abort(_('empty revision set'))
3855 raise error.Abort(_('empty revision set'))
3856 nodes = [repo[r].node() for r in revs]
3856 nodes = [repo[r].node() for r in revs]
3857 # moving revision from public to draft may hide them
3857 # moving revision from public to draft may hide them
3858 # We have to check result on an unfiltered repository
3858 # We have to check result on an unfiltered repository
3859 unfi = repo.unfiltered()
3859 unfi = repo.unfiltered()
3860 getphase = unfi._phasecache.phase
3860 getphase = unfi._phasecache.phase
3861 olddata = [getphase(unfi, r) for r in unfi]
3861 olddata = [getphase(unfi, r) for r in unfi]
3862 phases.advanceboundary(repo, tr, targetphase, nodes)
3862 phases.advanceboundary(repo, tr, targetphase, nodes)
3863 if opts['force']:
3863 if opts['force']:
3864 phases.retractboundary(repo, tr, targetphase, nodes)
3864 phases.retractboundary(repo, tr, targetphase, nodes)
3865 tr.close()
3865 tr.close()
3866 finally:
3866 finally:
3867 if tr is not None:
3867 if tr is not None:
3868 tr.release()
3868 tr.release()
3869 lock.release()
3869 lock.release()
3870 getphase = unfi._phasecache.phase
3870 getphase = unfi._phasecache.phase
3871 newdata = [getphase(unfi, r) for r in unfi]
3871 newdata = [getphase(unfi, r) for r in unfi]
3872 changes = sum(newdata[r] != olddata[r] for r in unfi)
3872 changes = sum(newdata[r] != olddata[r] for r in unfi)
3873 cl = unfi.changelog
3873 cl = unfi.changelog
3874 rejected = [n for n in nodes
3874 rejected = [n for n in nodes
3875 if newdata[cl.rev(n)] < targetphase]
3875 if newdata[cl.rev(n)] < targetphase]
3876 if rejected:
3876 if rejected:
3877 ui.warn(_('cannot move %i changesets to a higher '
3877 ui.warn(_('cannot move %i changesets to a higher '
3878 'phase, use --force\n') % len(rejected))
3878 'phase, use --force\n') % len(rejected))
3879 ret = 1
3879 ret = 1
3880 if changes:
3880 if changes:
3881 msg = _('phase changed for %i changesets\n') % changes
3881 msg = _('phase changed for %i changesets\n') % changes
3882 if ret:
3882 if ret:
3883 ui.status(msg)
3883 ui.status(msg)
3884 else:
3884 else:
3885 ui.note(msg)
3885 ui.note(msg)
3886 else:
3886 else:
3887 ui.warn(_('no phases changed\n'))
3887 ui.warn(_('no phases changed\n'))
3888 return ret
3888 return ret
3889
3889
3890 def postincoming(ui, repo, modheads, optupdate, checkout, brev):
3890 def postincoming(ui, repo, modheads, optupdate, checkout, brev):
3891 """Run after a changegroup has been added via pull/unbundle
3891 """Run after a changegroup has been added via pull/unbundle
3892
3892
3893 This takes arguments below:
3893 This takes arguments below:
3894
3894
3895 :modheads: change of heads by pull/unbundle
3895 :modheads: change of heads by pull/unbundle
3896 :optupdate: updating working directory is needed or not
3896 :optupdate: updating working directory is needed or not
3897 :checkout: update destination revision (or None to default destination)
3897 :checkout: update destination revision (or None to default destination)
3898 :brev: a name, which might be a bookmark to be activated after updating
3898 :brev: a name, which might be a bookmark to be activated after updating
3899 """
3899 """
3900 if modheads == 0:
3900 if modheads == 0:
3901 return
3901 return
3902 if optupdate:
3902 if optupdate:
3903 try:
3903 try:
3904 return hg.updatetotally(ui, repo, checkout, brev)
3904 return hg.updatetotally(ui, repo, checkout, brev)
3905 except error.UpdateAbort as inst:
3905 except error.UpdateAbort as inst:
3906 msg = _("not updating: %s") % str(inst)
3906 msg = _("not updating: %s") % str(inst)
3907 hint = inst.hint
3907 hint = inst.hint
3908 raise error.UpdateAbort(msg, hint=hint)
3908 raise error.UpdateAbort(msg, hint=hint)
3909 if modheads > 1:
3909 if modheads > 1:
3910 currentbranchheads = len(repo.branchheads())
3910 currentbranchheads = len(repo.branchheads())
3911 if currentbranchheads == modheads:
3911 if currentbranchheads == modheads:
3912 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
3912 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
3913 elif currentbranchheads > 1:
3913 elif currentbranchheads > 1:
3914 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to "
3914 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to "
3915 "merge)\n"))
3915 "merge)\n"))
3916 else:
3916 else:
3917 ui.status(_("(run 'hg heads' to see heads)\n"))
3917 ui.status(_("(run 'hg heads' to see heads)\n"))
3918 elif not ui.configbool('commands', 'update.requiredest'):
3918 elif not ui.configbool('commands', 'update.requiredest'):
3919 ui.status(_("(run 'hg update' to get a working copy)\n"))
3919 ui.status(_("(run 'hg update' to get a working copy)\n"))
3920
3920
3921 @command('^pull',
3921 @command('^pull',
3922 [('u', 'update', None,
3922 [('u', 'update', None,
3923 _('update to new branch head if new descendants were pulled')),
3923 _('update to new branch head if new descendants were pulled')),
3924 ('f', 'force', None, _('run even when remote repository is unrelated')),
3924 ('f', 'force', None, _('run even when remote repository is unrelated')),
3925 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3925 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3926 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
3926 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
3927 ('b', 'branch', [], _('a specific branch you would like to pull'),
3927 ('b', 'branch', [], _('a specific branch you would like to pull'),
3928 _('BRANCH')),
3928 _('BRANCH')),
3929 ] + remoteopts,
3929 ] + remoteopts,
3930 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
3930 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
3931 def pull(ui, repo, source="default", **opts):
3931 def pull(ui, repo, source="default", **opts):
3932 """pull changes from the specified source
3932 """pull changes from the specified source
3933
3933
3934 Pull changes from a remote repository to a local one.
3934 Pull changes from a remote repository to a local one.
3935
3935
3936 This finds all changes from the repository at the specified path
3936 This finds all changes from the repository at the specified path
3937 or URL and adds them to a local repository (the current one unless
3937 or URL and adds them to a local repository (the current one unless
3938 -R is specified). By default, this does not update the copy of the
3938 -R is specified). By default, this does not update the copy of the
3939 project in the working directory.
3939 project in the working directory.
3940
3940
3941 Use :hg:`incoming` if you want to see what would have been added
3941 Use :hg:`incoming` if you want to see what would have been added
3942 by a pull at the time you issued this command. If you then decide
3942 by a pull at the time you issued this command. If you then decide
3943 to add those changes to the repository, you should use :hg:`pull
3943 to add those changes to the repository, you should use :hg:`pull
3944 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
3944 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
3945
3945
3946 If SOURCE is omitted, the 'default' path will be used.
3946 If SOURCE is omitted, the 'default' path will be used.
3947 See :hg:`help urls` for more information.
3947 See :hg:`help urls` for more information.
3948
3948
3949 Specifying bookmark as ``.`` is equivalent to specifying the active
3949 Specifying bookmark as ``.`` is equivalent to specifying the active
3950 bookmark's name.
3950 bookmark's name.
3951
3951
3952 Returns 0 on success, 1 if an update had unresolved files.
3952 Returns 0 on success, 1 if an update had unresolved files.
3953 """
3953 """
3954
3954
3955 opts = pycompat.byteskwargs(opts)
3955 opts = pycompat.byteskwargs(opts)
3956 if ui.configbool('commands', 'update.requiredest') and opts.get('update'):
3956 if ui.configbool('commands', 'update.requiredest') and opts.get('update'):
3957 msg = _('update destination required by configuration')
3957 msg = _('update destination required by configuration')
3958 hint = _('use hg pull followed by hg update DEST')
3958 hint = _('use hg pull followed by hg update DEST')
3959 raise error.Abort(msg, hint=hint)
3959 raise error.Abort(msg, hint=hint)
3960
3960
3961 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
3961 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
3962 ui.status(_('pulling from %s\n') % util.hidepassword(source))
3962 ui.status(_('pulling from %s\n') % util.hidepassword(source))
3963 other = hg.peer(repo, opts, source)
3963 other = hg.peer(repo, opts, source)
3964 try:
3964 try:
3965 revs, checkout = hg.addbranchrevs(repo, other, branches,
3965 revs, checkout = hg.addbranchrevs(repo, other, branches,
3966 opts.get('rev'))
3966 opts.get('rev'))
3967
3967
3968
3968
3969 pullopargs = {}
3969 pullopargs = {}
3970 if opts.get('bookmark'):
3970 if opts.get('bookmark'):
3971 if not revs:
3971 if not revs:
3972 revs = []
3972 revs = []
3973 # The list of bookmark used here is not the one used to actually
3973 # The list of bookmark used here is not the one used to actually
3974 # update the bookmark name. This can result in the revision pulled
3974 # update the bookmark name. This can result in the revision pulled
3975 # not ending up with the name of the bookmark because of a race
3975 # not ending up with the name of the bookmark because of a race
3976 # condition on the server. (See issue 4689 for details)
3976 # condition on the server. (See issue 4689 for details)
3977 remotebookmarks = other.listkeys('bookmarks')
3977 remotebookmarks = other.listkeys('bookmarks')
3978 remotebookmarks = bookmarks.unhexlifybookmarks(remotebookmarks)
3978 remotebookmarks = bookmarks.unhexlifybookmarks(remotebookmarks)
3979 pullopargs['remotebookmarks'] = remotebookmarks
3979 pullopargs['remotebookmarks'] = remotebookmarks
3980 for b in opts['bookmark']:
3980 for b in opts['bookmark']:
3981 b = repo._bookmarks.expandname(b)
3981 b = repo._bookmarks.expandname(b)
3982 if b not in remotebookmarks:
3982 if b not in remotebookmarks:
3983 raise error.Abort(_('remote bookmark %s not found!') % b)
3983 raise error.Abort(_('remote bookmark %s not found!') % b)
3984 revs.append(hex(remotebookmarks[b]))
3984 revs.append(hex(remotebookmarks[b]))
3985
3985
3986 if revs:
3986 if revs:
3987 try:
3987 try:
3988 # When 'rev' is a bookmark name, we cannot guarantee that it
3988 # When 'rev' is a bookmark name, we cannot guarantee that it
3989 # will be updated with that name because of a race condition
3989 # will be updated with that name because of a race condition
3990 # server side. (See issue 4689 for details)
3990 # server side. (See issue 4689 for details)
3991 oldrevs = revs
3991 oldrevs = revs
3992 revs = [] # actually, nodes
3992 revs = [] # actually, nodes
3993 for r in oldrevs:
3993 for r in oldrevs:
3994 node = other.lookup(r)
3994 node = other.lookup(r)
3995 revs.append(node)
3995 revs.append(node)
3996 if r == checkout:
3996 if r == checkout:
3997 checkout = node
3997 checkout = node
3998 except error.CapabilityError:
3998 except error.CapabilityError:
3999 err = _("other repository doesn't support revision lookup, "
3999 err = _("other repository doesn't support revision lookup, "
4000 "so a rev cannot be specified.")
4000 "so a rev cannot be specified.")
4001 raise error.Abort(err)
4001 raise error.Abort(err)
4002
4002
4003 pullopargs.update(opts.get('opargs', {}))
4003 pullopargs.update(opts.get('opargs', {}))
4004 modheads = exchange.pull(repo, other, heads=revs,
4004 modheads = exchange.pull(repo, other, heads=revs,
4005 force=opts.get('force'),
4005 force=opts.get('force'),
4006 bookmarks=opts.get('bookmark', ()),
4006 bookmarks=opts.get('bookmark', ()),
4007 opargs=pullopargs).cgresult
4007 opargs=pullopargs).cgresult
4008
4008
4009 # brev is a name, which might be a bookmark to be activated at
4009 # brev is a name, which might be a bookmark to be activated at
4010 # the end of the update. In other words, it is an explicit
4010 # the end of the update. In other words, it is an explicit
4011 # destination of the update
4011 # destination of the update
4012 brev = None
4012 brev = None
4013
4013
4014 if checkout:
4014 if checkout:
4015 checkout = str(repo.changelog.rev(checkout))
4015 checkout = str(repo.changelog.rev(checkout))
4016
4016
4017 # order below depends on implementation of
4017 # order below depends on implementation of
4018 # hg.addbranchrevs(). opts['bookmark'] is ignored,
4018 # hg.addbranchrevs(). opts['bookmark'] is ignored,
4019 # because 'checkout' is determined without it.
4019 # because 'checkout' is determined without it.
4020 if opts.get('rev'):
4020 if opts.get('rev'):
4021 brev = opts['rev'][0]
4021 brev = opts['rev'][0]
4022 elif opts.get('branch'):
4022 elif opts.get('branch'):
4023 brev = opts['branch'][0]
4023 brev = opts['branch'][0]
4024 else:
4024 else:
4025 brev = branches[0]
4025 brev = branches[0]
4026 repo._subtoppath = source
4026 repo._subtoppath = source
4027 try:
4027 try:
4028 ret = postincoming(ui, repo, modheads, opts.get('update'),
4028 ret = postincoming(ui, repo, modheads, opts.get('update'),
4029 checkout, brev)
4029 checkout, brev)
4030
4030
4031 finally:
4031 finally:
4032 del repo._subtoppath
4032 del repo._subtoppath
4033
4033
4034 finally:
4034 finally:
4035 other.close()
4035 other.close()
4036 return ret
4036 return ret
4037
4037
4038 @command('^push',
4038 @command('^push',
4039 [('f', 'force', None, _('force push')),
4039 [('f', 'force', None, _('force push')),
4040 ('r', 'rev', [],
4040 ('r', 'rev', [],
4041 _('a changeset intended to be included in the destination'),
4041 _('a changeset intended to be included in the destination'),
4042 _('REV')),
4042 _('REV')),
4043 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
4043 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
4044 ('b', 'branch', [],
4044 ('b', 'branch', [],
4045 _('a specific branch you would like to push'), _('BRANCH')),
4045 _('a specific branch you would like to push'), _('BRANCH')),
4046 ('', 'new-branch', False, _('allow pushing a new branch')),
4046 ('', 'new-branch', False, _('allow pushing a new branch')),
4047 ('', 'pushvars', [], _('variables that can be sent to server (ADVANCED)')),
4047 ('', 'pushvars', [], _('variables that can be sent to server (ADVANCED)')),
4048 ] + remoteopts,
4048 ] + remoteopts,
4049 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
4049 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
4050 def push(ui, repo, dest=None, **opts):
4050 def push(ui, repo, dest=None, **opts):
4051 """push changes to the specified destination
4051 """push changes to the specified destination
4052
4052
4053 Push changesets from the local repository to the specified
4053 Push changesets from the local repository to the specified
4054 destination.
4054 destination.
4055
4055
4056 This operation is symmetrical to pull: it is identical to a pull
4056 This operation is symmetrical to pull: it is identical to a pull
4057 in the destination repository from the current one.
4057 in the destination repository from the current one.
4058
4058
4059 By default, push will not allow creation of new heads at the
4059 By default, push will not allow creation of new heads at the
4060 destination, since multiple heads would make it unclear which head
4060 destination, since multiple heads would make it unclear which head
4061 to use. In this situation, it is recommended to pull and merge
4061 to use. In this situation, it is recommended to pull and merge
4062 before pushing.
4062 before pushing.
4063
4063
4064 Use --new-branch if you want to allow push to create a new named
4064 Use --new-branch if you want to allow push to create a new named
4065 branch that is not present at the destination. This allows you to
4065 branch that is not present at the destination. This allows you to
4066 only create a new branch without forcing other changes.
4066 only create a new branch without forcing other changes.
4067
4067
4068 .. note::
4068 .. note::
4069
4069
4070 Extra care should be taken with the -f/--force option,
4070 Extra care should be taken with the -f/--force option,
4071 which will push all new heads on all branches, an action which will
4071 which will push all new heads on all branches, an action which will
4072 almost always cause confusion for collaborators.
4072 almost always cause confusion for collaborators.
4073
4073
4074 If -r/--rev is used, the specified revision and all its ancestors
4074 If -r/--rev is used, the specified revision and all its ancestors
4075 will be pushed to the remote repository.
4075 will be pushed to the remote repository.
4076
4076
4077 If -B/--bookmark is used, the specified bookmarked revision, its
4077 If -B/--bookmark is used, the specified bookmarked revision, its
4078 ancestors, and the bookmark will be pushed to the remote
4078 ancestors, and the bookmark will be pushed to the remote
4079 repository. Specifying ``.`` is equivalent to specifying the active
4079 repository. Specifying ``.`` is equivalent to specifying the active
4080 bookmark's name.
4080 bookmark's name.
4081
4081
4082 Please see :hg:`help urls` for important details about ``ssh://``
4082 Please see :hg:`help urls` for important details about ``ssh://``
4083 URLs. If DESTINATION is omitted, a default path will be used.
4083 URLs. If DESTINATION is omitted, a default path will be used.
4084
4084
4085 .. container:: verbose
4085 .. container:: verbose
4086
4086
4087 The --pushvars option sends strings to the server that become
4087 The --pushvars option sends strings to the server that become
4088 environment variables prepended with ``HG_USERVAR_``. For example,
4088 environment variables prepended with ``HG_USERVAR_``. For example,
4089 ``--pushvars ENABLE_FEATURE=true``, provides the server side hooks with
4089 ``--pushvars ENABLE_FEATURE=true``, provides the server side hooks with
4090 ``HG_USERVAR_ENABLE_FEATURE=true`` as part of their environment.
4090 ``HG_USERVAR_ENABLE_FEATURE=true`` as part of their environment.
4091
4091
4092 pushvars can provide for user-overridable hooks as well as set debug
4092 pushvars can provide for user-overridable hooks as well as set debug
4093 levels. One example is having a hook that blocks commits containing
4093 levels. One example is having a hook that blocks commits containing
4094 conflict markers, but enables the user to override the hook if the file
4094 conflict markers, but enables the user to override the hook if the file
4095 is using conflict markers for testing purposes or the file format has
4095 is using conflict markers for testing purposes or the file format has
4096 strings that look like conflict markers.
4096 strings that look like conflict markers.
4097
4097
4098 By default, servers will ignore `--pushvars`. To enable it add the
4098 By default, servers will ignore `--pushvars`. To enable it add the
4099 following to your configuration file::
4099 following to your configuration file::
4100
4100
4101 [push]
4101 [push]
4102 pushvars.server = true
4102 pushvars.server = true
4103
4103
4104 Returns 0 if push was successful, 1 if nothing to push.
4104 Returns 0 if push was successful, 1 if nothing to push.
4105 """
4105 """
4106
4106
4107 opts = pycompat.byteskwargs(opts)
4107 opts = pycompat.byteskwargs(opts)
4108 if opts.get('bookmark'):
4108 if opts.get('bookmark'):
4109 ui.setconfig('bookmarks', 'pushing', opts['bookmark'], 'push')
4109 ui.setconfig('bookmarks', 'pushing', opts['bookmark'], 'push')
4110 for b in opts['bookmark']:
4110 for b in opts['bookmark']:
4111 # translate -B options to -r so changesets get pushed
4111 # translate -B options to -r so changesets get pushed
4112 b = repo._bookmarks.expandname(b)
4112 b = repo._bookmarks.expandname(b)
4113 if b in repo._bookmarks:
4113 if b in repo._bookmarks:
4114 opts.setdefault('rev', []).append(b)
4114 opts.setdefault('rev', []).append(b)
4115 else:
4115 else:
4116 # if we try to push a deleted bookmark, translate it to null
4116 # if we try to push a deleted bookmark, translate it to null
4117 # this lets simultaneous -r, -b options continue working
4117 # this lets simultaneous -r, -b options continue working
4118 opts.setdefault('rev', []).append("null")
4118 opts.setdefault('rev', []).append("null")
4119
4119
4120 path = ui.paths.getpath(dest, default=('default-push', 'default'))
4120 path = ui.paths.getpath(dest, default=('default-push', 'default'))
4121 if not path:
4121 if not path:
4122 raise error.Abort(_('default repository not configured!'),
4122 raise error.Abort(_('default repository not configured!'),
4123 hint=_("see 'hg help config.paths'"))
4123 hint=_("see 'hg help config.paths'"))
4124 dest = path.pushloc or path.loc
4124 dest = path.pushloc or path.loc
4125 branches = (path.branch, opts.get('branch') or [])
4125 branches = (path.branch, opts.get('branch') or [])
4126 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
4126 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
4127 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
4127 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
4128 other = hg.peer(repo, opts, dest)
4128 other = hg.peer(repo, opts, dest)
4129
4129
4130 if revs:
4130 if revs:
4131 revs = [repo.lookup(r) for r in scmutil.revrange(repo, revs)]
4131 revs = [repo.lookup(r) for r in scmutil.revrange(repo, revs)]
4132 if not revs:
4132 if not revs:
4133 raise error.Abort(_("specified revisions evaluate to an empty set"),
4133 raise error.Abort(_("specified revisions evaluate to an empty set"),
4134 hint=_("use different revision arguments"))
4134 hint=_("use different revision arguments"))
4135 elif path.pushrev:
4135 elif path.pushrev:
4136 # It doesn't make any sense to specify ancestor revisions. So limit
4136 # It doesn't make any sense to specify ancestor revisions. So limit
4137 # to DAG heads to make discovery simpler.
4137 # to DAG heads to make discovery simpler.
4138 expr = revsetlang.formatspec('heads(%r)', path.pushrev)
4138 expr = revsetlang.formatspec('heads(%r)', path.pushrev)
4139 revs = scmutil.revrange(repo, [expr])
4139 revs = scmutil.revrange(repo, [expr])
4140 revs = [repo[rev].node() for rev in revs]
4140 revs = [repo[rev].node() for rev in revs]
4141 if not revs:
4141 if not revs:
4142 raise error.Abort(_('default push revset for path evaluates to an '
4142 raise error.Abort(_('default push revset for path evaluates to an '
4143 'empty set'))
4143 'empty set'))
4144
4144
4145 repo._subtoppath = dest
4145 repo._subtoppath = dest
4146 try:
4146 try:
4147 # push subrepos depth-first for coherent ordering
4147 # push subrepos depth-first for coherent ordering
4148 c = repo['']
4148 c = repo['']
4149 subs = c.substate # only repos that are committed
4149 subs = c.substate # only repos that are committed
4150 for s in sorted(subs):
4150 for s in sorted(subs):
4151 result = c.sub(s).push(opts)
4151 result = c.sub(s).push(opts)
4152 if result == 0:
4152 if result == 0:
4153 return not result
4153 return not result
4154 finally:
4154 finally:
4155 del repo._subtoppath
4155 del repo._subtoppath
4156
4156
4157 opargs = dict(opts.get('opargs', {})) # copy opargs since we may mutate it
4157 opargs = dict(opts.get('opargs', {})) # copy opargs since we may mutate it
4158 opargs.setdefault('pushvars', []).extend(opts.get('pushvars', []))
4158 opargs.setdefault('pushvars', []).extend(opts.get('pushvars', []))
4159
4159
4160 pushop = exchange.push(repo, other, opts.get('force'), revs=revs,
4160 pushop = exchange.push(repo, other, opts.get('force'), revs=revs,
4161 newbranch=opts.get('new_branch'),
4161 newbranch=opts.get('new_branch'),
4162 bookmarks=opts.get('bookmark', ()),
4162 bookmarks=opts.get('bookmark', ()),
4163 opargs=opargs)
4163 opargs=opargs)
4164
4164
4165 result = not pushop.cgresult
4165 result = not pushop.cgresult
4166
4166
4167 if pushop.bkresult is not None:
4167 if pushop.bkresult is not None:
4168 if pushop.bkresult == 2:
4168 if pushop.bkresult == 2:
4169 result = 2
4169 result = 2
4170 elif not result and pushop.bkresult:
4170 elif not result and pushop.bkresult:
4171 result = 2
4171 result = 2
4172
4172
4173 return result
4173 return result
4174
4174
4175 @command('recover', [])
4175 @command('recover', [])
4176 def recover(ui, repo):
4176 def recover(ui, repo):
4177 """roll back an interrupted transaction
4177 """roll back an interrupted transaction
4178
4178
4179 Recover from an interrupted commit or pull.
4179 Recover from an interrupted commit or pull.
4180
4180
4181 This command tries to fix the repository status after an
4181 This command tries to fix the repository status after an
4182 interrupted operation. It should only be necessary when Mercurial
4182 interrupted operation. It should only be necessary when Mercurial
4183 suggests it.
4183 suggests it.
4184
4184
4185 Returns 0 if successful, 1 if nothing to recover or verify fails.
4185 Returns 0 if successful, 1 if nothing to recover or verify fails.
4186 """
4186 """
4187 if repo.recover():
4187 if repo.recover():
4188 return hg.verify(repo)
4188 return hg.verify(repo)
4189 return 1
4189 return 1
4190
4190
4191 @command('^remove|rm',
4191 @command('^remove|rm',
4192 [('A', 'after', None, _('record delete for missing files')),
4192 [('A', 'after', None, _('record delete for missing files')),
4193 ('f', 'force', None,
4193 ('f', 'force', None,
4194 _('forget added files, delete modified files')),
4194 _('forget added files, delete modified files')),
4195 ] + subrepoopts + walkopts,
4195 ] + subrepoopts + walkopts,
4196 _('[OPTION]... FILE...'),
4196 _('[OPTION]... FILE...'),
4197 inferrepo=True)
4197 inferrepo=True)
4198 def remove(ui, repo, *pats, **opts):
4198 def remove(ui, repo, *pats, **opts):
4199 """remove the specified files on the next commit
4199 """remove the specified files on the next commit
4200
4200
4201 Schedule the indicated files for removal from the current branch.
4201 Schedule the indicated files for removal from the current branch.
4202
4202
4203 This command schedules the files to be removed at the next commit.
4203 This command schedules the files to be removed at the next commit.
4204 To undo a remove before that, see :hg:`revert`. To undo added
4204 To undo a remove before that, see :hg:`revert`. To undo added
4205 files, see :hg:`forget`.
4205 files, see :hg:`forget`.
4206
4206
4207 .. container:: verbose
4207 .. container:: verbose
4208
4208
4209 -A/--after can be used to remove only files that have already
4209 -A/--after can be used to remove only files that have already
4210 been deleted, -f/--force can be used to force deletion, and -Af
4210 been deleted, -f/--force can be used to force deletion, and -Af
4211 can be used to remove files from the next revision without
4211 can be used to remove files from the next revision without
4212 deleting them from the working directory.
4212 deleting them from the working directory.
4213
4213
4214 The following table details the behavior of remove for different
4214 The following table details the behavior of remove for different
4215 file states (columns) and option combinations (rows). The file
4215 file states (columns) and option combinations (rows). The file
4216 states are Added [A], Clean [C], Modified [M] and Missing [!]
4216 states are Added [A], Clean [C], Modified [M] and Missing [!]
4217 (as reported by :hg:`status`). The actions are Warn, Remove
4217 (as reported by :hg:`status`). The actions are Warn, Remove
4218 (from branch) and Delete (from disk):
4218 (from branch) and Delete (from disk):
4219
4219
4220 ========= == == == ==
4220 ========= == == == ==
4221 opt/state A C M !
4221 opt/state A C M !
4222 ========= == == == ==
4222 ========= == == == ==
4223 none W RD W R
4223 none W RD W R
4224 -f R RD RD R
4224 -f R RD RD R
4225 -A W W W R
4225 -A W W W R
4226 -Af R R R R
4226 -Af R R R R
4227 ========= == == == ==
4227 ========= == == == ==
4228
4228
4229 .. note::
4229 .. note::
4230
4230
4231 :hg:`remove` never deletes files in Added [A] state from the
4231 :hg:`remove` never deletes files in Added [A] state from the
4232 working directory, not even if ``--force`` is specified.
4232 working directory, not even if ``--force`` is specified.
4233
4233
4234 Returns 0 on success, 1 if any warnings encountered.
4234 Returns 0 on success, 1 if any warnings encountered.
4235 """
4235 """
4236
4236
4237 opts = pycompat.byteskwargs(opts)
4237 opts = pycompat.byteskwargs(opts)
4238 after, force = opts.get('after'), opts.get('force')
4238 after, force = opts.get('after'), opts.get('force')
4239 if not pats and not after:
4239 if not pats and not after:
4240 raise error.Abort(_('no files specified'))
4240 raise error.Abort(_('no files specified'))
4241
4241
4242 m = scmutil.match(repo[None], pats, opts)
4242 m = scmutil.match(repo[None], pats, opts)
4243 subrepos = opts.get('subrepos')
4243 subrepos = opts.get('subrepos')
4244 return cmdutil.remove(ui, repo, m, "", after, force, subrepos)
4244 return cmdutil.remove(ui, repo, m, "", after, force, subrepos)
4245
4245
4246 @command('rename|move|mv',
4246 @command('rename|move|mv',
4247 [('A', 'after', None, _('record a rename that has already occurred')),
4247 [('A', 'after', None, _('record a rename that has already occurred')),
4248 ('f', 'force', None, _('forcibly copy over an existing managed file')),
4248 ('f', 'force', None, _('forcibly copy over an existing managed file')),
4249 ] + walkopts + dryrunopts,
4249 ] + walkopts + dryrunopts,
4250 _('[OPTION]... SOURCE... DEST'))
4250 _('[OPTION]... SOURCE... DEST'))
4251 def rename(ui, repo, *pats, **opts):
4251 def rename(ui, repo, *pats, **opts):
4252 """rename files; equivalent of copy + remove
4252 """rename files; equivalent of copy + remove
4253
4253
4254 Mark dest as copies of sources; mark sources for deletion. If dest
4254 Mark dest as copies of sources; mark sources for deletion. If dest
4255 is a directory, copies are put in that directory. If dest is a
4255 is a directory, copies are put in that directory. If dest is a
4256 file, there can only be one source.
4256 file, there can only be one source.
4257
4257
4258 By default, this command copies the contents of files as they
4258 By default, this command copies the contents of files as they
4259 exist in the working directory. If invoked with -A/--after, the
4259 exist in the working directory. If invoked with -A/--after, the
4260 operation is recorded, but no copying is performed.
4260 operation is recorded, but no copying is performed.
4261
4261
4262 This command takes effect at the next commit. To undo a rename
4262 This command takes effect at the next commit. To undo a rename
4263 before that, see :hg:`revert`.
4263 before that, see :hg:`revert`.
4264
4264
4265 Returns 0 on success, 1 if errors are encountered.
4265 Returns 0 on success, 1 if errors are encountered.
4266 """
4266 """
4267 opts = pycompat.byteskwargs(opts)
4267 opts = pycompat.byteskwargs(opts)
4268 with repo.wlock(False):
4268 with repo.wlock(False):
4269 return cmdutil.copy(ui, repo, pats, opts, rename=True)
4269 return cmdutil.copy(ui, repo, pats, opts, rename=True)
4270
4270
4271 @command('resolve',
4271 @command('resolve',
4272 [('a', 'all', None, _('select all unresolved files')),
4272 [('a', 'all', None, _('select all unresolved files')),
4273 ('l', 'list', None, _('list state of files needing merge')),
4273 ('l', 'list', None, _('list state of files needing merge')),
4274 ('m', 'mark', None, _('mark files as resolved')),
4274 ('m', 'mark', None, _('mark files as resolved')),
4275 ('u', 'unmark', None, _('mark files as unresolved')),
4275 ('u', 'unmark', None, _('mark files as unresolved')),
4276 ('n', 'no-status', None, _('hide status prefix'))]
4276 ('n', 'no-status', None, _('hide status prefix'))]
4277 + mergetoolopts + walkopts + formatteropts,
4277 + mergetoolopts + walkopts + formatteropts,
4278 _('[OPTION]... [FILE]...'),
4278 _('[OPTION]... [FILE]...'),
4279 inferrepo=True)
4279 inferrepo=True)
4280 def resolve(ui, repo, *pats, **opts):
4280 def resolve(ui, repo, *pats, **opts):
4281 """redo merges or set/view the merge status of files
4281 """redo merges or set/view the merge status of files
4282
4282
4283 Merges with unresolved conflicts are often the result of
4283 Merges with unresolved conflicts are often the result of
4284 non-interactive merging using the ``internal:merge`` configuration
4284 non-interactive merging using the ``internal:merge`` configuration
4285 setting, or a command-line merge tool like ``diff3``. The resolve
4285 setting, or a command-line merge tool like ``diff3``. The resolve
4286 command is used to manage the files involved in a merge, after
4286 command is used to manage the files involved in a merge, after
4287 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
4287 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
4288 working directory must have two parents). See :hg:`help
4288 working directory must have two parents). See :hg:`help
4289 merge-tools` for information on configuring merge tools.
4289 merge-tools` for information on configuring merge tools.
4290
4290
4291 The resolve command can be used in the following ways:
4291 The resolve command can be used in the following ways:
4292
4292
4293 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
4293 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
4294 files, discarding any previous merge attempts. Re-merging is not
4294 files, discarding any previous merge attempts. Re-merging is not
4295 performed for files already marked as resolved. Use ``--all/-a``
4295 performed for files already marked as resolved. Use ``--all/-a``
4296 to select all unresolved files. ``--tool`` can be used to specify
4296 to select all unresolved files. ``--tool`` can be used to specify
4297 the merge tool used for the given files. It overrides the HGMERGE
4297 the merge tool used for the given files. It overrides the HGMERGE
4298 environment variable and your configuration files. Previous file
4298 environment variable and your configuration files. Previous file
4299 contents are saved with a ``.orig`` suffix.
4299 contents are saved with a ``.orig`` suffix.
4300
4300
4301 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
4301 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
4302 (e.g. after having manually fixed-up the files). The default is
4302 (e.g. after having manually fixed-up the files). The default is
4303 to mark all unresolved files.
4303 to mark all unresolved files.
4304
4304
4305 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
4305 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
4306 default is to mark all resolved files.
4306 default is to mark all resolved files.
4307
4307
4308 - :hg:`resolve -l`: list files which had or still have conflicts.
4308 - :hg:`resolve -l`: list files which had or still have conflicts.
4309 In the printed list, ``U`` = unresolved and ``R`` = resolved.
4309 In the printed list, ``U`` = unresolved and ``R`` = resolved.
4310 You can use ``set:unresolved()`` or ``set:resolved()`` to filter
4310 You can use ``set:unresolved()`` or ``set:resolved()`` to filter
4311 the list. See :hg:`help filesets` for details.
4311 the list. See :hg:`help filesets` for details.
4312
4312
4313 .. note::
4313 .. note::
4314
4314
4315 Mercurial will not let you commit files with unresolved merge
4315 Mercurial will not let you commit files with unresolved merge
4316 conflicts. You must use :hg:`resolve -m ...` before you can
4316 conflicts. You must use :hg:`resolve -m ...` before you can
4317 commit after a conflicting merge.
4317 commit after a conflicting merge.
4318
4318
4319 Returns 0 on success, 1 if any files fail a resolve attempt.
4319 Returns 0 on success, 1 if any files fail a resolve attempt.
4320 """
4320 """
4321
4321
4322 opts = pycompat.byteskwargs(opts)
4322 opts = pycompat.byteskwargs(opts)
4323 flaglist = 'all mark unmark list no_status'.split()
4323 flaglist = 'all mark unmark list no_status'.split()
4324 all, mark, unmark, show, nostatus = \
4324 all, mark, unmark, show, nostatus = \
4325 [opts.get(o) for o in flaglist]
4325 [opts.get(o) for o in flaglist]
4326
4326
4327 if (show and (mark or unmark)) or (mark and unmark):
4327 if (show and (mark or unmark)) or (mark and unmark):
4328 raise error.Abort(_("too many options specified"))
4328 raise error.Abort(_("too many options specified"))
4329 if pats and all:
4329 if pats and all:
4330 raise error.Abort(_("can't specify --all and patterns"))
4330 raise error.Abort(_("can't specify --all and patterns"))
4331 if not (all or pats or show or mark or unmark):
4331 if not (all or pats or show or mark or unmark):
4332 raise error.Abort(_('no files or directories specified'),
4332 raise error.Abort(_('no files or directories specified'),
4333 hint=('use --all to re-merge all unresolved files'))
4333 hint=('use --all to re-merge all unresolved files'))
4334
4334
4335 if show:
4335 if show:
4336 ui.pager('resolve')
4336 ui.pager('resolve')
4337 fm = ui.formatter('resolve', opts)
4337 fm = ui.formatter('resolve', opts)
4338 ms = mergemod.mergestate.read(repo)
4338 ms = mergemod.mergestate.read(repo)
4339 m = scmutil.match(repo[None], pats, opts)
4339 m = scmutil.match(repo[None], pats, opts)
4340
4340
4341 # Labels and keys based on merge state. Unresolved path conflicts show
4341 # Labels and keys based on merge state. Unresolved path conflicts show
4342 # as 'P'. Resolved path conflicts show as 'R', the same as normal
4342 # as 'P'. Resolved path conflicts show as 'R', the same as normal
4343 # resolved conflicts.
4343 # resolved conflicts.
4344 mergestateinfo = {
4344 mergestateinfo = {
4345 'u': ('resolve.unresolved', 'U'),
4345 'u': ('resolve.unresolved', 'U'),
4346 'r': ('resolve.resolved', 'R'),
4346 'r': ('resolve.resolved', 'R'),
4347 'pu': ('resolve.unresolved', 'P'),
4347 'pu': ('resolve.unresolved', 'P'),
4348 'pr': ('resolve.resolved', 'R'),
4348 'pr': ('resolve.resolved', 'R'),
4349 'd': ('resolve.driverresolved', 'D'),
4349 'd': ('resolve.driverresolved', 'D'),
4350 }
4350 }
4351
4351
4352 for f in ms:
4352 for f in ms:
4353 if not m(f):
4353 if not m(f):
4354 continue
4354 continue
4355
4355
4356 label, key = mergestateinfo[ms[f]]
4356 label, key = mergestateinfo[ms[f]]
4357 fm.startitem()
4357 fm.startitem()
4358 fm.condwrite(not nostatus, 'status', '%s ', key, label=label)
4358 fm.condwrite(not nostatus, 'status', '%s ', key, label=label)
4359 fm.write('path', '%s\n', f, label=label)
4359 fm.write('path', '%s\n', f, label=label)
4360 fm.end()
4360 fm.end()
4361 return 0
4361 return 0
4362
4362
4363 with repo.wlock():
4363 with repo.wlock():
4364 ms = mergemod.mergestate.read(repo)
4364 ms = mergemod.mergestate.read(repo)
4365
4365
4366 if not (ms.active() or repo.dirstate.p2() != nullid):
4366 if not (ms.active() or repo.dirstate.p2() != nullid):
4367 raise error.Abort(
4367 raise error.Abort(
4368 _('resolve command not applicable when not merging'))
4368 _('resolve command not applicable when not merging'))
4369
4369
4370 wctx = repo[None]
4370 wctx = repo[None]
4371
4371
4372 if ms.mergedriver and ms.mdstate() == 'u':
4372 if ms.mergedriver and ms.mdstate() == 'u':
4373 proceed = mergemod.driverpreprocess(repo, ms, wctx)
4373 proceed = mergemod.driverpreprocess(repo, ms, wctx)
4374 ms.commit()
4374 ms.commit()
4375 # allow mark and unmark to go through
4375 # allow mark and unmark to go through
4376 if not mark and not unmark and not proceed:
4376 if not mark and not unmark and not proceed:
4377 return 1
4377 return 1
4378
4378
4379 m = scmutil.match(wctx, pats, opts)
4379 m = scmutil.match(wctx, pats, opts)
4380 ret = 0
4380 ret = 0
4381 didwork = False
4381 didwork = False
4382 runconclude = False
4382 runconclude = False
4383
4383
4384 tocomplete = []
4384 tocomplete = []
4385 for f in ms:
4385 for f in ms:
4386 if not m(f):
4386 if not m(f):
4387 continue
4387 continue
4388
4388
4389 didwork = True
4389 didwork = True
4390
4390
4391 # don't let driver-resolved files be marked, and run the conclude
4391 # don't let driver-resolved files be marked, and run the conclude
4392 # step if asked to resolve
4392 # step if asked to resolve
4393 if ms[f] == "d":
4393 if ms[f] == "d":
4394 exact = m.exact(f)
4394 exact = m.exact(f)
4395 if mark:
4395 if mark:
4396 if exact:
4396 if exact:
4397 ui.warn(_('not marking %s as it is driver-resolved\n')
4397 ui.warn(_('not marking %s as it is driver-resolved\n')
4398 % f)
4398 % f)
4399 elif unmark:
4399 elif unmark:
4400 if exact:
4400 if exact:
4401 ui.warn(_('not unmarking %s as it is driver-resolved\n')
4401 ui.warn(_('not unmarking %s as it is driver-resolved\n')
4402 % f)
4402 % f)
4403 else:
4403 else:
4404 runconclude = True
4404 runconclude = True
4405 continue
4405 continue
4406
4406
4407 # path conflicts must be resolved manually
4407 # path conflicts must be resolved manually
4408 if ms[f] in ("pu", "pr"):
4408 if ms[f] in ("pu", "pr"):
4409 if mark:
4409 if mark:
4410 ms.mark(f, "pr")
4410 ms.mark(f, "pr")
4411 elif unmark:
4411 elif unmark:
4412 ms.mark(f, "pu")
4412 ms.mark(f, "pu")
4413 elif ms[f] == "pu":
4413 elif ms[f] == "pu":
4414 ui.warn(_('%s: path conflict must be resolved manually\n')
4414 ui.warn(_('%s: path conflict must be resolved manually\n')
4415 % f)
4415 % f)
4416 continue
4416 continue
4417
4417
4418 if mark:
4418 if mark:
4419 ms.mark(f, "r")
4419 ms.mark(f, "r")
4420 elif unmark:
4420 elif unmark:
4421 ms.mark(f, "u")
4421 ms.mark(f, "u")
4422 else:
4422 else:
4423 # backup pre-resolve (merge uses .orig for its own purposes)
4423 # backup pre-resolve (merge uses .orig for its own purposes)
4424 a = repo.wjoin(f)
4424 a = repo.wjoin(f)
4425 try:
4425 try:
4426 util.copyfile(a, a + ".resolve")
4426 util.copyfile(a, a + ".resolve")
4427 except (IOError, OSError) as inst:
4427 except (IOError, OSError) as inst:
4428 if inst.errno != errno.ENOENT:
4428 if inst.errno != errno.ENOENT:
4429 raise
4429 raise
4430
4430
4431 try:
4431 try:
4432 # preresolve file
4432 # preresolve file
4433 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
4433 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
4434 'resolve')
4434 'resolve')
4435 complete, r = ms.preresolve(f, wctx)
4435 complete, r = ms.preresolve(f, wctx)
4436 if not complete:
4436 if not complete:
4437 tocomplete.append(f)
4437 tocomplete.append(f)
4438 elif r:
4438 elif r:
4439 ret = 1
4439 ret = 1
4440 finally:
4440 finally:
4441 ui.setconfig('ui', 'forcemerge', '', 'resolve')
4441 ui.setconfig('ui', 'forcemerge', '', 'resolve')
4442 ms.commit()
4442 ms.commit()
4443
4443
4444 # replace filemerge's .orig file with our resolve file, but only
4444 # replace filemerge's .orig file with our resolve file, but only
4445 # for merges that are complete
4445 # for merges that are complete
4446 if complete:
4446 if complete:
4447 try:
4447 try:
4448 util.rename(a + ".resolve",
4448 util.rename(a + ".resolve",
4449 scmutil.origpath(ui, repo, a))
4449 scmutil.origpath(ui, repo, a))
4450 except OSError as inst:
4450 except OSError as inst:
4451 if inst.errno != errno.ENOENT:
4451 if inst.errno != errno.ENOENT:
4452 raise
4452 raise
4453
4453
4454 for f in tocomplete:
4454 for f in tocomplete:
4455 try:
4455 try:
4456 # resolve file
4456 # resolve file
4457 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
4457 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
4458 'resolve')
4458 'resolve')
4459 r = ms.resolve(f, wctx)
4459 r = ms.resolve(f, wctx)
4460 if r:
4460 if r:
4461 ret = 1
4461 ret = 1
4462 finally:
4462 finally:
4463 ui.setconfig('ui', 'forcemerge', '', 'resolve')
4463 ui.setconfig('ui', 'forcemerge', '', 'resolve')
4464 ms.commit()
4464 ms.commit()
4465
4465
4466 # replace filemerge's .orig file with our resolve file
4466 # replace filemerge's .orig file with our resolve file
4467 a = repo.wjoin(f)
4467 a = repo.wjoin(f)
4468 try:
4468 try:
4469 util.rename(a + ".resolve", scmutil.origpath(ui, repo, a))
4469 util.rename(a + ".resolve", scmutil.origpath(ui, repo, a))
4470 except OSError as inst:
4470 except OSError as inst:
4471 if inst.errno != errno.ENOENT:
4471 if inst.errno != errno.ENOENT:
4472 raise
4472 raise
4473
4473
4474 ms.commit()
4474 ms.commit()
4475 ms.recordactions()
4475 ms.recordactions()
4476
4476
4477 if not didwork and pats:
4477 if not didwork and pats:
4478 hint = None
4478 hint = None
4479 if not any([p for p in pats if p.find(':') >= 0]):
4479 if not any([p for p in pats if p.find(':') >= 0]):
4480 pats = ['path:%s' % p for p in pats]
4480 pats = ['path:%s' % p for p in pats]
4481 m = scmutil.match(wctx, pats, opts)
4481 m = scmutil.match(wctx, pats, opts)
4482 for f in ms:
4482 for f in ms:
4483 if not m(f):
4483 if not m(f):
4484 continue
4484 continue
4485 flags = ''.join(['-%s ' % o[0] for o in flaglist
4485 flags = ''.join(['-%s ' % o[0] for o in flaglist
4486 if opts.get(o)])
4486 if opts.get(o)])
4487 hint = _("(try: hg resolve %s%s)\n") % (
4487 hint = _("(try: hg resolve %s%s)\n") % (
4488 flags,
4488 flags,
4489 ' '.join(pats))
4489 ' '.join(pats))
4490 break
4490 break
4491 ui.warn(_("arguments do not match paths that need resolving\n"))
4491 ui.warn(_("arguments do not match paths that need resolving\n"))
4492 if hint:
4492 if hint:
4493 ui.warn(hint)
4493 ui.warn(hint)
4494 elif ms.mergedriver and ms.mdstate() != 's':
4494 elif ms.mergedriver and ms.mdstate() != 's':
4495 # run conclude step when either a driver-resolved file is requested
4495 # run conclude step when either a driver-resolved file is requested
4496 # or there are no driver-resolved files
4496 # or there are no driver-resolved files
4497 # we can't use 'ret' to determine whether any files are unresolved
4497 # we can't use 'ret' to determine whether any files are unresolved
4498 # because we might not have tried to resolve some
4498 # because we might not have tried to resolve some
4499 if ((runconclude or not list(ms.driverresolved()))
4499 if ((runconclude or not list(ms.driverresolved()))
4500 and not list(ms.unresolved())):
4500 and not list(ms.unresolved())):
4501 proceed = mergemod.driverconclude(repo, ms, wctx)
4501 proceed = mergemod.driverconclude(repo, ms, wctx)
4502 ms.commit()
4502 ms.commit()
4503 if not proceed:
4503 if not proceed:
4504 return 1
4504 return 1
4505
4505
4506 # Nudge users into finishing an unfinished operation
4506 # Nudge users into finishing an unfinished operation
4507 unresolvedf = list(ms.unresolved())
4507 unresolvedf = list(ms.unresolved())
4508 driverresolvedf = list(ms.driverresolved())
4508 driverresolvedf = list(ms.driverresolved())
4509 if not unresolvedf and not driverresolvedf:
4509 if not unresolvedf and not driverresolvedf:
4510 ui.status(_('(no more unresolved files)\n'))
4510 ui.status(_('(no more unresolved files)\n'))
4511 cmdutil.checkafterresolved(repo)
4511 cmdutil.checkafterresolved(repo)
4512 elif not unresolvedf:
4512 elif not unresolvedf:
4513 ui.status(_('(no more unresolved files -- '
4513 ui.status(_('(no more unresolved files -- '
4514 'run "hg resolve --all" to conclude)\n'))
4514 'run "hg resolve --all" to conclude)\n'))
4515
4515
4516 return ret
4516 return ret
4517
4517
4518 @command('revert',
4518 @command('revert',
4519 [('a', 'all', None, _('revert all changes when no arguments given')),
4519 [('a', 'all', None, _('revert all changes when no arguments given')),
4520 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
4520 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
4521 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
4521 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
4522 ('C', 'no-backup', None, _('do not save backup copies of files')),
4522 ('C', 'no-backup', None, _('do not save backup copies of files')),
4523 ('i', 'interactive', None, _('interactively select the changes')),
4523 ('i', 'interactive', None, _('interactively select the changes')),
4524 ] + walkopts + dryrunopts,
4524 ] + walkopts + dryrunopts,
4525 _('[OPTION]... [-r REV] [NAME]...'))
4525 _('[OPTION]... [-r REV] [NAME]...'))
4526 def revert(ui, repo, *pats, **opts):
4526 def revert(ui, repo, *pats, **opts):
4527 """restore files to their checkout state
4527 """restore files to their checkout state
4528
4528
4529 .. note::
4529 .. note::
4530
4530
4531 To check out earlier revisions, you should use :hg:`update REV`.
4531 To check out earlier revisions, you should use :hg:`update REV`.
4532 To cancel an uncommitted merge (and lose your changes),
4532 To cancel an uncommitted merge (and lose your changes),
4533 use :hg:`update --clean .`.
4533 use :hg:`update --clean .`.
4534
4534
4535 With no revision specified, revert the specified files or directories
4535 With no revision specified, revert the specified files or directories
4536 to the contents they had in the parent of the working directory.
4536 to the contents they had in the parent of the working directory.
4537 This restores the contents of files to an unmodified
4537 This restores the contents of files to an unmodified
4538 state and unschedules adds, removes, copies, and renames. If the
4538 state and unschedules adds, removes, copies, and renames. If the
4539 working directory has two parents, you must explicitly specify a
4539 working directory has two parents, you must explicitly specify a
4540 revision.
4540 revision.
4541
4541
4542 Using the -r/--rev or -d/--date options, revert the given files or
4542 Using the -r/--rev or -d/--date options, revert the given files or
4543 directories to their states as of a specific revision. Because
4543 directories to their states as of a specific revision. Because
4544 revert does not change the working directory parents, this will
4544 revert does not change the working directory parents, this will
4545 cause these files to appear modified. This can be helpful to "back
4545 cause these files to appear modified. This can be helpful to "back
4546 out" some or all of an earlier change. See :hg:`backout` for a
4546 out" some or all of an earlier change. See :hg:`backout` for a
4547 related method.
4547 related method.
4548
4548
4549 Modified files are saved with a .orig suffix before reverting.
4549 Modified files are saved with a .orig suffix before reverting.
4550 To disable these backups, use --no-backup. It is possible to store
4550 To disable these backups, use --no-backup. It is possible to store
4551 the backup files in a custom directory relative to the root of the
4551 the backup files in a custom directory relative to the root of the
4552 repository by setting the ``ui.origbackuppath`` configuration
4552 repository by setting the ``ui.origbackuppath`` configuration
4553 option.
4553 option.
4554
4554
4555 See :hg:`help dates` for a list of formats valid for -d/--date.
4555 See :hg:`help dates` for a list of formats valid for -d/--date.
4556
4556
4557 See :hg:`help backout` for a way to reverse the effect of an
4557 See :hg:`help backout` for a way to reverse the effect of an
4558 earlier changeset.
4558 earlier changeset.
4559
4559
4560 Returns 0 on success.
4560 Returns 0 on success.
4561 """
4561 """
4562
4562
4563 opts = pycompat.byteskwargs(opts)
4563 if opts.get("date"):
4564 if opts.get("date"):
4564 if opts.get("rev"):
4565 if opts.get("rev"):
4565 raise error.Abort(_("you can't specify a revision and a date"))
4566 raise error.Abort(_("you can't specify a revision and a date"))
4566 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
4567 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
4567
4568
4568 parent, p2 = repo.dirstate.parents()
4569 parent, p2 = repo.dirstate.parents()
4569 if not opts.get('rev') and p2 != nullid:
4570 if not opts.get('rev') and p2 != nullid:
4570 # revert after merge is a trap for new users (issue2915)
4571 # revert after merge is a trap for new users (issue2915)
4571 raise error.Abort(_('uncommitted merge with no revision specified'),
4572 raise error.Abort(_('uncommitted merge with no revision specified'),
4572 hint=_("use 'hg update' or see 'hg help revert'"))
4573 hint=_("use 'hg update' or see 'hg help revert'"))
4573
4574
4574 ctx = scmutil.revsingle(repo, opts.get('rev'))
4575 ctx = scmutil.revsingle(repo, opts.get('rev'))
4575
4576
4576 if (not (pats or opts.get('include') or opts.get('exclude') or
4577 if (not (pats or opts.get('include') or opts.get('exclude') or
4577 opts.get('all') or opts.get('interactive'))):
4578 opts.get('all') or opts.get('interactive'))):
4578 msg = _("no files or directories specified")
4579 msg = _("no files or directories specified")
4579 if p2 != nullid:
4580 if p2 != nullid:
4580 hint = _("uncommitted merge, use --all to discard all changes,"
4581 hint = _("uncommitted merge, use --all to discard all changes,"
4581 " or 'hg update -C .' to abort the merge")
4582 " or 'hg update -C .' to abort the merge")
4582 raise error.Abort(msg, hint=hint)
4583 raise error.Abort(msg, hint=hint)
4583 dirty = any(repo.status())
4584 dirty = any(repo.status())
4584 node = ctx.node()
4585 node = ctx.node()
4585 if node != parent:
4586 if node != parent:
4586 if dirty:
4587 if dirty:
4587 hint = _("uncommitted changes, use --all to discard all"
4588 hint = _("uncommitted changes, use --all to discard all"
4588 " changes, or 'hg update %s' to update") % ctx.rev()
4589 " changes, or 'hg update %s' to update") % ctx.rev()
4589 else:
4590 else:
4590 hint = _("use --all to revert all files,"
4591 hint = _("use --all to revert all files,"
4591 " or 'hg update %s' to update") % ctx.rev()
4592 " or 'hg update %s' to update") % ctx.rev()
4592 elif dirty:
4593 elif dirty:
4593 hint = _("uncommitted changes, use --all to discard all changes")
4594 hint = _("uncommitted changes, use --all to discard all changes")
4594 else:
4595 else:
4595 hint = _("use --all to revert all files")
4596 hint = _("use --all to revert all files")
4596 raise error.Abort(msg, hint=hint)
4597 raise error.Abort(msg, hint=hint)
4597
4598
4598 return cmdutil.revert(ui, repo, ctx, (parent, p2), *pats, **opts)
4599 return cmdutil.revert(ui, repo, ctx, (parent, p2), *pats,
4600 **pycompat.strkwargs(opts))
4599
4601
4600 @command('rollback', dryrunopts +
4602 @command('rollback', dryrunopts +
4601 [('f', 'force', False, _('ignore safety measures'))])
4603 [('f', 'force', False, _('ignore safety measures'))])
4602 def rollback(ui, repo, **opts):
4604 def rollback(ui, repo, **opts):
4603 """roll back the last transaction (DANGEROUS) (DEPRECATED)
4605 """roll back the last transaction (DANGEROUS) (DEPRECATED)
4604
4606
4605 Please use :hg:`commit --amend` instead of rollback to correct
4607 Please use :hg:`commit --amend` instead of rollback to correct
4606 mistakes in the last commit.
4608 mistakes in the last commit.
4607
4609
4608 This command should be used with care. There is only one level of
4610 This command should be used with care. There is only one level of
4609 rollback, and there is no way to undo a rollback. It will also
4611 rollback, and there is no way to undo a rollback. It will also
4610 restore the dirstate at the time of the last transaction, losing
4612 restore the dirstate at the time of the last transaction, losing
4611 any dirstate changes since that time. This command does not alter
4613 any dirstate changes since that time. This command does not alter
4612 the working directory.
4614 the working directory.
4613
4615
4614 Transactions are used to encapsulate the effects of all commands
4616 Transactions are used to encapsulate the effects of all commands
4615 that create new changesets or propagate existing changesets into a
4617 that create new changesets or propagate existing changesets into a
4616 repository.
4618 repository.
4617
4619
4618 .. container:: verbose
4620 .. container:: verbose
4619
4621
4620 For example, the following commands are transactional, and their
4622 For example, the following commands are transactional, and their
4621 effects can be rolled back:
4623 effects can be rolled back:
4622
4624
4623 - commit
4625 - commit
4624 - import
4626 - import
4625 - pull
4627 - pull
4626 - push (with this repository as the destination)
4628 - push (with this repository as the destination)
4627 - unbundle
4629 - unbundle
4628
4630
4629 To avoid permanent data loss, rollback will refuse to rollback a
4631 To avoid permanent data loss, rollback will refuse to rollback a
4630 commit transaction if it isn't checked out. Use --force to
4632 commit transaction if it isn't checked out. Use --force to
4631 override this protection.
4633 override this protection.
4632
4634
4633 The rollback command can be entirely disabled by setting the
4635 The rollback command can be entirely disabled by setting the
4634 ``ui.rollback`` configuration setting to false. If you're here
4636 ``ui.rollback`` configuration setting to false. If you're here
4635 because you want to use rollback and it's disabled, you can
4637 because you want to use rollback and it's disabled, you can
4636 re-enable the command by setting ``ui.rollback`` to true.
4638 re-enable the command by setting ``ui.rollback`` to true.
4637
4639
4638 This command is not intended for use on public repositories. Once
4640 This command is not intended for use on public repositories. Once
4639 changes are visible for pull by other users, rolling a transaction
4641 changes are visible for pull by other users, rolling a transaction
4640 back locally is ineffective (someone else may already have pulled
4642 back locally is ineffective (someone else may already have pulled
4641 the changes). Furthermore, a race is possible with readers of the
4643 the changes). Furthermore, a race is possible with readers of the
4642 repository; for example an in-progress pull from the repository
4644 repository; for example an in-progress pull from the repository
4643 may fail if a rollback is performed.
4645 may fail if a rollback is performed.
4644
4646
4645 Returns 0 on success, 1 if no rollback data is available.
4647 Returns 0 on success, 1 if no rollback data is available.
4646 """
4648 """
4647 if not ui.configbool('ui', 'rollback'):
4649 if not ui.configbool('ui', 'rollback'):
4648 raise error.Abort(_('rollback is disabled because it is unsafe'),
4650 raise error.Abort(_('rollback is disabled because it is unsafe'),
4649 hint=('see `hg help -v rollback` for information'))
4651 hint=('see `hg help -v rollback` for information'))
4650 return repo.rollback(dryrun=opts.get(r'dry_run'),
4652 return repo.rollback(dryrun=opts.get(r'dry_run'),
4651 force=opts.get(r'force'))
4653 force=opts.get(r'force'))
4652
4654
4653 @command('root', [], cmdtype=readonly)
4655 @command('root', [], cmdtype=readonly)
4654 def root(ui, repo):
4656 def root(ui, repo):
4655 """print the root (top) of the current working directory
4657 """print the root (top) of the current working directory
4656
4658
4657 Print the root directory of the current repository.
4659 Print the root directory of the current repository.
4658
4660
4659 Returns 0 on success.
4661 Returns 0 on success.
4660 """
4662 """
4661 ui.write(repo.root + "\n")
4663 ui.write(repo.root + "\n")
4662
4664
4663 @command('^serve',
4665 @command('^serve',
4664 [('A', 'accesslog', '', _('name of access log file to write to'),
4666 [('A', 'accesslog', '', _('name of access log file to write to'),
4665 _('FILE')),
4667 _('FILE')),
4666 ('d', 'daemon', None, _('run server in background')),
4668 ('d', 'daemon', None, _('run server in background')),
4667 ('', 'daemon-postexec', [], _('used internally by daemon mode')),
4669 ('', 'daemon-postexec', [], _('used internally by daemon mode')),
4668 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
4670 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
4669 # use string type, then we can check if something was passed
4671 # use string type, then we can check if something was passed
4670 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
4672 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
4671 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
4673 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
4672 _('ADDR')),
4674 _('ADDR')),
4673 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
4675 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
4674 _('PREFIX')),
4676 _('PREFIX')),
4675 ('n', 'name', '',
4677 ('n', 'name', '',
4676 _('name to show in web pages (default: working directory)'), _('NAME')),
4678 _('name to show in web pages (default: working directory)'), _('NAME')),
4677 ('', 'web-conf', '',
4679 ('', 'web-conf', '',
4678 _("name of the hgweb config file (see 'hg help hgweb')"), _('FILE')),
4680 _("name of the hgweb config file (see 'hg help hgweb')"), _('FILE')),
4679 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
4681 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
4680 _('FILE')),
4682 _('FILE')),
4681 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
4683 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
4682 ('', 'stdio', None, _('for remote clients (ADVANCED)')),
4684 ('', 'stdio', None, _('for remote clients (ADVANCED)')),
4683 ('', 'cmdserver', '', _('for remote clients (ADVANCED)'), _('MODE')),
4685 ('', 'cmdserver', '', _('for remote clients (ADVANCED)'), _('MODE')),
4684 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
4686 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
4685 ('', 'style', '', _('template style to use'), _('STYLE')),
4687 ('', 'style', '', _('template style to use'), _('STYLE')),
4686 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
4688 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
4687 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))]
4689 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))]
4688 + subrepoopts,
4690 + subrepoopts,
4689 _('[OPTION]...'),
4691 _('[OPTION]...'),
4690 optionalrepo=True)
4692 optionalrepo=True)
4691 def serve(ui, repo, **opts):
4693 def serve(ui, repo, **opts):
4692 """start stand-alone webserver
4694 """start stand-alone webserver
4693
4695
4694 Start a local HTTP repository browser and pull server. You can use
4696 Start a local HTTP repository browser and pull server. You can use
4695 this for ad-hoc sharing and browsing of repositories. It is
4697 this for ad-hoc sharing and browsing of repositories. It is
4696 recommended to use a real web server to serve a repository for
4698 recommended to use a real web server to serve a repository for
4697 longer periods of time.
4699 longer periods of time.
4698
4700
4699 Please note that the server does not implement access control.
4701 Please note that the server does not implement access control.
4700 This means that, by default, anybody can read from the server and
4702 This means that, by default, anybody can read from the server and
4701 nobody can write to it by default. Set the ``web.allow-push``
4703 nobody can write to it by default. Set the ``web.allow-push``
4702 option to ``*`` to allow everybody to push to the server. You
4704 option to ``*`` to allow everybody to push to the server. You
4703 should use a real web server if you need to authenticate users.
4705 should use a real web server if you need to authenticate users.
4704
4706
4705 By default, the server logs accesses to stdout and errors to
4707 By default, the server logs accesses to stdout and errors to
4706 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
4708 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
4707 files.
4709 files.
4708
4710
4709 To have the server choose a free port number to listen on, specify
4711 To have the server choose a free port number to listen on, specify
4710 a port number of 0; in this case, the server will print the port
4712 a port number of 0; in this case, the server will print the port
4711 number it uses.
4713 number it uses.
4712
4714
4713 Returns 0 on success.
4715 Returns 0 on success.
4714 """
4716 """
4715
4717
4716 opts = pycompat.byteskwargs(opts)
4718 opts = pycompat.byteskwargs(opts)
4717 if opts["stdio"] and opts["cmdserver"]:
4719 if opts["stdio"] and opts["cmdserver"]:
4718 raise error.Abort(_("cannot use --stdio with --cmdserver"))
4720 raise error.Abort(_("cannot use --stdio with --cmdserver"))
4719
4721
4720 if opts["stdio"]:
4722 if opts["stdio"]:
4721 if repo is None:
4723 if repo is None:
4722 raise error.RepoError(_("there is no Mercurial repository here"
4724 raise error.RepoError(_("there is no Mercurial repository here"
4723 " (.hg not found)"))
4725 " (.hg not found)"))
4724 s = sshserver.sshserver(ui, repo)
4726 s = sshserver.sshserver(ui, repo)
4725 s.serve_forever()
4727 s.serve_forever()
4726
4728
4727 service = server.createservice(ui, repo, opts)
4729 service = server.createservice(ui, repo, opts)
4728 return server.runservice(opts, initfn=service.init, runfn=service.run)
4730 return server.runservice(opts, initfn=service.init, runfn=service.run)
4729
4731
4730 @command('^status|st',
4732 @command('^status|st',
4731 [('A', 'all', None, _('show status of all files')),
4733 [('A', 'all', None, _('show status of all files')),
4732 ('m', 'modified', None, _('show only modified files')),
4734 ('m', 'modified', None, _('show only modified files')),
4733 ('a', 'added', None, _('show only added files')),
4735 ('a', 'added', None, _('show only added files')),
4734 ('r', 'removed', None, _('show only removed files')),
4736 ('r', 'removed', None, _('show only removed files')),
4735 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
4737 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
4736 ('c', 'clean', None, _('show only files without changes')),
4738 ('c', 'clean', None, _('show only files without changes')),
4737 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
4739 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
4738 ('i', 'ignored', None, _('show only ignored files')),
4740 ('i', 'ignored', None, _('show only ignored files')),
4739 ('n', 'no-status', None, _('hide status prefix')),
4741 ('n', 'no-status', None, _('hide status prefix')),
4740 ('t', 'terse', '', _('show the terse output (EXPERIMENTAL)')),
4742 ('t', 'terse', '', _('show the terse output (EXPERIMENTAL)')),
4741 ('C', 'copies', None, _('show source of copied files')),
4743 ('C', 'copies', None, _('show source of copied files')),
4742 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
4744 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
4743 ('', 'rev', [], _('show difference from revision'), _('REV')),
4745 ('', 'rev', [], _('show difference from revision'), _('REV')),
4744 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
4746 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
4745 ] + walkopts + subrepoopts + formatteropts,
4747 ] + walkopts + subrepoopts + formatteropts,
4746 _('[OPTION]... [FILE]...'),
4748 _('[OPTION]... [FILE]...'),
4747 inferrepo=True, cmdtype=readonly)
4749 inferrepo=True, cmdtype=readonly)
4748 def status(ui, repo, *pats, **opts):
4750 def status(ui, repo, *pats, **opts):
4749 """show changed files in the working directory
4751 """show changed files in the working directory
4750
4752
4751 Show status of files in the repository. If names are given, only
4753 Show status of files in the repository. If names are given, only
4752 files that match are shown. Files that are clean or ignored or
4754 files that match are shown. Files that are clean or ignored or
4753 the source of a copy/move operation, are not listed unless
4755 the source of a copy/move operation, are not listed unless
4754 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
4756 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
4755 Unless options described with "show only ..." are given, the
4757 Unless options described with "show only ..." are given, the
4756 options -mardu are used.
4758 options -mardu are used.
4757
4759
4758 Option -q/--quiet hides untracked (unknown and ignored) files
4760 Option -q/--quiet hides untracked (unknown and ignored) files
4759 unless explicitly requested with -u/--unknown or -i/--ignored.
4761 unless explicitly requested with -u/--unknown or -i/--ignored.
4760
4762
4761 .. note::
4763 .. note::
4762
4764
4763 :hg:`status` may appear to disagree with diff if permissions have
4765 :hg:`status` may appear to disagree with diff if permissions have
4764 changed or a merge has occurred. The standard diff format does
4766 changed or a merge has occurred. The standard diff format does
4765 not report permission changes and diff only reports changes
4767 not report permission changes and diff only reports changes
4766 relative to one merge parent.
4768 relative to one merge parent.
4767
4769
4768 If one revision is given, it is used as the base revision.
4770 If one revision is given, it is used as the base revision.
4769 If two revisions are given, the differences between them are
4771 If two revisions are given, the differences between them are
4770 shown. The --change option can also be used as a shortcut to list
4772 shown. The --change option can also be used as a shortcut to list
4771 the changed files of a revision from its first parent.
4773 the changed files of a revision from its first parent.
4772
4774
4773 The codes used to show the status of files are::
4775 The codes used to show the status of files are::
4774
4776
4775 M = modified
4777 M = modified
4776 A = added
4778 A = added
4777 R = removed
4779 R = removed
4778 C = clean
4780 C = clean
4779 ! = missing (deleted by non-hg command, but still tracked)
4781 ! = missing (deleted by non-hg command, but still tracked)
4780 ? = not tracked
4782 ? = not tracked
4781 I = ignored
4783 I = ignored
4782 = origin of the previous file (with --copies)
4784 = origin of the previous file (with --copies)
4783
4785
4784 .. container:: verbose
4786 .. container:: verbose
4785
4787
4786 The -t/--terse option abbreviates the output by showing only the directory
4788 The -t/--terse option abbreviates the output by showing only the directory
4787 name if all the files in it share the same status. The option takes an
4789 name if all the files in it share the same status. The option takes an
4788 argument indicating the statuses to abbreviate: 'm' for 'modified', 'a'
4790 argument indicating the statuses to abbreviate: 'm' for 'modified', 'a'
4789 for 'added', 'r' for 'removed', 'd' for 'deleted', 'u' for 'unknown', 'i'
4791 for 'added', 'r' for 'removed', 'd' for 'deleted', 'u' for 'unknown', 'i'
4790 for 'ignored' and 'c' for clean.
4792 for 'ignored' and 'c' for clean.
4791
4793
4792 It abbreviates only those statuses which are passed. Note that clean and
4794 It abbreviates only those statuses which are passed. Note that clean and
4793 ignored files are not displayed with '--terse ic' unless the -c/--clean
4795 ignored files are not displayed with '--terse ic' unless the -c/--clean
4794 and -i/--ignored options are also used.
4796 and -i/--ignored options are also used.
4795
4797
4796 The -v/--verbose option shows information when the repository is in an
4798 The -v/--verbose option shows information when the repository is in an
4797 unfinished merge, shelve, rebase state etc. You can have this behavior
4799 unfinished merge, shelve, rebase state etc. You can have this behavior
4798 turned on by default by enabling the ``commands.status.verbose`` option.
4800 turned on by default by enabling the ``commands.status.verbose`` option.
4799
4801
4800 You can skip displaying some of these states by setting
4802 You can skip displaying some of these states by setting
4801 ``commands.status.skipstates`` to one or more of: 'bisect', 'graft',
4803 ``commands.status.skipstates`` to one or more of: 'bisect', 'graft',
4802 'histedit', 'merge', 'rebase', or 'unshelve'.
4804 'histedit', 'merge', 'rebase', or 'unshelve'.
4803
4805
4804 Examples:
4806 Examples:
4805
4807
4806 - show changes in the working directory relative to a
4808 - show changes in the working directory relative to a
4807 changeset::
4809 changeset::
4808
4810
4809 hg status --rev 9353
4811 hg status --rev 9353
4810
4812
4811 - show changes in the working directory relative to the
4813 - show changes in the working directory relative to the
4812 current directory (see :hg:`help patterns` for more information)::
4814 current directory (see :hg:`help patterns` for more information)::
4813
4815
4814 hg status re:
4816 hg status re:
4815
4817
4816 - show all changes including copies in an existing changeset::
4818 - show all changes including copies in an existing changeset::
4817
4819
4818 hg status --copies --change 9353
4820 hg status --copies --change 9353
4819
4821
4820 - get a NUL separated list of added files, suitable for xargs::
4822 - get a NUL separated list of added files, suitable for xargs::
4821
4823
4822 hg status -an0
4824 hg status -an0
4823
4825
4824 - show more information about the repository status, abbreviating
4826 - show more information about the repository status, abbreviating
4825 added, removed, modified, deleted, and untracked paths::
4827 added, removed, modified, deleted, and untracked paths::
4826
4828
4827 hg status -v -t mardu
4829 hg status -v -t mardu
4828
4830
4829 Returns 0 on success.
4831 Returns 0 on success.
4830
4832
4831 """
4833 """
4832
4834
4833 opts = pycompat.byteskwargs(opts)
4835 opts = pycompat.byteskwargs(opts)
4834 revs = opts.get('rev')
4836 revs = opts.get('rev')
4835 change = opts.get('change')
4837 change = opts.get('change')
4836 terse = opts.get('terse')
4838 terse = opts.get('terse')
4837
4839
4838 if revs and change:
4840 if revs and change:
4839 msg = _('cannot specify --rev and --change at the same time')
4841 msg = _('cannot specify --rev and --change at the same time')
4840 raise error.Abort(msg)
4842 raise error.Abort(msg)
4841 elif revs and terse:
4843 elif revs and terse:
4842 msg = _('cannot use --terse with --rev')
4844 msg = _('cannot use --terse with --rev')
4843 raise error.Abort(msg)
4845 raise error.Abort(msg)
4844 elif change:
4846 elif change:
4845 node2 = scmutil.revsingle(repo, change, None).node()
4847 node2 = scmutil.revsingle(repo, change, None).node()
4846 node1 = repo[node2].p1().node()
4848 node1 = repo[node2].p1().node()
4847 else:
4849 else:
4848 node1, node2 = scmutil.revpair(repo, revs)
4850 node1, node2 = scmutil.revpair(repo, revs)
4849
4851
4850 if pats or ui.configbool('commands', 'status.relative'):
4852 if pats or ui.configbool('commands', 'status.relative'):
4851 cwd = repo.getcwd()
4853 cwd = repo.getcwd()
4852 else:
4854 else:
4853 cwd = ''
4855 cwd = ''
4854
4856
4855 if opts.get('print0'):
4857 if opts.get('print0'):
4856 end = '\0'
4858 end = '\0'
4857 else:
4859 else:
4858 end = '\n'
4860 end = '\n'
4859 copy = {}
4861 copy = {}
4860 states = 'modified added removed deleted unknown ignored clean'.split()
4862 states = 'modified added removed deleted unknown ignored clean'.split()
4861 show = [k for k in states if opts.get(k)]
4863 show = [k for k in states if opts.get(k)]
4862 if opts.get('all'):
4864 if opts.get('all'):
4863 show += ui.quiet and (states[:4] + ['clean']) or states
4865 show += ui.quiet and (states[:4] + ['clean']) or states
4864
4866
4865 if not show:
4867 if not show:
4866 if ui.quiet:
4868 if ui.quiet:
4867 show = states[:4]
4869 show = states[:4]
4868 else:
4870 else:
4869 show = states[:5]
4871 show = states[:5]
4870
4872
4871 m = scmutil.match(repo[node2], pats, opts)
4873 m = scmutil.match(repo[node2], pats, opts)
4872 if terse:
4874 if terse:
4873 # we need to compute clean and unknown to terse
4875 # we need to compute clean and unknown to terse
4874 stat = repo.status(node1, node2, m,
4876 stat = repo.status(node1, node2, m,
4875 'ignored' in show or 'i' in terse,
4877 'ignored' in show or 'i' in terse,
4876 True, True, opts.get('subrepos'))
4878 True, True, opts.get('subrepos'))
4877
4879
4878 stat = cmdutil.tersedir(stat, terse)
4880 stat = cmdutil.tersedir(stat, terse)
4879 else:
4881 else:
4880 stat = repo.status(node1, node2, m,
4882 stat = repo.status(node1, node2, m,
4881 'ignored' in show, 'clean' in show,
4883 'ignored' in show, 'clean' in show,
4882 'unknown' in show, opts.get('subrepos'))
4884 'unknown' in show, opts.get('subrepos'))
4883
4885
4884 changestates = zip(states, pycompat.iterbytestr('MAR!?IC'), stat)
4886 changestates = zip(states, pycompat.iterbytestr('MAR!?IC'), stat)
4885
4887
4886 if (opts.get('all') or opts.get('copies')
4888 if (opts.get('all') or opts.get('copies')
4887 or ui.configbool('ui', 'statuscopies')) and not opts.get('no_status'):
4889 or ui.configbool('ui', 'statuscopies')) and not opts.get('no_status'):
4888 copy = copies.pathcopies(repo[node1], repo[node2], m)
4890 copy = copies.pathcopies(repo[node1], repo[node2], m)
4889
4891
4890 ui.pager('status')
4892 ui.pager('status')
4891 fm = ui.formatter('status', opts)
4893 fm = ui.formatter('status', opts)
4892 fmt = '%s' + end
4894 fmt = '%s' + end
4893 showchar = not opts.get('no_status')
4895 showchar = not opts.get('no_status')
4894
4896
4895 for state, char, files in changestates:
4897 for state, char, files in changestates:
4896 if state in show:
4898 if state in show:
4897 label = 'status.' + state
4899 label = 'status.' + state
4898 for f in files:
4900 for f in files:
4899 fm.startitem()
4901 fm.startitem()
4900 fm.condwrite(showchar, 'status', '%s ', char, label=label)
4902 fm.condwrite(showchar, 'status', '%s ', char, label=label)
4901 fm.write('path', fmt, repo.pathto(f, cwd), label=label)
4903 fm.write('path', fmt, repo.pathto(f, cwd), label=label)
4902 if f in copy:
4904 if f in copy:
4903 fm.write("copy", ' %s' + end, repo.pathto(copy[f], cwd),
4905 fm.write("copy", ' %s' + end, repo.pathto(copy[f], cwd),
4904 label='status.copied')
4906 label='status.copied')
4905
4907
4906 if ((ui.verbose or ui.configbool('commands', 'status.verbose'))
4908 if ((ui.verbose or ui.configbool('commands', 'status.verbose'))
4907 and not ui.plain()):
4909 and not ui.plain()):
4908 cmdutil.morestatus(repo, fm)
4910 cmdutil.morestatus(repo, fm)
4909 fm.end()
4911 fm.end()
4910
4912
4911 @command('^summary|sum',
4913 @command('^summary|sum',
4912 [('', 'remote', None, _('check for push and pull'))],
4914 [('', 'remote', None, _('check for push and pull'))],
4913 '[--remote]', cmdtype=readonly)
4915 '[--remote]', cmdtype=readonly)
4914 def summary(ui, repo, **opts):
4916 def summary(ui, repo, **opts):
4915 """summarize working directory state
4917 """summarize working directory state
4916
4918
4917 This generates a brief summary of the working directory state,
4919 This generates a brief summary of the working directory state,
4918 including parents, branch, commit status, phase and available updates.
4920 including parents, branch, commit status, phase and available updates.
4919
4921
4920 With the --remote option, this will check the default paths for
4922 With the --remote option, this will check the default paths for
4921 incoming and outgoing changes. This can be time-consuming.
4923 incoming and outgoing changes. This can be time-consuming.
4922
4924
4923 Returns 0 on success.
4925 Returns 0 on success.
4924 """
4926 """
4925
4927
4926 opts = pycompat.byteskwargs(opts)
4928 opts = pycompat.byteskwargs(opts)
4927 ui.pager('summary')
4929 ui.pager('summary')
4928 ctx = repo[None]
4930 ctx = repo[None]
4929 parents = ctx.parents()
4931 parents = ctx.parents()
4930 pnode = parents[0].node()
4932 pnode = parents[0].node()
4931 marks = []
4933 marks = []
4932
4934
4933 ms = None
4935 ms = None
4934 try:
4936 try:
4935 ms = mergemod.mergestate.read(repo)
4937 ms = mergemod.mergestate.read(repo)
4936 except error.UnsupportedMergeRecords as e:
4938 except error.UnsupportedMergeRecords as e:
4937 s = ' '.join(e.recordtypes)
4939 s = ' '.join(e.recordtypes)
4938 ui.warn(
4940 ui.warn(
4939 _('warning: merge state has unsupported record types: %s\n') % s)
4941 _('warning: merge state has unsupported record types: %s\n') % s)
4940 unresolved = []
4942 unresolved = []
4941 else:
4943 else:
4942 unresolved = list(ms.unresolved())
4944 unresolved = list(ms.unresolved())
4943
4945
4944 for p in parents:
4946 for p in parents:
4945 # label with log.changeset (instead of log.parent) since this
4947 # label with log.changeset (instead of log.parent) since this
4946 # shows a working directory parent *changeset*:
4948 # shows a working directory parent *changeset*:
4947 # i18n: column positioning for "hg summary"
4949 # i18n: column positioning for "hg summary"
4948 ui.write(_('parent: %d:%s ') % (p.rev(), p),
4950 ui.write(_('parent: %d:%s ') % (p.rev(), p),
4949 label=cmdutil._changesetlabels(p))
4951 label=cmdutil._changesetlabels(p))
4950 ui.write(' '.join(p.tags()), label='log.tag')
4952 ui.write(' '.join(p.tags()), label='log.tag')
4951 if p.bookmarks():
4953 if p.bookmarks():
4952 marks.extend(p.bookmarks())
4954 marks.extend(p.bookmarks())
4953 if p.rev() == -1:
4955 if p.rev() == -1:
4954 if not len(repo):
4956 if not len(repo):
4955 ui.write(_(' (empty repository)'))
4957 ui.write(_(' (empty repository)'))
4956 else:
4958 else:
4957 ui.write(_(' (no revision checked out)'))
4959 ui.write(_(' (no revision checked out)'))
4958 if p.obsolete():
4960 if p.obsolete():
4959 ui.write(_(' (obsolete)'))
4961 ui.write(_(' (obsolete)'))
4960 if p.isunstable():
4962 if p.isunstable():
4961 instabilities = (ui.label(instability, 'trouble.%s' % instability)
4963 instabilities = (ui.label(instability, 'trouble.%s' % instability)
4962 for instability in p.instabilities())
4964 for instability in p.instabilities())
4963 ui.write(' ('
4965 ui.write(' ('
4964 + ', '.join(instabilities)
4966 + ', '.join(instabilities)
4965 + ')')
4967 + ')')
4966 ui.write('\n')
4968 ui.write('\n')
4967 if p.description():
4969 if p.description():
4968 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
4970 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
4969 label='log.summary')
4971 label='log.summary')
4970
4972
4971 branch = ctx.branch()
4973 branch = ctx.branch()
4972 bheads = repo.branchheads(branch)
4974 bheads = repo.branchheads(branch)
4973 # i18n: column positioning for "hg summary"
4975 # i18n: column positioning for "hg summary"
4974 m = _('branch: %s\n') % branch
4976 m = _('branch: %s\n') % branch
4975 if branch != 'default':
4977 if branch != 'default':
4976 ui.write(m, label='log.branch')
4978 ui.write(m, label='log.branch')
4977 else:
4979 else:
4978 ui.status(m, label='log.branch')
4980 ui.status(m, label='log.branch')
4979
4981
4980 if marks:
4982 if marks:
4981 active = repo._activebookmark
4983 active = repo._activebookmark
4982 # i18n: column positioning for "hg summary"
4984 # i18n: column positioning for "hg summary"
4983 ui.write(_('bookmarks:'), label='log.bookmark')
4985 ui.write(_('bookmarks:'), label='log.bookmark')
4984 if active is not None:
4986 if active is not None:
4985 if active in marks:
4987 if active in marks:
4986 ui.write(' *' + active, label=bookmarks.activebookmarklabel)
4988 ui.write(' *' + active, label=bookmarks.activebookmarklabel)
4987 marks.remove(active)
4989 marks.remove(active)
4988 else:
4990 else:
4989 ui.write(' [%s]' % active, label=bookmarks.activebookmarklabel)
4991 ui.write(' [%s]' % active, label=bookmarks.activebookmarklabel)
4990 for m in marks:
4992 for m in marks:
4991 ui.write(' ' + m, label='log.bookmark')
4993 ui.write(' ' + m, label='log.bookmark')
4992 ui.write('\n', label='log.bookmark')
4994 ui.write('\n', label='log.bookmark')
4993
4995
4994 status = repo.status(unknown=True)
4996 status = repo.status(unknown=True)
4995
4997
4996 c = repo.dirstate.copies()
4998 c = repo.dirstate.copies()
4997 copied, renamed = [], []
4999 copied, renamed = [], []
4998 for d, s in c.iteritems():
5000 for d, s in c.iteritems():
4999 if s in status.removed:
5001 if s in status.removed:
5000 status.removed.remove(s)
5002 status.removed.remove(s)
5001 renamed.append(d)
5003 renamed.append(d)
5002 else:
5004 else:
5003 copied.append(d)
5005 copied.append(d)
5004 if d in status.added:
5006 if d in status.added:
5005 status.added.remove(d)
5007 status.added.remove(d)
5006
5008
5007 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
5009 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
5008
5010
5009 labels = [(ui.label(_('%d modified'), 'status.modified'), status.modified),
5011 labels = [(ui.label(_('%d modified'), 'status.modified'), status.modified),
5010 (ui.label(_('%d added'), 'status.added'), status.added),
5012 (ui.label(_('%d added'), 'status.added'), status.added),
5011 (ui.label(_('%d removed'), 'status.removed'), status.removed),
5013 (ui.label(_('%d removed'), 'status.removed'), status.removed),
5012 (ui.label(_('%d renamed'), 'status.copied'), renamed),
5014 (ui.label(_('%d renamed'), 'status.copied'), renamed),
5013 (ui.label(_('%d copied'), 'status.copied'), copied),
5015 (ui.label(_('%d copied'), 'status.copied'), copied),
5014 (ui.label(_('%d deleted'), 'status.deleted'), status.deleted),
5016 (ui.label(_('%d deleted'), 'status.deleted'), status.deleted),
5015 (ui.label(_('%d unknown'), 'status.unknown'), status.unknown),
5017 (ui.label(_('%d unknown'), 'status.unknown'), status.unknown),
5016 (ui.label(_('%d unresolved'), 'resolve.unresolved'), unresolved),
5018 (ui.label(_('%d unresolved'), 'resolve.unresolved'), unresolved),
5017 (ui.label(_('%d subrepos'), 'status.modified'), subs)]
5019 (ui.label(_('%d subrepos'), 'status.modified'), subs)]
5018 t = []
5020 t = []
5019 for l, s in labels:
5021 for l, s in labels:
5020 if s:
5022 if s:
5021 t.append(l % len(s))
5023 t.append(l % len(s))
5022
5024
5023 t = ', '.join(t)
5025 t = ', '.join(t)
5024 cleanworkdir = False
5026 cleanworkdir = False
5025
5027
5026 if repo.vfs.exists('graftstate'):
5028 if repo.vfs.exists('graftstate'):
5027 t += _(' (graft in progress)')
5029 t += _(' (graft in progress)')
5028 if repo.vfs.exists('updatestate'):
5030 if repo.vfs.exists('updatestate'):
5029 t += _(' (interrupted update)')
5031 t += _(' (interrupted update)')
5030 elif len(parents) > 1:
5032 elif len(parents) > 1:
5031 t += _(' (merge)')
5033 t += _(' (merge)')
5032 elif branch != parents[0].branch():
5034 elif branch != parents[0].branch():
5033 t += _(' (new branch)')
5035 t += _(' (new branch)')
5034 elif (parents[0].closesbranch() and
5036 elif (parents[0].closesbranch() and
5035 pnode in repo.branchheads(branch, closed=True)):
5037 pnode in repo.branchheads(branch, closed=True)):
5036 t += _(' (head closed)')
5038 t += _(' (head closed)')
5037 elif not (status.modified or status.added or status.removed or renamed or
5039 elif not (status.modified or status.added or status.removed or renamed or
5038 copied or subs):
5040 copied or subs):
5039 t += _(' (clean)')
5041 t += _(' (clean)')
5040 cleanworkdir = True
5042 cleanworkdir = True
5041 elif pnode not in bheads:
5043 elif pnode not in bheads:
5042 t += _(' (new branch head)')
5044 t += _(' (new branch head)')
5043
5045
5044 if parents:
5046 if parents:
5045 pendingphase = max(p.phase() for p in parents)
5047 pendingphase = max(p.phase() for p in parents)
5046 else:
5048 else:
5047 pendingphase = phases.public
5049 pendingphase = phases.public
5048
5050
5049 if pendingphase > phases.newcommitphase(ui):
5051 if pendingphase > phases.newcommitphase(ui):
5050 t += ' (%s)' % phases.phasenames[pendingphase]
5052 t += ' (%s)' % phases.phasenames[pendingphase]
5051
5053
5052 if cleanworkdir:
5054 if cleanworkdir:
5053 # i18n: column positioning for "hg summary"
5055 # i18n: column positioning for "hg summary"
5054 ui.status(_('commit: %s\n') % t.strip())
5056 ui.status(_('commit: %s\n') % t.strip())
5055 else:
5057 else:
5056 # i18n: column positioning for "hg summary"
5058 # i18n: column positioning for "hg summary"
5057 ui.write(_('commit: %s\n') % t.strip())
5059 ui.write(_('commit: %s\n') % t.strip())
5058
5060
5059 # all ancestors of branch heads - all ancestors of parent = new csets
5061 # all ancestors of branch heads - all ancestors of parent = new csets
5060 new = len(repo.changelog.findmissing([pctx.node() for pctx in parents],
5062 new = len(repo.changelog.findmissing([pctx.node() for pctx in parents],
5061 bheads))
5063 bheads))
5062
5064
5063 if new == 0:
5065 if new == 0:
5064 # i18n: column positioning for "hg summary"
5066 # i18n: column positioning for "hg summary"
5065 ui.status(_('update: (current)\n'))
5067 ui.status(_('update: (current)\n'))
5066 elif pnode not in bheads:
5068 elif pnode not in bheads:
5067 # i18n: column positioning for "hg summary"
5069 # i18n: column positioning for "hg summary"
5068 ui.write(_('update: %d new changesets (update)\n') % new)
5070 ui.write(_('update: %d new changesets (update)\n') % new)
5069 else:
5071 else:
5070 # i18n: column positioning for "hg summary"
5072 # i18n: column positioning for "hg summary"
5071 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
5073 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
5072 (new, len(bheads)))
5074 (new, len(bheads)))
5073
5075
5074 t = []
5076 t = []
5075 draft = len(repo.revs('draft()'))
5077 draft = len(repo.revs('draft()'))
5076 if draft:
5078 if draft:
5077 t.append(_('%d draft') % draft)
5079 t.append(_('%d draft') % draft)
5078 secret = len(repo.revs('secret()'))
5080 secret = len(repo.revs('secret()'))
5079 if secret:
5081 if secret:
5080 t.append(_('%d secret') % secret)
5082 t.append(_('%d secret') % secret)
5081
5083
5082 if draft or secret:
5084 if draft or secret:
5083 ui.status(_('phases: %s\n') % ', '.join(t))
5085 ui.status(_('phases: %s\n') % ', '.join(t))
5084
5086
5085 if obsolete.isenabled(repo, obsolete.createmarkersopt):
5087 if obsolete.isenabled(repo, obsolete.createmarkersopt):
5086 for trouble in ("orphan", "contentdivergent", "phasedivergent"):
5088 for trouble in ("orphan", "contentdivergent", "phasedivergent"):
5087 numtrouble = len(repo.revs(trouble + "()"))
5089 numtrouble = len(repo.revs(trouble + "()"))
5088 # We write all the possibilities to ease translation
5090 # We write all the possibilities to ease translation
5089 troublemsg = {
5091 troublemsg = {
5090 "orphan": _("orphan: %d changesets"),
5092 "orphan": _("orphan: %d changesets"),
5091 "contentdivergent": _("content-divergent: %d changesets"),
5093 "contentdivergent": _("content-divergent: %d changesets"),
5092 "phasedivergent": _("phase-divergent: %d changesets"),
5094 "phasedivergent": _("phase-divergent: %d changesets"),
5093 }
5095 }
5094 if numtrouble > 0:
5096 if numtrouble > 0:
5095 ui.status(troublemsg[trouble] % numtrouble + "\n")
5097 ui.status(troublemsg[trouble] % numtrouble + "\n")
5096
5098
5097 cmdutil.summaryhooks(ui, repo)
5099 cmdutil.summaryhooks(ui, repo)
5098
5100
5099 if opts.get('remote'):
5101 if opts.get('remote'):
5100 needsincoming, needsoutgoing = True, True
5102 needsincoming, needsoutgoing = True, True
5101 else:
5103 else:
5102 needsincoming, needsoutgoing = False, False
5104 needsincoming, needsoutgoing = False, False
5103 for i, o in cmdutil.summaryremotehooks(ui, repo, opts, None):
5105 for i, o in cmdutil.summaryremotehooks(ui, repo, opts, None):
5104 if i:
5106 if i:
5105 needsincoming = True
5107 needsincoming = True
5106 if o:
5108 if o:
5107 needsoutgoing = True
5109 needsoutgoing = True
5108 if not needsincoming and not needsoutgoing:
5110 if not needsincoming and not needsoutgoing:
5109 return
5111 return
5110
5112
5111 def getincoming():
5113 def getincoming():
5112 source, branches = hg.parseurl(ui.expandpath('default'))
5114 source, branches = hg.parseurl(ui.expandpath('default'))
5113 sbranch = branches[0]
5115 sbranch = branches[0]
5114 try:
5116 try:
5115 other = hg.peer(repo, {}, source)
5117 other = hg.peer(repo, {}, source)
5116 except error.RepoError:
5118 except error.RepoError:
5117 if opts.get('remote'):
5119 if opts.get('remote'):
5118 raise
5120 raise
5119 return source, sbranch, None, None, None
5121 return source, sbranch, None, None, None
5120 revs, checkout = hg.addbranchrevs(repo, other, branches, None)
5122 revs, checkout = hg.addbranchrevs(repo, other, branches, None)
5121 if revs:
5123 if revs:
5122 revs = [other.lookup(rev) for rev in revs]
5124 revs = [other.lookup(rev) for rev in revs]
5123 ui.debug('comparing with %s\n' % util.hidepassword(source))
5125 ui.debug('comparing with %s\n' % util.hidepassword(source))
5124 repo.ui.pushbuffer()
5126 repo.ui.pushbuffer()
5125 commoninc = discovery.findcommonincoming(repo, other, heads=revs)
5127 commoninc = discovery.findcommonincoming(repo, other, heads=revs)
5126 repo.ui.popbuffer()
5128 repo.ui.popbuffer()
5127 return source, sbranch, other, commoninc, commoninc[1]
5129 return source, sbranch, other, commoninc, commoninc[1]
5128
5130
5129 if needsincoming:
5131 if needsincoming:
5130 source, sbranch, sother, commoninc, incoming = getincoming()
5132 source, sbranch, sother, commoninc, incoming = getincoming()
5131 else:
5133 else:
5132 source = sbranch = sother = commoninc = incoming = None
5134 source = sbranch = sother = commoninc = incoming = None
5133
5135
5134 def getoutgoing():
5136 def getoutgoing():
5135 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
5137 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
5136 dbranch = branches[0]
5138 dbranch = branches[0]
5137 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
5139 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
5138 if source != dest:
5140 if source != dest:
5139 try:
5141 try:
5140 dother = hg.peer(repo, {}, dest)
5142 dother = hg.peer(repo, {}, dest)
5141 except error.RepoError:
5143 except error.RepoError:
5142 if opts.get('remote'):
5144 if opts.get('remote'):
5143 raise
5145 raise
5144 return dest, dbranch, None, None
5146 return dest, dbranch, None, None
5145 ui.debug('comparing with %s\n' % util.hidepassword(dest))
5147 ui.debug('comparing with %s\n' % util.hidepassword(dest))
5146 elif sother is None:
5148 elif sother is None:
5147 # there is no explicit destination peer, but source one is invalid
5149 # there is no explicit destination peer, but source one is invalid
5148 return dest, dbranch, None, None
5150 return dest, dbranch, None, None
5149 else:
5151 else:
5150 dother = sother
5152 dother = sother
5151 if (source != dest or (sbranch is not None and sbranch != dbranch)):
5153 if (source != dest or (sbranch is not None and sbranch != dbranch)):
5152 common = None
5154 common = None
5153 else:
5155 else:
5154 common = commoninc
5156 common = commoninc
5155 if revs:
5157 if revs:
5156 revs = [repo.lookup(rev) for rev in revs]
5158 revs = [repo.lookup(rev) for rev in revs]
5157 repo.ui.pushbuffer()
5159 repo.ui.pushbuffer()
5158 outgoing = discovery.findcommonoutgoing(repo, dother, onlyheads=revs,
5160 outgoing = discovery.findcommonoutgoing(repo, dother, onlyheads=revs,
5159 commoninc=common)
5161 commoninc=common)
5160 repo.ui.popbuffer()
5162 repo.ui.popbuffer()
5161 return dest, dbranch, dother, outgoing
5163 return dest, dbranch, dother, outgoing
5162
5164
5163 if needsoutgoing:
5165 if needsoutgoing:
5164 dest, dbranch, dother, outgoing = getoutgoing()
5166 dest, dbranch, dother, outgoing = getoutgoing()
5165 else:
5167 else:
5166 dest = dbranch = dother = outgoing = None
5168 dest = dbranch = dother = outgoing = None
5167
5169
5168 if opts.get('remote'):
5170 if opts.get('remote'):
5169 t = []
5171 t = []
5170 if incoming:
5172 if incoming:
5171 t.append(_('1 or more incoming'))
5173 t.append(_('1 or more incoming'))
5172 o = outgoing.missing
5174 o = outgoing.missing
5173 if o:
5175 if o:
5174 t.append(_('%d outgoing') % len(o))
5176 t.append(_('%d outgoing') % len(o))
5175 other = dother or sother
5177 other = dother or sother
5176 if 'bookmarks' in other.listkeys('namespaces'):
5178 if 'bookmarks' in other.listkeys('namespaces'):
5177 counts = bookmarks.summary(repo, other)
5179 counts = bookmarks.summary(repo, other)
5178 if counts[0] > 0:
5180 if counts[0] > 0:
5179 t.append(_('%d incoming bookmarks') % counts[0])
5181 t.append(_('%d incoming bookmarks') % counts[0])
5180 if counts[1] > 0:
5182 if counts[1] > 0:
5181 t.append(_('%d outgoing bookmarks') % counts[1])
5183 t.append(_('%d outgoing bookmarks') % counts[1])
5182
5184
5183 if t:
5185 if t:
5184 # i18n: column positioning for "hg summary"
5186 # i18n: column positioning for "hg summary"
5185 ui.write(_('remote: %s\n') % (', '.join(t)))
5187 ui.write(_('remote: %s\n') % (', '.join(t)))
5186 else:
5188 else:
5187 # i18n: column positioning for "hg summary"
5189 # i18n: column positioning for "hg summary"
5188 ui.status(_('remote: (synced)\n'))
5190 ui.status(_('remote: (synced)\n'))
5189
5191
5190 cmdutil.summaryremotehooks(ui, repo, opts,
5192 cmdutil.summaryremotehooks(ui, repo, opts,
5191 ((source, sbranch, sother, commoninc),
5193 ((source, sbranch, sother, commoninc),
5192 (dest, dbranch, dother, outgoing)))
5194 (dest, dbranch, dother, outgoing)))
5193
5195
5194 @command('tag',
5196 @command('tag',
5195 [('f', 'force', None, _('force tag')),
5197 [('f', 'force', None, _('force tag')),
5196 ('l', 'local', None, _('make the tag local')),
5198 ('l', 'local', None, _('make the tag local')),
5197 ('r', 'rev', '', _('revision to tag'), _('REV')),
5199 ('r', 'rev', '', _('revision to tag'), _('REV')),
5198 ('', 'remove', None, _('remove a tag')),
5200 ('', 'remove', None, _('remove a tag')),
5199 # -l/--local is already there, commitopts cannot be used
5201 # -l/--local is already there, commitopts cannot be used
5200 ('e', 'edit', None, _('invoke editor on commit messages')),
5202 ('e', 'edit', None, _('invoke editor on commit messages')),
5201 ('m', 'message', '', _('use text as commit message'), _('TEXT')),
5203 ('m', 'message', '', _('use text as commit message'), _('TEXT')),
5202 ] + commitopts2,
5204 ] + commitopts2,
5203 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
5205 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
5204 def tag(ui, repo, name1, *names, **opts):
5206 def tag(ui, repo, name1, *names, **opts):
5205 """add one or more tags for the current or given revision
5207 """add one or more tags for the current or given revision
5206
5208
5207 Name a particular revision using <name>.
5209 Name a particular revision using <name>.
5208
5210
5209 Tags are used to name particular revisions of the repository and are
5211 Tags are used to name particular revisions of the repository and are
5210 very useful to compare different revisions, to go back to significant
5212 very useful to compare different revisions, to go back to significant
5211 earlier versions or to mark branch points as releases, etc. Changing
5213 earlier versions or to mark branch points as releases, etc. Changing
5212 an existing tag is normally disallowed; use -f/--force to override.
5214 an existing tag is normally disallowed; use -f/--force to override.
5213
5215
5214 If no revision is given, the parent of the working directory is
5216 If no revision is given, the parent of the working directory is
5215 used.
5217 used.
5216
5218
5217 To facilitate version control, distribution, and merging of tags,
5219 To facilitate version control, distribution, and merging of tags,
5218 they are stored as a file named ".hgtags" which is managed similarly
5220 they are stored as a file named ".hgtags" which is managed similarly
5219 to other project files and can be hand-edited if necessary. This
5221 to other project files and can be hand-edited if necessary. This
5220 also means that tagging creates a new commit. The file
5222 also means that tagging creates a new commit. The file
5221 ".hg/localtags" is used for local tags (not shared among
5223 ".hg/localtags" is used for local tags (not shared among
5222 repositories).
5224 repositories).
5223
5225
5224 Tag commits are usually made at the head of a branch. If the parent
5226 Tag commits are usually made at the head of a branch. If the parent
5225 of the working directory is not a branch head, :hg:`tag` aborts; use
5227 of the working directory is not a branch head, :hg:`tag` aborts; use
5226 -f/--force to force the tag commit to be based on a non-head
5228 -f/--force to force the tag commit to be based on a non-head
5227 changeset.
5229 changeset.
5228
5230
5229 See :hg:`help dates` for a list of formats valid for -d/--date.
5231 See :hg:`help dates` for a list of formats valid for -d/--date.
5230
5232
5231 Since tag names have priority over branch names during revision
5233 Since tag names have priority over branch names during revision
5232 lookup, using an existing branch name as a tag name is discouraged.
5234 lookup, using an existing branch name as a tag name is discouraged.
5233
5235
5234 Returns 0 on success.
5236 Returns 0 on success.
5235 """
5237 """
5236 opts = pycompat.byteskwargs(opts)
5238 opts = pycompat.byteskwargs(opts)
5237 wlock = lock = None
5239 wlock = lock = None
5238 try:
5240 try:
5239 wlock = repo.wlock()
5241 wlock = repo.wlock()
5240 lock = repo.lock()
5242 lock = repo.lock()
5241 rev_ = "."
5243 rev_ = "."
5242 names = [t.strip() for t in (name1,) + names]
5244 names = [t.strip() for t in (name1,) + names]
5243 if len(names) != len(set(names)):
5245 if len(names) != len(set(names)):
5244 raise error.Abort(_('tag names must be unique'))
5246 raise error.Abort(_('tag names must be unique'))
5245 for n in names:
5247 for n in names:
5246 scmutil.checknewlabel(repo, n, 'tag')
5248 scmutil.checknewlabel(repo, n, 'tag')
5247 if not n:
5249 if not n:
5248 raise error.Abort(_('tag names cannot consist entirely of '
5250 raise error.Abort(_('tag names cannot consist entirely of '
5249 'whitespace'))
5251 'whitespace'))
5250 if opts.get('rev') and opts.get('remove'):
5252 if opts.get('rev') and opts.get('remove'):
5251 raise error.Abort(_("--rev and --remove are incompatible"))
5253 raise error.Abort(_("--rev and --remove are incompatible"))
5252 if opts.get('rev'):
5254 if opts.get('rev'):
5253 rev_ = opts['rev']
5255 rev_ = opts['rev']
5254 message = opts.get('message')
5256 message = opts.get('message')
5255 if opts.get('remove'):
5257 if opts.get('remove'):
5256 if opts.get('local'):
5258 if opts.get('local'):
5257 expectedtype = 'local'
5259 expectedtype = 'local'
5258 else:
5260 else:
5259 expectedtype = 'global'
5261 expectedtype = 'global'
5260
5262
5261 for n in names:
5263 for n in names:
5262 if not repo.tagtype(n):
5264 if not repo.tagtype(n):
5263 raise error.Abort(_("tag '%s' does not exist") % n)
5265 raise error.Abort(_("tag '%s' does not exist") % n)
5264 if repo.tagtype(n) != expectedtype:
5266 if repo.tagtype(n) != expectedtype:
5265 if expectedtype == 'global':
5267 if expectedtype == 'global':
5266 raise error.Abort(_("tag '%s' is not a global tag") % n)
5268 raise error.Abort(_("tag '%s' is not a global tag") % n)
5267 else:
5269 else:
5268 raise error.Abort(_("tag '%s' is not a local tag") % n)
5270 raise error.Abort(_("tag '%s' is not a local tag") % n)
5269 rev_ = 'null'
5271 rev_ = 'null'
5270 if not message:
5272 if not message:
5271 # we don't translate commit messages
5273 # we don't translate commit messages
5272 message = 'Removed tag %s' % ', '.join(names)
5274 message = 'Removed tag %s' % ', '.join(names)
5273 elif not opts.get('force'):
5275 elif not opts.get('force'):
5274 for n in names:
5276 for n in names:
5275 if n in repo.tags():
5277 if n in repo.tags():
5276 raise error.Abort(_("tag '%s' already exists "
5278 raise error.Abort(_("tag '%s' already exists "
5277 "(use -f to force)") % n)
5279 "(use -f to force)") % n)
5278 if not opts.get('local'):
5280 if not opts.get('local'):
5279 p1, p2 = repo.dirstate.parents()
5281 p1, p2 = repo.dirstate.parents()
5280 if p2 != nullid:
5282 if p2 != nullid:
5281 raise error.Abort(_('uncommitted merge'))
5283 raise error.Abort(_('uncommitted merge'))
5282 bheads = repo.branchheads()
5284 bheads = repo.branchheads()
5283 if not opts.get('force') and bheads and p1 not in bheads:
5285 if not opts.get('force') and bheads and p1 not in bheads:
5284 raise error.Abort(_('working directory is not at a branch head '
5286 raise error.Abort(_('working directory is not at a branch head '
5285 '(use -f to force)'))
5287 '(use -f to force)'))
5286 r = scmutil.revsingle(repo, rev_).node()
5288 r = scmutil.revsingle(repo, rev_).node()
5287
5289
5288 if not message:
5290 if not message:
5289 # we don't translate commit messages
5291 # we don't translate commit messages
5290 message = ('Added tag %s for changeset %s' %
5292 message = ('Added tag %s for changeset %s' %
5291 (', '.join(names), short(r)))
5293 (', '.join(names), short(r)))
5292
5294
5293 date = opts.get('date')
5295 date = opts.get('date')
5294 if date:
5296 if date:
5295 date = util.parsedate(date)
5297 date = util.parsedate(date)
5296
5298
5297 if opts.get('remove'):
5299 if opts.get('remove'):
5298 editform = 'tag.remove'
5300 editform = 'tag.remove'
5299 else:
5301 else:
5300 editform = 'tag.add'
5302 editform = 'tag.add'
5301 editor = cmdutil.getcommiteditor(editform=editform,
5303 editor = cmdutil.getcommiteditor(editform=editform,
5302 **pycompat.strkwargs(opts))
5304 **pycompat.strkwargs(opts))
5303
5305
5304 # don't allow tagging the null rev
5306 # don't allow tagging the null rev
5305 if (not opts.get('remove') and
5307 if (not opts.get('remove') and
5306 scmutil.revsingle(repo, rev_).rev() == nullrev):
5308 scmutil.revsingle(repo, rev_).rev() == nullrev):
5307 raise error.Abort(_("cannot tag null revision"))
5309 raise error.Abort(_("cannot tag null revision"))
5308
5310
5309 tagsmod.tag(repo, names, r, message, opts.get('local'),
5311 tagsmod.tag(repo, names, r, message, opts.get('local'),
5310 opts.get('user'), date, editor=editor)
5312 opts.get('user'), date, editor=editor)
5311 finally:
5313 finally:
5312 release(lock, wlock)
5314 release(lock, wlock)
5313
5315
5314 @command('tags', formatteropts, '', cmdtype=readonly)
5316 @command('tags', formatteropts, '', cmdtype=readonly)
5315 def tags(ui, repo, **opts):
5317 def tags(ui, repo, **opts):
5316 """list repository tags
5318 """list repository tags
5317
5319
5318 This lists both regular and local tags. When the -v/--verbose
5320 This lists both regular and local tags. When the -v/--verbose
5319 switch is used, a third column "local" is printed for local tags.
5321 switch is used, a third column "local" is printed for local tags.
5320 When the -q/--quiet switch is used, only the tag name is printed.
5322 When the -q/--quiet switch is used, only the tag name is printed.
5321
5323
5322 Returns 0 on success.
5324 Returns 0 on success.
5323 """
5325 """
5324
5326
5325 opts = pycompat.byteskwargs(opts)
5327 opts = pycompat.byteskwargs(opts)
5326 ui.pager('tags')
5328 ui.pager('tags')
5327 fm = ui.formatter('tags', opts)
5329 fm = ui.formatter('tags', opts)
5328 hexfunc = fm.hexfunc
5330 hexfunc = fm.hexfunc
5329 tagtype = ""
5331 tagtype = ""
5330
5332
5331 for t, n in reversed(repo.tagslist()):
5333 for t, n in reversed(repo.tagslist()):
5332 hn = hexfunc(n)
5334 hn = hexfunc(n)
5333 label = 'tags.normal'
5335 label = 'tags.normal'
5334 tagtype = ''
5336 tagtype = ''
5335 if repo.tagtype(t) == 'local':
5337 if repo.tagtype(t) == 'local':
5336 label = 'tags.local'
5338 label = 'tags.local'
5337 tagtype = 'local'
5339 tagtype = 'local'
5338
5340
5339 fm.startitem()
5341 fm.startitem()
5340 fm.write('tag', '%s', t, label=label)
5342 fm.write('tag', '%s', t, label=label)
5341 fmt = " " * (30 - encoding.colwidth(t)) + ' %5d:%s'
5343 fmt = " " * (30 - encoding.colwidth(t)) + ' %5d:%s'
5342 fm.condwrite(not ui.quiet, 'rev node', fmt,
5344 fm.condwrite(not ui.quiet, 'rev node', fmt,
5343 repo.changelog.rev(n), hn, label=label)
5345 repo.changelog.rev(n), hn, label=label)
5344 fm.condwrite(ui.verbose and tagtype, 'type', ' %s',
5346 fm.condwrite(ui.verbose and tagtype, 'type', ' %s',
5345 tagtype, label=label)
5347 tagtype, label=label)
5346 fm.plain('\n')
5348 fm.plain('\n')
5347 fm.end()
5349 fm.end()
5348
5350
5349 @command('tip',
5351 @command('tip',
5350 [('p', 'patch', None, _('show patch')),
5352 [('p', 'patch', None, _('show patch')),
5351 ('g', 'git', None, _('use git extended diff format')),
5353 ('g', 'git', None, _('use git extended diff format')),
5352 ] + templateopts,
5354 ] + templateopts,
5353 _('[-p] [-g]'))
5355 _('[-p] [-g]'))
5354 def tip(ui, repo, **opts):
5356 def tip(ui, repo, **opts):
5355 """show the tip revision (DEPRECATED)
5357 """show the tip revision (DEPRECATED)
5356
5358
5357 The tip revision (usually just called the tip) is the changeset
5359 The tip revision (usually just called the tip) is the changeset
5358 most recently added to the repository (and therefore the most
5360 most recently added to the repository (and therefore the most
5359 recently changed head).
5361 recently changed head).
5360
5362
5361 If you have just made a commit, that commit will be the tip. If
5363 If you have just made a commit, that commit will be the tip. If
5362 you have just pulled changes from another repository, the tip of
5364 you have just pulled changes from another repository, the tip of
5363 that repository becomes the current tip. The "tip" tag is special
5365 that repository becomes the current tip. The "tip" tag is special
5364 and cannot be renamed or assigned to a different changeset.
5366 and cannot be renamed or assigned to a different changeset.
5365
5367
5366 This command is deprecated, please use :hg:`heads` instead.
5368 This command is deprecated, please use :hg:`heads` instead.
5367
5369
5368 Returns 0 on success.
5370 Returns 0 on success.
5369 """
5371 """
5370 opts = pycompat.byteskwargs(opts)
5372 opts = pycompat.byteskwargs(opts)
5371 displayer = cmdutil.show_changeset(ui, repo, opts)
5373 displayer = cmdutil.show_changeset(ui, repo, opts)
5372 displayer.show(repo['tip'])
5374 displayer.show(repo['tip'])
5373 displayer.close()
5375 displayer.close()
5374
5376
5375 @command('unbundle',
5377 @command('unbundle',
5376 [('u', 'update', None,
5378 [('u', 'update', None,
5377 _('update to new branch head if changesets were unbundled'))],
5379 _('update to new branch head if changesets were unbundled'))],
5378 _('[-u] FILE...'))
5380 _('[-u] FILE...'))
5379 def unbundle(ui, repo, fname1, *fnames, **opts):
5381 def unbundle(ui, repo, fname1, *fnames, **opts):
5380 """apply one or more bundle files
5382 """apply one or more bundle files
5381
5383
5382 Apply one or more bundle files generated by :hg:`bundle`.
5384 Apply one or more bundle files generated by :hg:`bundle`.
5383
5385
5384 Returns 0 on success, 1 if an update has unresolved files.
5386 Returns 0 on success, 1 if an update has unresolved files.
5385 """
5387 """
5386 fnames = (fname1,) + fnames
5388 fnames = (fname1,) + fnames
5387
5389
5388 with repo.lock():
5390 with repo.lock():
5389 for fname in fnames:
5391 for fname in fnames:
5390 f = hg.openpath(ui, fname)
5392 f = hg.openpath(ui, fname)
5391 gen = exchange.readbundle(ui, f, fname)
5393 gen = exchange.readbundle(ui, f, fname)
5392 if isinstance(gen, streamclone.streamcloneapplier):
5394 if isinstance(gen, streamclone.streamcloneapplier):
5393 raise error.Abort(
5395 raise error.Abort(
5394 _('packed bundles cannot be applied with '
5396 _('packed bundles cannot be applied with '
5395 '"hg unbundle"'),
5397 '"hg unbundle"'),
5396 hint=_('use "hg debugapplystreamclonebundle"'))
5398 hint=_('use "hg debugapplystreamclonebundle"'))
5397 url = 'bundle:' + fname
5399 url = 'bundle:' + fname
5398 try:
5400 try:
5399 txnname = 'unbundle'
5401 txnname = 'unbundle'
5400 if not isinstance(gen, bundle2.unbundle20):
5402 if not isinstance(gen, bundle2.unbundle20):
5401 txnname = 'unbundle\n%s' % util.hidepassword(url)
5403 txnname = 'unbundle\n%s' % util.hidepassword(url)
5402 with repo.transaction(txnname) as tr:
5404 with repo.transaction(txnname) as tr:
5403 op = bundle2.applybundle(repo, gen, tr, source='unbundle',
5405 op = bundle2.applybundle(repo, gen, tr, source='unbundle',
5404 url=url)
5406 url=url)
5405 except error.BundleUnknownFeatureError as exc:
5407 except error.BundleUnknownFeatureError as exc:
5406 raise error.Abort(
5408 raise error.Abort(
5407 _('%s: unknown bundle feature, %s') % (fname, exc),
5409 _('%s: unknown bundle feature, %s') % (fname, exc),
5408 hint=_("see https://mercurial-scm.org/"
5410 hint=_("see https://mercurial-scm.org/"
5409 "wiki/BundleFeature for more "
5411 "wiki/BundleFeature for more "
5410 "information"))
5412 "information"))
5411 modheads = bundle2.combinechangegroupresults(op)
5413 modheads = bundle2.combinechangegroupresults(op)
5412
5414
5413 return postincoming(ui, repo, modheads, opts.get(r'update'), None, None)
5415 return postincoming(ui, repo, modheads, opts.get(r'update'), None, None)
5414
5416
5415 @command('^update|up|checkout|co',
5417 @command('^update|up|checkout|co',
5416 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
5418 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
5417 ('c', 'check', None, _('require clean working directory')),
5419 ('c', 'check', None, _('require clean working directory')),
5418 ('m', 'merge', None, _('merge uncommitted changes')),
5420 ('m', 'merge', None, _('merge uncommitted changes')),
5419 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5421 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5420 ('r', 'rev', '', _('revision'), _('REV'))
5422 ('r', 'rev', '', _('revision'), _('REV'))
5421 ] + mergetoolopts,
5423 ] + mergetoolopts,
5422 _('[-C|-c|-m] [-d DATE] [[-r] REV]'))
5424 _('[-C|-c|-m] [-d DATE] [[-r] REV]'))
5423 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False,
5425 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False,
5424 merge=None, tool=None):
5426 merge=None, tool=None):
5425 """update working directory (or switch revisions)
5427 """update working directory (or switch revisions)
5426
5428
5427 Update the repository's working directory to the specified
5429 Update the repository's working directory to the specified
5428 changeset. If no changeset is specified, update to the tip of the
5430 changeset. If no changeset is specified, update to the tip of the
5429 current named branch and move the active bookmark (see :hg:`help
5431 current named branch and move the active bookmark (see :hg:`help
5430 bookmarks`).
5432 bookmarks`).
5431
5433
5432 Update sets the working directory's parent revision to the specified
5434 Update sets the working directory's parent revision to the specified
5433 changeset (see :hg:`help parents`).
5435 changeset (see :hg:`help parents`).
5434
5436
5435 If the changeset is not a descendant or ancestor of the working
5437 If the changeset is not a descendant or ancestor of the working
5436 directory's parent and there are uncommitted changes, the update is
5438 directory's parent and there are uncommitted changes, the update is
5437 aborted. With the -c/--check option, the working directory is checked
5439 aborted. With the -c/--check option, the working directory is checked
5438 for uncommitted changes; if none are found, the working directory is
5440 for uncommitted changes; if none are found, the working directory is
5439 updated to the specified changeset.
5441 updated to the specified changeset.
5440
5442
5441 .. container:: verbose
5443 .. container:: verbose
5442
5444
5443 The -C/--clean, -c/--check, and -m/--merge options control what
5445 The -C/--clean, -c/--check, and -m/--merge options control what
5444 happens if the working directory contains uncommitted changes.
5446 happens if the working directory contains uncommitted changes.
5445 At most of one of them can be specified.
5447 At most of one of them can be specified.
5446
5448
5447 1. If no option is specified, and if
5449 1. If no option is specified, and if
5448 the requested changeset is an ancestor or descendant of
5450 the requested changeset is an ancestor or descendant of
5449 the working directory's parent, the uncommitted changes
5451 the working directory's parent, the uncommitted changes
5450 are merged into the requested changeset and the merged
5452 are merged into the requested changeset and the merged
5451 result is left uncommitted. If the requested changeset is
5453 result is left uncommitted. If the requested changeset is
5452 not an ancestor or descendant (that is, it is on another
5454 not an ancestor or descendant (that is, it is on another
5453 branch), the update is aborted and the uncommitted changes
5455 branch), the update is aborted and the uncommitted changes
5454 are preserved.
5456 are preserved.
5455
5457
5456 2. With the -m/--merge option, the update is allowed even if the
5458 2. With the -m/--merge option, the update is allowed even if the
5457 requested changeset is not an ancestor or descendant of
5459 requested changeset is not an ancestor or descendant of
5458 the working directory's parent.
5460 the working directory's parent.
5459
5461
5460 3. With the -c/--check option, the update is aborted and the
5462 3. With the -c/--check option, the update is aborted and the
5461 uncommitted changes are preserved.
5463 uncommitted changes are preserved.
5462
5464
5463 4. With the -C/--clean option, uncommitted changes are discarded and
5465 4. With the -C/--clean option, uncommitted changes are discarded and
5464 the working directory is updated to the requested changeset.
5466 the working directory is updated to the requested changeset.
5465
5467
5466 To cancel an uncommitted merge (and lose your changes), use
5468 To cancel an uncommitted merge (and lose your changes), use
5467 :hg:`update --clean .`.
5469 :hg:`update --clean .`.
5468
5470
5469 Use null as the changeset to remove the working directory (like
5471 Use null as the changeset to remove the working directory (like
5470 :hg:`clone -U`).
5472 :hg:`clone -U`).
5471
5473
5472 If you want to revert just one file to an older revision, use
5474 If you want to revert just one file to an older revision, use
5473 :hg:`revert [-r REV] NAME`.
5475 :hg:`revert [-r REV] NAME`.
5474
5476
5475 See :hg:`help dates` for a list of formats valid for -d/--date.
5477 See :hg:`help dates` for a list of formats valid for -d/--date.
5476
5478
5477 Returns 0 on success, 1 if there are unresolved files.
5479 Returns 0 on success, 1 if there are unresolved files.
5478 """
5480 """
5479 if rev and node:
5481 if rev and node:
5480 raise error.Abort(_("please specify just one revision"))
5482 raise error.Abort(_("please specify just one revision"))
5481
5483
5482 if ui.configbool('commands', 'update.requiredest'):
5484 if ui.configbool('commands', 'update.requiredest'):
5483 if not node and not rev and not date:
5485 if not node and not rev and not date:
5484 raise error.Abort(_('you must specify a destination'),
5486 raise error.Abort(_('you must specify a destination'),
5485 hint=_('for example: hg update ".::"'))
5487 hint=_('for example: hg update ".::"'))
5486
5488
5487 if rev is None or rev == '':
5489 if rev is None or rev == '':
5488 rev = node
5490 rev = node
5489
5491
5490 if date and rev is not None:
5492 if date and rev is not None:
5491 raise error.Abort(_("you can't specify a revision and a date"))
5493 raise error.Abort(_("you can't specify a revision and a date"))
5492
5494
5493 if len([x for x in (clean, check, merge) if x]) > 1:
5495 if len([x for x in (clean, check, merge) if x]) > 1:
5494 raise error.Abort(_("can only specify one of -C/--clean, -c/--check, "
5496 raise error.Abort(_("can only specify one of -C/--clean, -c/--check, "
5495 "or -m/--merge"))
5497 "or -m/--merge"))
5496
5498
5497 updatecheck = None
5499 updatecheck = None
5498 if check:
5500 if check:
5499 updatecheck = 'abort'
5501 updatecheck = 'abort'
5500 elif merge:
5502 elif merge:
5501 updatecheck = 'none'
5503 updatecheck = 'none'
5502
5504
5503 with repo.wlock():
5505 with repo.wlock():
5504 cmdutil.clearunfinished(repo)
5506 cmdutil.clearunfinished(repo)
5505
5507
5506 if date:
5508 if date:
5507 rev = cmdutil.finddate(ui, repo, date)
5509 rev = cmdutil.finddate(ui, repo, date)
5508
5510
5509 # if we defined a bookmark, we have to remember the original name
5511 # if we defined a bookmark, we have to remember the original name
5510 brev = rev
5512 brev = rev
5511 rev = scmutil.revsingle(repo, rev, rev).rev()
5513 rev = scmutil.revsingle(repo, rev, rev).rev()
5512
5514
5513 repo.ui.setconfig('ui', 'forcemerge', tool, 'update')
5515 repo.ui.setconfig('ui', 'forcemerge', tool, 'update')
5514
5516
5515 return hg.updatetotally(ui, repo, rev, brev, clean=clean,
5517 return hg.updatetotally(ui, repo, rev, brev, clean=clean,
5516 updatecheck=updatecheck)
5518 updatecheck=updatecheck)
5517
5519
5518 @command('verify', [])
5520 @command('verify', [])
5519 def verify(ui, repo):
5521 def verify(ui, repo):
5520 """verify the integrity of the repository
5522 """verify the integrity of the repository
5521
5523
5522 Verify the integrity of the current repository.
5524 Verify the integrity of the current repository.
5523
5525
5524 This will perform an extensive check of the repository's
5526 This will perform an extensive check of the repository's
5525 integrity, validating the hashes and checksums of each entry in
5527 integrity, validating the hashes and checksums of each entry in
5526 the changelog, manifest, and tracked files, as well as the
5528 the changelog, manifest, and tracked files, as well as the
5527 integrity of their crosslinks and indices.
5529 integrity of their crosslinks and indices.
5528
5530
5529 Please see https://mercurial-scm.org/wiki/RepositoryCorruption
5531 Please see https://mercurial-scm.org/wiki/RepositoryCorruption
5530 for more information about recovery from corruption of the
5532 for more information about recovery from corruption of the
5531 repository.
5533 repository.
5532
5534
5533 Returns 0 on success, 1 if errors are encountered.
5535 Returns 0 on success, 1 if errors are encountered.
5534 """
5536 """
5535 return hg.verify(repo)
5537 return hg.verify(repo)
5536
5538
5537 @command('version', [] + formatteropts, norepo=True, cmdtype=readonly)
5539 @command('version', [] + formatteropts, norepo=True, cmdtype=readonly)
5538 def version_(ui, **opts):
5540 def version_(ui, **opts):
5539 """output version and copyright information"""
5541 """output version and copyright information"""
5540 opts = pycompat.byteskwargs(opts)
5542 opts = pycompat.byteskwargs(opts)
5541 if ui.verbose:
5543 if ui.verbose:
5542 ui.pager('version')
5544 ui.pager('version')
5543 fm = ui.formatter("version", opts)
5545 fm = ui.formatter("version", opts)
5544 fm.startitem()
5546 fm.startitem()
5545 fm.write("ver", _("Mercurial Distributed SCM (version %s)\n"),
5547 fm.write("ver", _("Mercurial Distributed SCM (version %s)\n"),
5546 util.version())
5548 util.version())
5547 license = _(
5549 license = _(
5548 "(see https://mercurial-scm.org for more information)\n"
5550 "(see https://mercurial-scm.org for more information)\n"
5549 "\nCopyright (C) 2005-2017 Matt Mackall and others\n"
5551 "\nCopyright (C) 2005-2017 Matt Mackall and others\n"
5550 "This is free software; see the source for copying conditions. "
5552 "This is free software; see the source for copying conditions. "
5551 "There is NO\nwarranty; "
5553 "There is NO\nwarranty; "
5552 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
5554 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
5553 )
5555 )
5554 if not ui.quiet:
5556 if not ui.quiet:
5555 fm.plain(license)
5557 fm.plain(license)
5556
5558
5557 if ui.verbose:
5559 if ui.verbose:
5558 fm.plain(_("\nEnabled extensions:\n\n"))
5560 fm.plain(_("\nEnabled extensions:\n\n"))
5559 # format names and versions into columns
5561 # format names and versions into columns
5560 names = []
5562 names = []
5561 vers = []
5563 vers = []
5562 isinternals = []
5564 isinternals = []
5563 for name, module in extensions.extensions():
5565 for name, module in extensions.extensions():
5564 names.append(name)
5566 names.append(name)
5565 vers.append(extensions.moduleversion(module) or None)
5567 vers.append(extensions.moduleversion(module) or None)
5566 isinternals.append(extensions.ismoduleinternal(module))
5568 isinternals.append(extensions.ismoduleinternal(module))
5567 fn = fm.nested("extensions")
5569 fn = fm.nested("extensions")
5568 if names:
5570 if names:
5569 namefmt = " %%-%ds " % max(len(n) for n in names)
5571 namefmt = " %%-%ds " % max(len(n) for n in names)
5570 places = [_("external"), _("internal")]
5572 places = [_("external"), _("internal")]
5571 for n, v, p in zip(names, vers, isinternals):
5573 for n, v, p in zip(names, vers, isinternals):
5572 fn.startitem()
5574 fn.startitem()
5573 fn.condwrite(ui.verbose, "name", namefmt, n)
5575 fn.condwrite(ui.verbose, "name", namefmt, n)
5574 if ui.verbose:
5576 if ui.verbose:
5575 fn.plain("%s " % places[p])
5577 fn.plain("%s " % places[p])
5576 fn.data(bundled=p)
5578 fn.data(bundled=p)
5577 fn.condwrite(ui.verbose and v, "ver", "%s", v)
5579 fn.condwrite(ui.verbose and v, "ver", "%s", v)
5578 if ui.verbose:
5580 if ui.verbose:
5579 fn.plain("\n")
5581 fn.plain("\n")
5580 fn.end()
5582 fn.end()
5581 fm.end()
5583 fm.end()
5582
5584
5583 def loadcmdtable(ui, name, cmdtable):
5585 def loadcmdtable(ui, name, cmdtable):
5584 """Load command functions from specified cmdtable
5586 """Load command functions from specified cmdtable
5585 """
5587 """
5586 overrides = [cmd for cmd in cmdtable if cmd in table]
5588 overrides = [cmd for cmd in cmdtable if cmd in table]
5587 if overrides:
5589 if overrides:
5588 ui.warn(_("extension '%s' overrides commands: %s\n")
5590 ui.warn(_("extension '%s' overrides commands: %s\n")
5589 % (name, " ".join(overrides)))
5591 % (name, " ".join(overrides)))
5590 table.update(cmdtable)
5592 table.update(cmdtable)
@@ -1,2063 +1,2063 b''
1 # subrepo.py - sub-repository handling for Mercurial
1 # subrepo.py - sub-repository handling for Mercurial
2 #
2 #
3 # Copyright 2009-2010 Matt Mackall <mpm@selenic.com>
3 # Copyright 2009-2010 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 from __future__ import absolute_import
8 from __future__ import absolute_import
9
9
10 import copy
10 import copy
11 import errno
11 import errno
12 import hashlib
12 import hashlib
13 import os
13 import os
14 import posixpath
14 import posixpath
15 import re
15 import re
16 import stat
16 import stat
17 import subprocess
17 import subprocess
18 import sys
18 import sys
19 import tarfile
19 import tarfile
20 import xml.dom.minidom
20 import xml.dom.minidom
21
21
22
22
23 from .i18n import _
23 from .i18n import _
24 from . import (
24 from . import (
25 cmdutil,
25 cmdutil,
26 config,
26 config,
27 encoding,
27 encoding,
28 error,
28 error,
29 exchange,
29 exchange,
30 filemerge,
30 filemerge,
31 match as matchmod,
31 match as matchmod,
32 node,
32 node,
33 pathutil,
33 pathutil,
34 phases,
34 phases,
35 pycompat,
35 pycompat,
36 scmutil,
36 scmutil,
37 util,
37 util,
38 vfs as vfsmod,
38 vfs as vfsmod,
39 )
39 )
40
40
41 hg = None
41 hg = None
42 propertycache = util.propertycache
42 propertycache = util.propertycache
43
43
44 nullstate = ('', '', 'empty')
44 nullstate = ('', '', 'empty')
45
45
46 def _expandedabspath(path):
46 def _expandedabspath(path):
47 '''
47 '''
48 get a path or url and if it is a path expand it and return an absolute path
48 get a path or url and if it is a path expand it and return an absolute path
49 '''
49 '''
50 expandedpath = util.urllocalpath(util.expandpath(path))
50 expandedpath = util.urllocalpath(util.expandpath(path))
51 u = util.url(expandedpath)
51 u = util.url(expandedpath)
52 if not u.scheme:
52 if not u.scheme:
53 path = util.normpath(os.path.abspath(u.path))
53 path = util.normpath(os.path.abspath(u.path))
54 return path
54 return path
55
55
56 def _getstorehashcachename(remotepath):
56 def _getstorehashcachename(remotepath):
57 '''get a unique filename for the store hash cache of a remote repository'''
57 '''get a unique filename for the store hash cache of a remote repository'''
58 return hashlib.sha1(_expandedabspath(remotepath)).hexdigest()[0:12]
58 return hashlib.sha1(_expandedabspath(remotepath)).hexdigest()[0:12]
59
59
60 class SubrepoAbort(error.Abort):
60 class SubrepoAbort(error.Abort):
61 """Exception class used to avoid handling a subrepo error more than once"""
61 """Exception class used to avoid handling a subrepo error more than once"""
62 def __init__(self, *args, **kw):
62 def __init__(self, *args, **kw):
63 self.subrepo = kw.pop('subrepo', None)
63 self.subrepo = kw.pop('subrepo', None)
64 self.cause = kw.pop('cause', None)
64 self.cause = kw.pop('cause', None)
65 error.Abort.__init__(self, *args, **kw)
65 error.Abort.__init__(self, *args, **kw)
66
66
67 def annotatesubrepoerror(func):
67 def annotatesubrepoerror(func):
68 def decoratedmethod(self, *args, **kargs):
68 def decoratedmethod(self, *args, **kargs):
69 try:
69 try:
70 res = func(self, *args, **kargs)
70 res = func(self, *args, **kargs)
71 except SubrepoAbort as ex:
71 except SubrepoAbort as ex:
72 # This exception has already been handled
72 # This exception has already been handled
73 raise ex
73 raise ex
74 except error.Abort as ex:
74 except error.Abort as ex:
75 subrepo = subrelpath(self)
75 subrepo = subrelpath(self)
76 errormsg = str(ex) + ' ' + _('(in subrepository "%s")') % subrepo
76 errormsg = str(ex) + ' ' + _('(in subrepository "%s")') % subrepo
77 # avoid handling this exception by raising a SubrepoAbort exception
77 # avoid handling this exception by raising a SubrepoAbort exception
78 raise SubrepoAbort(errormsg, hint=ex.hint, subrepo=subrepo,
78 raise SubrepoAbort(errormsg, hint=ex.hint, subrepo=subrepo,
79 cause=sys.exc_info())
79 cause=sys.exc_info())
80 return res
80 return res
81 return decoratedmethod
81 return decoratedmethod
82
82
83 def state(ctx, ui):
83 def state(ctx, ui):
84 """return a state dict, mapping subrepo paths configured in .hgsub
84 """return a state dict, mapping subrepo paths configured in .hgsub
85 to tuple: (source from .hgsub, revision from .hgsubstate, kind
85 to tuple: (source from .hgsub, revision from .hgsubstate, kind
86 (key in types dict))
86 (key in types dict))
87 """
87 """
88 p = config.config()
88 p = config.config()
89 repo = ctx.repo()
89 repo = ctx.repo()
90 def read(f, sections=None, remap=None):
90 def read(f, sections=None, remap=None):
91 if f in ctx:
91 if f in ctx:
92 try:
92 try:
93 data = ctx[f].data()
93 data = ctx[f].data()
94 except IOError as err:
94 except IOError as err:
95 if err.errno != errno.ENOENT:
95 if err.errno != errno.ENOENT:
96 raise
96 raise
97 # handle missing subrepo spec files as removed
97 # handle missing subrepo spec files as removed
98 ui.warn(_("warning: subrepo spec file \'%s\' not found\n") %
98 ui.warn(_("warning: subrepo spec file \'%s\' not found\n") %
99 repo.pathto(f))
99 repo.pathto(f))
100 return
100 return
101 p.parse(f, data, sections, remap, read)
101 p.parse(f, data, sections, remap, read)
102 else:
102 else:
103 raise error.Abort(_("subrepo spec file \'%s\' not found") %
103 raise error.Abort(_("subrepo spec file \'%s\' not found") %
104 repo.pathto(f))
104 repo.pathto(f))
105 if '.hgsub' in ctx:
105 if '.hgsub' in ctx:
106 read('.hgsub')
106 read('.hgsub')
107
107
108 for path, src in ui.configitems('subpaths'):
108 for path, src in ui.configitems('subpaths'):
109 p.set('subpaths', path, src, ui.configsource('subpaths', path))
109 p.set('subpaths', path, src, ui.configsource('subpaths', path))
110
110
111 rev = {}
111 rev = {}
112 if '.hgsubstate' in ctx:
112 if '.hgsubstate' in ctx:
113 try:
113 try:
114 for i, l in enumerate(ctx['.hgsubstate'].data().splitlines()):
114 for i, l in enumerate(ctx['.hgsubstate'].data().splitlines()):
115 l = l.lstrip()
115 l = l.lstrip()
116 if not l:
116 if not l:
117 continue
117 continue
118 try:
118 try:
119 revision, path = l.split(" ", 1)
119 revision, path = l.split(" ", 1)
120 except ValueError:
120 except ValueError:
121 raise error.Abort(_("invalid subrepository revision "
121 raise error.Abort(_("invalid subrepository revision "
122 "specifier in \'%s\' line %d")
122 "specifier in \'%s\' line %d")
123 % (repo.pathto('.hgsubstate'), (i + 1)))
123 % (repo.pathto('.hgsubstate'), (i + 1)))
124 rev[path] = revision
124 rev[path] = revision
125 except IOError as err:
125 except IOError as err:
126 if err.errno != errno.ENOENT:
126 if err.errno != errno.ENOENT:
127 raise
127 raise
128
128
129 def remap(src):
129 def remap(src):
130 for pattern, repl in p.items('subpaths'):
130 for pattern, repl in p.items('subpaths'):
131 # Turn r'C:\foo\bar' into r'C:\\foo\\bar' since re.sub
131 # Turn r'C:\foo\bar' into r'C:\\foo\\bar' since re.sub
132 # does a string decode.
132 # does a string decode.
133 repl = util.escapestr(repl)
133 repl = util.escapestr(repl)
134 # However, we still want to allow back references to go
134 # However, we still want to allow back references to go
135 # through unharmed, so we turn r'\\1' into r'\1'. Again,
135 # through unharmed, so we turn r'\\1' into r'\1'. Again,
136 # extra escapes are needed because re.sub string decodes.
136 # extra escapes are needed because re.sub string decodes.
137 repl = re.sub(br'\\\\([0-9]+)', br'\\\1', repl)
137 repl = re.sub(br'\\\\([0-9]+)', br'\\\1', repl)
138 try:
138 try:
139 src = re.sub(pattern, repl, src, 1)
139 src = re.sub(pattern, repl, src, 1)
140 except re.error as e:
140 except re.error as e:
141 raise error.Abort(_("bad subrepository pattern in %s: %s")
141 raise error.Abort(_("bad subrepository pattern in %s: %s")
142 % (p.source('subpaths', pattern), e))
142 % (p.source('subpaths', pattern), e))
143 return src
143 return src
144
144
145 state = {}
145 state = {}
146 for path, src in p[''].items():
146 for path, src in p[''].items():
147 kind = 'hg'
147 kind = 'hg'
148 if src.startswith('['):
148 if src.startswith('['):
149 if ']' not in src:
149 if ']' not in src:
150 raise error.Abort(_('missing ] in subrepository source'))
150 raise error.Abort(_('missing ] in subrepository source'))
151 kind, src = src.split(']', 1)
151 kind, src = src.split(']', 1)
152 kind = kind[1:]
152 kind = kind[1:]
153 src = src.lstrip() # strip any extra whitespace after ']'
153 src = src.lstrip() # strip any extra whitespace after ']'
154
154
155 if not util.url(src).isabs():
155 if not util.url(src).isabs():
156 parent = _abssource(repo, abort=False)
156 parent = _abssource(repo, abort=False)
157 if parent:
157 if parent:
158 parent = util.url(parent)
158 parent = util.url(parent)
159 parent.path = posixpath.join(parent.path or '', src)
159 parent.path = posixpath.join(parent.path or '', src)
160 parent.path = posixpath.normpath(parent.path)
160 parent.path = posixpath.normpath(parent.path)
161 joined = str(parent)
161 joined = str(parent)
162 # Remap the full joined path and use it if it changes,
162 # Remap the full joined path and use it if it changes,
163 # else remap the original source.
163 # else remap the original source.
164 remapped = remap(joined)
164 remapped = remap(joined)
165 if remapped == joined:
165 if remapped == joined:
166 src = remap(src)
166 src = remap(src)
167 else:
167 else:
168 src = remapped
168 src = remapped
169
169
170 src = remap(src)
170 src = remap(src)
171 state[util.pconvert(path)] = (src.strip(), rev.get(path, ''), kind)
171 state[util.pconvert(path)] = (src.strip(), rev.get(path, ''), kind)
172
172
173 return state
173 return state
174
174
175 def writestate(repo, state):
175 def writestate(repo, state):
176 """rewrite .hgsubstate in (outer) repo with these subrepo states"""
176 """rewrite .hgsubstate in (outer) repo with these subrepo states"""
177 lines = ['%s %s\n' % (state[s][1], s) for s in sorted(state)
177 lines = ['%s %s\n' % (state[s][1], s) for s in sorted(state)
178 if state[s][1] != nullstate[1]]
178 if state[s][1] != nullstate[1]]
179 repo.wwrite('.hgsubstate', ''.join(lines), '')
179 repo.wwrite('.hgsubstate', ''.join(lines), '')
180
180
181 def submerge(repo, wctx, mctx, actx, overwrite, labels=None):
181 def submerge(repo, wctx, mctx, actx, overwrite, labels=None):
182 """delegated from merge.applyupdates: merging of .hgsubstate file
182 """delegated from merge.applyupdates: merging of .hgsubstate file
183 in working context, merging context and ancestor context"""
183 in working context, merging context and ancestor context"""
184 if mctx == actx: # backwards?
184 if mctx == actx: # backwards?
185 actx = wctx.p1()
185 actx = wctx.p1()
186 s1 = wctx.substate
186 s1 = wctx.substate
187 s2 = mctx.substate
187 s2 = mctx.substate
188 sa = actx.substate
188 sa = actx.substate
189 sm = {}
189 sm = {}
190
190
191 repo.ui.debug("subrepo merge %s %s %s\n" % (wctx, mctx, actx))
191 repo.ui.debug("subrepo merge %s %s %s\n" % (wctx, mctx, actx))
192
192
193 def debug(s, msg, r=""):
193 def debug(s, msg, r=""):
194 if r:
194 if r:
195 r = "%s:%s:%s" % r
195 r = "%s:%s:%s" % r
196 repo.ui.debug(" subrepo %s: %s %s\n" % (s, msg, r))
196 repo.ui.debug(" subrepo %s: %s %s\n" % (s, msg, r))
197
197
198 promptssrc = filemerge.partextras(labels)
198 promptssrc = filemerge.partextras(labels)
199 for s, l in sorted(s1.iteritems()):
199 for s, l in sorted(s1.iteritems()):
200 prompts = None
200 prompts = None
201 a = sa.get(s, nullstate)
201 a = sa.get(s, nullstate)
202 ld = l # local state with possible dirty flag for compares
202 ld = l # local state with possible dirty flag for compares
203 if wctx.sub(s).dirty():
203 if wctx.sub(s).dirty():
204 ld = (l[0], l[1] + "+")
204 ld = (l[0], l[1] + "+")
205 if wctx == actx: # overwrite
205 if wctx == actx: # overwrite
206 a = ld
206 a = ld
207
207
208 prompts = promptssrc.copy()
208 prompts = promptssrc.copy()
209 prompts['s'] = s
209 prompts['s'] = s
210 if s in s2:
210 if s in s2:
211 r = s2[s]
211 r = s2[s]
212 if ld == r or r == a: # no change or local is newer
212 if ld == r or r == a: # no change or local is newer
213 sm[s] = l
213 sm[s] = l
214 continue
214 continue
215 elif ld == a: # other side changed
215 elif ld == a: # other side changed
216 debug(s, "other changed, get", r)
216 debug(s, "other changed, get", r)
217 wctx.sub(s).get(r, overwrite)
217 wctx.sub(s).get(r, overwrite)
218 sm[s] = r
218 sm[s] = r
219 elif ld[0] != r[0]: # sources differ
219 elif ld[0] != r[0]: # sources differ
220 prompts['lo'] = l[0]
220 prompts['lo'] = l[0]
221 prompts['ro'] = r[0]
221 prompts['ro'] = r[0]
222 if repo.ui.promptchoice(
222 if repo.ui.promptchoice(
223 _(' subrepository sources for %(s)s differ\n'
223 _(' subrepository sources for %(s)s differ\n'
224 'use (l)ocal%(l)s source (%(lo)s)'
224 'use (l)ocal%(l)s source (%(lo)s)'
225 ' or (r)emote%(o)s source (%(ro)s)?'
225 ' or (r)emote%(o)s source (%(ro)s)?'
226 '$$ &Local $$ &Remote') % prompts, 0):
226 '$$ &Local $$ &Remote') % prompts, 0):
227 debug(s, "prompt changed, get", r)
227 debug(s, "prompt changed, get", r)
228 wctx.sub(s).get(r, overwrite)
228 wctx.sub(s).get(r, overwrite)
229 sm[s] = r
229 sm[s] = r
230 elif ld[1] == a[1]: # local side is unchanged
230 elif ld[1] == a[1]: # local side is unchanged
231 debug(s, "other side changed, get", r)
231 debug(s, "other side changed, get", r)
232 wctx.sub(s).get(r, overwrite)
232 wctx.sub(s).get(r, overwrite)
233 sm[s] = r
233 sm[s] = r
234 else:
234 else:
235 debug(s, "both sides changed")
235 debug(s, "both sides changed")
236 srepo = wctx.sub(s)
236 srepo = wctx.sub(s)
237 prompts['sl'] = srepo.shortid(l[1])
237 prompts['sl'] = srepo.shortid(l[1])
238 prompts['sr'] = srepo.shortid(r[1])
238 prompts['sr'] = srepo.shortid(r[1])
239 option = repo.ui.promptchoice(
239 option = repo.ui.promptchoice(
240 _(' subrepository %(s)s diverged (local revision: %(sl)s, '
240 _(' subrepository %(s)s diverged (local revision: %(sl)s, '
241 'remote revision: %(sr)s)\n'
241 'remote revision: %(sr)s)\n'
242 '(M)erge, keep (l)ocal%(l)s or keep (r)emote%(o)s?'
242 '(M)erge, keep (l)ocal%(l)s or keep (r)emote%(o)s?'
243 '$$ &Merge $$ &Local $$ &Remote')
243 '$$ &Merge $$ &Local $$ &Remote')
244 % prompts, 0)
244 % prompts, 0)
245 if option == 0:
245 if option == 0:
246 wctx.sub(s).merge(r)
246 wctx.sub(s).merge(r)
247 sm[s] = l
247 sm[s] = l
248 debug(s, "merge with", r)
248 debug(s, "merge with", r)
249 elif option == 1:
249 elif option == 1:
250 sm[s] = l
250 sm[s] = l
251 debug(s, "keep local subrepo revision", l)
251 debug(s, "keep local subrepo revision", l)
252 else:
252 else:
253 wctx.sub(s).get(r, overwrite)
253 wctx.sub(s).get(r, overwrite)
254 sm[s] = r
254 sm[s] = r
255 debug(s, "get remote subrepo revision", r)
255 debug(s, "get remote subrepo revision", r)
256 elif ld == a: # remote removed, local unchanged
256 elif ld == a: # remote removed, local unchanged
257 debug(s, "remote removed, remove")
257 debug(s, "remote removed, remove")
258 wctx.sub(s).remove()
258 wctx.sub(s).remove()
259 elif a == nullstate: # not present in remote or ancestor
259 elif a == nullstate: # not present in remote or ancestor
260 debug(s, "local added, keep")
260 debug(s, "local added, keep")
261 sm[s] = l
261 sm[s] = l
262 continue
262 continue
263 else:
263 else:
264 if repo.ui.promptchoice(
264 if repo.ui.promptchoice(
265 _(' local%(l)s changed subrepository %(s)s'
265 _(' local%(l)s changed subrepository %(s)s'
266 ' which remote%(o)s removed\n'
266 ' which remote%(o)s removed\n'
267 'use (c)hanged version or (d)elete?'
267 'use (c)hanged version or (d)elete?'
268 '$$ &Changed $$ &Delete') % prompts, 0):
268 '$$ &Changed $$ &Delete') % prompts, 0):
269 debug(s, "prompt remove")
269 debug(s, "prompt remove")
270 wctx.sub(s).remove()
270 wctx.sub(s).remove()
271
271
272 for s, r in sorted(s2.items()):
272 for s, r in sorted(s2.items()):
273 prompts = None
273 prompts = None
274 if s in s1:
274 if s in s1:
275 continue
275 continue
276 elif s not in sa:
276 elif s not in sa:
277 debug(s, "remote added, get", r)
277 debug(s, "remote added, get", r)
278 mctx.sub(s).get(r)
278 mctx.sub(s).get(r)
279 sm[s] = r
279 sm[s] = r
280 elif r != sa[s]:
280 elif r != sa[s]:
281 prompts = promptssrc.copy()
281 prompts = promptssrc.copy()
282 prompts['s'] = s
282 prompts['s'] = s
283 if repo.ui.promptchoice(
283 if repo.ui.promptchoice(
284 _(' remote%(o)s changed subrepository %(s)s'
284 _(' remote%(o)s changed subrepository %(s)s'
285 ' which local%(l)s removed\n'
285 ' which local%(l)s removed\n'
286 'use (c)hanged version or (d)elete?'
286 'use (c)hanged version or (d)elete?'
287 '$$ &Changed $$ &Delete') % prompts, 0) == 0:
287 '$$ &Changed $$ &Delete') % prompts, 0) == 0:
288 debug(s, "prompt recreate", r)
288 debug(s, "prompt recreate", r)
289 mctx.sub(s).get(r)
289 mctx.sub(s).get(r)
290 sm[s] = r
290 sm[s] = r
291
291
292 # record merged .hgsubstate
292 # record merged .hgsubstate
293 writestate(repo, sm)
293 writestate(repo, sm)
294 return sm
294 return sm
295
295
296 def _updateprompt(ui, sub, dirty, local, remote):
296 def _updateprompt(ui, sub, dirty, local, remote):
297 if dirty:
297 if dirty:
298 msg = (_(' subrepository sources for %s differ\n'
298 msg = (_(' subrepository sources for %s differ\n'
299 'use (l)ocal source (%s) or (r)emote source (%s)?'
299 'use (l)ocal source (%s) or (r)emote source (%s)?'
300 '$$ &Local $$ &Remote')
300 '$$ &Local $$ &Remote')
301 % (subrelpath(sub), local, remote))
301 % (subrelpath(sub), local, remote))
302 else:
302 else:
303 msg = (_(' subrepository sources for %s differ (in checked out '
303 msg = (_(' subrepository sources for %s differ (in checked out '
304 'version)\n'
304 'version)\n'
305 'use (l)ocal source (%s) or (r)emote source (%s)?'
305 'use (l)ocal source (%s) or (r)emote source (%s)?'
306 '$$ &Local $$ &Remote')
306 '$$ &Local $$ &Remote')
307 % (subrelpath(sub), local, remote))
307 % (subrelpath(sub), local, remote))
308 return ui.promptchoice(msg, 0)
308 return ui.promptchoice(msg, 0)
309
309
310 def reporelpath(repo):
310 def reporelpath(repo):
311 """return path to this (sub)repo as seen from outermost repo"""
311 """return path to this (sub)repo as seen from outermost repo"""
312 parent = repo
312 parent = repo
313 while util.safehasattr(parent, '_subparent'):
313 while util.safehasattr(parent, '_subparent'):
314 parent = parent._subparent
314 parent = parent._subparent
315 return repo.root[len(pathutil.normasprefix(parent.root)):]
315 return repo.root[len(pathutil.normasprefix(parent.root)):]
316
316
317 def subrelpath(sub):
317 def subrelpath(sub):
318 """return path to this subrepo as seen from outermost repo"""
318 """return path to this subrepo as seen from outermost repo"""
319 return sub._relpath
319 return sub._relpath
320
320
321 def _abssource(repo, push=False, abort=True):
321 def _abssource(repo, push=False, abort=True):
322 """return pull/push path of repo - either based on parent repo .hgsub info
322 """return pull/push path of repo - either based on parent repo .hgsub info
323 or on the top repo config. Abort or return None if no source found."""
323 or on the top repo config. Abort or return None if no source found."""
324 if util.safehasattr(repo, '_subparent'):
324 if util.safehasattr(repo, '_subparent'):
325 source = util.url(repo._subsource)
325 source = util.url(repo._subsource)
326 if source.isabs():
326 if source.isabs():
327 return str(source)
327 return str(source)
328 source.path = posixpath.normpath(source.path)
328 source.path = posixpath.normpath(source.path)
329 parent = _abssource(repo._subparent, push, abort=False)
329 parent = _abssource(repo._subparent, push, abort=False)
330 if parent:
330 if parent:
331 parent = util.url(util.pconvert(parent))
331 parent = util.url(util.pconvert(parent))
332 parent.path = posixpath.join(parent.path or '', source.path)
332 parent.path = posixpath.join(parent.path or '', source.path)
333 parent.path = posixpath.normpath(parent.path)
333 parent.path = posixpath.normpath(parent.path)
334 return str(parent)
334 return str(parent)
335 else: # recursion reached top repo
335 else: # recursion reached top repo
336 if util.safehasattr(repo, '_subtoppath'):
336 if util.safehasattr(repo, '_subtoppath'):
337 return repo._subtoppath
337 return repo._subtoppath
338 if push and repo.ui.config('paths', 'default-push'):
338 if push and repo.ui.config('paths', 'default-push'):
339 return repo.ui.config('paths', 'default-push')
339 return repo.ui.config('paths', 'default-push')
340 if repo.ui.config('paths', 'default'):
340 if repo.ui.config('paths', 'default'):
341 return repo.ui.config('paths', 'default')
341 return repo.ui.config('paths', 'default')
342 if repo.shared():
342 if repo.shared():
343 # chop off the .hg component to get the default path form
343 # chop off the .hg component to get the default path form
344 return os.path.dirname(repo.sharedpath)
344 return os.path.dirname(repo.sharedpath)
345 if abort:
345 if abort:
346 raise error.Abort(_("default path for subrepository not found"))
346 raise error.Abort(_("default path for subrepository not found"))
347
347
348 def _sanitize(ui, vfs, ignore):
348 def _sanitize(ui, vfs, ignore):
349 for dirname, dirs, names in vfs.walk():
349 for dirname, dirs, names in vfs.walk():
350 for i, d in enumerate(dirs):
350 for i, d in enumerate(dirs):
351 if d.lower() == ignore:
351 if d.lower() == ignore:
352 del dirs[i]
352 del dirs[i]
353 break
353 break
354 if vfs.basename(dirname).lower() != '.hg':
354 if vfs.basename(dirname).lower() != '.hg':
355 continue
355 continue
356 for f in names:
356 for f in names:
357 if f.lower() == 'hgrc':
357 if f.lower() == 'hgrc':
358 ui.warn(_("warning: removing potentially hostile 'hgrc' "
358 ui.warn(_("warning: removing potentially hostile 'hgrc' "
359 "in '%s'\n") % vfs.join(dirname))
359 "in '%s'\n") % vfs.join(dirname))
360 vfs.unlink(vfs.reljoin(dirname, f))
360 vfs.unlink(vfs.reljoin(dirname, f))
361
361
362 def _auditsubrepopath(repo, path):
362 def _auditsubrepopath(repo, path):
363 # auditor doesn't check if the path itself is a symlink
363 # auditor doesn't check if the path itself is a symlink
364 pathutil.pathauditor(repo.root)(path)
364 pathutil.pathauditor(repo.root)(path)
365 if repo.wvfs.islink(path):
365 if repo.wvfs.islink(path):
366 raise error.Abort(_("subrepo '%s' traverses symbolic link") % path)
366 raise error.Abort(_("subrepo '%s' traverses symbolic link") % path)
367
367
368 SUBREPO_ALLOWED_DEFAULTS = {
368 SUBREPO_ALLOWED_DEFAULTS = {
369 'hg': True,
369 'hg': True,
370 'git': False,
370 'git': False,
371 'svn': False,
371 'svn': False,
372 }
372 }
373
373
374 def _checktype(ui, kind):
374 def _checktype(ui, kind):
375 # subrepos.allowed is a master kill switch. If disabled, subrepos are
375 # subrepos.allowed is a master kill switch. If disabled, subrepos are
376 # disabled period.
376 # disabled period.
377 if not ui.configbool('subrepos', 'allowed', True):
377 if not ui.configbool('subrepos', 'allowed', True):
378 raise error.Abort(_('subrepos not enabled'),
378 raise error.Abort(_('subrepos not enabled'),
379 hint=_("see 'hg help config.subrepos' for details"))
379 hint=_("see 'hg help config.subrepos' for details"))
380
380
381 default = SUBREPO_ALLOWED_DEFAULTS.get(kind, False)
381 default = SUBREPO_ALLOWED_DEFAULTS.get(kind, False)
382 if not ui.configbool('subrepos', '%s:allowed' % kind, default):
382 if not ui.configbool('subrepos', '%s:allowed' % kind, default):
383 raise error.Abort(_('%s subrepos not allowed') % kind,
383 raise error.Abort(_('%s subrepos not allowed') % kind,
384 hint=_("see 'hg help config.subrepos' for details"))
384 hint=_("see 'hg help config.subrepos' for details"))
385
385
386 if kind not in types:
386 if kind not in types:
387 raise error.Abort(_('unknown subrepo type %s') % kind)
387 raise error.Abort(_('unknown subrepo type %s') % kind)
388
388
389 def subrepo(ctx, path, allowwdir=False, allowcreate=True):
389 def subrepo(ctx, path, allowwdir=False, allowcreate=True):
390 """return instance of the right subrepo class for subrepo in path"""
390 """return instance of the right subrepo class for subrepo in path"""
391 # subrepo inherently violates our import layering rules
391 # subrepo inherently violates our import layering rules
392 # because it wants to make repo objects from deep inside the stack
392 # because it wants to make repo objects from deep inside the stack
393 # so we manually delay the circular imports to not break
393 # so we manually delay the circular imports to not break
394 # scripts that don't use our demand-loading
394 # scripts that don't use our demand-loading
395 global hg
395 global hg
396 from . import hg as h
396 from . import hg as h
397 hg = h
397 hg = h
398
398
399 repo = ctx.repo()
399 repo = ctx.repo()
400 _auditsubrepopath(repo, path)
400 _auditsubrepopath(repo, path)
401 state = ctx.substate[path]
401 state = ctx.substate[path]
402 _checktype(repo.ui, state[2])
402 _checktype(repo.ui, state[2])
403 if allowwdir:
403 if allowwdir:
404 state = (state[0], ctx.subrev(path), state[2])
404 state = (state[0], ctx.subrev(path), state[2])
405 return types[state[2]](ctx, path, state[:2], allowcreate)
405 return types[state[2]](ctx, path, state[:2], allowcreate)
406
406
407 def nullsubrepo(ctx, path, pctx):
407 def nullsubrepo(ctx, path, pctx):
408 """return an empty subrepo in pctx for the extant subrepo in ctx"""
408 """return an empty subrepo in pctx for the extant subrepo in ctx"""
409 # subrepo inherently violates our import layering rules
409 # subrepo inherently violates our import layering rules
410 # because it wants to make repo objects from deep inside the stack
410 # because it wants to make repo objects from deep inside the stack
411 # so we manually delay the circular imports to not break
411 # so we manually delay the circular imports to not break
412 # scripts that don't use our demand-loading
412 # scripts that don't use our demand-loading
413 global hg
413 global hg
414 from . import hg as h
414 from . import hg as h
415 hg = h
415 hg = h
416
416
417 repo = ctx.repo()
417 repo = ctx.repo()
418 _auditsubrepopath(repo, path)
418 _auditsubrepopath(repo, path)
419 state = ctx.substate[path]
419 state = ctx.substate[path]
420 _checktype(repo.ui, state[2])
420 _checktype(repo.ui, state[2])
421 subrev = ''
421 subrev = ''
422 if state[2] == 'hg':
422 if state[2] == 'hg':
423 subrev = "0" * 40
423 subrev = "0" * 40
424 return types[state[2]](pctx, path, (state[0], subrev), True)
424 return types[state[2]](pctx, path, (state[0], subrev), True)
425
425
426 def newcommitphase(ui, ctx):
426 def newcommitphase(ui, ctx):
427 commitphase = phases.newcommitphase(ui)
427 commitphase = phases.newcommitphase(ui)
428 substate = getattr(ctx, "substate", None)
428 substate = getattr(ctx, "substate", None)
429 if not substate:
429 if not substate:
430 return commitphase
430 return commitphase
431 check = ui.config('phases', 'checksubrepos')
431 check = ui.config('phases', 'checksubrepos')
432 if check not in ('ignore', 'follow', 'abort'):
432 if check not in ('ignore', 'follow', 'abort'):
433 raise error.Abort(_('invalid phases.checksubrepos configuration: %s')
433 raise error.Abort(_('invalid phases.checksubrepos configuration: %s')
434 % (check))
434 % (check))
435 if check == 'ignore':
435 if check == 'ignore':
436 return commitphase
436 return commitphase
437 maxphase = phases.public
437 maxphase = phases.public
438 maxsub = None
438 maxsub = None
439 for s in sorted(substate):
439 for s in sorted(substate):
440 sub = ctx.sub(s)
440 sub = ctx.sub(s)
441 subphase = sub.phase(substate[s][1])
441 subphase = sub.phase(substate[s][1])
442 if maxphase < subphase:
442 if maxphase < subphase:
443 maxphase = subphase
443 maxphase = subphase
444 maxsub = s
444 maxsub = s
445 if commitphase < maxphase:
445 if commitphase < maxphase:
446 if check == 'abort':
446 if check == 'abort':
447 raise error.Abort(_("can't commit in %s phase"
447 raise error.Abort(_("can't commit in %s phase"
448 " conflicting %s from subrepository %s") %
448 " conflicting %s from subrepository %s") %
449 (phases.phasenames[commitphase],
449 (phases.phasenames[commitphase],
450 phases.phasenames[maxphase], maxsub))
450 phases.phasenames[maxphase], maxsub))
451 ui.warn(_("warning: changes are committed in"
451 ui.warn(_("warning: changes are committed in"
452 " %s phase from subrepository %s\n") %
452 " %s phase from subrepository %s\n") %
453 (phases.phasenames[maxphase], maxsub))
453 (phases.phasenames[maxphase], maxsub))
454 return maxphase
454 return maxphase
455 return commitphase
455 return commitphase
456
456
457 # subrepo classes need to implement the following abstract class:
457 # subrepo classes need to implement the following abstract class:
458
458
459 class abstractsubrepo(object):
459 class abstractsubrepo(object):
460
460
461 def __init__(self, ctx, path):
461 def __init__(self, ctx, path):
462 """Initialize abstractsubrepo part
462 """Initialize abstractsubrepo part
463
463
464 ``ctx`` is the context referring this subrepository in the
464 ``ctx`` is the context referring this subrepository in the
465 parent repository.
465 parent repository.
466
466
467 ``path`` is the path to this subrepository as seen from
467 ``path`` is the path to this subrepository as seen from
468 innermost repository.
468 innermost repository.
469 """
469 """
470 self.ui = ctx.repo().ui
470 self.ui = ctx.repo().ui
471 self._ctx = ctx
471 self._ctx = ctx
472 self._path = path
472 self._path = path
473
473
474 def addwebdirpath(self, serverpath, webconf):
474 def addwebdirpath(self, serverpath, webconf):
475 """Add the hgwebdir entries for this subrepo, and any of its subrepos.
475 """Add the hgwebdir entries for this subrepo, and any of its subrepos.
476
476
477 ``serverpath`` is the path component of the URL for this repo.
477 ``serverpath`` is the path component of the URL for this repo.
478
478
479 ``webconf`` is the dictionary of hgwebdir entries.
479 ``webconf`` is the dictionary of hgwebdir entries.
480 """
480 """
481 pass
481 pass
482
482
483 def storeclean(self, path):
483 def storeclean(self, path):
484 """
484 """
485 returns true if the repository has not changed since it was last
485 returns true if the repository has not changed since it was last
486 cloned from or pushed to a given repository.
486 cloned from or pushed to a given repository.
487 """
487 """
488 return False
488 return False
489
489
490 def dirty(self, ignoreupdate=False, missing=False):
490 def dirty(self, ignoreupdate=False, missing=False):
491 """returns true if the dirstate of the subrepo is dirty or does not
491 """returns true if the dirstate of the subrepo is dirty or does not
492 match current stored state. If ignoreupdate is true, only check
492 match current stored state. If ignoreupdate is true, only check
493 whether the subrepo has uncommitted changes in its dirstate. If missing
493 whether the subrepo has uncommitted changes in its dirstate. If missing
494 is true, check for deleted files.
494 is true, check for deleted files.
495 """
495 """
496 raise NotImplementedError
496 raise NotImplementedError
497
497
498 def dirtyreason(self, ignoreupdate=False, missing=False):
498 def dirtyreason(self, ignoreupdate=False, missing=False):
499 """return reason string if it is ``dirty()``
499 """return reason string if it is ``dirty()``
500
500
501 Returned string should have enough information for the message
501 Returned string should have enough information for the message
502 of exception.
502 of exception.
503
503
504 This returns None, otherwise.
504 This returns None, otherwise.
505 """
505 """
506 if self.dirty(ignoreupdate=ignoreupdate, missing=missing):
506 if self.dirty(ignoreupdate=ignoreupdate, missing=missing):
507 return _('uncommitted changes in subrepository "%s"'
507 return _('uncommitted changes in subrepository "%s"'
508 ) % subrelpath(self)
508 ) % subrelpath(self)
509
509
510 def bailifchanged(self, ignoreupdate=False, hint=None):
510 def bailifchanged(self, ignoreupdate=False, hint=None):
511 """raise Abort if subrepository is ``dirty()``
511 """raise Abort if subrepository is ``dirty()``
512 """
512 """
513 dirtyreason = self.dirtyreason(ignoreupdate=ignoreupdate,
513 dirtyreason = self.dirtyreason(ignoreupdate=ignoreupdate,
514 missing=True)
514 missing=True)
515 if dirtyreason:
515 if dirtyreason:
516 raise error.Abort(dirtyreason, hint=hint)
516 raise error.Abort(dirtyreason, hint=hint)
517
517
518 def basestate(self):
518 def basestate(self):
519 """current working directory base state, disregarding .hgsubstate
519 """current working directory base state, disregarding .hgsubstate
520 state and working directory modifications"""
520 state and working directory modifications"""
521 raise NotImplementedError
521 raise NotImplementedError
522
522
523 def checknested(self, path):
523 def checknested(self, path):
524 """check if path is a subrepository within this repository"""
524 """check if path is a subrepository within this repository"""
525 return False
525 return False
526
526
527 def commit(self, text, user, date):
527 def commit(self, text, user, date):
528 """commit the current changes to the subrepo with the given
528 """commit the current changes to the subrepo with the given
529 log message. Use given user and date if possible. Return the
529 log message. Use given user and date if possible. Return the
530 new state of the subrepo.
530 new state of the subrepo.
531 """
531 """
532 raise NotImplementedError
532 raise NotImplementedError
533
533
534 def phase(self, state):
534 def phase(self, state):
535 """returns phase of specified state in the subrepository.
535 """returns phase of specified state in the subrepository.
536 """
536 """
537 return phases.public
537 return phases.public
538
538
539 def remove(self):
539 def remove(self):
540 """remove the subrepo
540 """remove the subrepo
541
541
542 (should verify the dirstate is not dirty first)
542 (should verify the dirstate is not dirty first)
543 """
543 """
544 raise NotImplementedError
544 raise NotImplementedError
545
545
546 def get(self, state, overwrite=False):
546 def get(self, state, overwrite=False):
547 """run whatever commands are needed to put the subrepo into
547 """run whatever commands are needed to put the subrepo into
548 this state
548 this state
549 """
549 """
550 raise NotImplementedError
550 raise NotImplementedError
551
551
552 def merge(self, state):
552 def merge(self, state):
553 """merge currently-saved state with the new state."""
553 """merge currently-saved state with the new state."""
554 raise NotImplementedError
554 raise NotImplementedError
555
555
556 def push(self, opts):
556 def push(self, opts):
557 """perform whatever action is analogous to 'hg push'
557 """perform whatever action is analogous to 'hg push'
558
558
559 This may be a no-op on some systems.
559 This may be a no-op on some systems.
560 """
560 """
561 raise NotImplementedError
561 raise NotImplementedError
562
562
563 def add(self, ui, match, prefix, explicitonly, **opts):
563 def add(self, ui, match, prefix, explicitonly, **opts):
564 return []
564 return []
565
565
566 def addremove(self, matcher, prefix, opts, dry_run, similarity):
566 def addremove(self, matcher, prefix, opts, dry_run, similarity):
567 self.ui.warn("%s: %s" % (prefix, _("addremove is not supported")))
567 self.ui.warn("%s: %s" % (prefix, _("addremove is not supported")))
568 return 1
568 return 1
569
569
570 def cat(self, match, fm, fntemplate, prefix, **opts):
570 def cat(self, match, fm, fntemplate, prefix, **opts):
571 return 1
571 return 1
572
572
573 def status(self, rev2, **opts):
573 def status(self, rev2, **opts):
574 return scmutil.status([], [], [], [], [], [], [])
574 return scmutil.status([], [], [], [], [], [], [])
575
575
576 def diff(self, ui, diffopts, node2, match, prefix, **opts):
576 def diff(self, ui, diffopts, node2, match, prefix, **opts):
577 pass
577 pass
578
578
579 def outgoing(self, ui, dest, opts):
579 def outgoing(self, ui, dest, opts):
580 return 1
580 return 1
581
581
582 def incoming(self, ui, source, opts):
582 def incoming(self, ui, source, opts):
583 return 1
583 return 1
584
584
585 def files(self):
585 def files(self):
586 """return filename iterator"""
586 """return filename iterator"""
587 raise NotImplementedError
587 raise NotImplementedError
588
588
589 def filedata(self, name, decode):
589 def filedata(self, name, decode):
590 """return file data, optionally passed through repo decoders"""
590 """return file data, optionally passed through repo decoders"""
591 raise NotImplementedError
591 raise NotImplementedError
592
592
593 def fileflags(self, name):
593 def fileflags(self, name):
594 """return file flags"""
594 """return file flags"""
595 return ''
595 return ''
596
596
597 def getfileset(self, expr):
597 def getfileset(self, expr):
598 """Resolve the fileset expression for this repo"""
598 """Resolve the fileset expression for this repo"""
599 return set()
599 return set()
600
600
601 def printfiles(self, ui, m, fm, fmt, subrepos):
601 def printfiles(self, ui, m, fm, fmt, subrepos):
602 """handle the files command for this subrepo"""
602 """handle the files command for this subrepo"""
603 return 1
603 return 1
604
604
605 def archive(self, archiver, prefix, match=None, decode=True):
605 def archive(self, archiver, prefix, match=None, decode=True):
606 if match is not None:
606 if match is not None:
607 files = [f for f in self.files() if match(f)]
607 files = [f for f in self.files() if match(f)]
608 else:
608 else:
609 files = self.files()
609 files = self.files()
610 total = len(files)
610 total = len(files)
611 relpath = subrelpath(self)
611 relpath = subrelpath(self)
612 self.ui.progress(_('archiving (%s)') % relpath, 0,
612 self.ui.progress(_('archiving (%s)') % relpath, 0,
613 unit=_('files'), total=total)
613 unit=_('files'), total=total)
614 for i, name in enumerate(files):
614 for i, name in enumerate(files):
615 flags = self.fileflags(name)
615 flags = self.fileflags(name)
616 mode = 'x' in flags and 0o755 or 0o644
616 mode = 'x' in flags and 0o755 or 0o644
617 symlink = 'l' in flags
617 symlink = 'l' in flags
618 archiver.addfile(prefix + self._path + '/' + name,
618 archiver.addfile(prefix + self._path + '/' + name,
619 mode, symlink, self.filedata(name, decode))
619 mode, symlink, self.filedata(name, decode))
620 self.ui.progress(_('archiving (%s)') % relpath, i + 1,
620 self.ui.progress(_('archiving (%s)') % relpath, i + 1,
621 unit=_('files'), total=total)
621 unit=_('files'), total=total)
622 self.ui.progress(_('archiving (%s)') % relpath, None)
622 self.ui.progress(_('archiving (%s)') % relpath, None)
623 return total
623 return total
624
624
625 def walk(self, match):
625 def walk(self, match):
626 '''
626 '''
627 walk recursively through the directory tree, finding all files
627 walk recursively through the directory tree, finding all files
628 matched by the match function
628 matched by the match function
629 '''
629 '''
630
630
631 def forget(self, match, prefix):
631 def forget(self, match, prefix):
632 return ([], [])
632 return ([], [])
633
633
634 def removefiles(self, matcher, prefix, after, force, subrepos, warnings):
634 def removefiles(self, matcher, prefix, after, force, subrepos, warnings):
635 """remove the matched files from the subrepository and the filesystem,
635 """remove the matched files from the subrepository and the filesystem,
636 possibly by force and/or after the file has been removed from the
636 possibly by force and/or after the file has been removed from the
637 filesystem. Return 0 on success, 1 on any warning.
637 filesystem. Return 0 on success, 1 on any warning.
638 """
638 """
639 warnings.append(_("warning: removefiles not implemented (%s)")
639 warnings.append(_("warning: removefiles not implemented (%s)")
640 % self._path)
640 % self._path)
641 return 1
641 return 1
642
642
643 def revert(self, substate, *pats, **opts):
643 def revert(self, substate, *pats, **opts):
644 self.ui.warn(_('%s: reverting %s subrepos is unsupported\n') \
644 self.ui.warn(_('%s: reverting %s subrepos is unsupported\n') \
645 % (substate[0], substate[2]))
645 % (substate[0], substate[2]))
646 return []
646 return []
647
647
648 def shortid(self, revid):
648 def shortid(self, revid):
649 return revid
649 return revid
650
650
651 def unshare(self):
651 def unshare(self):
652 '''
652 '''
653 convert this repository from shared to normal storage.
653 convert this repository from shared to normal storage.
654 '''
654 '''
655
655
656 def verify(self):
656 def verify(self):
657 '''verify the integrity of the repository. Return 0 on success or
657 '''verify the integrity of the repository. Return 0 on success or
658 warning, 1 on any error.
658 warning, 1 on any error.
659 '''
659 '''
660 return 0
660 return 0
661
661
662 @propertycache
662 @propertycache
663 def wvfs(self):
663 def wvfs(self):
664 """return vfs to access the working directory of this subrepository
664 """return vfs to access the working directory of this subrepository
665 """
665 """
666 return vfsmod.vfs(self._ctx.repo().wvfs.join(self._path))
666 return vfsmod.vfs(self._ctx.repo().wvfs.join(self._path))
667
667
668 @propertycache
668 @propertycache
669 def _relpath(self):
669 def _relpath(self):
670 """return path to this subrepository as seen from outermost repository
670 """return path to this subrepository as seen from outermost repository
671 """
671 """
672 return self.wvfs.reljoin(reporelpath(self._ctx.repo()), self._path)
672 return self.wvfs.reljoin(reporelpath(self._ctx.repo()), self._path)
673
673
674 class hgsubrepo(abstractsubrepo):
674 class hgsubrepo(abstractsubrepo):
675 def __init__(self, ctx, path, state, allowcreate):
675 def __init__(self, ctx, path, state, allowcreate):
676 super(hgsubrepo, self).__init__(ctx, path)
676 super(hgsubrepo, self).__init__(ctx, path)
677 self._state = state
677 self._state = state
678 r = ctx.repo()
678 r = ctx.repo()
679 root = r.wjoin(path)
679 root = r.wjoin(path)
680 create = allowcreate and not r.wvfs.exists('%s/.hg' % path)
680 create = allowcreate and not r.wvfs.exists('%s/.hg' % path)
681 self._repo = hg.repository(r.baseui, root, create=create)
681 self._repo = hg.repository(r.baseui, root, create=create)
682
682
683 # Propagate the parent's --hidden option
683 # Propagate the parent's --hidden option
684 if r is r.unfiltered():
684 if r is r.unfiltered():
685 self._repo = self._repo.unfiltered()
685 self._repo = self._repo.unfiltered()
686
686
687 self.ui = self._repo.ui
687 self.ui = self._repo.ui
688 for s, k in [('ui', 'commitsubrepos')]:
688 for s, k in [('ui', 'commitsubrepos')]:
689 v = r.ui.config(s, k)
689 v = r.ui.config(s, k)
690 if v:
690 if v:
691 self.ui.setconfig(s, k, v, 'subrepo')
691 self.ui.setconfig(s, k, v, 'subrepo')
692 # internal config: ui._usedassubrepo
692 # internal config: ui._usedassubrepo
693 self.ui.setconfig('ui', '_usedassubrepo', 'True', 'subrepo')
693 self.ui.setconfig('ui', '_usedassubrepo', 'True', 'subrepo')
694 self._initrepo(r, state[0], create)
694 self._initrepo(r, state[0], create)
695
695
696 @annotatesubrepoerror
696 @annotatesubrepoerror
697 def addwebdirpath(self, serverpath, webconf):
697 def addwebdirpath(self, serverpath, webconf):
698 cmdutil.addwebdirpath(self._repo, subrelpath(self), webconf)
698 cmdutil.addwebdirpath(self._repo, subrelpath(self), webconf)
699
699
700 def storeclean(self, path):
700 def storeclean(self, path):
701 with self._repo.lock():
701 with self._repo.lock():
702 return self._storeclean(path)
702 return self._storeclean(path)
703
703
704 def _storeclean(self, path):
704 def _storeclean(self, path):
705 clean = True
705 clean = True
706 itercache = self._calcstorehash(path)
706 itercache = self._calcstorehash(path)
707 for filehash in self._readstorehashcache(path):
707 for filehash in self._readstorehashcache(path):
708 if filehash != next(itercache, None):
708 if filehash != next(itercache, None):
709 clean = False
709 clean = False
710 break
710 break
711 if clean:
711 if clean:
712 # if not empty:
712 # if not empty:
713 # the cached and current pull states have a different size
713 # the cached and current pull states have a different size
714 clean = next(itercache, None) is None
714 clean = next(itercache, None) is None
715 return clean
715 return clean
716
716
717 def _calcstorehash(self, remotepath):
717 def _calcstorehash(self, remotepath):
718 '''calculate a unique "store hash"
718 '''calculate a unique "store hash"
719
719
720 This method is used to to detect when there are changes that may
720 This method is used to to detect when there are changes that may
721 require a push to a given remote path.'''
721 require a push to a given remote path.'''
722 # sort the files that will be hashed in increasing (likely) file size
722 # sort the files that will be hashed in increasing (likely) file size
723 filelist = ('bookmarks', 'store/phaseroots', 'store/00changelog.i')
723 filelist = ('bookmarks', 'store/phaseroots', 'store/00changelog.i')
724 yield '# %s\n' % _expandedabspath(remotepath)
724 yield '# %s\n' % _expandedabspath(remotepath)
725 vfs = self._repo.vfs
725 vfs = self._repo.vfs
726 for relname in filelist:
726 for relname in filelist:
727 filehash = hashlib.sha1(vfs.tryread(relname)).hexdigest()
727 filehash = hashlib.sha1(vfs.tryread(relname)).hexdigest()
728 yield '%s = %s\n' % (relname, filehash)
728 yield '%s = %s\n' % (relname, filehash)
729
729
730 @propertycache
730 @propertycache
731 def _cachestorehashvfs(self):
731 def _cachestorehashvfs(self):
732 return vfsmod.vfs(self._repo.vfs.join('cache/storehash'))
732 return vfsmod.vfs(self._repo.vfs.join('cache/storehash'))
733
733
734 def _readstorehashcache(self, remotepath):
734 def _readstorehashcache(self, remotepath):
735 '''read the store hash cache for a given remote repository'''
735 '''read the store hash cache for a given remote repository'''
736 cachefile = _getstorehashcachename(remotepath)
736 cachefile = _getstorehashcachename(remotepath)
737 return self._cachestorehashvfs.tryreadlines(cachefile, 'r')
737 return self._cachestorehashvfs.tryreadlines(cachefile, 'r')
738
738
739 def _cachestorehash(self, remotepath):
739 def _cachestorehash(self, remotepath):
740 '''cache the current store hash
740 '''cache the current store hash
741
741
742 Each remote repo requires its own store hash cache, because a subrepo
742 Each remote repo requires its own store hash cache, because a subrepo
743 store may be "clean" versus a given remote repo, but not versus another
743 store may be "clean" versus a given remote repo, but not versus another
744 '''
744 '''
745 cachefile = _getstorehashcachename(remotepath)
745 cachefile = _getstorehashcachename(remotepath)
746 with self._repo.lock():
746 with self._repo.lock():
747 storehash = list(self._calcstorehash(remotepath))
747 storehash = list(self._calcstorehash(remotepath))
748 vfs = self._cachestorehashvfs
748 vfs = self._cachestorehashvfs
749 vfs.writelines(cachefile, storehash, mode='w', notindexed=True)
749 vfs.writelines(cachefile, storehash, mode='w', notindexed=True)
750
750
751 def _getctx(self):
751 def _getctx(self):
752 '''fetch the context for this subrepo revision, possibly a workingctx
752 '''fetch the context for this subrepo revision, possibly a workingctx
753 '''
753 '''
754 if self._ctx.rev() is None:
754 if self._ctx.rev() is None:
755 return self._repo[None] # workingctx if parent is workingctx
755 return self._repo[None] # workingctx if parent is workingctx
756 else:
756 else:
757 rev = self._state[1]
757 rev = self._state[1]
758 return self._repo[rev]
758 return self._repo[rev]
759
759
760 @annotatesubrepoerror
760 @annotatesubrepoerror
761 def _initrepo(self, parentrepo, source, create):
761 def _initrepo(self, parentrepo, source, create):
762 self._repo._subparent = parentrepo
762 self._repo._subparent = parentrepo
763 self._repo._subsource = source
763 self._repo._subsource = source
764
764
765 if create:
765 if create:
766 lines = ['[paths]\n']
766 lines = ['[paths]\n']
767
767
768 def addpathconfig(key, value):
768 def addpathconfig(key, value):
769 if value:
769 if value:
770 lines.append('%s = %s\n' % (key, value))
770 lines.append('%s = %s\n' % (key, value))
771 self.ui.setconfig('paths', key, value, 'subrepo')
771 self.ui.setconfig('paths', key, value, 'subrepo')
772
772
773 defpath = _abssource(self._repo, abort=False)
773 defpath = _abssource(self._repo, abort=False)
774 defpushpath = _abssource(self._repo, True, abort=False)
774 defpushpath = _abssource(self._repo, True, abort=False)
775 addpathconfig('default', defpath)
775 addpathconfig('default', defpath)
776 if defpath != defpushpath:
776 if defpath != defpushpath:
777 addpathconfig('default-push', defpushpath)
777 addpathconfig('default-push', defpushpath)
778
778
779 fp = self._repo.vfs("hgrc", "w", text=True)
779 fp = self._repo.vfs("hgrc", "w", text=True)
780 try:
780 try:
781 fp.write(''.join(lines))
781 fp.write(''.join(lines))
782 finally:
782 finally:
783 fp.close()
783 fp.close()
784
784
785 @annotatesubrepoerror
785 @annotatesubrepoerror
786 def add(self, ui, match, prefix, explicitonly, **opts):
786 def add(self, ui, match, prefix, explicitonly, **opts):
787 return cmdutil.add(ui, self._repo, match,
787 return cmdutil.add(ui, self._repo, match,
788 self.wvfs.reljoin(prefix, self._path),
788 self.wvfs.reljoin(prefix, self._path),
789 explicitonly, **opts)
789 explicitonly, **opts)
790
790
791 @annotatesubrepoerror
791 @annotatesubrepoerror
792 def addremove(self, m, prefix, opts, dry_run, similarity):
792 def addremove(self, m, prefix, opts, dry_run, similarity):
793 # In the same way as sub directories are processed, once in a subrepo,
793 # In the same way as sub directories are processed, once in a subrepo,
794 # always entry any of its subrepos. Don't corrupt the options that will
794 # always entry any of its subrepos. Don't corrupt the options that will
795 # be used to process sibling subrepos however.
795 # be used to process sibling subrepos however.
796 opts = copy.copy(opts)
796 opts = copy.copy(opts)
797 opts['subrepos'] = True
797 opts['subrepos'] = True
798 return scmutil.addremove(self._repo, m,
798 return scmutil.addremove(self._repo, m,
799 self.wvfs.reljoin(prefix, self._path), opts,
799 self.wvfs.reljoin(prefix, self._path), opts,
800 dry_run, similarity)
800 dry_run, similarity)
801
801
802 @annotatesubrepoerror
802 @annotatesubrepoerror
803 def cat(self, match, fm, fntemplate, prefix, **opts):
803 def cat(self, match, fm, fntemplate, prefix, **opts):
804 rev = self._state[1]
804 rev = self._state[1]
805 ctx = self._repo[rev]
805 ctx = self._repo[rev]
806 return cmdutil.cat(self.ui, self._repo, ctx, match, fm, fntemplate,
806 return cmdutil.cat(self.ui, self._repo, ctx, match, fm, fntemplate,
807 prefix, **opts)
807 prefix, **opts)
808
808
809 @annotatesubrepoerror
809 @annotatesubrepoerror
810 def status(self, rev2, **opts):
810 def status(self, rev2, **opts):
811 try:
811 try:
812 rev1 = self._state[1]
812 rev1 = self._state[1]
813 ctx1 = self._repo[rev1]
813 ctx1 = self._repo[rev1]
814 ctx2 = self._repo[rev2]
814 ctx2 = self._repo[rev2]
815 return self._repo.status(ctx1, ctx2, **opts)
815 return self._repo.status(ctx1, ctx2, **opts)
816 except error.RepoLookupError as inst:
816 except error.RepoLookupError as inst:
817 self.ui.warn(_('warning: error "%s" in subrepository "%s"\n')
817 self.ui.warn(_('warning: error "%s" in subrepository "%s"\n')
818 % (inst, subrelpath(self)))
818 % (inst, subrelpath(self)))
819 return scmutil.status([], [], [], [], [], [], [])
819 return scmutil.status([], [], [], [], [], [], [])
820
820
821 @annotatesubrepoerror
821 @annotatesubrepoerror
822 def diff(self, ui, diffopts, node2, match, prefix, **opts):
822 def diff(self, ui, diffopts, node2, match, prefix, **opts):
823 try:
823 try:
824 node1 = node.bin(self._state[1])
824 node1 = node.bin(self._state[1])
825 # We currently expect node2 to come from substate and be
825 # We currently expect node2 to come from substate and be
826 # in hex format
826 # in hex format
827 if node2 is not None:
827 if node2 is not None:
828 node2 = node.bin(node2)
828 node2 = node.bin(node2)
829 cmdutil.diffordiffstat(ui, self._repo, diffopts,
829 cmdutil.diffordiffstat(ui, self._repo, diffopts,
830 node1, node2, match,
830 node1, node2, match,
831 prefix=posixpath.join(prefix, self._path),
831 prefix=posixpath.join(prefix, self._path),
832 listsubrepos=True, **opts)
832 listsubrepos=True, **opts)
833 except error.RepoLookupError as inst:
833 except error.RepoLookupError as inst:
834 self.ui.warn(_('warning: error "%s" in subrepository "%s"\n')
834 self.ui.warn(_('warning: error "%s" in subrepository "%s"\n')
835 % (inst, subrelpath(self)))
835 % (inst, subrelpath(self)))
836
836
837 @annotatesubrepoerror
837 @annotatesubrepoerror
838 def archive(self, archiver, prefix, match=None, decode=True):
838 def archive(self, archiver, prefix, match=None, decode=True):
839 self._get(self._state + ('hg',))
839 self._get(self._state + ('hg',))
840 total = abstractsubrepo.archive(self, archiver, prefix, match)
840 total = abstractsubrepo.archive(self, archiver, prefix, match)
841 rev = self._state[1]
841 rev = self._state[1]
842 ctx = self._repo[rev]
842 ctx = self._repo[rev]
843 for subpath in ctx.substate:
843 for subpath in ctx.substate:
844 s = subrepo(ctx, subpath, True)
844 s = subrepo(ctx, subpath, True)
845 submatch = matchmod.subdirmatcher(subpath, match)
845 submatch = matchmod.subdirmatcher(subpath, match)
846 total += s.archive(archiver, prefix + self._path + '/', submatch,
846 total += s.archive(archiver, prefix + self._path + '/', submatch,
847 decode)
847 decode)
848 return total
848 return total
849
849
850 @annotatesubrepoerror
850 @annotatesubrepoerror
851 def dirty(self, ignoreupdate=False, missing=False):
851 def dirty(self, ignoreupdate=False, missing=False):
852 r = self._state[1]
852 r = self._state[1]
853 if r == '' and not ignoreupdate: # no state recorded
853 if r == '' and not ignoreupdate: # no state recorded
854 return True
854 return True
855 w = self._repo[None]
855 w = self._repo[None]
856 if r != w.p1().hex() and not ignoreupdate:
856 if r != w.p1().hex() and not ignoreupdate:
857 # different version checked out
857 # different version checked out
858 return True
858 return True
859 return w.dirty(missing=missing) # working directory changed
859 return w.dirty(missing=missing) # working directory changed
860
860
861 def basestate(self):
861 def basestate(self):
862 return self._repo['.'].hex()
862 return self._repo['.'].hex()
863
863
864 def checknested(self, path):
864 def checknested(self, path):
865 return self._repo._checknested(self._repo.wjoin(path))
865 return self._repo._checknested(self._repo.wjoin(path))
866
866
867 @annotatesubrepoerror
867 @annotatesubrepoerror
868 def commit(self, text, user, date):
868 def commit(self, text, user, date):
869 # don't bother committing in the subrepo if it's only been
869 # don't bother committing in the subrepo if it's only been
870 # updated
870 # updated
871 if not self.dirty(True):
871 if not self.dirty(True):
872 return self._repo['.'].hex()
872 return self._repo['.'].hex()
873 self.ui.debug("committing subrepo %s\n" % subrelpath(self))
873 self.ui.debug("committing subrepo %s\n" % subrelpath(self))
874 n = self._repo.commit(text, user, date)
874 n = self._repo.commit(text, user, date)
875 if not n:
875 if not n:
876 return self._repo['.'].hex() # different version checked out
876 return self._repo['.'].hex() # different version checked out
877 return node.hex(n)
877 return node.hex(n)
878
878
879 @annotatesubrepoerror
879 @annotatesubrepoerror
880 def phase(self, state):
880 def phase(self, state):
881 return self._repo[state].phase()
881 return self._repo[state].phase()
882
882
883 @annotatesubrepoerror
883 @annotatesubrepoerror
884 def remove(self):
884 def remove(self):
885 # we can't fully delete the repository as it may contain
885 # we can't fully delete the repository as it may contain
886 # local-only history
886 # local-only history
887 self.ui.note(_('removing subrepo %s\n') % subrelpath(self))
887 self.ui.note(_('removing subrepo %s\n') % subrelpath(self))
888 hg.clean(self._repo, node.nullid, False)
888 hg.clean(self._repo, node.nullid, False)
889
889
890 def _get(self, state):
890 def _get(self, state):
891 source, revision, kind = state
891 source, revision, kind = state
892 parentrepo = self._repo._subparent
892 parentrepo = self._repo._subparent
893
893
894 if revision in self._repo.unfiltered():
894 if revision in self._repo.unfiltered():
895 # Allow shared subrepos tracked at null to setup the sharedpath
895 # Allow shared subrepos tracked at null to setup the sharedpath
896 if len(self._repo) != 0 or not parentrepo.shared():
896 if len(self._repo) != 0 or not parentrepo.shared():
897 return True
897 return True
898 self._repo._subsource = source
898 self._repo._subsource = source
899 srcurl = _abssource(self._repo)
899 srcurl = _abssource(self._repo)
900 other = hg.peer(self._repo, {}, srcurl)
900 other = hg.peer(self._repo, {}, srcurl)
901 if len(self._repo) == 0:
901 if len(self._repo) == 0:
902 # use self._repo.vfs instead of self.wvfs to remove .hg only
902 # use self._repo.vfs instead of self.wvfs to remove .hg only
903 self._repo.vfs.rmtree()
903 self._repo.vfs.rmtree()
904 if parentrepo.shared():
904 if parentrepo.shared():
905 self.ui.status(_('sharing subrepo %s from %s\n')
905 self.ui.status(_('sharing subrepo %s from %s\n')
906 % (subrelpath(self), srcurl))
906 % (subrelpath(self), srcurl))
907 shared = hg.share(self._repo._subparent.baseui,
907 shared = hg.share(self._repo._subparent.baseui,
908 other, self._repo.root,
908 other, self._repo.root,
909 update=False, bookmarks=False)
909 update=False, bookmarks=False)
910 self._repo = shared.local()
910 self._repo = shared.local()
911 else:
911 else:
912 self.ui.status(_('cloning subrepo %s from %s\n')
912 self.ui.status(_('cloning subrepo %s from %s\n')
913 % (subrelpath(self), srcurl))
913 % (subrelpath(self), srcurl))
914 other, cloned = hg.clone(self._repo._subparent.baseui, {},
914 other, cloned = hg.clone(self._repo._subparent.baseui, {},
915 other, self._repo.root,
915 other, self._repo.root,
916 update=False)
916 update=False)
917 self._repo = cloned.local()
917 self._repo = cloned.local()
918 self._initrepo(parentrepo, source, create=True)
918 self._initrepo(parentrepo, source, create=True)
919 self._cachestorehash(srcurl)
919 self._cachestorehash(srcurl)
920 else:
920 else:
921 self.ui.status(_('pulling subrepo %s from %s\n')
921 self.ui.status(_('pulling subrepo %s from %s\n')
922 % (subrelpath(self), srcurl))
922 % (subrelpath(self), srcurl))
923 cleansub = self.storeclean(srcurl)
923 cleansub = self.storeclean(srcurl)
924 exchange.pull(self._repo, other)
924 exchange.pull(self._repo, other)
925 if cleansub:
925 if cleansub:
926 # keep the repo clean after pull
926 # keep the repo clean after pull
927 self._cachestorehash(srcurl)
927 self._cachestorehash(srcurl)
928 return False
928 return False
929
929
930 @annotatesubrepoerror
930 @annotatesubrepoerror
931 def get(self, state, overwrite=False):
931 def get(self, state, overwrite=False):
932 inrepo = self._get(state)
932 inrepo = self._get(state)
933 source, revision, kind = state
933 source, revision, kind = state
934 repo = self._repo
934 repo = self._repo
935 repo.ui.debug("getting subrepo %s\n" % self._path)
935 repo.ui.debug("getting subrepo %s\n" % self._path)
936 if inrepo:
936 if inrepo:
937 urepo = repo.unfiltered()
937 urepo = repo.unfiltered()
938 ctx = urepo[revision]
938 ctx = urepo[revision]
939 if ctx.hidden():
939 if ctx.hidden():
940 urepo.ui.warn(
940 urepo.ui.warn(
941 _('revision %s in subrepository "%s" is hidden\n') \
941 _('revision %s in subrepository "%s" is hidden\n') \
942 % (revision[0:12], self._path))
942 % (revision[0:12], self._path))
943 repo = urepo
943 repo = urepo
944 hg.updaterepo(repo, revision, overwrite)
944 hg.updaterepo(repo, revision, overwrite)
945
945
946 @annotatesubrepoerror
946 @annotatesubrepoerror
947 def merge(self, state):
947 def merge(self, state):
948 self._get(state)
948 self._get(state)
949 cur = self._repo['.']
949 cur = self._repo['.']
950 dst = self._repo[state[1]]
950 dst = self._repo[state[1]]
951 anc = dst.ancestor(cur)
951 anc = dst.ancestor(cur)
952
952
953 def mergefunc():
953 def mergefunc():
954 if anc == cur and dst.branch() == cur.branch():
954 if anc == cur and dst.branch() == cur.branch():
955 self.ui.debug('updating subrepository "%s"\n'
955 self.ui.debug('updating subrepository "%s"\n'
956 % subrelpath(self))
956 % subrelpath(self))
957 hg.update(self._repo, state[1])
957 hg.update(self._repo, state[1])
958 elif anc == dst:
958 elif anc == dst:
959 self.ui.debug('skipping subrepository "%s"\n'
959 self.ui.debug('skipping subrepository "%s"\n'
960 % subrelpath(self))
960 % subrelpath(self))
961 else:
961 else:
962 self.ui.debug('merging subrepository "%s"\n' % subrelpath(self))
962 self.ui.debug('merging subrepository "%s"\n' % subrelpath(self))
963 hg.merge(self._repo, state[1], remind=False)
963 hg.merge(self._repo, state[1], remind=False)
964
964
965 wctx = self._repo[None]
965 wctx = self._repo[None]
966 if self.dirty():
966 if self.dirty():
967 if anc != dst:
967 if anc != dst:
968 if _updateprompt(self.ui, self, wctx.dirty(), cur, dst):
968 if _updateprompt(self.ui, self, wctx.dirty(), cur, dst):
969 mergefunc()
969 mergefunc()
970 else:
970 else:
971 mergefunc()
971 mergefunc()
972 else:
972 else:
973 mergefunc()
973 mergefunc()
974
974
975 @annotatesubrepoerror
975 @annotatesubrepoerror
976 def push(self, opts):
976 def push(self, opts):
977 force = opts.get('force')
977 force = opts.get('force')
978 newbranch = opts.get('new_branch')
978 newbranch = opts.get('new_branch')
979 ssh = opts.get('ssh')
979 ssh = opts.get('ssh')
980
980
981 # push subrepos depth-first for coherent ordering
981 # push subrepos depth-first for coherent ordering
982 c = self._repo['']
982 c = self._repo['']
983 subs = c.substate # only repos that are committed
983 subs = c.substate # only repos that are committed
984 for s in sorted(subs):
984 for s in sorted(subs):
985 if c.sub(s).push(opts) == 0:
985 if c.sub(s).push(opts) == 0:
986 return False
986 return False
987
987
988 dsturl = _abssource(self._repo, True)
988 dsturl = _abssource(self._repo, True)
989 if not force:
989 if not force:
990 if self.storeclean(dsturl):
990 if self.storeclean(dsturl):
991 self.ui.status(
991 self.ui.status(
992 _('no changes made to subrepo %s since last push to %s\n')
992 _('no changes made to subrepo %s since last push to %s\n')
993 % (subrelpath(self), dsturl))
993 % (subrelpath(self), dsturl))
994 return None
994 return None
995 self.ui.status(_('pushing subrepo %s to %s\n') %
995 self.ui.status(_('pushing subrepo %s to %s\n') %
996 (subrelpath(self), dsturl))
996 (subrelpath(self), dsturl))
997 other = hg.peer(self._repo, {'ssh': ssh}, dsturl)
997 other = hg.peer(self._repo, {'ssh': ssh}, dsturl)
998 res = exchange.push(self._repo, other, force, newbranch=newbranch)
998 res = exchange.push(self._repo, other, force, newbranch=newbranch)
999
999
1000 # the repo is now clean
1000 # the repo is now clean
1001 self._cachestorehash(dsturl)
1001 self._cachestorehash(dsturl)
1002 return res.cgresult
1002 return res.cgresult
1003
1003
1004 @annotatesubrepoerror
1004 @annotatesubrepoerror
1005 def outgoing(self, ui, dest, opts):
1005 def outgoing(self, ui, dest, opts):
1006 if 'rev' in opts or 'branch' in opts:
1006 if 'rev' in opts or 'branch' in opts:
1007 opts = copy.copy(opts)
1007 opts = copy.copy(opts)
1008 opts.pop('rev', None)
1008 opts.pop('rev', None)
1009 opts.pop('branch', None)
1009 opts.pop('branch', None)
1010 return hg.outgoing(ui, self._repo, _abssource(self._repo, True), opts)
1010 return hg.outgoing(ui, self._repo, _abssource(self._repo, True), opts)
1011
1011
1012 @annotatesubrepoerror
1012 @annotatesubrepoerror
1013 def incoming(self, ui, source, opts):
1013 def incoming(self, ui, source, opts):
1014 if 'rev' in opts or 'branch' in opts:
1014 if 'rev' in opts or 'branch' in opts:
1015 opts = copy.copy(opts)
1015 opts = copy.copy(opts)
1016 opts.pop('rev', None)
1016 opts.pop('rev', None)
1017 opts.pop('branch', None)
1017 opts.pop('branch', None)
1018 return hg.incoming(ui, self._repo, _abssource(self._repo, False), opts)
1018 return hg.incoming(ui, self._repo, _abssource(self._repo, False), opts)
1019
1019
1020 @annotatesubrepoerror
1020 @annotatesubrepoerror
1021 def files(self):
1021 def files(self):
1022 rev = self._state[1]
1022 rev = self._state[1]
1023 ctx = self._repo[rev]
1023 ctx = self._repo[rev]
1024 return ctx.manifest().keys()
1024 return ctx.manifest().keys()
1025
1025
1026 def filedata(self, name, decode):
1026 def filedata(self, name, decode):
1027 rev = self._state[1]
1027 rev = self._state[1]
1028 data = self._repo[rev][name].data()
1028 data = self._repo[rev][name].data()
1029 if decode:
1029 if decode:
1030 data = self._repo.wwritedata(name, data)
1030 data = self._repo.wwritedata(name, data)
1031 return data
1031 return data
1032
1032
1033 def fileflags(self, name):
1033 def fileflags(self, name):
1034 rev = self._state[1]
1034 rev = self._state[1]
1035 ctx = self._repo[rev]
1035 ctx = self._repo[rev]
1036 return ctx.flags(name)
1036 return ctx.flags(name)
1037
1037
1038 @annotatesubrepoerror
1038 @annotatesubrepoerror
1039 def printfiles(self, ui, m, fm, fmt, subrepos):
1039 def printfiles(self, ui, m, fm, fmt, subrepos):
1040 # If the parent context is a workingctx, use the workingctx here for
1040 # If the parent context is a workingctx, use the workingctx here for
1041 # consistency.
1041 # consistency.
1042 if self._ctx.rev() is None:
1042 if self._ctx.rev() is None:
1043 ctx = self._repo[None]
1043 ctx = self._repo[None]
1044 else:
1044 else:
1045 rev = self._state[1]
1045 rev = self._state[1]
1046 ctx = self._repo[rev]
1046 ctx = self._repo[rev]
1047 return cmdutil.files(ui, ctx, m, fm, fmt, subrepos)
1047 return cmdutil.files(ui, ctx, m, fm, fmt, subrepos)
1048
1048
1049 @annotatesubrepoerror
1049 @annotatesubrepoerror
1050 def getfileset(self, expr):
1050 def getfileset(self, expr):
1051 if self._ctx.rev() is None:
1051 if self._ctx.rev() is None:
1052 ctx = self._repo[None]
1052 ctx = self._repo[None]
1053 else:
1053 else:
1054 rev = self._state[1]
1054 rev = self._state[1]
1055 ctx = self._repo[rev]
1055 ctx = self._repo[rev]
1056
1056
1057 files = ctx.getfileset(expr)
1057 files = ctx.getfileset(expr)
1058
1058
1059 for subpath in ctx.substate:
1059 for subpath in ctx.substate:
1060 sub = ctx.sub(subpath)
1060 sub = ctx.sub(subpath)
1061
1061
1062 try:
1062 try:
1063 files.extend(subpath + '/' + f for f in sub.getfileset(expr))
1063 files.extend(subpath + '/' + f for f in sub.getfileset(expr))
1064 except error.LookupError:
1064 except error.LookupError:
1065 self.ui.status(_("skipping missing subrepository: %s\n")
1065 self.ui.status(_("skipping missing subrepository: %s\n")
1066 % self.wvfs.reljoin(reporelpath(self), subpath))
1066 % self.wvfs.reljoin(reporelpath(self), subpath))
1067 return files
1067 return files
1068
1068
1069 def walk(self, match):
1069 def walk(self, match):
1070 ctx = self._repo[None]
1070 ctx = self._repo[None]
1071 return ctx.walk(match)
1071 return ctx.walk(match)
1072
1072
1073 @annotatesubrepoerror
1073 @annotatesubrepoerror
1074 def forget(self, match, prefix):
1074 def forget(self, match, prefix):
1075 return cmdutil.forget(self.ui, self._repo, match,
1075 return cmdutil.forget(self.ui, self._repo, match,
1076 self.wvfs.reljoin(prefix, self._path), True)
1076 self.wvfs.reljoin(prefix, self._path), True)
1077
1077
1078 @annotatesubrepoerror
1078 @annotatesubrepoerror
1079 def removefiles(self, matcher, prefix, after, force, subrepos, warnings):
1079 def removefiles(self, matcher, prefix, after, force, subrepos, warnings):
1080 return cmdutil.remove(self.ui, self._repo, matcher,
1080 return cmdutil.remove(self.ui, self._repo, matcher,
1081 self.wvfs.reljoin(prefix, self._path),
1081 self.wvfs.reljoin(prefix, self._path),
1082 after, force, subrepos)
1082 after, force, subrepos)
1083
1083
1084 @annotatesubrepoerror
1084 @annotatesubrepoerror
1085 def revert(self, substate, *pats, **opts):
1085 def revert(self, substate, *pats, **opts):
1086 # reverting a subrepo is a 2 step process:
1086 # reverting a subrepo is a 2 step process:
1087 # 1. if the no_backup is not set, revert all modified
1087 # 1. if the no_backup is not set, revert all modified
1088 # files inside the subrepo
1088 # files inside the subrepo
1089 # 2. update the subrepo to the revision specified in
1089 # 2. update the subrepo to the revision specified in
1090 # the corresponding substate dictionary
1090 # the corresponding substate dictionary
1091 self.ui.status(_('reverting subrepo %s\n') % substate[0])
1091 self.ui.status(_('reverting subrepo %s\n') % substate[0])
1092 if not opts.get('no_backup'):
1092 if not opts.get(r'no_backup'):
1093 # Revert all files on the subrepo, creating backups
1093 # Revert all files on the subrepo, creating backups
1094 # Note that this will not recursively revert subrepos
1094 # Note that this will not recursively revert subrepos
1095 # We could do it if there was a set:subrepos() predicate
1095 # We could do it if there was a set:subrepos() predicate
1096 opts = opts.copy()
1096 opts = opts.copy()
1097 opts['date'] = None
1097 opts[r'date'] = None
1098 opts['rev'] = substate[1]
1098 opts[r'rev'] = substate[1]
1099
1099
1100 self.filerevert(*pats, **opts)
1100 self.filerevert(*pats, **opts)
1101
1101
1102 # Update the repo to the revision specified in the given substate
1102 # Update the repo to the revision specified in the given substate
1103 if not opts.get('dry_run'):
1103 if not opts.get(r'dry_run'):
1104 self.get(substate, overwrite=True)
1104 self.get(substate, overwrite=True)
1105
1105
1106 def filerevert(self, *pats, **opts):
1106 def filerevert(self, *pats, **opts):
1107 ctx = self._repo[opts['rev']]
1107 ctx = self._repo[opts[r'rev']]
1108 parents = self._repo.dirstate.parents()
1108 parents = self._repo.dirstate.parents()
1109 if opts.get('all'):
1109 if opts.get(r'all'):
1110 pats = ['set:modified()']
1110 pats = ['set:modified()']
1111 else:
1111 else:
1112 pats = []
1112 pats = []
1113 cmdutil.revert(self.ui, self._repo, ctx, parents, *pats, **opts)
1113 cmdutil.revert(self.ui, self._repo, ctx, parents, *pats, **opts)
1114
1114
1115 def shortid(self, revid):
1115 def shortid(self, revid):
1116 return revid[:12]
1116 return revid[:12]
1117
1117
1118 @annotatesubrepoerror
1118 @annotatesubrepoerror
1119 def unshare(self):
1119 def unshare(self):
1120 # subrepo inherently violates our import layering rules
1120 # subrepo inherently violates our import layering rules
1121 # because it wants to make repo objects from deep inside the stack
1121 # because it wants to make repo objects from deep inside the stack
1122 # so we manually delay the circular imports to not break
1122 # so we manually delay the circular imports to not break
1123 # scripts that don't use our demand-loading
1123 # scripts that don't use our demand-loading
1124 global hg
1124 global hg
1125 from . import hg as h
1125 from . import hg as h
1126 hg = h
1126 hg = h
1127
1127
1128 # Nothing prevents a user from sharing in a repo, and then making that a
1128 # Nothing prevents a user from sharing in a repo, and then making that a
1129 # subrepo. Alternately, the previous unshare attempt may have failed
1129 # subrepo. Alternately, the previous unshare attempt may have failed
1130 # part way through. So recurse whether or not this layer is shared.
1130 # part way through. So recurse whether or not this layer is shared.
1131 if self._repo.shared():
1131 if self._repo.shared():
1132 self.ui.status(_("unsharing subrepo '%s'\n") % self._relpath)
1132 self.ui.status(_("unsharing subrepo '%s'\n") % self._relpath)
1133
1133
1134 hg.unshare(self.ui, self._repo)
1134 hg.unshare(self.ui, self._repo)
1135
1135
1136 def verify(self):
1136 def verify(self):
1137 try:
1137 try:
1138 rev = self._state[1]
1138 rev = self._state[1]
1139 ctx = self._repo.unfiltered()[rev]
1139 ctx = self._repo.unfiltered()[rev]
1140 if ctx.hidden():
1140 if ctx.hidden():
1141 # Since hidden revisions aren't pushed/pulled, it seems worth an
1141 # Since hidden revisions aren't pushed/pulled, it seems worth an
1142 # explicit warning.
1142 # explicit warning.
1143 ui = self._repo.ui
1143 ui = self._repo.ui
1144 ui.warn(_("subrepo '%s' is hidden in revision %s\n") %
1144 ui.warn(_("subrepo '%s' is hidden in revision %s\n") %
1145 (self._relpath, node.short(self._ctx.node())))
1145 (self._relpath, node.short(self._ctx.node())))
1146 return 0
1146 return 0
1147 except error.RepoLookupError:
1147 except error.RepoLookupError:
1148 # A missing subrepo revision may be a case of needing to pull it, so
1148 # A missing subrepo revision may be a case of needing to pull it, so
1149 # don't treat this as an error.
1149 # don't treat this as an error.
1150 self._repo.ui.warn(_("subrepo '%s' not found in revision %s\n") %
1150 self._repo.ui.warn(_("subrepo '%s' not found in revision %s\n") %
1151 (self._relpath, node.short(self._ctx.node())))
1151 (self._relpath, node.short(self._ctx.node())))
1152 return 0
1152 return 0
1153
1153
1154 @propertycache
1154 @propertycache
1155 def wvfs(self):
1155 def wvfs(self):
1156 """return own wvfs for efficiency and consistency
1156 """return own wvfs for efficiency and consistency
1157 """
1157 """
1158 return self._repo.wvfs
1158 return self._repo.wvfs
1159
1159
1160 @propertycache
1160 @propertycache
1161 def _relpath(self):
1161 def _relpath(self):
1162 """return path to this subrepository as seen from outermost repository
1162 """return path to this subrepository as seen from outermost repository
1163 """
1163 """
1164 # Keep consistent dir separators by avoiding vfs.join(self._path)
1164 # Keep consistent dir separators by avoiding vfs.join(self._path)
1165 return reporelpath(self._repo)
1165 return reporelpath(self._repo)
1166
1166
1167 class svnsubrepo(abstractsubrepo):
1167 class svnsubrepo(abstractsubrepo):
1168 def __init__(self, ctx, path, state, allowcreate):
1168 def __init__(self, ctx, path, state, allowcreate):
1169 super(svnsubrepo, self).__init__(ctx, path)
1169 super(svnsubrepo, self).__init__(ctx, path)
1170 self._state = state
1170 self._state = state
1171 self._exe = util.findexe('svn')
1171 self._exe = util.findexe('svn')
1172 if not self._exe:
1172 if not self._exe:
1173 raise error.Abort(_("'svn' executable not found for subrepo '%s'")
1173 raise error.Abort(_("'svn' executable not found for subrepo '%s'")
1174 % self._path)
1174 % self._path)
1175
1175
1176 def _svncommand(self, commands, filename='', failok=False):
1176 def _svncommand(self, commands, filename='', failok=False):
1177 cmd = [self._exe]
1177 cmd = [self._exe]
1178 extrakw = {}
1178 extrakw = {}
1179 if not self.ui.interactive():
1179 if not self.ui.interactive():
1180 # Making stdin be a pipe should prevent svn from behaving
1180 # Making stdin be a pipe should prevent svn from behaving
1181 # interactively even if we can't pass --non-interactive.
1181 # interactively even if we can't pass --non-interactive.
1182 extrakw['stdin'] = subprocess.PIPE
1182 extrakw['stdin'] = subprocess.PIPE
1183 # Starting in svn 1.5 --non-interactive is a global flag
1183 # Starting in svn 1.5 --non-interactive is a global flag
1184 # instead of being per-command, but we need to support 1.4 so
1184 # instead of being per-command, but we need to support 1.4 so
1185 # we have to be intelligent about what commands take
1185 # we have to be intelligent about what commands take
1186 # --non-interactive.
1186 # --non-interactive.
1187 if commands[0] in ('update', 'checkout', 'commit'):
1187 if commands[0] in ('update', 'checkout', 'commit'):
1188 cmd.append('--non-interactive')
1188 cmd.append('--non-interactive')
1189 cmd.extend(commands)
1189 cmd.extend(commands)
1190 if filename is not None:
1190 if filename is not None:
1191 path = self.wvfs.reljoin(self._ctx.repo().origroot,
1191 path = self.wvfs.reljoin(self._ctx.repo().origroot,
1192 self._path, filename)
1192 self._path, filename)
1193 cmd.append(path)
1193 cmd.append(path)
1194 env = dict(encoding.environ)
1194 env = dict(encoding.environ)
1195 # Avoid localized output, preserve current locale for everything else.
1195 # Avoid localized output, preserve current locale for everything else.
1196 lc_all = env.get('LC_ALL')
1196 lc_all = env.get('LC_ALL')
1197 if lc_all:
1197 if lc_all:
1198 env['LANG'] = lc_all
1198 env['LANG'] = lc_all
1199 del env['LC_ALL']
1199 del env['LC_ALL']
1200 env['LC_MESSAGES'] = 'C'
1200 env['LC_MESSAGES'] = 'C'
1201 p = subprocess.Popen(cmd, bufsize=-1, close_fds=util.closefds,
1201 p = subprocess.Popen(cmd, bufsize=-1, close_fds=util.closefds,
1202 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
1202 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
1203 universal_newlines=True, env=env, **extrakw)
1203 universal_newlines=True, env=env, **extrakw)
1204 stdout, stderr = p.communicate()
1204 stdout, stderr = p.communicate()
1205 stderr = stderr.strip()
1205 stderr = stderr.strip()
1206 if not failok:
1206 if not failok:
1207 if p.returncode:
1207 if p.returncode:
1208 raise error.Abort(stderr or 'exited with code %d'
1208 raise error.Abort(stderr or 'exited with code %d'
1209 % p.returncode)
1209 % p.returncode)
1210 if stderr:
1210 if stderr:
1211 self.ui.warn(stderr + '\n')
1211 self.ui.warn(stderr + '\n')
1212 return stdout, stderr
1212 return stdout, stderr
1213
1213
1214 @propertycache
1214 @propertycache
1215 def _svnversion(self):
1215 def _svnversion(self):
1216 output, err = self._svncommand(['--version', '--quiet'], filename=None)
1216 output, err = self._svncommand(['--version', '--quiet'], filename=None)
1217 m = re.search(br'^(\d+)\.(\d+)', output)
1217 m = re.search(br'^(\d+)\.(\d+)', output)
1218 if not m:
1218 if not m:
1219 raise error.Abort(_('cannot retrieve svn tool version'))
1219 raise error.Abort(_('cannot retrieve svn tool version'))
1220 return (int(m.group(1)), int(m.group(2)))
1220 return (int(m.group(1)), int(m.group(2)))
1221
1221
1222 def _wcrevs(self):
1222 def _wcrevs(self):
1223 # Get the working directory revision as well as the last
1223 # Get the working directory revision as well as the last
1224 # commit revision so we can compare the subrepo state with
1224 # commit revision so we can compare the subrepo state with
1225 # both. We used to store the working directory one.
1225 # both. We used to store the working directory one.
1226 output, err = self._svncommand(['info', '--xml'])
1226 output, err = self._svncommand(['info', '--xml'])
1227 doc = xml.dom.minidom.parseString(output)
1227 doc = xml.dom.minidom.parseString(output)
1228 entries = doc.getElementsByTagName('entry')
1228 entries = doc.getElementsByTagName('entry')
1229 lastrev, rev = '0', '0'
1229 lastrev, rev = '0', '0'
1230 if entries:
1230 if entries:
1231 rev = str(entries[0].getAttribute('revision')) or '0'
1231 rev = str(entries[0].getAttribute('revision')) or '0'
1232 commits = entries[0].getElementsByTagName('commit')
1232 commits = entries[0].getElementsByTagName('commit')
1233 if commits:
1233 if commits:
1234 lastrev = str(commits[0].getAttribute('revision')) or '0'
1234 lastrev = str(commits[0].getAttribute('revision')) or '0'
1235 return (lastrev, rev)
1235 return (lastrev, rev)
1236
1236
1237 def _wcrev(self):
1237 def _wcrev(self):
1238 return self._wcrevs()[0]
1238 return self._wcrevs()[0]
1239
1239
1240 def _wcchanged(self):
1240 def _wcchanged(self):
1241 """Return (changes, extchanges, missing) where changes is True
1241 """Return (changes, extchanges, missing) where changes is True
1242 if the working directory was changed, extchanges is
1242 if the working directory was changed, extchanges is
1243 True if any of these changes concern an external entry and missing
1243 True if any of these changes concern an external entry and missing
1244 is True if any change is a missing entry.
1244 is True if any change is a missing entry.
1245 """
1245 """
1246 output, err = self._svncommand(['status', '--xml'])
1246 output, err = self._svncommand(['status', '--xml'])
1247 externals, changes, missing = [], [], []
1247 externals, changes, missing = [], [], []
1248 doc = xml.dom.minidom.parseString(output)
1248 doc = xml.dom.minidom.parseString(output)
1249 for e in doc.getElementsByTagName('entry'):
1249 for e in doc.getElementsByTagName('entry'):
1250 s = e.getElementsByTagName('wc-status')
1250 s = e.getElementsByTagName('wc-status')
1251 if not s:
1251 if not s:
1252 continue
1252 continue
1253 item = s[0].getAttribute('item')
1253 item = s[0].getAttribute('item')
1254 props = s[0].getAttribute('props')
1254 props = s[0].getAttribute('props')
1255 path = e.getAttribute('path')
1255 path = e.getAttribute('path')
1256 if item == 'external':
1256 if item == 'external':
1257 externals.append(path)
1257 externals.append(path)
1258 elif item == 'missing':
1258 elif item == 'missing':
1259 missing.append(path)
1259 missing.append(path)
1260 if (item not in ('', 'normal', 'unversioned', 'external')
1260 if (item not in ('', 'normal', 'unversioned', 'external')
1261 or props not in ('', 'none', 'normal')):
1261 or props not in ('', 'none', 'normal')):
1262 changes.append(path)
1262 changes.append(path)
1263 for path in changes:
1263 for path in changes:
1264 for ext in externals:
1264 for ext in externals:
1265 if path == ext or path.startswith(ext + pycompat.ossep):
1265 if path == ext or path.startswith(ext + pycompat.ossep):
1266 return True, True, bool(missing)
1266 return True, True, bool(missing)
1267 return bool(changes), False, bool(missing)
1267 return bool(changes), False, bool(missing)
1268
1268
1269 def dirty(self, ignoreupdate=False, missing=False):
1269 def dirty(self, ignoreupdate=False, missing=False):
1270 wcchanged = self._wcchanged()
1270 wcchanged = self._wcchanged()
1271 changed = wcchanged[0] or (missing and wcchanged[2])
1271 changed = wcchanged[0] or (missing and wcchanged[2])
1272 if not changed:
1272 if not changed:
1273 if self._state[1] in self._wcrevs() or ignoreupdate:
1273 if self._state[1] in self._wcrevs() or ignoreupdate:
1274 return False
1274 return False
1275 return True
1275 return True
1276
1276
1277 def basestate(self):
1277 def basestate(self):
1278 lastrev, rev = self._wcrevs()
1278 lastrev, rev = self._wcrevs()
1279 if lastrev != rev:
1279 if lastrev != rev:
1280 # Last committed rev is not the same than rev. We would
1280 # Last committed rev is not the same than rev. We would
1281 # like to take lastrev but we do not know if the subrepo
1281 # like to take lastrev but we do not know if the subrepo
1282 # URL exists at lastrev. Test it and fallback to rev it
1282 # URL exists at lastrev. Test it and fallback to rev it
1283 # is not there.
1283 # is not there.
1284 try:
1284 try:
1285 self._svncommand(['list', '%s@%s' % (self._state[0], lastrev)])
1285 self._svncommand(['list', '%s@%s' % (self._state[0], lastrev)])
1286 return lastrev
1286 return lastrev
1287 except error.Abort:
1287 except error.Abort:
1288 pass
1288 pass
1289 return rev
1289 return rev
1290
1290
1291 @annotatesubrepoerror
1291 @annotatesubrepoerror
1292 def commit(self, text, user, date):
1292 def commit(self, text, user, date):
1293 # user and date are out of our hands since svn is centralized
1293 # user and date are out of our hands since svn is centralized
1294 changed, extchanged, missing = self._wcchanged()
1294 changed, extchanged, missing = self._wcchanged()
1295 if not changed:
1295 if not changed:
1296 return self.basestate()
1296 return self.basestate()
1297 if extchanged:
1297 if extchanged:
1298 # Do not try to commit externals
1298 # Do not try to commit externals
1299 raise error.Abort(_('cannot commit svn externals'))
1299 raise error.Abort(_('cannot commit svn externals'))
1300 if missing:
1300 if missing:
1301 # svn can commit with missing entries but aborting like hg
1301 # svn can commit with missing entries but aborting like hg
1302 # seems a better approach.
1302 # seems a better approach.
1303 raise error.Abort(_('cannot commit missing svn entries'))
1303 raise error.Abort(_('cannot commit missing svn entries'))
1304 commitinfo, err = self._svncommand(['commit', '-m', text])
1304 commitinfo, err = self._svncommand(['commit', '-m', text])
1305 self.ui.status(commitinfo)
1305 self.ui.status(commitinfo)
1306 newrev = re.search('Committed revision ([0-9]+).', commitinfo)
1306 newrev = re.search('Committed revision ([0-9]+).', commitinfo)
1307 if not newrev:
1307 if not newrev:
1308 if not commitinfo.strip():
1308 if not commitinfo.strip():
1309 # Sometimes, our definition of "changed" differs from
1309 # Sometimes, our definition of "changed" differs from
1310 # svn one. For instance, svn ignores missing files
1310 # svn one. For instance, svn ignores missing files
1311 # when committing. If there are only missing files, no
1311 # when committing. If there are only missing files, no
1312 # commit is made, no output and no error code.
1312 # commit is made, no output and no error code.
1313 raise error.Abort(_('failed to commit svn changes'))
1313 raise error.Abort(_('failed to commit svn changes'))
1314 raise error.Abort(commitinfo.splitlines()[-1])
1314 raise error.Abort(commitinfo.splitlines()[-1])
1315 newrev = newrev.groups()[0]
1315 newrev = newrev.groups()[0]
1316 self.ui.status(self._svncommand(['update', '-r', newrev])[0])
1316 self.ui.status(self._svncommand(['update', '-r', newrev])[0])
1317 return newrev
1317 return newrev
1318
1318
1319 @annotatesubrepoerror
1319 @annotatesubrepoerror
1320 def remove(self):
1320 def remove(self):
1321 if self.dirty():
1321 if self.dirty():
1322 self.ui.warn(_('not removing repo %s because '
1322 self.ui.warn(_('not removing repo %s because '
1323 'it has changes.\n') % self._path)
1323 'it has changes.\n') % self._path)
1324 return
1324 return
1325 self.ui.note(_('removing subrepo %s\n') % self._path)
1325 self.ui.note(_('removing subrepo %s\n') % self._path)
1326
1326
1327 self.wvfs.rmtree(forcibly=True)
1327 self.wvfs.rmtree(forcibly=True)
1328 try:
1328 try:
1329 pwvfs = self._ctx.repo().wvfs
1329 pwvfs = self._ctx.repo().wvfs
1330 pwvfs.removedirs(pwvfs.dirname(self._path))
1330 pwvfs.removedirs(pwvfs.dirname(self._path))
1331 except OSError:
1331 except OSError:
1332 pass
1332 pass
1333
1333
1334 @annotatesubrepoerror
1334 @annotatesubrepoerror
1335 def get(self, state, overwrite=False):
1335 def get(self, state, overwrite=False):
1336 if overwrite:
1336 if overwrite:
1337 self._svncommand(['revert', '--recursive'])
1337 self._svncommand(['revert', '--recursive'])
1338 args = ['checkout']
1338 args = ['checkout']
1339 if self._svnversion >= (1, 5):
1339 if self._svnversion >= (1, 5):
1340 args.append('--force')
1340 args.append('--force')
1341 # The revision must be specified at the end of the URL to properly
1341 # The revision must be specified at the end of the URL to properly
1342 # update to a directory which has since been deleted and recreated.
1342 # update to a directory which has since been deleted and recreated.
1343 args.append('%s@%s' % (state[0], state[1]))
1343 args.append('%s@%s' % (state[0], state[1]))
1344
1344
1345 # SEC: check that the ssh url is safe
1345 # SEC: check that the ssh url is safe
1346 util.checksafessh(state[0])
1346 util.checksafessh(state[0])
1347
1347
1348 status, err = self._svncommand(args, failok=True)
1348 status, err = self._svncommand(args, failok=True)
1349 _sanitize(self.ui, self.wvfs, '.svn')
1349 _sanitize(self.ui, self.wvfs, '.svn')
1350 if not re.search('Checked out revision [0-9]+.', status):
1350 if not re.search('Checked out revision [0-9]+.', status):
1351 if ('is already a working copy for a different URL' in err
1351 if ('is already a working copy for a different URL' in err
1352 and (self._wcchanged()[:2] == (False, False))):
1352 and (self._wcchanged()[:2] == (False, False))):
1353 # obstructed but clean working copy, so just blow it away.
1353 # obstructed but clean working copy, so just blow it away.
1354 self.remove()
1354 self.remove()
1355 self.get(state, overwrite=False)
1355 self.get(state, overwrite=False)
1356 return
1356 return
1357 raise error.Abort((status or err).splitlines()[-1])
1357 raise error.Abort((status or err).splitlines()[-1])
1358 self.ui.status(status)
1358 self.ui.status(status)
1359
1359
1360 @annotatesubrepoerror
1360 @annotatesubrepoerror
1361 def merge(self, state):
1361 def merge(self, state):
1362 old = self._state[1]
1362 old = self._state[1]
1363 new = state[1]
1363 new = state[1]
1364 wcrev = self._wcrev()
1364 wcrev = self._wcrev()
1365 if new != wcrev:
1365 if new != wcrev:
1366 dirty = old == wcrev or self._wcchanged()[0]
1366 dirty = old == wcrev or self._wcchanged()[0]
1367 if _updateprompt(self.ui, self, dirty, wcrev, new):
1367 if _updateprompt(self.ui, self, dirty, wcrev, new):
1368 self.get(state, False)
1368 self.get(state, False)
1369
1369
1370 def push(self, opts):
1370 def push(self, opts):
1371 # push is a no-op for SVN
1371 # push is a no-op for SVN
1372 return True
1372 return True
1373
1373
1374 @annotatesubrepoerror
1374 @annotatesubrepoerror
1375 def files(self):
1375 def files(self):
1376 output = self._svncommand(['list', '--recursive', '--xml'])[0]
1376 output = self._svncommand(['list', '--recursive', '--xml'])[0]
1377 doc = xml.dom.minidom.parseString(output)
1377 doc = xml.dom.minidom.parseString(output)
1378 paths = []
1378 paths = []
1379 for e in doc.getElementsByTagName('entry'):
1379 for e in doc.getElementsByTagName('entry'):
1380 kind = str(e.getAttribute('kind'))
1380 kind = str(e.getAttribute('kind'))
1381 if kind != 'file':
1381 if kind != 'file':
1382 continue
1382 continue
1383 name = ''.join(c.data for c
1383 name = ''.join(c.data for c
1384 in e.getElementsByTagName('name')[0].childNodes
1384 in e.getElementsByTagName('name')[0].childNodes
1385 if c.nodeType == c.TEXT_NODE)
1385 if c.nodeType == c.TEXT_NODE)
1386 paths.append(name.encode('utf-8'))
1386 paths.append(name.encode('utf-8'))
1387 return paths
1387 return paths
1388
1388
1389 def filedata(self, name, decode):
1389 def filedata(self, name, decode):
1390 return self._svncommand(['cat'], name)[0]
1390 return self._svncommand(['cat'], name)[0]
1391
1391
1392
1392
1393 class gitsubrepo(abstractsubrepo):
1393 class gitsubrepo(abstractsubrepo):
1394 def __init__(self, ctx, path, state, allowcreate):
1394 def __init__(self, ctx, path, state, allowcreate):
1395 super(gitsubrepo, self).__init__(ctx, path)
1395 super(gitsubrepo, self).__init__(ctx, path)
1396 self._state = state
1396 self._state = state
1397 self._abspath = ctx.repo().wjoin(path)
1397 self._abspath = ctx.repo().wjoin(path)
1398 self._subparent = ctx.repo()
1398 self._subparent = ctx.repo()
1399 self._ensuregit()
1399 self._ensuregit()
1400
1400
1401 def _ensuregit(self):
1401 def _ensuregit(self):
1402 try:
1402 try:
1403 self._gitexecutable = 'git'
1403 self._gitexecutable = 'git'
1404 out, err = self._gitnodir(['--version'])
1404 out, err = self._gitnodir(['--version'])
1405 except OSError as e:
1405 except OSError as e:
1406 genericerror = _("error executing git for subrepo '%s': %s")
1406 genericerror = _("error executing git for subrepo '%s': %s")
1407 notfoundhint = _("check git is installed and in your PATH")
1407 notfoundhint = _("check git is installed and in your PATH")
1408 if e.errno != errno.ENOENT:
1408 if e.errno != errno.ENOENT:
1409 raise error.Abort(genericerror % (
1409 raise error.Abort(genericerror % (
1410 self._path, encoding.strtolocal(e.strerror)))
1410 self._path, encoding.strtolocal(e.strerror)))
1411 elif pycompat.iswindows:
1411 elif pycompat.iswindows:
1412 try:
1412 try:
1413 self._gitexecutable = 'git.cmd'
1413 self._gitexecutable = 'git.cmd'
1414 out, err = self._gitnodir(['--version'])
1414 out, err = self._gitnodir(['--version'])
1415 except OSError as e2:
1415 except OSError as e2:
1416 if e2.errno == errno.ENOENT:
1416 if e2.errno == errno.ENOENT:
1417 raise error.Abort(_("couldn't find 'git' or 'git.cmd'"
1417 raise error.Abort(_("couldn't find 'git' or 'git.cmd'"
1418 " for subrepo '%s'") % self._path,
1418 " for subrepo '%s'") % self._path,
1419 hint=notfoundhint)
1419 hint=notfoundhint)
1420 else:
1420 else:
1421 raise error.Abort(genericerror % (self._path,
1421 raise error.Abort(genericerror % (self._path,
1422 encoding.strtolocal(e2.strerror)))
1422 encoding.strtolocal(e2.strerror)))
1423 else:
1423 else:
1424 raise error.Abort(_("couldn't find git for subrepo '%s'")
1424 raise error.Abort(_("couldn't find git for subrepo '%s'")
1425 % self._path, hint=notfoundhint)
1425 % self._path, hint=notfoundhint)
1426 versionstatus = self._checkversion(out)
1426 versionstatus = self._checkversion(out)
1427 if versionstatus == 'unknown':
1427 if versionstatus == 'unknown':
1428 self.ui.warn(_('cannot retrieve git version\n'))
1428 self.ui.warn(_('cannot retrieve git version\n'))
1429 elif versionstatus == 'abort':
1429 elif versionstatus == 'abort':
1430 raise error.Abort(_('git subrepo requires at least 1.6.0 or later'))
1430 raise error.Abort(_('git subrepo requires at least 1.6.0 or later'))
1431 elif versionstatus == 'warning':
1431 elif versionstatus == 'warning':
1432 self.ui.warn(_('git subrepo requires at least 1.6.0 or later\n'))
1432 self.ui.warn(_('git subrepo requires at least 1.6.0 or later\n'))
1433
1433
1434 @staticmethod
1434 @staticmethod
1435 def _gitversion(out):
1435 def _gitversion(out):
1436 m = re.search(br'^git version (\d+)\.(\d+)\.(\d+)', out)
1436 m = re.search(br'^git version (\d+)\.(\d+)\.(\d+)', out)
1437 if m:
1437 if m:
1438 return (int(m.group(1)), int(m.group(2)), int(m.group(3)))
1438 return (int(m.group(1)), int(m.group(2)), int(m.group(3)))
1439
1439
1440 m = re.search(br'^git version (\d+)\.(\d+)', out)
1440 m = re.search(br'^git version (\d+)\.(\d+)', out)
1441 if m:
1441 if m:
1442 return (int(m.group(1)), int(m.group(2)), 0)
1442 return (int(m.group(1)), int(m.group(2)), 0)
1443
1443
1444 return -1
1444 return -1
1445
1445
1446 @staticmethod
1446 @staticmethod
1447 def _checkversion(out):
1447 def _checkversion(out):
1448 '''ensure git version is new enough
1448 '''ensure git version is new enough
1449
1449
1450 >>> _checkversion = gitsubrepo._checkversion
1450 >>> _checkversion = gitsubrepo._checkversion
1451 >>> _checkversion(b'git version 1.6.0')
1451 >>> _checkversion(b'git version 1.6.0')
1452 'ok'
1452 'ok'
1453 >>> _checkversion(b'git version 1.8.5')
1453 >>> _checkversion(b'git version 1.8.5')
1454 'ok'
1454 'ok'
1455 >>> _checkversion(b'git version 1.4.0')
1455 >>> _checkversion(b'git version 1.4.0')
1456 'abort'
1456 'abort'
1457 >>> _checkversion(b'git version 1.5.0')
1457 >>> _checkversion(b'git version 1.5.0')
1458 'warning'
1458 'warning'
1459 >>> _checkversion(b'git version 1.9-rc0')
1459 >>> _checkversion(b'git version 1.9-rc0')
1460 'ok'
1460 'ok'
1461 >>> _checkversion(b'git version 1.9.0.265.g81cdec2')
1461 >>> _checkversion(b'git version 1.9.0.265.g81cdec2')
1462 'ok'
1462 'ok'
1463 >>> _checkversion(b'git version 1.9.0.GIT')
1463 >>> _checkversion(b'git version 1.9.0.GIT')
1464 'ok'
1464 'ok'
1465 >>> _checkversion(b'git version 12345')
1465 >>> _checkversion(b'git version 12345')
1466 'unknown'
1466 'unknown'
1467 >>> _checkversion(b'no')
1467 >>> _checkversion(b'no')
1468 'unknown'
1468 'unknown'
1469 '''
1469 '''
1470 version = gitsubrepo._gitversion(out)
1470 version = gitsubrepo._gitversion(out)
1471 # git 1.4.0 can't work at all, but 1.5.X can in at least some cases,
1471 # git 1.4.0 can't work at all, but 1.5.X can in at least some cases,
1472 # despite the docstring comment. For now, error on 1.4.0, warn on
1472 # despite the docstring comment. For now, error on 1.4.0, warn on
1473 # 1.5.0 but attempt to continue.
1473 # 1.5.0 but attempt to continue.
1474 if version == -1:
1474 if version == -1:
1475 return 'unknown'
1475 return 'unknown'
1476 if version < (1, 5, 0):
1476 if version < (1, 5, 0):
1477 return 'abort'
1477 return 'abort'
1478 elif version < (1, 6, 0):
1478 elif version < (1, 6, 0):
1479 return 'warning'
1479 return 'warning'
1480 return 'ok'
1480 return 'ok'
1481
1481
1482 def _gitcommand(self, commands, env=None, stream=False):
1482 def _gitcommand(self, commands, env=None, stream=False):
1483 return self._gitdir(commands, env=env, stream=stream)[0]
1483 return self._gitdir(commands, env=env, stream=stream)[0]
1484
1484
1485 def _gitdir(self, commands, env=None, stream=False):
1485 def _gitdir(self, commands, env=None, stream=False):
1486 return self._gitnodir(commands, env=env, stream=stream,
1486 return self._gitnodir(commands, env=env, stream=stream,
1487 cwd=self._abspath)
1487 cwd=self._abspath)
1488
1488
1489 def _gitnodir(self, commands, env=None, stream=False, cwd=None):
1489 def _gitnodir(self, commands, env=None, stream=False, cwd=None):
1490 """Calls the git command
1490 """Calls the git command
1491
1491
1492 The methods tries to call the git command. versions prior to 1.6.0
1492 The methods tries to call the git command. versions prior to 1.6.0
1493 are not supported and very probably fail.
1493 are not supported and very probably fail.
1494 """
1494 """
1495 self.ui.debug('%s: git %s\n' % (self._relpath, ' '.join(commands)))
1495 self.ui.debug('%s: git %s\n' % (self._relpath, ' '.join(commands)))
1496 if env is None:
1496 if env is None:
1497 env = encoding.environ.copy()
1497 env = encoding.environ.copy()
1498 # disable localization for Git output (issue5176)
1498 # disable localization for Git output (issue5176)
1499 env['LC_ALL'] = 'C'
1499 env['LC_ALL'] = 'C'
1500 # fix for Git CVE-2015-7545
1500 # fix for Git CVE-2015-7545
1501 if 'GIT_ALLOW_PROTOCOL' not in env:
1501 if 'GIT_ALLOW_PROTOCOL' not in env:
1502 env['GIT_ALLOW_PROTOCOL'] = 'file:git:http:https:ssh'
1502 env['GIT_ALLOW_PROTOCOL'] = 'file:git:http:https:ssh'
1503 # unless ui.quiet is set, print git's stderr,
1503 # unless ui.quiet is set, print git's stderr,
1504 # which is mostly progress and useful info
1504 # which is mostly progress and useful info
1505 errpipe = None
1505 errpipe = None
1506 if self.ui.quiet:
1506 if self.ui.quiet:
1507 errpipe = open(os.devnull, 'w')
1507 errpipe = open(os.devnull, 'w')
1508 if self.ui._colormode and len(commands) and commands[0] == "diff":
1508 if self.ui._colormode and len(commands) and commands[0] == "diff":
1509 # insert the argument in the front,
1509 # insert the argument in the front,
1510 # the end of git diff arguments is used for paths
1510 # the end of git diff arguments is used for paths
1511 commands.insert(1, '--color')
1511 commands.insert(1, '--color')
1512 p = subprocess.Popen([self._gitexecutable] + commands, bufsize=-1,
1512 p = subprocess.Popen([self._gitexecutable] + commands, bufsize=-1,
1513 cwd=cwd, env=env, close_fds=util.closefds,
1513 cwd=cwd, env=env, close_fds=util.closefds,
1514 stdout=subprocess.PIPE, stderr=errpipe)
1514 stdout=subprocess.PIPE, stderr=errpipe)
1515 if stream:
1515 if stream:
1516 return p.stdout, None
1516 return p.stdout, None
1517
1517
1518 retdata = p.stdout.read().strip()
1518 retdata = p.stdout.read().strip()
1519 # wait for the child to exit to avoid race condition.
1519 # wait for the child to exit to avoid race condition.
1520 p.wait()
1520 p.wait()
1521
1521
1522 if p.returncode != 0 and p.returncode != 1:
1522 if p.returncode != 0 and p.returncode != 1:
1523 # there are certain error codes that are ok
1523 # there are certain error codes that are ok
1524 command = commands[0]
1524 command = commands[0]
1525 if command in ('cat-file', 'symbolic-ref'):
1525 if command in ('cat-file', 'symbolic-ref'):
1526 return retdata, p.returncode
1526 return retdata, p.returncode
1527 # for all others, abort
1527 # for all others, abort
1528 raise error.Abort(_('git %s error %d in %s') %
1528 raise error.Abort(_('git %s error %d in %s') %
1529 (command, p.returncode, self._relpath))
1529 (command, p.returncode, self._relpath))
1530
1530
1531 return retdata, p.returncode
1531 return retdata, p.returncode
1532
1532
1533 def _gitmissing(self):
1533 def _gitmissing(self):
1534 return not self.wvfs.exists('.git')
1534 return not self.wvfs.exists('.git')
1535
1535
1536 def _gitstate(self):
1536 def _gitstate(self):
1537 return self._gitcommand(['rev-parse', 'HEAD'])
1537 return self._gitcommand(['rev-parse', 'HEAD'])
1538
1538
1539 def _gitcurrentbranch(self):
1539 def _gitcurrentbranch(self):
1540 current, err = self._gitdir(['symbolic-ref', 'HEAD', '--quiet'])
1540 current, err = self._gitdir(['symbolic-ref', 'HEAD', '--quiet'])
1541 if err:
1541 if err:
1542 current = None
1542 current = None
1543 return current
1543 return current
1544
1544
1545 def _gitremote(self, remote):
1545 def _gitremote(self, remote):
1546 out = self._gitcommand(['remote', 'show', '-n', remote])
1546 out = self._gitcommand(['remote', 'show', '-n', remote])
1547 line = out.split('\n')[1]
1547 line = out.split('\n')[1]
1548 i = line.index('URL: ') + len('URL: ')
1548 i = line.index('URL: ') + len('URL: ')
1549 return line[i:]
1549 return line[i:]
1550
1550
1551 def _githavelocally(self, revision):
1551 def _githavelocally(self, revision):
1552 out, code = self._gitdir(['cat-file', '-e', revision])
1552 out, code = self._gitdir(['cat-file', '-e', revision])
1553 return code == 0
1553 return code == 0
1554
1554
1555 def _gitisancestor(self, r1, r2):
1555 def _gitisancestor(self, r1, r2):
1556 base = self._gitcommand(['merge-base', r1, r2])
1556 base = self._gitcommand(['merge-base', r1, r2])
1557 return base == r1
1557 return base == r1
1558
1558
1559 def _gitisbare(self):
1559 def _gitisbare(self):
1560 return self._gitcommand(['config', '--bool', 'core.bare']) == 'true'
1560 return self._gitcommand(['config', '--bool', 'core.bare']) == 'true'
1561
1561
1562 def _gitupdatestat(self):
1562 def _gitupdatestat(self):
1563 """This must be run before git diff-index.
1563 """This must be run before git diff-index.
1564 diff-index only looks at changes to file stat;
1564 diff-index only looks at changes to file stat;
1565 this command looks at file contents and updates the stat."""
1565 this command looks at file contents and updates the stat."""
1566 self._gitcommand(['update-index', '-q', '--refresh'])
1566 self._gitcommand(['update-index', '-q', '--refresh'])
1567
1567
1568 def _gitbranchmap(self):
1568 def _gitbranchmap(self):
1569 '''returns 2 things:
1569 '''returns 2 things:
1570 a map from git branch to revision
1570 a map from git branch to revision
1571 a map from revision to branches'''
1571 a map from revision to branches'''
1572 branch2rev = {}
1572 branch2rev = {}
1573 rev2branch = {}
1573 rev2branch = {}
1574
1574
1575 out = self._gitcommand(['for-each-ref', '--format',
1575 out = self._gitcommand(['for-each-ref', '--format',
1576 '%(objectname) %(refname)'])
1576 '%(objectname) %(refname)'])
1577 for line in out.split('\n'):
1577 for line in out.split('\n'):
1578 revision, ref = line.split(' ')
1578 revision, ref = line.split(' ')
1579 if (not ref.startswith('refs/heads/') and
1579 if (not ref.startswith('refs/heads/') and
1580 not ref.startswith('refs/remotes/')):
1580 not ref.startswith('refs/remotes/')):
1581 continue
1581 continue
1582 if ref.startswith('refs/remotes/') and ref.endswith('/HEAD'):
1582 if ref.startswith('refs/remotes/') and ref.endswith('/HEAD'):
1583 continue # ignore remote/HEAD redirects
1583 continue # ignore remote/HEAD redirects
1584 branch2rev[ref] = revision
1584 branch2rev[ref] = revision
1585 rev2branch.setdefault(revision, []).append(ref)
1585 rev2branch.setdefault(revision, []).append(ref)
1586 return branch2rev, rev2branch
1586 return branch2rev, rev2branch
1587
1587
1588 def _gittracking(self, branches):
1588 def _gittracking(self, branches):
1589 'return map of remote branch to local tracking branch'
1589 'return map of remote branch to local tracking branch'
1590 # assumes no more than one local tracking branch for each remote
1590 # assumes no more than one local tracking branch for each remote
1591 tracking = {}
1591 tracking = {}
1592 for b in branches:
1592 for b in branches:
1593 if b.startswith('refs/remotes/'):
1593 if b.startswith('refs/remotes/'):
1594 continue
1594 continue
1595 bname = b.split('/', 2)[2]
1595 bname = b.split('/', 2)[2]
1596 remote = self._gitcommand(['config', 'branch.%s.remote' % bname])
1596 remote = self._gitcommand(['config', 'branch.%s.remote' % bname])
1597 if remote:
1597 if remote:
1598 ref = self._gitcommand(['config', 'branch.%s.merge' % bname])
1598 ref = self._gitcommand(['config', 'branch.%s.merge' % bname])
1599 tracking['refs/remotes/%s/%s' %
1599 tracking['refs/remotes/%s/%s' %
1600 (remote, ref.split('/', 2)[2])] = b
1600 (remote, ref.split('/', 2)[2])] = b
1601 return tracking
1601 return tracking
1602
1602
1603 def _abssource(self, source):
1603 def _abssource(self, source):
1604 if '://' not in source:
1604 if '://' not in source:
1605 # recognize the scp syntax as an absolute source
1605 # recognize the scp syntax as an absolute source
1606 colon = source.find(':')
1606 colon = source.find(':')
1607 if colon != -1 and '/' not in source[:colon]:
1607 if colon != -1 and '/' not in source[:colon]:
1608 return source
1608 return source
1609 self._subsource = source
1609 self._subsource = source
1610 return _abssource(self)
1610 return _abssource(self)
1611
1611
1612 def _fetch(self, source, revision):
1612 def _fetch(self, source, revision):
1613 if self._gitmissing():
1613 if self._gitmissing():
1614 # SEC: check for safe ssh url
1614 # SEC: check for safe ssh url
1615 util.checksafessh(source)
1615 util.checksafessh(source)
1616
1616
1617 source = self._abssource(source)
1617 source = self._abssource(source)
1618 self.ui.status(_('cloning subrepo %s from %s\n') %
1618 self.ui.status(_('cloning subrepo %s from %s\n') %
1619 (self._relpath, source))
1619 (self._relpath, source))
1620 self._gitnodir(['clone', source, self._abspath])
1620 self._gitnodir(['clone', source, self._abspath])
1621 if self._githavelocally(revision):
1621 if self._githavelocally(revision):
1622 return
1622 return
1623 self.ui.status(_('pulling subrepo %s from %s\n') %
1623 self.ui.status(_('pulling subrepo %s from %s\n') %
1624 (self._relpath, self._gitremote('origin')))
1624 (self._relpath, self._gitremote('origin')))
1625 # try only origin: the originally cloned repo
1625 # try only origin: the originally cloned repo
1626 self._gitcommand(['fetch'])
1626 self._gitcommand(['fetch'])
1627 if not self._githavelocally(revision):
1627 if not self._githavelocally(revision):
1628 raise error.Abort(_('revision %s does not exist in subrepository '
1628 raise error.Abort(_('revision %s does not exist in subrepository '
1629 '"%s"\n') % (revision, self._relpath))
1629 '"%s"\n') % (revision, self._relpath))
1630
1630
1631 @annotatesubrepoerror
1631 @annotatesubrepoerror
1632 def dirty(self, ignoreupdate=False, missing=False):
1632 def dirty(self, ignoreupdate=False, missing=False):
1633 if self._gitmissing():
1633 if self._gitmissing():
1634 return self._state[1] != ''
1634 return self._state[1] != ''
1635 if self._gitisbare():
1635 if self._gitisbare():
1636 return True
1636 return True
1637 if not ignoreupdate and self._state[1] != self._gitstate():
1637 if not ignoreupdate and self._state[1] != self._gitstate():
1638 # different version checked out
1638 # different version checked out
1639 return True
1639 return True
1640 # check for staged changes or modified files; ignore untracked files
1640 # check for staged changes or modified files; ignore untracked files
1641 self._gitupdatestat()
1641 self._gitupdatestat()
1642 out, code = self._gitdir(['diff-index', '--quiet', 'HEAD'])
1642 out, code = self._gitdir(['diff-index', '--quiet', 'HEAD'])
1643 return code == 1
1643 return code == 1
1644
1644
1645 def basestate(self):
1645 def basestate(self):
1646 return self._gitstate()
1646 return self._gitstate()
1647
1647
1648 @annotatesubrepoerror
1648 @annotatesubrepoerror
1649 def get(self, state, overwrite=False):
1649 def get(self, state, overwrite=False):
1650 source, revision, kind = state
1650 source, revision, kind = state
1651 if not revision:
1651 if not revision:
1652 self.remove()
1652 self.remove()
1653 return
1653 return
1654 self._fetch(source, revision)
1654 self._fetch(source, revision)
1655 # if the repo was set to be bare, unbare it
1655 # if the repo was set to be bare, unbare it
1656 if self._gitisbare():
1656 if self._gitisbare():
1657 self._gitcommand(['config', 'core.bare', 'false'])
1657 self._gitcommand(['config', 'core.bare', 'false'])
1658 if self._gitstate() == revision:
1658 if self._gitstate() == revision:
1659 self._gitcommand(['reset', '--hard', 'HEAD'])
1659 self._gitcommand(['reset', '--hard', 'HEAD'])
1660 return
1660 return
1661 elif self._gitstate() == revision:
1661 elif self._gitstate() == revision:
1662 if overwrite:
1662 if overwrite:
1663 # first reset the index to unmark new files for commit, because
1663 # first reset the index to unmark new files for commit, because
1664 # reset --hard will otherwise throw away files added for commit,
1664 # reset --hard will otherwise throw away files added for commit,
1665 # not just unmark them.
1665 # not just unmark them.
1666 self._gitcommand(['reset', 'HEAD'])
1666 self._gitcommand(['reset', 'HEAD'])
1667 self._gitcommand(['reset', '--hard', 'HEAD'])
1667 self._gitcommand(['reset', '--hard', 'HEAD'])
1668 return
1668 return
1669 branch2rev, rev2branch = self._gitbranchmap()
1669 branch2rev, rev2branch = self._gitbranchmap()
1670
1670
1671 def checkout(args):
1671 def checkout(args):
1672 cmd = ['checkout']
1672 cmd = ['checkout']
1673 if overwrite:
1673 if overwrite:
1674 # first reset the index to unmark new files for commit, because
1674 # first reset the index to unmark new files for commit, because
1675 # the -f option will otherwise throw away files added for
1675 # the -f option will otherwise throw away files added for
1676 # commit, not just unmark them.
1676 # commit, not just unmark them.
1677 self._gitcommand(['reset', 'HEAD'])
1677 self._gitcommand(['reset', 'HEAD'])
1678 cmd.append('-f')
1678 cmd.append('-f')
1679 self._gitcommand(cmd + args)
1679 self._gitcommand(cmd + args)
1680 _sanitize(self.ui, self.wvfs, '.git')
1680 _sanitize(self.ui, self.wvfs, '.git')
1681
1681
1682 def rawcheckout():
1682 def rawcheckout():
1683 # no branch to checkout, check it out with no branch
1683 # no branch to checkout, check it out with no branch
1684 self.ui.warn(_('checking out detached HEAD in '
1684 self.ui.warn(_('checking out detached HEAD in '
1685 'subrepository "%s"\n') % self._relpath)
1685 'subrepository "%s"\n') % self._relpath)
1686 self.ui.warn(_('check out a git branch if you intend '
1686 self.ui.warn(_('check out a git branch if you intend '
1687 'to make changes\n'))
1687 'to make changes\n'))
1688 checkout(['-q', revision])
1688 checkout(['-q', revision])
1689
1689
1690 if revision not in rev2branch:
1690 if revision not in rev2branch:
1691 rawcheckout()
1691 rawcheckout()
1692 return
1692 return
1693 branches = rev2branch[revision]
1693 branches = rev2branch[revision]
1694 firstlocalbranch = None
1694 firstlocalbranch = None
1695 for b in branches:
1695 for b in branches:
1696 if b == 'refs/heads/master':
1696 if b == 'refs/heads/master':
1697 # master trumps all other branches
1697 # master trumps all other branches
1698 checkout(['refs/heads/master'])
1698 checkout(['refs/heads/master'])
1699 return
1699 return
1700 if not firstlocalbranch and not b.startswith('refs/remotes/'):
1700 if not firstlocalbranch and not b.startswith('refs/remotes/'):
1701 firstlocalbranch = b
1701 firstlocalbranch = b
1702 if firstlocalbranch:
1702 if firstlocalbranch:
1703 checkout([firstlocalbranch])
1703 checkout([firstlocalbranch])
1704 return
1704 return
1705
1705
1706 tracking = self._gittracking(branch2rev.keys())
1706 tracking = self._gittracking(branch2rev.keys())
1707 # choose a remote branch already tracked if possible
1707 # choose a remote branch already tracked if possible
1708 remote = branches[0]
1708 remote = branches[0]
1709 if remote not in tracking:
1709 if remote not in tracking:
1710 for b in branches:
1710 for b in branches:
1711 if b in tracking:
1711 if b in tracking:
1712 remote = b
1712 remote = b
1713 break
1713 break
1714
1714
1715 if remote not in tracking:
1715 if remote not in tracking:
1716 # create a new local tracking branch
1716 # create a new local tracking branch
1717 local = remote.split('/', 3)[3]
1717 local = remote.split('/', 3)[3]
1718 checkout(['-b', local, remote])
1718 checkout(['-b', local, remote])
1719 elif self._gitisancestor(branch2rev[tracking[remote]], remote):
1719 elif self._gitisancestor(branch2rev[tracking[remote]], remote):
1720 # When updating to a tracked remote branch,
1720 # When updating to a tracked remote branch,
1721 # if the local tracking branch is downstream of it,
1721 # if the local tracking branch is downstream of it,
1722 # a normal `git pull` would have performed a "fast-forward merge"
1722 # a normal `git pull` would have performed a "fast-forward merge"
1723 # which is equivalent to updating the local branch to the remote.
1723 # which is equivalent to updating the local branch to the remote.
1724 # Since we are only looking at branching at update, we need to
1724 # Since we are only looking at branching at update, we need to
1725 # detect this situation and perform this action lazily.
1725 # detect this situation and perform this action lazily.
1726 if tracking[remote] != self._gitcurrentbranch():
1726 if tracking[remote] != self._gitcurrentbranch():
1727 checkout([tracking[remote]])
1727 checkout([tracking[remote]])
1728 self._gitcommand(['merge', '--ff', remote])
1728 self._gitcommand(['merge', '--ff', remote])
1729 _sanitize(self.ui, self.wvfs, '.git')
1729 _sanitize(self.ui, self.wvfs, '.git')
1730 else:
1730 else:
1731 # a real merge would be required, just checkout the revision
1731 # a real merge would be required, just checkout the revision
1732 rawcheckout()
1732 rawcheckout()
1733
1733
1734 @annotatesubrepoerror
1734 @annotatesubrepoerror
1735 def commit(self, text, user, date):
1735 def commit(self, text, user, date):
1736 if self._gitmissing():
1736 if self._gitmissing():
1737 raise error.Abort(_("subrepo %s is missing") % self._relpath)
1737 raise error.Abort(_("subrepo %s is missing") % self._relpath)
1738 cmd = ['commit', '-a', '-m', text]
1738 cmd = ['commit', '-a', '-m', text]
1739 env = encoding.environ.copy()
1739 env = encoding.environ.copy()
1740 if user:
1740 if user:
1741 cmd += ['--author', user]
1741 cmd += ['--author', user]
1742 if date:
1742 if date:
1743 # git's date parser silently ignores when seconds < 1e9
1743 # git's date parser silently ignores when seconds < 1e9
1744 # convert to ISO8601
1744 # convert to ISO8601
1745 env['GIT_AUTHOR_DATE'] = util.datestr(date,
1745 env['GIT_AUTHOR_DATE'] = util.datestr(date,
1746 '%Y-%m-%dT%H:%M:%S %1%2')
1746 '%Y-%m-%dT%H:%M:%S %1%2')
1747 self._gitcommand(cmd, env=env)
1747 self._gitcommand(cmd, env=env)
1748 # make sure commit works otherwise HEAD might not exist under certain
1748 # make sure commit works otherwise HEAD might not exist under certain
1749 # circumstances
1749 # circumstances
1750 return self._gitstate()
1750 return self._gitstate()
1751
1751
1752 @annotatesubrepoerror
1752 @annotatesubrepoerror
1753 def merge(self, state):
1753 def merge(self, state):
1754 source, revision, kind = state
1754 source, revision, kind = state
1755 self._fetch(source, revision)
1755 self._fetch(source, revision)
1756 base = self._gitcommand(['merge-base', revision, self._state[1]])
1756 base = self._gitcommand(['merge-base', revision, self._state[1]])
1757 self._gitupdatestat()
1757 self._gitupdatestat()
1758 out, code = self._gitdir(['diff-index', '--quiet', 'HEAD'])
1758 out, code = self._gitdir(['diff-index', '--quiet', 'HEAD'])
1759
1759
1760 def mergefunc():
1760 def mergefunc():
1761 if base == revision:
1761 if base == revision:
1762 self.get(state) # fast forward merge
1762 self.get(state) # fast forward merge
1763 elif base != self._state[1]:
1763 elif base != self._state[1]:
1764 self._gitcommand(['merge', '--no-commit', revision])
1764 self._gitcommand(['merge', '--no-commit', revision])
1765 _sanitize(self.ui, self.wvfs, '.git')
1765 _sanitize(self.ui, self.wvfs, '.git')
1766
1766
1767 if self.dirty():
1767 if self.dirty():
1768 if self._gitstate() != revision:
1768 if self._gitstate() != revision:
1769 dirty = self._gitstate() == self._state[1] or code != 0
1769 dirty = self._gitstate() == self._state[1] or code != 0
1770 if _updateprompt(self.ui, self, dirty,
1770 if _updateprompt(self.ui, self, dirty,
1771 self._state[1][:7], revision[:7]):
1771 self._state[1][:7], revision[:7]):
1772 mergefunc()
1772 mergefunc()
1773 else:
1773 else:
1774 mergefunc()
1774 mergefunc()
1775
1775
1776 @annotatesubrepoerror
1776 @annotatesubrepoerror
1777 def push(self, opts):
1777 def push(self, opts):
1778 force = opts.get('force')
1778 force = opts.get('force')
1779
1779
1780 if not self._state[1]:
1780 if not self._state[1]:
1781 return True
1781 return True
1782 if self._gitmissing():
1782 if self._gitmissing():
1783 raise error.Abort(_("subrepo %s is missing") % self._relpath)
1783 raise error.Abort(_("subrepo %s is missing") % self._relpath)
1784 # if a branch in origin contains the revision, nothing to do
1784 # if a branch in origin contains the revision, nothing to do
1785 branch2rev, rev2branch = self._gitbranchmap()
1785 branch2rev, rev2branch = self._gitbranchmap()
1786 if self._state[1] in rev2branch:
1786 if self._state[1] in rev2branch:
1787 for b in rev2branch[self._state[1]]:
1787 for b in rev2branch[self._state[1]]:
1788 if b.startswith('refs/remotes/origin/'):
1788 if b.startswith('refs/remotes/origin/'):
1789 return True
1789 return True
1790 for b, revision in branch2rev.iteritems():
1790 for b, revision in branch2rev.iteritems():
1791 if b.startswith('refs/remotes/origin/'):
1791 if b.startswith('refs/remotes/origin/'):
1792 if self._gitisancestor(self._state[1], revision):
1792 if self._gitisancestor(self._state[1], revision):
1793 return True
1793 return True
1794 # otherwise, try to push the currently checked out branch
1794 # otherwise, try to push the currently checked out branch
1795 cmd = ['push']
1795 cmd = ['push']
1796 if force:
1796 if force:
1797 cmd.append('--force')
1797 cmd.append('--force')
1798
1798
1799 current = self._gitcurrentbranch()
1799 current = self._gitcurrentbranch()
1800 if current:
1800 if current:
1801 # determine if the current branch is even useful
1801 # determine if the current branch is even useful
1802 if not self._gitisancestor(self._state[1], current):
1802 if not self._gitisancestor(self._state[1], current):
1803 self.ui.warn(_('unrelated git branch checked out '
1803 self.ui.warn(_('unrelated git branch checked out '
1804 'in subrepository "%s"\n') % self._relpath)
1804 'in subrepository "%s"\n') % self._relpath)
1805 return False
1805 return False
1806 self.ui.status(_('pushing branch %s of subrepository "%s"\n') %
1806 self.ui.status(_('pushing branch %s of subrepository "%s"\n') %
1807 (current.split('/', 2)[2], self._relpath))
1807 (current.split('/', 2)[2], self._relpath))
1808 ret = self._gitdir(cmd + ['origin', current])
1808 ret = self._gitdir(cmd + ['origin', current])
1809 return ret[1] == 0
1809 return ret[1] == 0
1810 else:
1810 else:
1811 self.ui.warn(_('no branch checked out in subrepository "%s"\n'
1811 self.ui.warn(_('no branch checked out in subrepository "%s"\n'
1812 'cannot push revision %s\n') %
1812 'cannot push revision %s\n') %
1813 (self._relpath, self._state[1]))
1813 (self._relpath, self._state[1]))
1814 return False
1814 return False
1815
1815
1816 @annotatesubrepoerror
1816 @annotatesubrepoerror
1817 def add(self, ui, match, prefix, explicitonly, **opts):
1817 def add(self, ui, match, prefix, explicitonly, **opts):
1818 if self._gitmissing():
1818 if self._gitmissing():
1819 return []
1819 return []
1820
1820
1821 (modified, added, removed,
1821 (modified, added, removed,
1822 deleted, unknown, ignored, clean) = self.status(None, unknown=True,
1822 deleted, unknown, ignored, clean) = self.status(None, unknown=True,
1823 clean=True)
1823 clean=True)
1824
1824
1825 tracked = set()
1825 tracked = set()
1826 # dirstates 'amn' warn, 'r' is added again
1826 # dirstates 'amn' warn, 'r' is added again
1827 for l in (modified, added, deleted, clean):
1827 for l in (modified, added, deleted, clean):
1828 tracked.update(l)
1828 tracked.update(l)
1829
1829
1830 # Unknown files not of interest will be rejected by the matcher
1830 # Unknown files not of interest will be rejected by the matcher
1831 files = unknown
1831 files = unknown
1832 files.extend(match.files())
1832 files.extend(match.files())
1833
1833
1834 rejected = []
1834 rejected = []
1835
1835
1836 files = [f for f in sorted(set(files)) if match(f)]
1836 files = [f for f in sorted(set(files)) if match(f)]
1837 for f in files:
1837 for f in files:
1838 exact = match.exact(f)
1838 exact = match.exact(f)
1839 command = ["add"]
1839 command = ["add"]
1840 if exact:
1840 if exact:
1841 command.append("-f") #should be added, even if ignored
1841 command.append("-f") #should be added, even if ignored
1842 if ui.verbose or not exact:
1842 if ui.verbose or not exact:
1843 ui.status(_('adding %s\n') % match.rel(f))
1843 ui.status(_('adding %s\n') % match.rel(f))
1844
1844
1845 if f in tracked: # hg prints 'adding' even if already tracked
1845 if f in tracked: # hg prints 'adding' even if already tracked
1846 if exact:
1846 if exact:
1847 rejected.append(f)
1847 rejected.append(f)
1848 continue
1848 continue
1849 if not opts.get(r'dry_run'):
1849 if not opts.get(r'dry_run'):
1850 self._gitcommand(command + [f])
1850 self._gitcommand(command + [f])
1851
1851
1852 for f in rejected:
1852 for f in rejected:
1853 ui.warn(_("%s already tracked!\n") % match.abs(f))
1853 ui.warn(_("%s already tracked!\n") % match.abs(f))
1854
1854
1855 return rejected
1855 return rejected
1856
1856
1857 @annotatesubrepoerror
1857 @annotatesubrepoerror
1858 def remove(self):
1858 def remove(self):
1859 if self._gitmissing():
1859 if self._gitmissing():
1860 return
1860 return
1861 if self.dirty():
1861 if self.dirty():
1862 self.ui.warn(_('not removing repo %s because '
1862 self.ui.warn(_('not removing repo %s because '
1863 'it has changes.\n') % self._relpath)
1863 'it has changes.\n') % self._relpath)
1864 return
1864 return
1865 # we can't fully delete the repository as it may contain
1865 # we can't fully delete the repository as it may contain
1866 # local-only history
1866 # local-only history
1867 self.ui.note(_('removing subrepo %s\n') % self._relpath)
1867 self.ui.note(_('removing subrepo %s\n') % self._relpath)
1868 self._gitcommand(['config', 'core.bare', 'true'])
1868 self._gitcommand(['config', 'core.bare', 'true'])
1869 for f, kind in self.wvfs.readdir():
1869 for f, kind in self.wvfs.readdir():
1870 if f == '.git':
1870 if f == '.git':
1871 continue
1871 continue
1872 if kind == stat.S_IFDIR:
1872 if kind == stat.S_IFDIR:
1873 self.wvfs.rmtree(f)
1873 self.wvfs.rmtree(f)
1874 else:
1874 else:
1875 self.wvfs.unlink(f)
1875 self.wvfs.unlink(f)
1876
1876
1877 def archive(self, archiver, prefix, match=None, decode=True):
1877 def archive(self, archiver, prefix, match=None, decode=True):
1878 total = 0
1878 total = 0
1879 source, revision = self._state
1879 source, revision = self._state
1880 if not revision:
1880 if not revision:
1881 return total
1881 return total
1882 self._fetch(source, revision)
1882 self._fetch(source, revision)
1883
1883
1884 # Parse git's native archive command.
1884 # Parse git's native archive command.
1885 # This should be much faster than manually traversing the trees
1885 # This should be much faster than manually traversing the trees
1886 # and objects with many subprocess calls.
1886 # and objects with many subprocess calls.
1887 tarstream = self._gitcommand(['archive', revision], stream=True)
1887 tarstream = self._gitcommand(['archive', revision], stream=True)
1888 tar = tarfile.open(fileobj=tarstream, mode='r|')
1888 tar = tarfile.open(fileobj=tarstream, mode='r|')
1889 relpath = subrelpath(self)
1889 relpath = subrelpath(self)
1890 self.ui.progress(_('archiving (%s)') % relpath, 0, unit=_('files'))
1890 self.ui.progress(_('archiving (%s)') % relpath, 0, unit=_('files'))
1891 for i, info in enumerate(tar):
1891 for i, info in enumerate(tar):
1892 if info.isdir():
1892 if info.isdir():
1893 continue
1893 continue
1894 if match and not match(info.name):
1894 if match and not match(info.name):
1895 continue
1895 continue
1896 if info.issym():
1896 if info.issym():
1897 data = info.linkname
1897 data = info.linkname
1898 else:
1898 else:
1899 data = tar.extractfile(info).read()
1899 data = tar.extractfile(info).read()
1900 archiver.addfile(prefix + self._path + '/' + info.name,
1900 archiver.addfile(prefix + self._path + '/' + info.name,
1901 info.mode, info.issym(), data)
1901 info.mode, info.issym(), data)
1902 total += 1
1902 total += 1
1903 self.ui.progress(_('archiving (%s)') % relpath, i + 1,
1903 self.ui.progress(_('archiving (%s)') % relpath, i + 1,
1904 unit=_('files'))
1904 unit=_('files'))
1905 self.ui.progress(_('archiving (%s)') % relpath, None)
1905 self.ui.progress(_('archiving (%s)') % relpath, None)
1906 return total
1906 return total
1907
1907
1908
1908
1909 @annotatesubrepoerror
1909 @annotatesubrepoerror
1910 def cat(self, match, fm, fntemplate, prefix, **opts):
1910 def cat(self, match, fm, fntemplate, prefix, **opts):
1911 rev = self._state[1]
1911 rev = self._state[1]
1912 if match.anypats():
1912 if match.anypats():
1913 return 1 #No support for include/exclude yet
1913 return 1 #No support for include/exclude yet
1914
1914
1915 if not match.files():
1915 if not match.files():
1916 return 1
1916 return 1
1917
1917
1918 # TODO: add support for non-plain formatter (see cmdutil.cat())
1918 # TODO: add support for non-plain formatter (see cmdutil.cat())
1919 for f in match.files():
1919 for f in match.files():
1920 output = self._gitcommand(["show", "%s:%s" % (rev, f)])
1920 output = self._gitcommand(["show", "%s:%s" % (rev, f)])
1921 fp = cmdutil.makefileobj(self._subparent, fntemplate,
1921 fp = cmdutil.makefileobj(self._subparent, fntemplate,
1922 self._ctx.node(),
1922 self._ctx.node(),
1923 pathname=self.wvfs.reljoin(prefix, f))
1923 pathname=self.wvfs.reljoin(prefix, f))
1924 fp.write(output)
1924 fp.write(output)
1925 fp.close()
1925 fp.close()
1926 return 0
1926 return 0
1927
1927
1928
1928
1929 @annotatesubrepoerror
1929 @annotatesubrepoerror
1930 def status(self, rev2, **opts):
1930 def status(self, rev2, **opts):
1931 rev1 = self._state[1]
1931 rev1 = self._state[1]
1932 if self._gitmissing() or not rev1:
1932 if self._gitmissing() or not rev1:
1933 # if the repo is missing, return no results
1933 # if the repo is missing, return no results
1934 return scmutil.status([], [], [], [], [], [], [])
1934 return scmutil.status([], [], [], [], [], [], [])
1935 modified, added, removed = [], [], []
1935 modified, added, removed = [], [], []
1936 self._gitupdatestat()
1936 self._gitupdatestat()
1937 if rev2:
1937 if rev2:
1938 command = ['diff-tree', '--no-renames', '-r', rev1, rev2]
1938 command = ['diff-tree', '--no-renames', '-r', rev1, rev2]
1939 else:
1939 else:
1940 command = ['diff-index', '--no-renames', rev1]
1940 command = ['diff-index', '--no-renames', rev1]
1941 out = self._gitcommand(command)
1941 out = self._gitcommand(command)
1942 for line in out.split('\n'):
1942 for line in out.split('\n'):
1943 tab = line.find('\t')
1943 tab = line.find('\t')
1944 if tab == -1:
1944 if tab == -1:
1945 continue
1945 continue
1946 status, f = line[tab - 1], line[tab + 1:]
1946 status, f = line[tab - 1], line[tab + 1:]
1947 if status == 'M':
1947 if status == 'M':
1948 modified.append(f)
1948 modified.append(f)
1949 elif status == 'A':
1949 elif status == 'A':
1950 added.append(f)
1950 added.append(f)
1951 elif status == 'D':
1951 elif status == 'D':
1952 removed.append(f)
1952 removed.append(f)
1953
1953
1954 deleted, unknown, ignored, clean = [], [], [], []
1954 deleted, unknown, ignored, clean = [], [], [], []
1955
1955
1956 command = ['status', '--porcelain', '-z']
1956 command = ['status', '--porcelain', '-z']
1957 if opts.get(r'unknown'):
1957 if opts.get(r'unknown'):
1958 command += ['--untracked-files=all']
1958 command += ['--untracked-files=all']
1959 if opts.get(r'ignored'):
1959 if opts.get(r'ignored'):
1960 command += ['--ignored']
1960 command += ['--ignored']
1961 out = self._gitcommand(command)
1961 out = self._gitcommand(command)
1962
1962
1963 changedfiles = set()
1963 changedfiles = set()
1964 changedfiles.update(modified)
1964 changedfiles.update(modified)
1965 changedfiles.update(added)
1965 changedfiles.update(added)
1966 changedfiles.update(removed)
1966 changedfiles.update(removed)
1967 for line in out.split('\0'):
1967 for line in out.split('\0'):
1968 if not line:
1968 if not line:
1969 continue
1969 continue
1970 st = line[0:2]
1970 st = line[0:2]
1971 #moves and copies show 2 files on one line
1971 #moves and copies show 2 files on one line
1972 if line.find('\0') >= 0:
1972 if line.find('\0') >= 0:
1973 filename1, filename2 = line[3:].split('\0')
1973 filename1, filename2 = line[3:].split('\0')
1974 else:
1974 else:
1975 filename1 = line[3:]
1975 filename1 = line[3:]
1976 filename2 = None
1976 filename2 = None
1977
1977
1978 changedfiles.add(filename1)
1978 changedfiles.add(filename1)
1979 if filename2:
1979 if filename2:
1980 changedfiles.add(filename2)
1980 changedfiles.add(filename2)
1981
1981
1982 if st == '??':
1982 if st == '??':
1983 unknown.append(filename1)
1983 unknown.append(filename1)
1984 elif st == '!!':
1984 elif st == '!!':
1985 ignored.append(filename1)
1985 ignored.append(filename1)
1986
1986
1987 if opts.get(r'clean'):
1987 if opts.get(r'clean'):
1988 out = self._gitcommand(['ls-files'])
1988 out = self._gitcommand(['ls-files'])
1989 for f in out.split('\n'):
1989 for f in out.split('\n'):
1990 if not f in changedfiles:
1990 if not f in changedfiles:
1991 clean.append(f)
1991 clean.append(f)
1992
1992
1993 return scmutil.status(modified, added, removed, deleted,
1993 return scmutil.status(modified, added, removed, deleted,
1994 unknown, ignored, clean)
1994 unknown, ignored, clean)
1995
1995
1996 @annotatesubrepoerror
1996 @annotatesubrepoerror
1997 def diff(self, ui, diffopts, node2, match, prefix, **opts):
1997 def diff(self, ui, diffopts, node2, match, prefix, **opts):
1998 node1 = self._state[1]
1998 node1 = self._state[1]
1999 cmd = ['diff', '--no-renames']
1999 cmd = ['diff', '--no-renames']
2000 if opts[r'stat']:
2000 if opts[r'stat']:
2001 cmd.append('--stat')
2001 cmd.append('--stat')
2002 else:
2002 else:
2003 # for Git, this also implies '-p'
2003 # for Git, this also implies '-p'
2004 cmd.append('-U%d' % diffopts.context)
2004 cmd.append('-U%d' % diffopts.context)
2005
2005
2006 gitprefix = self.wvfs.reljoin(prefix, self._path)
2006 gitprefix = self.wvfs.reljoin(prefix, self._path)
2007
2007
2008 if diffopts.noprefix:
2008 if diffopts.noprefix:
2009 cmd.extend(['--src-prefix=%s/' % gitprefix,
2009 cmd.extend(['--src-prefix=%s/' % gitprefix,
2010 '--dst-prefix=%s/' % gitprefix])
2010 '--dst-prefix=%s/' % gitprefix])
2011 else:
2011 else:
2012 cmd.extend(['--src-prefix=a/%s/' % gitprefix,
2012 cmd.extend(['--src-prefix=a/%s/' % gitprefix,
2013 '--dst-prefix=b/%s/' % gitprefix])
2013 '--dst-prefix=b/%s/' % gitprefix])
2014
2014
2015 if diffopts.ignorews:
2015 if diffopts.ignorews:
2016 cmd.append('--ignore-all-space')
2016 cmd.append('--ignore-all-space')
2017 if diffopts.ignorewsamount:
2017 if diffopts.ignorewsamount:
2018 cmd.append('--ignore-space-change')
2018 cmd.append('--ignore-space-change')
2019 if self._gitversion(self._gitcommand(['--version'])) >= (1, 8, 4) \
2019 if self._gitversion(self._gitcommand(['--version'])) >= (1, 8, 4) \
2020 and diffopts.ignoreblanklines:
2020 and diffopts.ignoreblanklines:
2021 cmd.append('--ignore-blank-lines')
2021 cmd.append('--ignore-blank-lines')
2022
2022
2023 cmd.append(node1)
2023 cmd.append(node1)
2024 if node2:
2024 if node2:
2025 cmd.append(node2)
2025 cmd.append(node2)
2026
2026
2027 output = ""
2027 output = ""
2028 if match.always():
2028 if match.always():
2029 output += self._gitcommand(cmd) + '\n'
2029 output += self._gitcommand(cmd) + '\n'
2030 else:
2030 else:
2031 st = self.status(node2)[:3]
2031 st = self.status(node2)[:3]
2032 files = [f for sublist in st for f in sublist]
2032 files = [f for sublist in st for f in sublist]
2033 for f in files:
2033 for f in files:
2034 if match(f):
2034 if match(f):
2035 output += self._gitcommand(cmd + ['--', f]) + '\n'
2035 output += self._gitcommand(cmd + ['--', f]) + '\n'
2036
2036
2037 if output.strip():
2037 if output.strip():
2038 ui.write(output)
2038 ui.write(output)
2039
2039
2040 @annotatesubrepoerror
2040 @annotatesubrepoerror
2041 def revert(self, substate, *pats, **opts):
2041 def revert(self, substate, *pats, **opts):
2042 self.ui.status(_('reverting subrepo %s\n') % substate[0])
2042 self.ui.status(_('reverting subrepo %s\n') % substate[0])
2043 if not opts.get(r'no_backup'):
2043 if not opts.get(r'no_backup'):
2044 status = self.status(None)
2044 status = self.status(None)
2045 names = status.modified
2045 names = status.modified
2046 for name in names:
2046 for name in names:
2047 bakname = scmutil.origpath(self.ui, self._subparent, name)
2047 bakname = scmutil.origpath(self.ui, self._subparent, name)
2048 self.ui.note(_('saving current version of %s as %s\n') %
2048 self.ui.note(_('saving current version of %s as %s\n') %
2049 (name, bakname))
2049 (name, bakname))
2050 self.wvfs.rename(name, bakname)
2050 self.wvfs.rename(name, bakname)
2051
2051
2052 if not opts.get(r'dry_run'):
2052 if not opts.get(r'dry_run'):
2053 self.get(substate, overwrite=True)
2053 self.get(substate, overwrite=True)
2054 return []
2054 return []
2055
2055
2056 def shortid(self, revid):
2056 def shortid(self, revid):
2057 return revid[:7]
2057 return revid[:7]
2058
2058
2059 types = {
2059 types = {
2060 'hg': hgsubrepo,
2060 'hg': hgsubrepo,
2061 'svn': svnsubrepo,
2061 'svn': svnsubrepo,
2062 'git': gitsubrepo,
2062 'git': gitsubrepo,
2063 }
2063 }
General Comments 0
You need to be logged in to leave comments. Login now