##// END OF EJS Templates
bundle: extract the parsing of the bundle type in a function...
Pierre-Yves David -
r26510:77c13f3c default
parent child Browse files
Show More
@@ -1,3332 +1,3349 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 node import hex, bin, nullid, nullrev, short
8 from node import hex, bin, nullid, nullrev, short
9 from i18n import _
9 from i18n import _
10 import os, sys, errno, re, tempfile, cStringIO, shutil
10 import os, sys, errno, re, tempfile, cStringIO, shutil
11 import util, scmutil, templater, patch, error, templatekw, revlog, copies
11 import util, scmutil, templater, patch, error, templatekw, revlog, copies
12 import match as matchmod
12 import match as matchmod
13 import repair, graphmod, revset, phases, obsolete, pathutil
13 import repair, graphmod, revset, phases, obsolete, pathutil, changegroup
14 import changelog
14 import changelog
15 import bookmarks
15 import bookmarks
16 import encoding
16 import encoding
17 import formatter
17 import formatter
18 import crecord as crecordmod
18 import crecord as crecordmod
19 import lock as lockmod
19 import lock as lockmod
20
20
21 def ishunk(x):
21 def ishunk(x):
22 hunkclasses = (crecordmod.uihunk, patch.recordhunk)
22 hunkclasses = (crecordmod.uihunk, patch.recordhunk)
23 return isinstance(x, hunkclasses)
23 return isinstance(x, hunkclasses)
24
24
25 def newandmodified(chunks, originalchunks):
25 def newandmodified(chunks, originalchunks):
26 newlyaddedandmodifiedfiles = set()
26 newlyaddedandmodifiedfiles = set()
27 for chunk in chunks:
27 for chunk in chunks:
28 if ishunk(chunk) and chunk.header.isnewfile() and chunk not in \
28 if ishunk(chunk) and chunk.header.isnewfile() and chunk not in \
29 originalchunks:
29 originalchunks:
30 newlyaddedandmodifiedfiles.add(chunk.header.filename())
30 newlyaddedandmodifiedfiles.add(chunk.header.filename())
31 return newlyaddedandmodifiedfiles
31 return newlyaddedandmodifiedfiles
32
32
33 def parsealiases(cmd):
33 def parsealiases(cmd):
34 return cmd.lstrip("^").split("|")
34 return cmd.lstrip("^").split("|")
35
35
36 def setupwrapcolorwrite(ui):
36 def setupwrapcolorwrite(ui):
37 # wrap ui.write so diff output can be labeled/colorized
37 # wrap ui.write so diff output can be labeled/colorized
38 def wrapwrite(orig, *args, **kw):
38 def wrapwrite(orig, *args, **kw):
39 label = kw.pop('label', '')
39 label = kw.pop('label', '')
40 for chunk, l in patch.difflabel(lambda: args):
40 for chunk, l in patch.difflabel(lambda: args):
41 orig(chunk, label=label + l)
41 orig(chunk, label=label + l)
42
42
43 oldwrite = ui.write
43 oldwrite = ui.write
44 def wrap(*args, **kwargs):
44 def wrap(*args, **kwargs):
45 return wrapwrite(oldwrite, *args, **kwargs)
45 return wrapwrite(oldwrite, *args, **kwargs)
46 setattr(ui, 'write', wrap)
46 setattr(ui, 'write', wrap)
47 return oldwrite
47 return oldwrite
48
48
49 def filterchunks(ui, originalhunks, usecurses, testfile, operation=None):
49 def filterchunks(ui, originalhunks, usecurses, testfile, operation=None):
50 if usecurses:
50 if usecurses:
51 if testfile:
51 if testfile:
52 recordfn = crecordmod.testdecorator(testfile,
52 recordfn = crecordmod.testdecorator(testfile,
53 crecordmod.testchunkselector)
53 crecordmod.testchunkselector)
54 else:
54 else:
55 recordfn = crecordmod.chunkselector
55 recordfn = crecordmod.chunkselector
56
56
57 return crecordmod.filterpatch(ui, originalhunks, recordfn, operation)
57 return crecordmod.filterpatch(ui, originalhunks, recordfn, operation)
58
58
59 else:
59 else:
60 return patch.filterpatch(ui, originalhunks, operation)
60 return patch.filterpatch(ui, originalhunks, operation)
61
61
62 def recordfilter(ui, originalhunks, operation=None):
62 def recordfilter(ui, originalhunks, operation=None):
63 """ Prompts the user to filter the originalhunks and return a list of
63 """ Prompts the user to filter the originalhunks and return a list of
64 selected hunks.
64 selected hunks.
65 *operation* is used for ui purposes to indicate the user
65 *operation* is used for ui purposes to indicate the user
66 what kind of filtering they are doing: reverting, commiting, shelving, etc.
66 what kind of filtering they are doing: reverting, commiting, shelving, etc.
67 *operation* has to be a translated string.
67 *operation* has to be a translated string.
68 """
68 """
69 usecurses = ui.configbool('experimental', 'crecord', False)
69 usecurses = ui.configbool('experimental', 'crecord', False)
70 testfile = ui.config('experimental', 'crecordtest', None)
70 testfile = ui.config('experimental', 'crecordtest', None)
71 oldwrite = setupwrapcolorwrite(ui)
71 oldwrite = setupwrapcolorwrite(ui)
72 try:
72 try:
73 newchunks = filterchunks(ui, originalhunks, usecurses, testfile,
73 newchunks = filterchunks(ui, originalhunks, usecurses, testfile,
74 operation)
74 operation)
75 finally:
75 finally:
76 ui.write = oldwrite
76 ui.write = oldwrite
77 return newchunks
77 return newchunks
78
78
79 def dorecord(ui, repo, commitfunc, cmdsuggest, backupall,
79 def dorecord(ui, repo, commitfunc, cmdsuggest, backupall,
80 filterfn, *pats, **opts):
80 filterfn, *pats, **opts):
81 import merge as mergemod
81 import merge as mergemod
82
82
83 if not ui.interactive():
83 if not ui.interactive():
84 if cmdsuggest:
84 if cmdsuggest:
85 msg = _('running non-interactively, use %s instead') % cmdsuggest
85 msg = _('running non-interactively, use %s instead') % cmdsuggest
86 else:
86 else:
87 msg = _('running non-interactively')
87 msg = _('running non-interactively')
88 raise util.Abort(msg)
88 raise util.Abort(msg)
89
89
90 # make sure username is set before going interactive
90 # make sure username is set before going interactive
91 if not opts.get('user'):
91 if not opts.get('user'):
92 ui.username() # raise exception, username not provided
92 ui.username() # raise exception, username not provided
93
93
94 def recordfunc(ui, repo, message, match, opts):
94 def recordfunc(ui, repo, message, match, opts):
95 """This is generic record driver.
95 """This is generic record driver.
96
96
97 Its job is to interactively filter local changes, and
97 Its job is to interactively filter local changes, and
98 accordingly prepare working directory into a state in which the
98 accordingly prepare working directory into a state in which the
99 job can be delegated to a non-interactive commit command such as
99 job can be delegated to a non-interactive commit command such as
100 'commit' or 'qrefresh'.
100 'commit' or 'qrefresh'.
101
101
102 After the actual job is done by non-interactive command, the
102 After the actual job is done by non-interactive command, the
103 working directory is restored to its original state.
103 working directory is restored to its original state.
104
104
105 In the end we'll record interesting changes, and everything else
105 In the end we'll record interesting changes, and everything else
106 will be left in place, so the user can continue working.
106 will be left in place, so the user can continue working.
107 """
107 """
108
108
109 checkunfinished(repo, commit=True)
109 checkunfinished(repo, commit=True)
110 merge = len(repo[None].parents()) > 1
110 merge = len(repo[None].parents()) > 1
111 if merge:
111 if merge:
112 raise util.Abort(_('cannot partially commit a merge '
112 raise util.Abort(_('cannot partially commit a merge '
113 '(use "hg commit" instead)'))
113 '(use "hg commit" instead)'))
114
114
115 status = repo.status(match=match)
115 status = repo.status(match=match)
116 diffopts = patch.difffeatureopts(ui, opts=opts, whitespace=True)
116 diffopts = patch.difffeatureopts(ui, opts=opts, whitespace=True)
117 diffopts.nodates = True
117 diffopts.nodates = True
118 diffopts.git = True
118 diffopts.git = True
119 originaldiff = patch.diff(repo, changes=status, opts=diffopts)
119 originaldiff = patch.diff(repo, changes=status, opts=diffopts)
120 originalchunks = patch.parsepatch(originaldiff)
120 originalchunks = patch.parsepatch(originaldiff)
121
121
122 # 1. filter patch, so we have intending-to apply subset of it
122 # 1. filter patch, so we have intending-to apply subset of it
123 try:
123 try:
124 chunks = filterfn(ui, originalchunks)
124 chunks = filterfn(ui, originalchunks)
125 except patch.PatchError as err:
125 except patch.PatchError as err:
126 raise util.Abort(_('error parsing patch: %s') % err)
126 raise util.Abort(_('error parsing patch: %s') % err)
127
127
128 # We need to keep a backup of files that have been newly added and
128 # We need to keep a backup of files that have been newly added and
129 # modified during the recording process because there is a previous
129 # modified during the recording process because there is a previous
130 # version without the edit in the workdir
130 # version without the edit in the workdir
131 newlyaddedandmodifiedfiles = newandmodified(chunks, originalchunks)
131 newlyaddedandmodifiedfiles = newandmodified(chunks, originalchunks)
132 contenders = set()
132 contenders = set()
133 for h in chunks:
133 for h in chunks:
134 try:
134 try:
135 contenders.update(set(h.files()))
135 contenders.update(set(h.files()))
136 except AttributeError:
136 except AttributeError:
137 pass
137 pass
138
138
139 changed = status.modified + status.added + status.removed
139 changed = status.modified + status.added + status.removed
140 newfiles = [f for f in changed if f in contenders]
140 newfiles = [f for f in changed if f in contenders]
141 if not newfiles:
141 if not newfiles:
142 ui.status(_('no changes to record\n'))
142 ui.status(_('no changes to record\n'))
143 return 0
143 return 0
144
144
145 modified = set(status.modified)
145 modified = set(status.modified)
146
146
147 # 2. backup changed files, so we can restore them in the end
147 # 2. backup changed files, so we can restore them in the end
148
148
149 if backupall:
149 if backupall:
150 tobackup = changed
150 tobackup = changed
151 else:
151 else:
152 tobackup = [f for f in newfiles if f in modified or f in \
152 tobackup = [f for f in newfiles if f in modified or f in \
153 newlyaddedandmodifiedfiles]
153 newlyaddedandmodifiedfiles]
154 backups = {}
154 backups = {}
155 if tobackup:
155 if tobackup:
156 backupdir = repo.join('record-backups')
156 backupdir = repo.join('record-backups')
157 try:
157 try:
158 os.mkdir(backupdir)
158 os.mkdir(backupdir)
159 except OSError as err:
159 except OSError as err:
160 if err.errno != errno.EEXIST:
160 if err.errno != errno.EEXIST:
161 raise
161 raise
162 try:
162 try:
163 # backup continues
163 # backup continues
164 for f in tobackup:
164 for f in tobackup:
165 fd, tmpname = tempfile.mkstemp(prefix=f.replace('/', '_')+'.',
165 fd, tmpname = tempfile.mkstemp(prefix=f.replace('/', '_')+'.',
166 dir=backupdir)
166 dir=backupdir)
167 os.close(fd)
167 os.close(fd)
168 ui.debug('backup %r as %r\n' % (f, tmpname))
168 ui.debug('backup %r as %r\n' % (f, tmpname))
169 util.copyfile(repo.wjoin(f), tmpname)
169 util.copyfile(repo.wjoin(f), tmpname)
170 shutil.copystat(repo.wjoin(f), tmpname)
170 shutil.copystat(repo.wjoin(f), tmpname)
171 backups[f] = tmpname
171 backups[f] = tmpname
172
172
173 fp = cStringIO.StringIO()
173 fp = cStringIO.StringIO()
174 for c in chunks:
174 for c in chunks:
175 fname = c.filename()
175 fname = c.filename()
176 if fname in backups:
176 if fname in backups:
177 c.write(fp)
177 c.write(fp)
178 dopatch = fp.tell()
178 dopatch = fp.tell()
179 fp.seek(0)
179 fp.seek(0)
180
180
181 [os.unlink(repo.wjoin(c)) for c in newlyaddedandmodifiedfiles]
181 [os.unlink(repo.wjoin(c)) for c in newlyaddedandmodifiedfiles]
182 # 3a. apply filtered patch to clean repo (clean)
182 # 3a. apply filtered patch to clean repo (clean)
183 if backups:
183 if backups:
184 # Equivalent to hg.revert
184 # Equivalent to hg.revert
185 choices = lambda key: key in backups
185 choices = lambda key: key in backups
186 mergemod.update(repo, repo.dirstate.p1(),
186 mergemod.update(repo, repo.dirstate.p1(),
187 False, True, choices)
187 False, True, choices)
188
188
189 # 3b. (apply)
189 # 3b. (apply)
190 if dopatch:
190 if dopatch:
191 try:
191 try:
192 ui.debug('applying patch\n')
192 ui.debug('applying patch\n')
193 ui.debug(fp.getvalue())
193 ui.debug(fp.getvalue())
194 patch.internalpatch(ui, repo, fp, 1, eolmode=None)
194 patch.internalpatch(ui, repo, fp, 1, eolmode=None)
195 except patch.PatchError as err:
195 except patch.PatchError as err:
196 raise util.Abort(str(err))
196 raise util.Abort(str(err))
197 del fp
197 del fp
198
198
199 # 4. We prepared working directory according to filtered
199 # 4. We prepared working directory according to filtered
200 # patch. Now is the time to delegate the job to
200 # patch. Now is the time to delegate the job to
201 # commit/qrefresh or the like!
201 # commit/qrefresh or the like!
202
202
203 # Make all of the pathnames absolute.
203 # Make all of the pathnames absolute.
204 newfiles = [repo.wjoin(nf) for nf in newfiles]
204 newfiles = [repo.wjoin(nf) for nf in newfiles]
205 return commitfunc(ui, repo, *newfiles, **opts)
205 return commitfunc(ui, repo, *newfiles, **opts)
206 finally:
206 finally:
207 # 5. finally restore backed-up files
207 # 5. finally restore backed-up files
208 try:
208 try:
209 dirstate = repo.dirstate
209 dirstate = repo.dirstate
210 for realname, tmpname in backups.iteritems():
210 for realname, tmpname in backups.iteritems():
211 ui.debug('restoring %r to %r\n' % (tmpname, realname))
211 ui.debug('restoring %r to %r\n' % (tmpname, realname))
212
212
213 if dirstate[realname] == 'n':
213 if dirstate[realname] == 'n':
214 # without normallookup, restoring timestamp
214 # without normallookup, restoring timestamp
215 # may cause partially committed files
215 # may cause partially committed files
216 # to be treated as unmodified
216 # to be treated as unmodified
217 dirstate.normallookup(realname)
217 dirstate.normallookup(realname)
218
218
219 util.copyfile(tmpname, repo.wjoin(realname))
219 util.copyfile(tmpname, repo.wjoin(realname))
220 # Our calls to copystat() here and above are a
220 # Our calls to copystat() here and above are a
221 # hack to trick any editors that have f open that
221 # hack to trick any editors that have f open that
222 # we haven't modified them.
222 # we haven't modified them.
223 #
223 #
224 # Also note that this racy as an editor could
224 # Also note that this racy as an editor could
225 # notice the file's mtime before we've finished
225 # notice the file's mtime before we've finished
226 # writing it.
226 # writing it.
227 shutil.copystat(tmpname, repo.wjoin(realname))
227 shutil.copystat(tmpname, repo.wjoin(realname))
228 os.unlink(tmpname)
228 os.unlink(tmpname)
229 if tobackup:
229 if tobackup:
230 os.rmdir(backupdir)
230 os.rmdir(backupdir)
231 except OSError:
231 except OSError:
232 pass
232 pass
233
233
234 def recordinwlock(ui, repo, message, match, opts):
234 def recordinwlock(ui, repo, message, match, opts):
235 wlock = repo.wlock()
235 wlock = repo.wlock()
236 try:
236 try:
237 return recordfunc(ui, repo, message, match, opts)
237 return recordfunc(ui, repo, message, match, opts)
238 finally:
238 finally:
239 wlock.release()
239 wlock.release()
240
240
241 return commit(ui, repo, recordinwlock, pats, opts)
241 return commit(ui, repo, recordinwlock, pats, opts)
242
242
243 def findpossible(cmd, table, strict=False):
243 def findpossible(cmd, table, strict=False):
244 """
244 """
245 Return cmd -> (aliases, command table entry)
245 Return cmd -> (aliases, command table entry)
246 for each matching command.
246 for each matching command.
247 Return debug commands (or their aliases) only if no normal command matches.
247 Return debug commands (or their aliases) only if no normal command matches.
248 """
248 """
249 choice = {}
249 choice = {}
250 debugchoice = {}
250 debugchoice = {}
251
251
252 if cmd in table:
252 if cmd in table:
253 # short-circuit exact matches, "log" alias beats "^log|history"
253 # short-circuit exact matches, "log" alias beats "^log|history"
254 keys = [cmd]
254 keys = [cmd]
255 else:
255 else:
256 keys = table.keys()
256 keys = table.keys()
257
257
258 allcmds = []
258 allcmds = []
259 for e in keys:
259 for e in keys:
260 aliases = parsealiases(e)
260 aliases = parsealiases(e)
261 allcmds.extend(aliases)
261 allcmds.extend(aliases)
262 found = None
262 found = None
263 if cmd in aliases:
263 if cmd in aliases:
264 found = cmd
264 found = cmd
265 elif not strict:
265 elif not strict:
266 for a in aliases:
266 for a in aliases:
267 if a.startswith(cmd):
267 if a.startswith(cmd):
268 found = a
268 found = a
269 break
269 break
270 if found is not None:
270 if found is not None:
271 if aliases[0].startswith("debug") or found.startswith("debug"):
271 if aliases[0].startswith("debug") or found.startswith("debug"):
272 debugchoice[found] = (aliases, table[e])
272 debugchoice[found] = (aliases, table[e])
273 else:
273 else:
274 choice[found] = (aliases, table[e])
274 choice[found] = (aliases, table[e])
275
275
276 if not choice and debugchoice:
276 if not choice and debugchoice:
277 choice = debugchoice
277 choice = debugchoice
278
278
279 return choice, allcmds
279 return choice, allcmds
280
280
281 def findcmd(cmd, table, strict=True):
281 def findcmd(cmd, table, strict=True):
282 """Return (aliases, command table entry) for command string."""
282 """Return (aliases, command table entry) for command string."""
283 choice, allcmds = findpossible(cmd, table, strict)
283 choice, allcmds = findpossible(cmd, table, strict)
284
284
285 if cmd in choice:
285 if cmd in choice:
286 return choice[cmd]
286 return choice[cmd]
287
287
288 if len(choice) > 1:
288 if len(choice) > 1:
289 clist = choice.keys()
289 clist = choice.keys()
290 clist.sort()
290 clist.sort()
291 raise error.AmbiguousCommand(cmd, clist)
291 raise error.AmbiguousCommand(cmd, clist)
292
292
293 if choice:
293 if choice:
294 return choice.values()[0]
294 return choice.values()[0]
295
295
296 raise error.UnknownCommand(cmd, allcmds)
296 raise error.UnknownCommand(cmd, allcmds)
297
297
298 def findrepo(p):
298 def findrepo(p):
299 while not os.path.isdir(os.path.join(p, ".hg")):
299 while not os.path.isdir(os.path.join(p, ".hg")):
300 oldp, p = p, os.path.dirname(p)
300 oldp, p = p, os.path.dirname(p)
301 if p == oldp:
301 if p == oldp:
302 return None
302 return None
303
303
304 return p
304 return p
305
305
306 def bailifchanged(repo, merge=True):
306 def bailifchanged(repo, merge=True):
307 if merge and repo.dirstate.p2() != nullid:
307 if merge and repo.dirstate.p2() != nullid:
308 raise util.Abort(_('outstanding uncommitted merge'))
308 raise util.Abort(_('outstanding uncommitted merge'))
309 modified, added, removed, deleted = repo.status()[:4]
309 modified, added, removed, deleted = repo.status()[:4]
310 if modified or added or removed or deleted:
310 if modified or added or removed or deleted:
311 raise util.Abort(_('uncommitted changes'))
311 raise util.Abort(_('uncommitted changes'))
312 ctx = repo[None]
312 ctx = repo[None]
313 for s in sorted(ctx.substate):
313 for s in sorted(ctx.substate):
314 ctx.sub(s).bailifchanged()
314 ctx.sub(s).bailifchanged()
315
315
316 def logmessage(ui, opts):
316 def logmessage(ui, opts):
317 """ get the log message according to -m and -l option """
317 """ get the log message according to -m and -l option """
318 message = opts.get('message')
318 message = opts.get('message')
319 logfile = opts.get('logfile')
319 logfile = opts.get('logfile')
320
320
321 if message and logfile:
321 if message and logfile:
322 raise util.Abort(_('options --message and --logfile are mutually '
322 raise util.Abort(_('options --message and --logfile are mutually '
323 'exclusive'))
323 'exclusive'))
324 if not message and logfile:
324 if not message and logfile:
325 try:
325 try:
326 if logfile == '-':
326 if logfile == '-':
327 message = ui.fin.read()
327 message = ui.fin.read()
328 else:
328 else:
329 message = '\n'.join(util.readfile(logfile).splitlines())
329 message = '\n'.join(util.readfile(logfile).splitlines())
330 except IOError as inst:
330 except IOError as inst:
331 raise util.Abort(_("can't read commit message '%s': %s") %
331 raise util.Abort(_("can't read commit message '%s': %s") %
332 (logfile, inst.strerror))
332 (logfile, inst.strerror))
333 return message
333 return message
334
334
335 def mergeeditform(ctxorbool, baseformname):
335 def mergeeditform(ctxorbool, baseformname):
336 """return appropriate editform name (referencing a committemplate)
336 """return appropriate editform name (referencing a committemplate)
337
337
338 'ctxorbool' is either a ctx to be committed, or a bool indicating whether
338 'ctxorbool' is either a ctx to be committed, or a bool indicating whether
339 merging is committed.
339 merging is committed.
340
340
341 This returns baseformname with '.merge' appended if it is a merge,
341 This returns baseformname with '.merge' appended if it is a merge,
342 otherwise '.normal' is appended.
342 otherwise '.normal' is appended.
343 """
343 """
344 if isinstance(ctxorbool, bool):
344 if isinstance(ctxorbool, bool):
345 if ctxorbool:
345 if ctxorbool:
346 return baseformname + ".merge"
346 return baseformname + ".merge"
347 elif 1 < len(ctxorbool.parents()):
347 elif 1 < len(ctxorbool.parents()):
348 return baseformname + ".merge"
348 return baseformname + ".merge"
349
349
350 return baseformname + ".normal"
350 return baseformname + ".normal"
351
351
352 def getcommiteditor(edit=False, finishdesc=None, extramsg=None,
352 def getcommiteditor(edit=False, finishdesc=None, extramsg=None,
353 editform='', **opts):
353 editform='', **opts):
354 """get appropriate commit message editor according to '--edit' option
354 """get appropriate commit message editor according to '--edit' option
355
355
356 'finishdesc' is a function to be called with edited commit message
356 'finishdesc' is a function to be called with edited commit message
357 (= 'description' of the new changeset) just after editing, but
357 (= 'description' of the new changeset) just after editing, but
358 before checking empty-ness. It should return actual text to be
358 before checking empty-ness. It should return actual text to be
359 stored into history. This allows to change description before
359 stored into history. This allows to change description before
360 storing.
360 storing.
361
361
362 'extramsg' is a extra message to be shown in the editor instead of
362 'extramsg' is a extra message to be shown in the editor instead of
363 'Leave message empty to abort commit' line. 'HG: ' prefix and EOL
363 'Leave message empty to abort commit' line. 'HG: ' prefix and EOL
364 is automatically added.
364 is automatically added.
365
365
366 'editform' is a dot-separated list of names, to distinguish
366 'editform' is a dot-separated list of names, to distinguish
367 the purpose of commit text editing.
367 the purpose of commit text editing.
368
368
369 'getcommiteditor' returns 'commitforceeditor' regardless of
369 'getcommiteditor' returns 'commitforceeditor' regardless of
370 'edit', if one of 'finishdesc' or 'extramsg' is specified, because
370 'edit', if one of 'finishdesc' or 'extramsg' is specified, because
371 they are specific for usage in MQ.
371 they are specific for usage in MQ.
372 """
372 """
373 if edit or finishdesc or extramsg:
373 if edit or finishdesc or extramsg:
374 return lambda r, c, s: commitforceeditor(r, c, s,
374 return lambda r, c, s: commitforceeditor(r, c, s,
375 finishdesc=finishdesc,
375 finishdesc=finishdesc,
376 extramsg=extramsg,
376 extramsg=extramsg,
377 editform=editform)
377 editform=editform)
378 elif editform:
378 elif editform:
379 return lambda r, c, s: commiteditor(r, c, s, editform=editform)
379 return lambda r, c, s: commiteditor(r, c, s, editform=editform)
380 else:
380 else:
381 return commiteditor
381 return commiteditor
382
382
383 def loglimit(opts):
383 def loglimit(opts):
384 """get the log limit according to option -l/--limit"""
384 """get the log limit according to option -l/--limit"""
385 limit = opts.get('limit')
385 limit = opts.get('limit')
386 if limit:
386 if limit:
387 try:
387 try:
388 limit = int(limit)
388 limit = int(limit)
389 except ValueError:
389 except ValueError:
390 raise util.Abort(_('limit must be a positive integer'))
390 raise util.Abort(_('limit must be a positive integer'))
391 if limit <= 0:
391 if limit <= 0:
392 raise util.Abort(_('limit must be positive'))
392 raise util.Abort(_('limit must be positive'))
393 else:
393 else:
394 limit = None
394 limit = None
395 return limit
395 return limit
396
396
397 def makefilename(repo, pat, node, desc=None,
397 def makefilename(repo, pat, node, desc=None,
398 total=None, seqno=None, revwidth=None, pathname=None):
398 total=None, seqno=None, revwidth=None, pathname=None):
399 node_expander = {
399 node_expander = {
400 'H': lambda: hex(node),
400 'H': lambda: hex(node),
401 'R': lambda: str(repo.changelog.rev(node)),
401 'R': lambda: str(repo.changelog.rev(node)),
402 'h': lambda: short(node),
402 'h': lambda: short(node),
403 'm': lambda: re.sub('[^\w]', '_', str(desc))
403 'm': lambda: re.sub('[^\w]', '_', str(desc))
404 }
404 }
405 expander = {
405 expander = {
406 '%': lambda: '%',
406 '%': lambda: '%',
407 'b': lambda: os.path.basename(repo.root),
407 'b': lambda: os.path.basename(repo.root),
408 }
408 }
409
409
410 try:
410 try:
411 if node:
411 if node:
412 expander.update(node_expander)
412 expander.update(node_expander)
413 if node:
413 if node:
414 expander['r'] = (lambda:
414 expander['r'] = (lambda:
415 str(repo.changelog.rev(node)).zfill(revwidth or 0))
415 str(repo.changelog.rev(node)).zfill(revwidth or 0))
416 if total is not None:
416 if total is not None:
417 expander['N'] = lambda: str(total)
417 expander['N'] = lambda: str(total)
418 if seqno is not None:
418 if seqno is not None:
419 expander['n'] = lambda: str(seqno)
419 expander['n'] = lambda: str(seqno)
420 if total is not None and seqno is not None:
420 if total is not None and seqno is not None:
421 expander['n'] = lambda: str(seqno).zfill(len(str(total)))
421 expander['n'] = lambda: str(seqno).zfill(len(str(total)))
422 if pathname is not None:
422 if pathname is not None:
423 expander['s'] = lambda: os.path.basename(pathname)
423 expander['s'] = lambda: os.path.basename(pathname)
424 expander['d'] = lambda: os.path.dirname(pathname) or '.'
424 expander['d'] = lambda: os.path.dirname(pathname) or '.'
425 expander['p'] = lambda: pathname
425 expander['p'] = lambda: pathname
426
426
427 newname = []
427 newname = []
428 patlen = len(pat)
428 patlen = len(pat)
429 i = 0
429 i = 0
430 while i < patlen:
430 while i < patlen:
431 c = pat[i]
431 c = pat[i]
432 if c == '%':
432 if c == '%':
433 i += 1
433 i += 1
434 c = pat[i]
434 c = pat[i]
435 c = expander[c]()
435 c = expander[c]()
436 newname.append(c)
436 newname.append(c)
437 i += 1
437 i += 1
438 return ''.join(newname)
438 return ''.join(newname)
439 except KeyError as inst:
439 except KeyError as inst:
440 raise util.Abort(_("invalid format spec '%%%s' in output filename") %
440 raise util.Abort(_("invalid format spec '%%%s' in output filename") %
441 inst.args[0])
441 inst.args[0])
442
442
443 def makefileobj(repo, pat, node=None, desc=None, total=None,
443 def makefileobj(repo, pat, node=None, desc=None, total=None,
444 seqno=None, revwidth=None, mode='wb', modemap=None,
444 seqno=None, revwidth=None, mode='wb', modemap=None,
445 pathname=None):
445 pathname=None):
446
446
447 writable = mode not in ('r', 'rb')
447 writable = mode not in ('r', 'rb')
448
448
449 if not pat or pat == '-':
449 if not pat or pat == '-':
450 if writable:
450 if writable:
451 fp = repo.ui.fout
451 fp = repo.ui.fout
452 else:
452 else:
453 fp = repo.ui.fin
453 fp = repo.ui.fin
454 if util.safehasattr(fp, 'fileno'):
454 if util.safehasattr(fp, 'fileno'):
455 return os.fdopen(os.dup(fp.fileno()), mode)
455 return os.fdopen(os.dup(fp.fileno()), mode)
456 else:
456 else:
457 # if this fp can't be duped properly, return
457 # if this fp can't be duped properly, return
458 # a dummy object that can be closed
458 # a dummy object that can be closed
459 class wrappedfileobj(object):
459 class wrappedfileobj(object):
460 noop = lambda x: None
460 noop = lambda x: None
461 def __init__(self, f):
461 def __init__(self, f):
462 self.f = f
462 self.f = f
463 def __getattr__(self, attr):
463 def __getattr__(self, attr):
464 if attr == 'close':
464 if attr == 'close':
465 return self.noop
465 return self.noop
466 else:
466 else:
467 return getattr(self.f, attr)
467 return getattr(self.f, attr)
468
468
469 return wrappedfileobj(fp)
469 return wrappedfileobj(fp)
470 if util.safehasattr(pat, 'write') and writable:
470 if util.safehasattr(pat, 'write') and writable:
471 return pat
471 return pat
472 if util.safehasattr(pat, 'read') and 'r' in mode:
472 if util.safehasattr(pat, 'read') and 'r' in mode:
473 return pat
473 return pat
474 fn = makefilename(repo, pat, node, desc, total, seqno, revwidth, pathname)
474 fn = makefilename(repo, pat, node, desc, total, seqno, revwidth, pathname)
475 if modemap is not None:
475 if modemap is not None:
476 mode = modemap.get(fn, mode)
476 mode = modemap.get(fn, mode)
477 if mode == 'wb':
477 if mode == 'wb':
478 modemap[fn] = 'ab'
478 modemap[fn] = 'ab'
479 return open(fn, mode)
479 return open(fn, mode)
480
480
481 def openrevlog(repo, cmd, file_, opts):
481 def openrevlog(repo, cmd, file_, opts):
482 """opens the changelog, manifest, a filelog or a given revlog"""
482 """opens the changelog, manifest, a filelog or a given revlog"""
483 cl = opts['changelog']
483 cl = opts['changelog']
484 mf = opts['manifest']
484 mf = opts['manifest']
485 dir = opts['dir']
485 dir = opts['dir']
486 msg = None
486 msg = None
487 if cl and mf:
487 if cl and mf:
488 msg = _('cannot specify --changelog and --manifest at the same time')
488 msg = _('cannot specify --changelog and --manifest at the same time')
489 elif cl and dir:
489 elif cl and dir:
490 msg = _('cannot specify --changelog and --dir at the same time')
490 msg = _('cannot specify --changelog and --dir at the same time')
491 elif cl or mf:
491 elif cl or mf:
492 if file_:
492 if file_:
493 msg = _('cannot specify filename with --changelog or --manifest')
493 msg = _('cannot specify filename with --changelog or --manifest')
494 elif not repo:
494 elif not repo:
495 msg = _('cannot specify --changelog or --manifest or --dir '
495 msg = _('cannot specify --changelog or --manifest or --dir '
496 'without a repository')
496 'without a repository')
497 if msg:
497 if msg:
498 raise util.Abort(msg)
498 raise util.Abort(msg)
499
499
500 r = None
500 r = None
501 if repo:
501 if repo:
502 if cl:
502 if cl:
503 r = repo.unfiltered().changelog
503 r = repo.unfiltered().changelog
504 elif dir:
504 elif dir:
505 if 'treemanifest' not in repo.requirements:
505 if 'treemanifest' not in repo.requirements:
506 raise util.Abort(_("--dir can only be used on repos with "
506 raise util.Abort(_("--dir can only be used on repos with "
507 "treemanifest enabled"))
507 "treemanifest enabled"))
508 dirlog = repo.dirlog(file_)
508 dirlog = repo.dirlog(file_)
509 if len(dirlog):
509 if len(dirlog):
510 r = dirlog
510 r = dirlog
511 elif mf:
511 elif mf:
512 r = repo.manifest
512 r = repo.manifest
513 elif file_:
513 elif file_:
514 filelog = repo.file(file_)
514 filelog = repo.file(file_)
515 if len(filelog):
515 if len(filelog):
516 r = filelog
516 r = filelog
517 if not r:
517 if not r:
518 if not file_:
518 if not file_:
519 raise error.CommandError(cmd, _('invalid arguments'))
519 raise error.CommandError(cmd, _('invalid arguments'))
520 if not os.path.isfile(file_):
520 if not os.path.isfile(file_):
521 raise util.Abort(_("revlog '%s' not found") % file_)
521 raise util.Abort(_("revlog '%s' not found") % file_)
522 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False),
522 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False),
523 file_[:-2] + ".i")
523 file_[:-2] + ".i")
524 return r
524 return r
525
525
526 def copy(ui, repo, pats, opts, rename=False):
526 def copy(ui, repo, pats, opts, rename=False):
527 # called with the repo lock held
527 # called with the repo lock held
528 #
528 #
529 # hgsep => pathname that uses "/" to separate directories
529 # hgsep => pathname that uses "/" to separate directories
530 # ossep => pathname that uses os.sep to separate directories
530 # ossep => pathname that uses os.sep to separate directories
531 cwd = repo.getcwd()
531 cwd = repo.getcwd()
532 targets = {}
532 targets = {}
533 after = opts.get("after")
533 after = opts.get("after")
534 dryrun = opts.get("dry_run")
534 dryrun = opts.get("dry_run")
535 wctx = repo[None]
535 wctx = repo[None]
536
536
537 def walkpat(pat):
537 def walkpat(pat):
538 srcs = []
538 srcs = []
539 if after:
539 if after:
540 badstates = '?'
540 badstates = '?'
541 else:
541 else:
542 badstates = '?r'
542 badstates = '?r'
543 m = scmutil.match(repo[None], [pat], opts, globbed=True)
543 m = scmutil.match(repo[None], [pat], opts, globbed=True)
544 for abs in repo.walk(m):
544 for abs in repo.walk(m):
545 state = repo.dirstate[abs]
545 state = repo.dirstate[abs]
546 rel = m.rel(abs)
546 rel = m.rel(abs)
547 exact = m.exact(abs)
547 exact = m.exact(abs)
548 if state in badstates:
548 if state in badstates:
549 if exact and state == '?':
549 if exact and state == '?':
550 ui.warn(_('%s: not copying - file is not managed\n') % rel)
550 ui.warn(_('%s: not copying - file is not managed\n') % rel)
551 if exact and state == 'r':
551 if exact and state == 'r':
552 ui.warn(_('%s: not copying - file has been marked for'
552 ui.warn(_('%s: not copying - file has been marked for'
553 ' remove\n') % rel)
553 ' remove\n') % rel)
554 continue
554 continue
555 # abs: hgsep
555 # abs: hgsep
556 # rel: ossep
556 # rel: ossep
557 srcs.append((abs, rel, exact))
557 srcs.append((abs, rel, exact))
558 return srcs
558 return srcs
559
559
560 # abssrc: hgsep
560 # abssrc: hgsep
561 # relsrc: ossep
561 # relsrc: ossep
562 # otarget: ossep
562 # otarget: ossep
563 def copyfile(abssrc, relsrc, otarget, exact):
563 def copyfile(abssrc, relsrc, otarget, exact):
564 abstarget = pathutil.canonpath(repo.root, cwd, otarget)
564 abstarget = pathutil.canonpath(repo.root, cwd, otarget)
565 if '/' in abstarget:
565 if '/' in abstarget:
566 # We cannot normalize abstarget itself, this would prevent
566 # We cannot normalize abstarget itself, this would prevent
567 # case only renames, like a => A.
567 # case only renames, like a => A.
568 abspath, absname = abstarget.rsplit('/', 1)
568 abspath, absname = abstarget.rsplit('/', 1)
569 abstarget = repo.dirstate.normalize(abspath) + '/' + absname
569 abstarget = repo.dirstate.normalize(abspath) + '/' + absname
570 reltarget = repo.pathto(abstarget, cwd)
570 reltarget = repo.pathto(abstarget, cwd)
571 target = repo.wjoin(abstarget)
571 target = repo.wjoin(abstarget)
572 src = repo.wjoin(abssrc)
572 src = repo.wjoin(abssrc)
573 state = repo.dirstate[abstarget]
573 state = repo.dirstate[abstarget]
574
574
575 scmutil.checkportable(ui, abstarget)
575 scmutil.checkportable(ui, abstarget)
576
576
577 # check for collisions
577 # check for collisions
578 prevsrc = targets.get(abstarget)
578 prevsrc = targets.get(abstarget)
579 if prevsrc is not None:
579 if prevsrc is not None:
580 ui.warn(_('%s: not overwriting - %s collides with %s\n') %
580 ui.warn(_('%s: not overwriting - %s collides with %s\n') %
581 (reltarget, repo.pathto(abssrc, cwd),
581 (reltarget, repo.pathto(abssrc, cwd),
582 repo.pathto(prevsrc, cwd)))
582 repo.pathto(prevsrc, cwd)))
583 return
583 return
584
584
585 # check for overwrites
585 # check for overwrites
586 exists = os.path.lexists(target)
586 exists = os.path.lexists(target)
587 samefile = False
587 samefile = False
588 if exists and abssrc != abstarget:
588 if exists and abssrc != abstarget:
589 if (repo.dirstate.normalize(abssrc) ==
589 if (repo.dirstate.normalize(abssrc) ==
590 repo.dirstate.normalize(abstarget)):
590 repo.dirstate.normalize(abstarget)):
591 if not rename:
591 if not rename:
592 ui.warn(_("%s: can't copy - same file\n") % reltarget)
592 ui.warn(_("%s: can't copy - same file\n") % reltarget)
593 return
593 return
594 exists = False
594 exists = False
595 samefile = True
595 samefile = True
596
596
597 if not after and exists or after and state in 'mn':
597 if not after and exists or after and state in 'mn':
598 if not opts['force']:
598 if not opts['force']:
599 ui.warn(_('%s: not overwriting - file exists\n') %
599 ui.warn(_('%s: not overwriting - file exists\n') %
600 reltarget)
600 reltarget)
601 return
601 return
602
602
603 if after:
603 if after:
604 if not exists:
604 if not exists:
605 if rename:
605 if rename:
606 ui.warn(_('%s: not recording move - %s does not exist\n') %
606 ui.warn(_('%s: not recording move - %s does not exist\n') %
607 (relsrc, reltarget))
607 (relsrc, reltarget))
608 else:
608 else:
609 ui.warn(_('%s: not recording copy - %s does not exist\n') %
609 ui.warn(_('%s: not recording copy - %s does not exist\n') %
610 (relsrc, reltarget))
610 (relsrc, reltarget))
611 return
611 return
612 elif not dryrun:
612 elif not dryrun:
613 try:
613 try:
614 if exists:
614 if exists:
615 os.unlink(target)
615 os.unlink(target)
616 targetdir = os.path.dirname(target) or '.'
616 targetdir = os.path.dirname(target) or '.'
617 if not os.path.isdir(targetdir):
617 if not os.path.isdir(targetdir):
618 os.makedirs(targetdir)
618 os.makedirs(targetdir)
619 if samefile:
619 if samefile:
620 tmp = target + "~hgrename"
620 tmp = target + "~hgrename"
621 os.rename(src, tmp)
621 os.rename(src, tmp)
622 os.rename(tmp, target)
622 os.rename(tmp, target)
623 else:
623 else:
624 util.copyfile(src, target)
624 util.copyfile(src, target)
625 srcexists = True
625 srcexists = True
626 except IOError as inst:
626 except IOError as inst:
627 if inst.errno == errno.ENOENT:
627 if inst.errno == errno.ENOENT:
628 ui.warn(_('%s: deleted in working directory\n') % relsrc)
628 ui.warn(_('%s: deleted in working directory\n') % relsrc)
629 srcexists = False
629 srcexists = False
630 else:
630 else:
631 ui.warn(_('%s: cannot copy - %s\n') %
631 ui.warn(_('%s: cannot copy - %s\n') %
632 (relsrc, inst.strerror))
632 (relsrc, inst.strerror))
633 return True # report a failure
633 return True # report a failure
634
634
635 if ui.verbose or not exact:
635 if ui.verbose or not exact:
636 if rename:
636 if rename:
637 ui.status(_('moving %s to %s\n') % (relsrc, reltarget))
637 ui.status(_('moving %s to %s\n') % (relsrc, reltarget))
638 else:
638 else:
639 ui.status(_('copying %s to %s\n') % (relsrc, reltarget))
639 ui.status(_('copying %s to %s\n') % (relsrc, reltarget))
640
640
641 targets[abstarget] = abssrc
641 targets[abstarget] = abssrc
642
642
643 # fix up dirstate
643 # fix up dirstate
644 scmutil.dirstatecopy(ui, repo, wctx, abssrc, abstarget,
644 scmutil.dirstatecopy(ui, repo, wctx, abssrc, abstarget,
645 dryrun=dryrun, cwd=cwd)
645 dryrun=dryrun, cwd=cwd)
646 if rename and not dryrun:
646 if rename and not dryrun:
647 if not after and srcexists and not samefile:
647 if not after and srcexists and not samefile:
648 util.unlinkpath(repo.wjoin(abssrc))
648 util.unlinkpath(repo.wjoin(abssrc))
649 wctx.forget([abssrc])
649 wctx.forget([abssrc])
650
650
651 # pat: ossep
651 # pat: ossep
652 # dest ossep
652 # dest ossep
653 # srcs: list of (hgsep, hgsep, ossep, bool)
653 # srcs: list of (hgsep, hgsep, ossep, bool)
654 # return: function that takes hgsep and returns ossep
654 # return: function that takes hgsep and returns ossep
655 def targetpathfn(pat, dest, srcs):
655 def targetpathfn(pat, dest, srcs):
656 if os.path.isdir(pat):
656 if os.path.isdir(pat):
657 abspfx = pathutil.canonpath(repo.root, cwd, pat)
657 abspfx = pathutil.canonpath(repo.root, cwd, pat)
658 abspfx = util.localpath(abspfx)
658 abspfx = util.localpath(abspfx)
659 if destdirexists:
659 if destdirexists:
660 striplen = len(os.path.split(abspfx)[0])
660 striplen = len(os.path.split(abspfx)[0])
661 else:
661 else:
662 striplen = len(abspfx)
662 striplen = len(abspfx)
663 if striplen:
663 if striplen:
664 striplen += len(os.sep)
664 striplen += len(os.sep)
665 res = lambda p: os.path.join(dest, util.localpath(p)[striplen:])
665 res = lambda p: os.path.join(dest, util.localpath(p)[striplen:])
666 elif destdirexists:
666 elif destdirexists:
667 res = lambda p: os.path.join(dest,
667 res = lambda p: os.path.join(dest,
668 os.path.basename(util.localpath(p)))
668 os.path.basename(util.localpath(p)))
669 else:
669 else:
670 res = lambda p: dest
670 res = lambda p: dest
671 return res
671 return res
672
672
673 # pat: ossep
673 # pat: ossep
674 # dest ossep
674 # dest ossep
675 # srcs: list of (hgsep, hgsep, ossep, bool)
675 # srcs: list of (hgsep, hgsep, ossep, bool)
676 # return: function that takes hgsep and returns ossep
676 # return: function that takes hgsep and returns ossep
677 def targetpathafterfn(pat, dest, srcs):
677 def targetpathafterfn(pat, dest, srcs):
678 if matchmod.patkind(pat):
678 if matchmod.patkind(pat):
679 # a mercurial pattern
679 # a mercurial pattern
680 res = lambda p: os.path.join(dest,
680 res = lambda p: os.path.join(dest,
681 os.path.basename(util.localpath(p)))
681 os.path.basename(util.localpath(p)))
682 else:
682 else:
683 abspfx = pathutil.canonpath(repo.root, cwd, pat)
683 abspfx = pathutil.canonpath(repo.root, cwd, pat)
684 if len(abspfx) < len(srcs[0][0]):
684 if len(abspfx) < len(srcs[0][0]):
685 # A directory. Either the target path contains the last
685 # A directory. Either the target path contains the last
686 # component of the source path or it does not.
686 # component of the source path or it does not.
687 def evalpath(striplen):
687 def evalpath(striplen):
688 score = 0
688 score = 0
689 for s in srcs:
689 for s in srcs:
690 t = os.path.join(dest, util.localpath(s[0])[striplen:])
690 t = os.path.join(dest, util.localpath(s[0])[striplen:])
691 if os.path.lexists(t):
691 if os.path.lexists(t):
692 score += 1
692 score += 1
693 return score
693 return score
694
694
695 abspfx = util.localpath(abspfx)
695 abspfx = util.localpath(abspfx)
696 striplen = len(abspfx)
696 striplen = len(abspfx)
697 if striplen:
697 if striplen:
698 striplen += len(os.sep)
698 striplen += len(os.sep)
699 if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])):
699 if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])):
700 score = evalpath(striplen)
700 score = evalpath(striplen)
701 striplen1 = len(os.path.split(abspfx)[0])
701 striplen1 = len(os.path.split(abspfx)[0])
702 if striplen1:
702 if striplen1:
703 striplen1 += len(os.sep)
703 striplen1 += len(os.sep)
704 if evalpath(striplen1) > score:
704 if evalpath(striplen1) > score:
705 striplen = striplen1
705 striplen = striplen1
706 res = lambda p: os.path.join(dest,
706 res = lambda p: os.path.join(dest,
707 util.localpath(p)[striplen:])
707 util.localpath(p)[striplen:])
708 else:
708 else:
709 # a file
709 # a file
710 if destdirexists:
710 if destdirexists:
711 res = lambda p: os.path.join(dest,
711 res = lambda p: os.path.join(dest,
712 os.path.basename(util.localpath(p)))
712 os.path.basename(util.localpath(p)))
713 else:
713 else:
714 res = lambda p: dest
714 res = lambda p: dest
715 return res
715 return res
716
716
717 pats = scmutil.expandpats(pats)
717 pats = scmutil.expandpats(pats)
718 if not pats:
718 if not pats:
719 raise util.Abort(_('no source or destination specified'))
719 raise util.Abort(_('no source or destination specified'))
720 if len(pats) == 1:
720 if len(pats) == 1:
721 raise util.Abort(_('no destination specified'))
721 raise util.Abort(_('no destination specified'))
722 dest = pats.pop()
722 dest = pats.pop()
723 destdirexists = os.path.isdir(dest) and not os.path.islink(dest)
723 destdirexists = os.path.isdir(dest) and not os.path.islink(dest)
724 if not destdirexists:
724 if not destdirexists:
725 if len(pats) > 1 or matchmod.patkind(pats[0]):
725 if len(pats) > 1 or matchmod.patkind(pats[0]):
726 raise util.Abort(_('with multiple sources, destination must be an '
726 raise util.Abort(_('with multiple sources, destination must be an '
727 'existing directory'))
727 'existing directory'))
728 if util.endswithsep(dest):
728 if util.endswithsep(dest):
729 raise util.Abort(_('destination %s is not a directory') % dest)
729 raise util.Abort(_('destination %s is not a directory') % dest)
730
730
731 tfn = targetpathfn
731 tfn = targetpathfn
732 if after:
732 if after:
733 tfn = targetpathafterfn
733 tfn = targetpathafterfn
734 copylist = []
734 copylist = []
735 for pat in pats:
735 for pat in pats:
736 srcs = walkpat(pat)
736 srcs = walkpat(pat)
737 if not srcs:
737 if not srcs:
738 continue
738 continue
739 copylist.append((tfn(pat, dest, srcs), srcs))
739 copylist.append((tfn(pat, dest, srcs), srcs))
740 if not copylist:
740 if not copylist:
741 raise util.Abort(_('no files to copy'))
741 raise util.Abort(_('no files to copy'))
742
742
743 errors = 0
743 errors = 0
744 for targetpath, srcs in copylist:
744 for targetpath, srcs in copylist:
745 for abssrc, relsrc, exact in srcs:
745 for abssrc, relsrc, exact in srcs:
746 if copyfile(abssrc, relsrc, targetpath(abssrc), exact):
746 if copyfile(abssrc, relsrc, targetpath(abssrc), exact):
747 errors += 1
747 errors += 1
748
748
749 if errors:
749 if errors:
750 ui.warn(_('(consider using --after)\n'))
750 ui.warn(_('(consider using --after)\n'))
751
751
752 return errors != 0
752 return errors != 0
753
753
754 def service(opts, parentfn=None, initfn=None, runfn=None, logfile=None,
754 def service(opts, parentfn=None, initfn=None, runfn=None, logfile=None,
755 runargs=None, appendpid=False):
755 runargs=None, appendpid=False):
756 '''Run a command as a service.'''
756 '''Run a command as a service.'''
757
757
758 def writepid(pid):
758 def writepid(pid):
759 if opts['pid_file']:
759 if opts['pid_file']:
760 if appendpid:
760 if appendpid:
761 mode = 'a'
761 mode = 'a'
762 else:
762 else:
763 mode = 'w'
763 mode = 'w'
764 fp = open(opts['pid_file'], mode)
764 fp = open(opts['pid_file'], mode)
765 fp.write(str(pid) + '\n')
765 fp.write(str(pid) + '\n')
766 fp.close()
766 fp.close()
767
767
768 if opts['daemon'] and not opts['daemon_pipefds']:
768 if opts['daemon'] and not opts['daemon_pipefds']:
769 # Signal child process startup with file removal
769 # Signal child process startup with file removal
770 lockfd, lockpath = tempfile.mkstemp(prefix='hg-service-')
770 lockfd, lockpath = tempfile.mkstemp(prefix='hg-service-')
771 os.close(lockfd)
771 os.close(lockfd)
772 try:
772 try:
773 if not runargs:
773 if not runargs:
774 runargs = util.hgcmd() + sys.argv[1:]
774 runargs = util.hgcmd() + sys.argv[1:]
775 runargs.append('--daemon-pipefds=%s' % lockpath)
775 runargs.append('--daemon-pipefds=%s' % lockpath)
776 # Don't pass --cwd to the child process, because we've already
776 # Don't pass --cwd to the child process, because we've already
777 # changed directory.
777 # changed directory.
778 for i in xrange(1, len(runargs)):
778 for i in xrange(1, len(runargs)):
779 if runargs[i].startswith('--cwd='):
779 if runargs[i].startswith('--cwd='):
780 del runargs[i]
780 del runargs[i]
781 break
781 break
782 elif runargs[i].startswith('--cwd'):
782 elif runargs[i].startswith('--cwd'):
783 del runargs[i:i + 2]
783 del runargs[i:i + 2]
784 break
784 break
785 def condfn():
785 def condfn():
786 return not os.path.exists(lockpath)
786 return not os.path.exists(lockpath)
787 pid = util.rundetached(runargs, condfn)
787 pid = util.rundetached(runargs, condfn)
788 if pid < 0:
788 if pid < 0:
789 raise util.Abort(_('child process failed to start'))
789 raise util.Abort(_('child process failed to start'))
790 writepid(pid)
790 writepid(pid)
791 finally:
791 finally:
792 try:
792 try:
793 os.unlink(lockpath)
793 os.unlink(lockpath)
794 except OSError as e:
794 except OSError as e:
795 if e.errno != errno.ENOENT:
795 if e.errno != errno.ENOENT:
796 raise
796 raise
797 if parentfn:
797 if parentfn:
798 return parentfn(pid)
798 return parentfn(pid)
799 else:
799 else:
800 return
800 return
801
801
802 if initfn:
802 if initfn:
803 initfn()
803 initfn()
804
804
805 if not opts['daemon']:
805 if not opts['daemon']:
806 writepid(os.getpid())
806 writepid(os.getpid())
807
807
808 if opts['daemon_pipefds']:
808 if opts['daemon_pipefds']:
809 lockpath = opts['daemon_pipefds']
809 lockpath = opts['daemon_pipefds']
810 try:
810 try:
811 os.setsid()
811 os.setsid()
812 except AttributeError:
812 except AttributeError:
813 pass
813 pass
814 os.unlink(lockpath)
814 os.unlink(lockpath)
815 util.hidewindow()
815 util.hidewindow()
816 sys.stdout.flush()
816 sys.stdout.flush()
817 sys.stderr.flush()
817 sys.stderr.flush()
818
818
819 nullfd = os.open(os.devnull, os.O_RDWR)
819 nullfd = os.open(os.devnull, os.O_RDWR)
820 logfilefd = nullfd
820 logfilefd = nullfd
821 if logfile:
821 if logfile:
822 logfilefd = os.open(logfile, os.O_RDWR | os.O_CREAT | os.O_APPEND)
822 logfilefd = os.open(logfile, os.O_RDWR | os.O_CREAT | os.O_APPEND)
823 os.dup2(nullfd, 0)
823 os.dup2(nullfd, 0)
824 os.dup2(logfilefd, 1)
824 os.dup2(logfilefd, 1)
825 os.dup2(logfilefd, 2)
825 os.dup2(logfilefd, 2)
826 if nullfd not in (0, 1, 2):
826 if nullfd not in (0, 1, 2):
827 os.close(nullfd)
827 os.close(nullfd)
828 if logfile and logfilefd not in (0, 1, 2):
828 if logfile and logfilefd not in (0, 1, 2):
829 os.close(logfilefd)
829 os.close(logfilefd)
830
830
831 if runfn:
831 if runfn:
832 return runfn()
832 return runfn()
833
833
834 def tryimportone(ui, repo, hunk, parents, opts, msgs, updatefunc):
834 def tryimportone(ui, repo, hunk, parents, opts, msgs, updatefunc):
835 """Utility function used by commands.import to import a single patch
835 """Utility function used by commands.import to import a single patch
836
836
837 This function is explicitly defined here to help the evolve extension to
837 This function is explicitly defined here to help the evolve extension to
838 wrap this part of the import logic.
838 wrap this part of the import logic.
839
839
840 The API is currently a bit ugly because it a simple code translation from
840 The API is currently a bit ugly because it a simple code translation from
841 the import command. Feel free to make it better.
841 the import command. Feel free to make it better.
842
842
843 :hunk: a patch (as a binary string)
843 :hunk: a patch (as a binary string)
844 :parents: nodes that will be parent of the created commit
844 :parents: nodes that will be parent of the created commit
845 :opts: the full dict of option passed to the import command
845 :opts: the full dict of option passed to the import command
846 :msgs: list to save commit message to.
846 :msgs: list to save commit message to.
847 (used in case we need to save it when failing)
847 (used in case we need to save it when failing)
848 :updatefunc: a function that update a repo to a given node
848 :updatefunc: a function that update a repo to a given node
849 updatefunc(<repo>, <node>)
849 updatefunc(<repo>, <node>)
850 """
850 """
851 # avoid cycle context -> subrepo -> cmdutil
851 # avoid cycle context -> subrepo -> cmdutil
852 import context
852 import context
853 tmpname, message, user, date, branch, nodeid, p1, p2 = \
853 tmpname, message, user, date, branch, nodeid, p1, p2 = \
854 patch.extract(ui, hunk)
854 patch.extract(ui, hunk)
855
855
856 update = not opts.get('bypass')
856 update = not opts.get('bypass')
857 strip = opts["strip"]
857 strip = opts["strip"]
858 prefix = opts["prefix"]
858 prefix = opts["prefix"]
859 sim = float(opts.get('similarity') or 0)
859 sim = float(opts.get('similarity') or 0)
860 if not tmpname:
860 if not tmpname:
861 return (None, None, False)
861 return (None, None, False)
862 msg = _('applied to working directory')
862 msg = _('applied to working directory')
863
863
864 rejects = False
864 rejects = False
865 dsguard = None
865 dsguard = None
866
866
867 try:
867 try:
868 cmdline_message = logmessage(ui, opts)
868 cmdline_message = logmessage(ui, opts)
869 if cmdline_message:
869 if cmdline_message:
870 # pickup the cmdline msg
870 # pickup the cmdline msg
871 message = cmdline_message
871 message = cmdline_message
872 elif message:
872 elif message:
873 # pickup the patch msg
873 # pickup the patch msg
874 message = message.strip()
874 message = message.strip()
875 else:
875 else:
876 # launch the editor
876 # launch the editor
877 message = None
877 message = None
878 ui.debug('message:\n%s\n' % message)
878 ui.debug('message:\n%s\n' % message)
879
879
880 if len(parents) == 1:
880 if len(parents) == 1:
881 parents.append(repo[nullid])
881 parents.append(repo[nullid])
882 if opts.get('exact'):
882 if opts.get('exact'):
883 if not nodeid or not p1:
883 if not nodeid or not p1:
884 raise util.Abort(_('not a Mercurial patch'))
884 raise util.Abort(_('not a Mercurial patch'))
885 p1 = repo[p1]
885 p1 = repo[p1]
886 p2 = repo[p2 or nullid]
886 p2 = repo[p2 or nullid]
887 elif p2:
887 elif p2:
888 try:
888 try:
889 p1 = repo[p1]
889 p1 = repo[p1]
890 p2 = repo[p2]
890 p2 = repo[p2]
891 # Without any options, consider p2 only if the
891 # Without any options, consider p2 only if the
892 # patch is being applied on top of the recorded
892 # patch is being applied on top of the recorded
893 # first parent.
893 # first parent.
894 if p1 != parents[0]:
894 if p1 != parents[0]:
895 p1 = parents[0]
895 p1 = parents[0]
896 p2 = repo[nullid]
896 p2 = repo[nullid]
897 except error.RepoError:
897 except error.RepoError:
898 p1, p2 = parents
898 p1, p2 = parents
899 if p2.node() == nullid:
899 if p2.node() == nullid:
900 ui.warn(_("warning: import the patch as a normal revision\n"
900 ui.warn(_("warning: import the patch as a normal revision\n"
901 "(use --exact to import the patch as a merge)\n"))
901 "(use --exact to import the patch as a merge)\n"))
902 else:
902 else:
903 p1, p2 = parents
903 p1, p2 = parents
904
904
905 n = None
905 n = None
906 if update:
906 if update:
907 dsguard = dirstateguard(repo, 'tryimportone')
907 dsguard = dirstateguard(repo, 'tryimportone')
908 if p1 != parents[0]:
908 if p1 != parents[0]:
909 updatefunc(repo, p1.node())
909 updatefunc(repo, p1.node())
910 if p2 != parents[1]:
910 if p2 != parents[1]:
911 repo.setparents(p1.node(), p2.node())
911 repo.setparents(p1.node(), p2.node())
912
912
913 if opts.get('exact') or opts.get('import_branch'):
913 if opts.get('exact') or opts.get('import_branch'):
914 repo.dirstate.setbranch(branch or 'default')
914 repo.dirstate.setbranch(branch or 'default')
915
915
916 partial = opts.get('partial', False)
916 partial = opts.get('partial', False)
917 files = set()
917 files = set()
918 try:
918 try:
919 patch.patch(ui, repo, tmpname, strip=strip, prefix=prefix,
919 patch.patch(ui, repo, tmpname, strip=strip, prefix=prefix,
920 files=files, eolmode=None, similarity=sim / 100.0)
920 files=files, eolmode=None, similarity=sim / 100.0)
921 except patch.PatchError as e:
921 except patch.PatchError as e:
922 if not partial:
922 if not partial:
923 raise util.Abort(str(e))
923 raise util.Abort(str(e))
924 if partial:
924 if partial:
925 rejects = True
925 rejects = True
926
926
927 files = list(files)
927 files = list(files)
928 if opts.get('no_commit'):
928 if opts.get('no_commit'):
929 if message:
929 if message:
930 msgs.append(message)
930 msgs.append(message)
931 else:
931 else:
932 if opts.get('exact') or p2:
932 if opts.get('exact') or p2:
933 # If you got here, you either use --force and know what
933 # If you got here, you either use --force and know what
934 # you are doing or used --exact or a merge patch while
934 # you are doing or used --exact or a merge patch while
935 # being updated to its first parent.
935 # being updated to its first parent.
936 m = None
936 m = None
937 else:
937 else:
938 m = scmutil.matchfiles(repo, files or [])
938 m = scmutil.matchfiles(repo, files or [])
939 editform = mergeeditform(repo[None], 'import.normal')
939 editform = mergeeditform(repo[None], 'import.normal')
940 if opts.get('exact'):
940 if opts.get('exact'):
941 editor = None
941 editor = None
942 else:
942 else:
943 editor = getcommiteditor(editform=editform, **opts)
943 editor = getcommiteditor(editform=editform, **opts)
944 allowemptyback = repo.ui.backupconfig('ui', 'allowemptycommit')
944 allowemptyback = repo.ui.backupconfig('ui', 'allowemptycommit')
945 try:
945 try:
946 if partial:
946 if partial:
947 repo.ui.setconfig('ui', 'allowemptycommit', True)
947 repo.ui.setconfig('ui', 'allowemptycommit', True)
948 n = repo.commit(message, opts.get('user') or user,
948 n = repo.commit(message, opts.get('user') or user,
949 opts.get('date') or date, match=m,
949 opts.get('date') or date, match=m,
950 editor=editor)
950 editor=editor)
951 finally:
951 finally:
952 repo.ui.restoreconfig(allowemptyback)
952 repo.ui.restoreconfig(allowemptyback)
953 dsguard.close()
953 dsguard.close()
954 else:
954 else:
955 if opts.get('exact') or opts.get('import_branch'):
955 if opts.get('exact') or opts.get('import_branch'):
956 branch = branch or 'default'
956 branch = branch or 'default'
957 else:
957 else:
958 branch = p1.branch()
958 branch = p1.branch()
959 store = patch.filestore()
959 store = patch.filestore()
960 try:
960 try:
961 files = set()
961 files = set()
962 try:
962 try:
963 patch.patchrepo(ui, repo, p1, store, tmpname, strip, prefix,
963 patch.patchrepo(ui, repo, p1, store, tmpname, strip, prefix,
964 files, eolmode=None)
964 files, eolmode=None)
965 except patch.PatchError as e:
965 except patch.PatchError as e:
966 raise util.Abort(str(e))
966 raise util.Abort(str(e))
967 if opts.get('exact'):
967 if opts.get('exact'):
968 editor = None
968 editor = None
969 else:
969 else:
970 editor = getcommiteditor(editform='import.bypass')
970 editor = getcommiteditor(editform='import.bypass')
971 memctx = context.makememctx(repo, (p1.node(), p2.node()),
971 memctx = context.makememctx(repo, (p1.node(), p2.node()),
972 message,
972 message,
973 opts.get('user') or user,
973 opts.get('user') or user,
974 opts.get('date') or date,
974 opts.get('date') or date,
975 branch, files, store,
975 branch, files, store,
976 editor=editor)
976 editor=editor)
977 n = memctx.commit()
977 n = memctx.commit()
978 finally:
978 finally:
979 store.close()
979 store.close()
980 if opts.get('exact') and opts.get('no_commit'):
980 if opts.get('exact') and opts.get('no_commit'):
981 # --exact with --no-commit is still useful in that it does merge
981 # --exact with --no-commit is still useful in that it does merge
982 # and branch bits
982 # and branch bits
983 ui.warn(_("warning: can't check exact import with --no-commit\n"))
983 ui.warn(_("warning: can't check exact import with --no-commit\n"))
984 elif opts.get('exact') and hex(n) != nodeid:
984 elif opts.get('exact') and hex(n) != nodeid:
985 raise util.Abort(_('patch is damaged or loses information'))
985 raise util.Abort(_('patch is damaged or loses information'))
986 if n:
986 if n:
987 # i18n: refers to a short changeset id
987 # i18n: refers to a short changeset id
988 msg = _('created %s') % short(n)
988 msg = _('created %s') % short(n)
989 return (msg, n, rejects)
989 return (msg, n, rejects)
990 finally:
990 finally:
991 lockmod.release(dsguard)
991 lockmod.release(dsguard)
992 os.unlink(tmpname)
992 os.unlink(tmpname)
993
993
994 def export(repo, revs, template='hg-%h.patch', fp=None, switch_parent=False,
994 def export(repo, revs, template='hg-%h.patch', fp=None, switch_parent=False,
995 opts=None, match=None):
995 opts=None, match=None):
996 '''export changesets as hg patches.'''
996 '''export changesets as hg patches.'''
997
997
998 total = len(revs)
998 total = len(revs)
999 revwidth = max([len(str(rev)) for rev in revs])
999 revwidth = max([len(str(rev)) for rev in revs])
1000 filemode = {}
1000 filemode = {}
1001
1001
1002 def single(rev, seqno, fp):
1002 def single(rev, seqno, fp):
1003 ctx = repo[rev]
1003 ctx = repo[rev]
1004 node = ctx.node()
1004 node = ctx.node()
1005 parents = [p.node() for p in ctx.parents() if p]
1005 parents = [p.node() for p in ctx.parents() if p]
1006 branch = ctx.branch()
1006 branch = ctx.branch()
1007 if switch_parent:
1007 if switch_parent:
1008 parents.reverse()
1008 parents.reverse()
1009
1009
1010 if parents:
1010 if parents:
1011 prev = parents[0]
1011 prev = parents[0]
1012 else:
1012 else:
1013 prev = nullid
1013 prev = nullid
1014
1014
1015 shouldclose = False
1015 shouldclose = False
1016 if not fp and len(template) > 0:
1016 if not fp and len(template) > 0:
1017 desc_lines = ctx.description().rstrip().split('\n')
1017 desc_lines = ctx.description().rstrip().split('\n')
1018 desc = desc_lines[0] #Commit always has a first line.
1018 desc = desc_lines[0] #Commit always has a first line.
1019 fp = makefileobj(repo, template, node, desc=desc, total=total,
1019 fp = makefileobj(repo, template, node, desc=desc, total=total,
1020 seqno=seqno, revwidth=revwidth, mode='wb',
1020 seqno=seqno, revwidth=revwidth, mode='wb',
1021 modemap=filemode)
1021 modemap=filemode)
1022 if fp != template:
1022 if fp != template:
1023 shouldclose = True
1023 shouldclose = True
1024 if fp and fp != sys.stdout and util.safehasattr(fp, 'name'):
1024 if fp and fp != sys.stdout and util.safehasattr(fp, 'name'):
1025 repo.ui.note("%s\n" % fp.name)
1025 repo.ui.note("%s\n" % fp.name)
1026
1026
1027 if not fp:
1027 if not fp:
1028 write = repo.ui.write
1028 write = repo.ui.write
1029 else:
1029 else:
1030 def write(s, **kw):
1030 def write(s, **kw):
1031 fp.write(s)
1031 fp.write(s)
1032
1032
1033 write("# HG changeset patch\n")
1033 write("# HG changeset patch\n")
1034 write("# User %s\n" % ctx.user())
1034 write("# User %s\n" % ctx.user())
1035 write("# Date %d %d\n" % ctx.date())
1035 write("# Date %d %d\n" % ctx.date())
1036 write("# %s\n" % util.datestr(ctx.date()))
1036 write("# %s\n" % util.datestr(ctx.date()))
1037 if branch and branch != 'default':
1037 if branch and branch != 'default':
1038 write("# Branch %s\n" % branch)
1038 write("# Branch %s\n" % branch)
1039 write("# Node ID %s\n" % hex(node))
1039 write("# Node ID %s\n" % hex(node))
1040 write("# Parent %s\n" % hex(prev))
1040 write("# Parent %s\n" % hex(prev))
1041 if len(parents) > 1:
1041 if len(parents) > 1:
1042 write("# Parent %s\n" % hex(parents[1]))
1042 write("# Parent %s\n" % hex(parents[1]))
1043 write(ctx.description().rstrip())
1043 write(ctx.description().rstrip())
1044 write("\n\n")
1044 write("\n\n")
1045
1045
1046 for chunk, label in patch.diffui(repo, prev, node, match, opts=opts):
1046 for chunk, label in patch.diffui(repo, prev, node, match, opts=opts):
1047 write(chunk, label=label)
1047 write(chunk, label=label)
1048
1048
1049 if shouldclose:
1049 if shouldclose:
1050 fp.close()
1050 fp.close()
1051
1051
1052 for seqno, rev in enumerate(revs):
1052 for seqno, rev in enumerate(revs):
1053 single(rev, seqno + 1, fp)
1053 single(rev, seqno + 1, fp)
1054
1054
1055 def diffordiffstat(ui, repo, diffopts, node1, node2, match,
1055 def diffordiffstat(ui, repo, diffopts, node1, node2, match,
1056 changes=None, stat=False, fp=None, prefix='',
1056 changes=None, stat=False, fp=None, prefix='',
1057 root='', listsubrepos=False):
1057 root='', listsubrepos=False):
1058 '''show diff or diffstat.'''
1058 '''show diff or diffstat.'''
1059 if fp is None:
1059 if fp is None:
1060 write = ui.write
1060 write = ui.write
1061 else:
1061 else:
1062 def write(s, **kw):
1062 def write(s, **kw):
1063 fp.write(s)
1063 fp.write(s)
1064
1064
1065 if root:
1065 if root:
1066 relroot = pathutil.canonpath(repo.root, repo.getcwd(), root)
1066 relroot = pathutil.canonpath(repo.root, repo.getcwd(), root)
1067 else:
1067 else:
1068 relroot = ''
1068 relroot = ''
1069 if relroot != '':
1069 if relroot != '':
1070 # XXX relative roots currently don't work if the root is within a
1070 # XXX relative roots currently don't work if the root is within a
1071 # subrepo
1071 # subrepo
1072 uirelroot = match.uipath(relroot)
1072 uirelroot = match.uipath(relroot)
1073 relroot += '/'
1073 relroot += '/'
1074 for matchroot in match.files():
1074 for matchroot in match.files():
1075 if not matchroot.startswith(relroot):
1075 if not matchroot.startswith(relroot):
1076 ui.warn(_('warning: %s not inside relative root %s\n') % (
1076 ui.warn(_('warning: %s not inside relative root %s\n') % (
1077 match.uipath(matchroot), uirelroot))
1077 match.uipath(matchroot), uirelroot))
1078
1078
1079 if stat:
1079 if stat:
1080 diffopts = diffopts.copy(context=0)
1080 diffopts = diffopts.copy(context=0)
1081 width = 80
1081 width = 80
1082 if not ui.plain():
1082 if not ui.plain():
1083 width = ui.termwidth()
1083 width = ui.termwidth()
1084 chunks = patch.diff(repo, node1, node2, match, changes, diffopts,
1084 chunks = patch.diff(repo, node1, node2, match, changes, diffopts,
1085 prefix=prefix, relroot=relroot)
1085 prefix=prefix, relroot=relroot)
1086 for chunk, label in patch.diffstatui(util.iterlines(chunks),
1086 for chunk, label in patch.diffstatui(util.iterlines(chunks),
1087 width=width,
1087 width=width,
1088 git=diffopts.git):
1088 git=diffopts.git):
1089 write(chunk, label=label)
1089 write(chunk, label=label)
1090 else:
1090 else:
1091 for chunk, label in patch.diffui(repo, node1, node2, match,
1091 for chunk, label in patch.diffui(repo, node1, node2, match,
1092 changes, diffopts, prefix=prefix,
1092 changes, diffopts, prefix=prefix,
1093 relroot=relroot):
1093 relroot=relroot):
1094 write(chunk, label=label)
1094 write(chunk, label=label)
1095
1095
1096 if listsubrepos:
1096 if listsubrepos:
1097 ctx1 = repo[node1]
1097 ctx1 = repo[node1]
1098 ctx2 = repo[node2]
1098 ctx2 = repo[node2]
1099 for subpath, sub in scmutil.itersubrepos(ctx1, ctx2):
1099 for subpath, sub in scmutil.itersubrepos(ctx1, ctx2):
1100 tempnode2 = node2
1100 tempnode2 = node2
1101 try:
1101 try:
1102 if node2 is not None:
1102 if node2 is not None:
1103 tempnode2 = ctx2.substate[subpath][1]
1103 tempnode2 = ctx2.substate[subpath][1]
1104 except KeyError:
1104 except KeyError:
1105 # A subrepo that existed in node1 was deleted between node1 and
1105 # A subrepo that existed in node1 was deleted between node1 and
1106 # node2 (inclusive). Thus, ctx2's substate won't contain that
1106 # node2 (inclusive). Thus, ctx2's substate won't contain that
1107 # subpath. The best we can do is to ignore it.
1107 # subpath. The best we can do is to ignore it.
1108 tempnode2 = None
1108 tempnode2 = None
1109 submatch = matchmod.narrowmatcher(subpath, match)
1109 submatch = matchmod.narrowmatcher(subpath, match)
1110 sub.diff(ui, diffopts, tempnode2, submatch, changes=changes,
1110 sub.diff(ui, diffopts, tempnode2, submatch, changes=changes,
1111 stat=stat, fp=fp, prefix=prefix)
1111 stat=stat, fp=fp, prefix=prefix)
1112
1112
1113 class changeset_printer(object):
1113 class changeset_printer(object):
1114 '''show changeset information when templating not requested.'''
1114 '''show changeset information when templating not requested.'''
1115
1115
1116 def __init__(self, ui, repo, matchfn, diffopts, buffered):
1116 def __init__(self, ui, repo, matchfn, diffopts, buffered):
1117 self.ui = ui
1117 self.ui = ui
1118 self.repo = repo
1118 self.repo = repo
1119 self.buffered = buffered
1119 self.buffered = buffered
1120 self.matchfn = matchfn
1120 self.matchfn = matchfn
1121 self.diffopts = diffopts
1121 self.diffopts = diffopts
1122 self.header = {}
1122 self.header = {}
1123 self.hunk = {}
1123 self.hunk = {}
1124 self.lastheader = None
1124 self.lastheader = None
1125 self.footer = None
1125 self.footer = None
1126
1126
1127 def flush(self, ctx):
1127 def flush(self, ctx):
1128 rev = ctx.rev()
1128 rev = ctx.rev()
1129 if rev in self.header:
1129 if rev in self.header:
1130 h = self.header[rev]
1130 h = self.header[rev]
1131 if h != self.lastheader:
1131 if h != self.lastheader:
1132 self.lastheader = h
1132 self.lastheader = h
1133 self.ui.write(h)
1133 self.ui.write(h)
1134 del self.header[rev]
1134 del self.header[rev]
1135 if rev in self.hunk:
1135 if rev in self.hunk:
1136 self.ui.write(self.hunk[rev])
1136 self.ui.write(self.hunk[rev])
1137 del self.hunk[rev]
1137 del self.hunk[rev]
1138 return 1
1138 return 1
1139 return 0
1139 return 0
1140
1140
1141 def close(self):
1141 def close(self):
1142 if self.footer:
1142 if self.footer:
1143 self.ui.write(self.footer)
1143 self.ui.write(self.footer)
1144
1144
1145 def show(self, ctx, copies=None, matchfn=None, **props):
1145 def show(self, ctx, copies=None, matchfn=None, **props):
1146 if self.buffered:
1146 if self.buffered:
1147 self.ui.pushbuffer()
1147 self.ui.pushbuffer()
1148 self._show(ctx, copies, matchfn, props)
1148 self._show(ctx, copies, matchfn, props)
1149 self.hunk[ctx.rev()] = self.ui.popbuffer(labeled=True)
1149 self.hunk[ctx.rev()] = self.ui.popbuffer(labeled=True)
1150 else:
1150 else:
1151 self._show(ctx, copies, matchfn, props)
1151 self._show(ctx, copies, matchfn, props)
1152
1152
1153 def _show(self, ctx, copies, matchfn, props):
1153 def _show(self, ctx, copies, matchfn, props):
1154 '''show a single changeset or file revision'''
1154 '''show a single changeset or file revision'''
1155 changenode = ctx.node()
1155 changenode = ctx.node()
1156 rev = ctx.rev()
1156 rev = ctx.rev()
1157 if self.ui.debugflag:
1157 if self.ui.debugflag:
1158 hexfunc = hex
1158 hexfunc = hex
1159 else:
1159 else:
1160 hexfunc = short
1160 hexfunc = short
1161 # as of now, wctx.node() and wctx.rev() return None, but we want to
1161 # as of now, wctx.node() and wctx.rev() return None, but we want to
1162 # show the same values as {node} and {rev} templatekw
1162 # show the same values as {node} and {rev} templatekw
1163 revnode = (scmutil.intrev(rev), hexfunc(bin(ctx.hex())))
1163 revnode = (scmutil.intrev(rev), hexfunc(bin(ctx.hex())))
1164
1164
1165 if self.ui.quiet:
1165 if self.ui.quiet:
1166 self.ui.write("%d:%s\n" % revnode, label='log.node')
1166 self.ui.write("%d:%s\n" % revnode, label='log.node')
1167 return
1167 return
1168
1168
1169 date = util.datestr(ctx.date())
1169 date = util.datestr(ctx.date())
1170
1170
1171 # i18n: column positioning for "hg log"
1171 # i18n: column positioning for "hg log"
1172 self.ui.write(_("changeset: %d:%s\n") % revnode,
1172 self.ui.write(_("changeset: %d:%s\n") % revnode,
1173 label='log.changeset changeset.%s' % ctx.phasestr())
1173 label='log.changeset changeset.%s' % ctx.phasestr())
1174
1174
1175 # branches are shown first before any other names due to backwards
1175 # branches are shown first before any other names due to backwards
1176 # compatibility
1176 # compatibility
1177 branch = ctx.branch()
1177 branch = ctx.branch()
1178 # don't show the default branch name
1178 # don't show the default branch name
1179 if branch != 'default':
1179 if branch != 'default':
1180 # i18n: column positioning for "hg log"
1180 # i18n: column positioning for "hg log"
1181 self.ui.write(_("branch: %s\n") % branch,
1181 self.ui.write(_("branch: %s\n") % branch,
1182 label='log.branch')
1182 label='log.branch')
1183
1183
1184 for name, ns in self.repo.names.iteritems():
1184 for name, ns in self.repo.names.iteritems():
1185 # branches has special logic already handled above, so here we just
1185 # branches has special logic already handled above, so here we just
1186 # skip it
1186 # skip it
1187 if name == 'branches':
1187 if name == 'branches':
1188 continue
1188 continue
1189 # we will use the templatename as the color name since those two
1189 # we will use the templatename as the color name since those two
1190 # should be the same
1190 # should be the same
1191 for name in ns.names(self.repo, changenode):
1191 for name in ns.names(self.repo, changenode):
1192 self.ui.write(ns.logfmt % name,
1192 self.ui.write(ns.logfmt % name,
1193 label='log.%s' % ns.colorname)
1193 label='log.%s' % ns.colorname)
1194 if self.ui.debugflag:
1194 if self.ui.debugflag:
1195 # i18n: column positioning for "hg log"
1195 # i18n: column positioning for "hg log"
1196 self.ui.write(_("phase: %s\n") % ctx.phasestr(),
1196 self.ui.write(_("phase: %s\n") % ctx.phasestr(),
1197 label='log.phase')
1197 label='log.phase')
1198 for pctx in scmutil.meaningfulparents(self.repo, ctx):
1198 for pctx in scmutil.meaningfulparents(self.repo, ctx):
1199 label = 'log.parent changeset.%s' % pctx.phasestr()
1199 label = 'log.parent changeset.%s' % pctx.phasestr()
1200 # i18n: column positioning for "hg log"
1200 # i18n: column positioning for "hg log"
1201 self.ui.write(_("parent: %d:%s\n")
1201 self.ui.write(_("parent: %d:%s\n")
1202 % (pctx.rev(), hexfunc(pctx.node())),
1202 % (pctx.rev(), hexfunc(pctx.node())),
1203 label=label)
1203 label=label)
1204
1204
1205 if self.ui.debugflag and rev is not None:
1205 if self.ui.debugflag and rev is not None:
1206 mnode = ctx.manifestnode()
1206 mnode = ctx.manifestnode()
1207 # i18n: column positioning for "hg log"
1207 # i18n: column positioning for "hg log"
1208 self.ui.write(_("manifest: %d:%s\n") %
1208 self.ui.write(_("manifest: %d:%s\n") %
1209 (self.repo.manifest.rev(mnode), hex(mnode)),
1209 (self.repo.manifest.rev(mnode), hex(mnode)),
1210 label='ui.debug log.manifest')
1210 label='ui.debug log.manifest')
1211 # i18n: column positioning for "hg log"
1211 # i18n: column positioning for "hg log"
1212 self.ui.write(_("user: %s\n") % ctx.user(),
1212 self.ui.write(_("user: %s\n") % ctx.user(),
1213 label='log.user')
1213 label='log.user')
1214 # i18n: column positioning for "hg log"
1214 # i18n: column positioning for "hg log"
1215 self.ui.write(_("date: %s\n") % date,
1215 self.ui.write(_("date: %s\n") % date,
1216 label='log.date')
1216 label='log.date')
1217
1217
1218 if self.ui.debugflag:
1218 if self.ui.debugflag:
1219 files = ctx.p1().status(ctx)[:3]
1219 files = ctx.p1().status(ctx)[:3]
1220 for key, value in zip([# i18n: column positioning for "hg log"
1220 for key, value in zip([# i18n: column positioning for "hg log"
1221 _("files:"),
1221 _("files:"),
1222 # i18n: column positioning for "hg log"
1222 # i18n: column positioning for "hg log"
1223 _("files+:"),
1223 _("files+:"),
1224 # i18n: column positioning for "hg log"
1224 # i18n: column positioning for "hg log"
1225 _("files-:")], files):
1225 _("files-:")], files):
1226 if value:
1226 if value:
1227 self.ui.write("%-12s %s\n" % (key, " ".join(value)),
1227 self.ui.write("%-12s %s\n" % (key, " ".join(value)),
1228 label='ui.debug log.files')
1228 label='ui.debug log.files')
1229 elif ctx.files() and self.ui.verbose:
1229 elif ctx.files() and self.ui.verbose:
1230 # i18n: column positioning for "hg log"
1230 # i18n: column positioning for "hg log"
1231 self.ui.write(_("files: %s\n") % " ".join(ctx.files()),
1231 self.ui.write(_("files: %s\n") % " ".join(ctx.files()),
1232 label='ui.note log.files')
1232 label='ui.note log.files')
1233 if copies and self.ui.verbose:
1233 if copies and self.ui.verbose:
1234 copies = ['%s (%s)' % c for c in copies]
1234 copies = ['%s (%s)' % c for c in copies]
1235 # i18n: column positioning for "hg log"
1235 # i18n: column positioning for "hg log"
1236 self.ui.write(_("copies: %s\n") % ' '.join(copies),
1236 self.ui.write(_("copies: %s\n") % ' '.join(copies),
1237 label='ui.note log.copies')
1237 label='ui.note log.copies')
1238
1238
1239 extra = ctx.extra()
1239 extra = ctx.extra()
1240 if extra and self.ui.debugflag:
1240 if extra and self.ui.debugflag:
1241 for key, value in sorted(extra.items()):
1241 for key, value in sorted(extra.items()):
1242 # i18n: column positioning for "hg log"
1242 # i18n: column positioning for "hg log"
1243 self.ui.write(_("extra: %s=%s\n")
1243 self.ui.write(_("extra: %s=%s\n")
1244 % (key, value.encode('string_escape')),
1244 % (key, value.encode('string_escape')),
1245 label='ui.debug log.extra')
1245 label='ui.debug log.extra')
1246
1246
1247 description = ctx.description().strip()
1247 description = ctx.description().strip()
1248 if description:
1248 if description:
1249 if self.ui.verbose:
1249 if self.ui.verbose:
1250 self.ui.write(_("description:\n"),
1250 self.ui.write(_("description:\n"),
1251 label='ui.note log.description')
1251 label='ui.note log.description')
1252 self.ui.write(description,
1252 self.ui.write(description,
1253 label='ui.note log.description')
1253 label='ui.note log.description')
1254 self.ui.write("\n\n")
1254 self.ui.write("\n\n")
1255 else:
1255 else:
1256 # i18n: column positioning for "hg log"
1256 # i18n: column positioning for "hg log"
1257 self.ui.write(_("summary: %s\n") %
1257 self.ui.write(_("summary: %s\n") %
1258 description.splitlines()[0],
1258 description.splitlines()[0],
1259 label='log.summary')
1259 label='log.summary')
1260 self.ui.write("\n")
1260 self.ui.write("\n")
1261
1261
1262 self.showpatch(changenode, matchfn)
1262 self.showpatch(changenode, matchfn)
1263
1263
1264 def showpatch(self, node, matchfn):
1264 def showpatch(self, node, matchfn):
1265 if not matchfn:
1265 if not matchfn:
1266 matchfn = self.matchfn
1266 matchfn = self.matchfn
1267 if matchfn:
1267 if matchfn:
1268 stat = self.diffopts.get('stat')
1268 stat = self.diffopts.get('stat')
1269 diff = self.diffopts.get('patch')
1269 diff = self.diffopts.get('patch')
1270 diffopts = patch.diffallopts(self.ui, self.diffopts)
1270 diffopts = patch.diffallopts(self.ui, self.diffopts)
1271 prev = self.repo.changelog.parents(node)[0]
1271 prev = self.repo.changelog.parents(node)[0]
1272 if stat:
1272 if stat:
1273 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1273 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1274 match=matchfn, stat=True)
1274 match=matchfn, stat=True)
1275 if diff:
1275 if diff:
1276 if stat:
1276 if stat:
1277 self.ui.write("\n")
1277 self.ui.write("\n")
1278 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1278 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1279 match=matchfn, stat=False)
1279 match=matchfn, stat=False)
1280 self.ui.write("\n")
1280 self.ui.write("\n")
1281
1281
1282 class jsonchangeset(changeset_printer):
1282 class jsonchangeset(changeset_printer):
1283 '''format changeset information.'''
1283 '''format changeset information.'''
1284
1284
1285 def __init__(self, ui, repo, matchfn, diffopts, buffered):
1285 def __init__(self, ui, repo, matchfn, diffopts, buffered):
1286 changeset_printer.__init__(self, ui, repo, matchfn, diffopts, buffered)
1286 changeset_printer.__init__(self, ui, repo, matchfn, diffopts, buffered)
1287 self.cache = {}
1287 self.cache = {}
1288 self._first = True
1288 self._first = True
1289
1289
1290 def close(self):
1290 def close(self):
1291 if not self._first:
1291 if not self._first:
1292 self.ui.write("\n]\n")
1292 self.ui.write("\n]\n")
1293 else:
1293 else:
1294 self.ui.write("[]\n")
1294 self.ui.write("[]\n")
1295
1295
1296 def _show(self, ctx, copies, matchfn, props):
1296 def _show(self, ctx, copies, matchfn, props):
1297 '''show a single changeset or file revision'''
1297 '''show a single changeset or file revision'''
1298 rev = ctx.rev()
1298 rev = ctx.rev()
1299 if rev is None:
1299 if rev is None:
1300 jrev = jnode = 'null'
1300 jrev = jnode = 'null'
1301 else:
1301 else:
1302 jrev = str(rev)
1302 jrev = str(rev)
1303 jnode = '"%s"' % hex(ctx.node())
1303 jnode = '"%s"' % hex(ctx.node())
1304 j = encoding.jsonescape
1304 j = encoding.jsonescape
1305
1305
1306 if self._first:
1306 if self._first:
1307 self.ui.write("[\n {")
1307 self.ui.write("[\n {")
1308 self._first = False
1308 self._first = False
1309 else:
1309 else:
1310 self.ui.write(",\n {")
1310 self.ui.write(",\n {")
1311
1311
1312 if self.ui.quiet:
1312 if self.ui.quiet:
1313 self.ui.write('\n "rev": %s' % jrev)
1313 self.ui.write('\n "rev": %s' % jrev)
1314 self.ui.write(',\n "node": %s' % jnode)
1314 self.ui.write(',\n "node": %s' % jnode)
1315 self.ui.write('\n }')
1315 self.ui.write('\n }')
1316 return
1316 return
1317
1317
1318 self.ui.write('\n "rev": %s' % jrev)
1318 self.ui.write('\n "rev": %s' % jrev)
1319 self.ui.write(',\n "node": %s' % jnode)
1319 self.ui.write(',\n "node": %s' % jnode)
1320 self.ui.write(',\n "branch": "%s"' % j(ctx.branch()))
1320 self.ui.write(',\n "branch": "%s"' % j(ctx.branch()))
1321 self.ui.write(',\n "phase": "%s"' % ctx.phasestr())
1321 self.ui.write(',\n "phase": "%s"' % ctx.phasestr())
1322 self.ui.write(',\n "user": "%s"' % j(ctx.user()))
1322 self.ui.write(',\n "user": "%s"' % j(ctx.user()))
1323 self.ui.write(',\n "date": [%d, %d]' % ctx.date())
1323 self.ui.write(',\n "date": [%d, %d]' % ctx.date())
1324 self.ui.write(',\n "desc": "%s"' % j(ctx.description()))
1324 self.ui.write(',\n "desc": "%s"' % j(ctx.description()))
1325
1325
1326 self.ui.write(',\n "bookmarks": [%s]' %
1326 self.ui.write(',\n "bookmarks": [%s]' %
1327 ", ".join('"%s"' % j(b) for b in ctx.bookmarks()))
1327 ", ".join('"%s"' % j(b) for b in ctx.bookmarks()))
1328 self.ui.write(',\n "tags": [%s]' %
1328 self.ui.write(',\n "tags": [%s]' %
1329 ", ".join('"%s"' % j(t) for t in ctx.tags()))
1329 ", ".join('"%s"' % j(t) for t in ctx.tags()))
1330 self.ui.write(',\n "parents": [%s]' %
1330 self.ui.write(',\n "parents": [%s]' %
1331 ", ".join('"%s"' % c.hex() for c in ctx.parents()))
1331 ", ".join('"%s"' % c.hex() for c in ctx.parents()))
1332
1332
1333 if self.ui.debugflag:
1333 if self.ui.debugflag:
1334 if rev is None:
1334 if rev is None:
1335 jmanifestnode = 'null'
1335 jmanifestnode = 'null'
1336 else:
1336 else:
1337 jmanifestnode = '"%s"' % hex(ctx.manifestnode())
1337 jmanifestnode = '"%s"' % hex(ctx.manifestnode())
1338 self.ui.write(',\n "manifest": %s' % jmanifestnode)
1338 self.ui.write(',\n "manifest": %s' % jmanifestnode)
1339
1339
1340 self.ui.write(',\n "extra": {%s}' %
1340 self.ui.write(',\n "extra": {%s}' %
1341 ", ".join('"%s": "%s"' % (j(k), j(v))
1341 ", ".join('"%s": "%s"' % (j(k), j(v))
1342 for k, v in ctx.extra().items()))
1342 for k, v in ctx.extra().items()))
1343
1343
1344 files = ctx.p1().status(ctx)
1344 files = ctx.p1().status(ctx)
1345 self.ui.write(',\n "modified": [%s]' %
1345 self.ui.write(',\n "modified": [%s]' %
1346 ", ".join('"%s"' % j(f) for f in files[0]))
1346 ", ".join('"%s"' % j(f) for f in files[0]))
1347 self.ui.write(',\n "added": [%s]' %
1347 self.ui.write(',\n "added": [%s]' %
1348 ", ".join('"%s"' % j(f) for f in files[1]))
1348 ", ".join('"%s"' % j(f) for f in files[1]))
1349 self.ui.write(',\n "removed": [%s]' %
1349 self.ui.write(',\n "removed": [%s]' %
1350 ", ".join('"%s"' % j(f) for f in files[2]))
1350 ", ".join('"%s"' % j(f) for f in files[2]))
1351
1351
1352 elif self.ui.verbose:
1352 elif self.ui.verbose:
1353 self.ui.write(',\n "files": [%s]' %
1353 self.ui.write(',\n "files": [%s]' %
1354 ", ".join('"%s"' % j(f) for f in ctx.files()))
1354 ", ".join('"%s"' % j(f) for f in ctx.files()))
1355
1355
1356 if copies:
1356 if copies:
1357 self.ui.write(',\n "copies": {%s}' %
1357 self.ui.write(',\n "copies": {%s}' %
1358 ", ".join('"%s": "%s"' % (j(k), j(v))
1358 ", ".join('"%s": "%s"' % (j(k), j(v))
1359 for k, v in copies))
1359 for k, v in copies))
1360
1360
1361 matchfn = self.matchfn
1361 matchfn = self.matchfn
1362 if matchfn:
1362 if matchfn:
1363 stat = self.diffopts.get('stat')
1363 stat = self.diffopts.get('stat')
1364 diff = self.diffopts.get('patch')
1364 diff = self.diffopts.get('patch')
1365 diffopts = patch.difffeatureopts(self.ui, self.diffopts, git=True)
1365 diffopts = patch.difffeatureopts(self.ui, self.diffopts, git=True)
1366 node, prev = ctx.node(), ctx.p1().node()
1366 node, prev = ctx.node(), ctx.p1().node()
1367 if stat:
1367 if stat:
1368 self.ui.pushbuffer()
1368 self.ui.pushbuffer()
1369 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1369 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1370 match=matchfn, stat=True)
1370 match=matchfn, stat=True)
1371 self.ui.write(',\n "diffstat": "%s"' % j(self.ui.popbuffer()))
1371 self.ui.write(',\n "diffstat": "%s"' % j(self.ui.popbuffer()))
1372 if diff:
1372 if diff:
1373 self.ui.pushbuffer()
1373 self.ui.pushbuffer()
1374 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1374 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1375 match=matchfn, stat=False)
1375 match=matchfn, stat=False)
1376 self.ui.write(',\n "diff": "%s"' % j(self.ui.popbuffer()))
1376 self.ui.write(',\n "diff": "%s"' % j(self.ui.popbuffer()))
1377
1377
1378 self.ui.write("\n }")
1378 self.ui.write("\n }")
1379
1379
1380 class changeset_templater(changeset_printer):
1380 class changeset_templater(changeset_printer):
1381 '''format changeset information.'''
1381 '''format changeset information.'''
1382
1382
1383 def __init__(self, ui, repo, matchfn, diffopts, tmpl, mapfile, buffered):
1383 def __init__(self, ui, repo, matchfn, diffopts, tmpl, mapfile, buffered):
1384 changeset_printer.__init__(self, ui, repo, matchfn, diffopts, buffered)
1384 changeset_printer.__init__(self, ui, repo, matchfn, diffopts, buffered)
1385 formatnode = ui.debugflag and (lambda x: x) or (lambda x: x[:12])
1385 formatnode = ui.debugflag and (lambda x: x) or (lambda x: x[:12])
1386 defaulttempl = {
1386 defaulttempl = {
1387 'parent': '{rev}:{node|formatnode} ',
1387 'parent': '{rev}:{node|formatnode} ',
1388 'manifest': '{rev}:{node|formatnode}',
1388 'manifest': '{rev}:{node|formatnode}',
1389 'file_copy': '{name} ({source})',
1389 'file_copy': '{name} ({source})',
1390 'extra': '{key}={value|stringescape}'
1390 'extra': '{key}={value|stringescape}'
1391 }
1391 }
1392 # filecopy is preserved for compatibility reasons
1392 # filecopy is preserved for compatibility reasons
1393 defaulttempl['filecopy'] = defaulttempl['file_copy']
1393 defaulttempl['filecopy'] = defaulttempl['file_copy']
1394 self.t = templater.templater(mapfile, {'formatnode': formatnode},
1394 self.t = templater.templater(mapfile, {'formatnode': formatnode},
1395 cache=defaulttempl)
1395 cache=defaulttempl)
1396 if tmpl:
1396 if tmpl:
1397 self.t.cache['changeset'] = tmpl
1397 self.t.cache['changeset'] = tmpl
1398
1398
1399 self.cache = {}
1399 self.cache = {}
1400
1400
1401 # find correct templates for current mode
1401 # find correct templates for current mode
1402 tmplmodes = [
1402 tmplmodes = [
1403 (True, None),
1403 (True, None),
1404 (self.ui.verbose, 'verbose'),
1404 (self.ui.verbose, 'verbose'),
1405 (self.ui.quiet, 'quiet'),
1405 (self.ui.quiet, 'quiet'),
1406 (self.ui.debugflag, 'debug'),
1406 (self.ui.debugflag, 'debug'),
1407 ]
1407 ]
1408
1408
1409 self._parts = {'header': '', 'footer': '', 'changeset': 'changeset',
1409 self._parts = {'header': '', 'footer': '', 'changeset': 'changeset',
1410 'docheader': '', 'docfooter': ''}
1410 'docheader': '', 'docfooter': ''}
1411 for mode, postfix in tmplmodes:
1411 for mode, postfix in tmplmodes:
1412 for t in self._parts:
1412 for t in self._parts:
1413 cur = t
1413 cur = t
1414 if postfix:
1414 if postfix:
1415 cur += "_" + postfix
1415 cur += "_" + postfix
1416 if mode and cur in self.t:
1416 if mode and cur in self.t:
1417 self._parts[t] = cur
1417 self._parts[t] = cur
1418
1418
1419 if self._parts['docheader']:
1419 if self._parts['docheader']:
1420 self.ui.write(templater.stringify(self.t(self._parts['docheader'])))
1420 self.ui.write(templater.stringify(self.t(self._parts['docheader'])))
1421
1421
1422 def close(self):
1422 def close(self):
1423 if self._parts['docfooter']:
1423 if self._parts['docfooter']:
1424 if not self.footer:
1424 if not self.footer:
1425 self.footer = ""
1425 self.footer = ""
1426 self.footer += templater.stringify(self.t(self._parts['docfooter']))
1426 self.footer += templater.stringify(self.t(self._parts['docfooter']))
1427 return super(changeset_templater, self).close()
1427 return super(changeset_templater, self).close()
1428
1428
1429 def _show(self, ctx, copies, matchfn, props):
1429 def _show(self, ctx, copies, matchfn, props):
1430 '''show a single changeset or file revision'''
1430 '''show a single changeset or file revision'''
1431 props = props.copy()
1431 props = props.copy()
1432 props.update(templatekw.keywords)
1432 props.update(templatekw.keywords)
1433 props['templ'] = self.t
1433 props['templ'] = self.t
1434 props['ctx'] = ctx
1434 props['ctx'] = ctx
1435 props['repo'] = self.repo
1435 props['repo'] = self.repo
1436 props['revcache'] = {'copies': copies}
1436 props['revcache'] = {'copies': copies}
1437 props['cache'] = self.cache
1437 props['cache'] = self.cache
1438
1438
1439 try:
1439 try:
1440 # write header
1440 # write header
1441 if self._parts['header']:
1441 if self._parts['header']:
1442 h = templater.stringify(self.t(self._parts['header'], **props))
1442 h = templater.stringify(self.t(self._parts['header'], **props))
1443 if self.buffered:
1443 if self.buffered:
1444 self.header[ctx.rev()] = h
1444 self.header[ctx.rev()] = h
1445 else:
1445 else:
1446 if self.lastheader != h:
1446 if self.lastheader != h:
1447 self.lastheader = h
1447 self.lastheader = h
1448 self.ui.write(h)
1448 self.ui.write(h)
1449
1449
1450 # write changeset metadata, then patch if requested
1450 # write changeset metadata, then patch if requested
1451 key = self._parts['changeset']
1451 key = self._parts['changeset']
1452 self.ui.write(templater.stringify(self.t(key, **props)))
1452 self.ui.write(templater.stringify(self.t(key, **props)))
1453 self.showpatch(ctx.node(), matchfn)
1453 self.showpatch(ctx.node(), matchfn)
1454
1454
1455 if self._parts['footer']:
1455 if self._parts['footer']:
1456 if not self.footer:
1456 if not self.footer:
1457 self.footer = templater.stringify(
1457 self.footer = templater.stringify(
1458 self.t(self._parts['footer'], **props))
1458 self.t(self._parts['footer'], **props))
1459 except KeyError as inst:
1459 except KeyError as inst:
1460 msg = _("%s: no key named '%s'")
1460 msg = _("%s: no key named '%s'")
1461 raise util.Abort(msg % (self.t.mapfile, inst.args[0]))
1461 raise util.Abort(msg % (self.t.mapfile, inst.args[0]))
1462 except SyntaxError as inst:
1462 except SyntaxError as inst:
1463 raise util.Abort('%s: %s' % (self.t.mapfile, inst.args[0]))
1463 raise util.Abort('%s: %s' % (self.t.mapfile, inst.args[0]))
1464
1464
1465 def gettemplate(ui, tmpl, style):
1465 def gettemplate(ui, tmpl, style):
1466 """
1466 """
1467 Find the template matching the given template spec or style.
1467 Find the template matching the given template spec or style.
1468 """
1468 """
1469
1469
1470 # ui settings
1470 # ui settings
1471 if not tmpl and not style: # template are stronger than style
1471 if not tmpl and not style: # template are stronger than style
1472 tmpl = ui.config('ui', 'logtemplate')
1472 tmpl = ui.config('ui', 'logtemplate')
1473 if tmpl:
1473 if tmpl:
1474 try:
1474 try:
1475 tmpl = templater.unquotestring(tmpl)
1475 tmpl = templater.unquotestring(tmpl)
1476 except SyntaxError:
1476 except SyntaxError:
1477 pass
1477 pass
1478 return tmpl, None
1478 return tmpl, None
1479 else:
1479 else:
1480 style = util.expandpath(ui.config('ui', 'style', ''))
1480 style = util.expandpath(ui.config('ui', 'style', ''))
1481
1481
1482 if not tmpl and style:
1482 if not tmpl and style:
1483 mapfile = style
1483 mapfile = style
1484 if not os.path.split(mapfile)[0]:
1484 if not os.path.split(mapfile)[0]:
1485 mapname = (templater.templatepath('map-cmdline.' + mapfile)
1485 mapname = (templater.templatepath('map-cmdline.' + mapfile)
1486 or templater.templatepath(mapfile))
1486 or templater.templatepath(mapfile))
1487 if mapname:
1487 if mapname:
1488 mapfile = mapname
1488 mapfile = mapname
1489 return None, mapfile
1489 return None, mapfile
1490
1490
1491 if not tmpl:
1491 if not tmpl:
1492 return None, None
1492 return None, None
1493
1493
1494 return formatter.lookuptemplate(ui, 'changeset', tmpl)
1494 return formatter.lookuptemplate(ui, 'changeset', tmpl)
1495
1495
1496 def show_changeset(ui, repo, opts, buffered=False):
1496 def show_changeset(ui, repo, opts, buffered=False):
1497 """show one changeset using template or regular display.
1497 """show one changeset using template or regular display.
1498
1498
1499 Display format will be the first non-empty hit of:
1499 Display format will be the first non-empty hit of:
1500 1. option 'template'
1500 1. option 'template'
1501 2. option 'style'
1501 2. option 'style'
1502 3. [ui] setting 'logtemplate'
1502 3. [ui] setting 'logtemplate'
1503 4. [ui] setting 'style'
1503 4. [ui] setting 'style'
1504 If all of these values are either the unset or the empty string,
1504 If all of these values are either the unset or the empty string,
1505 regular display via changeset_printer() is done.
1505 regular display via changeset_printer() is done.
1506 """
1506 """
1507 # options
1507 # options
1508 matchfn = None
1508 matchfn = None
1509 if opts.get('patch') or opts.get('stat'):
1509 if opts.get('patch') or opts.get('stat'):
1510 matchfn = scmutil.matchall(repo)
1510 matchfn = scmutil.matchall(repo)
1511
1511
1512 if opts.get('template') == 'json':
1512 if opts.get('template') == 'json':
1513 return jsonchangeset(ui, repo, matchfn, opts, buffered)
1513 return jsonchangeset(ui, repo, matchfn, opts, buffered)
1514
1514
1515 tmpl, mapfile = gettemplate(ui, opts.get('template'), opts.get('style'))
1515 tmpl, mapfile = gettemplate(ui, opts.get('template'), opts.get('style'))
1516
1516
1517 if not tmpl and not mapfile:
1517 if not tmpl and not mapfile:
1518 return changeset_printer(ui, repo, matchfn, opts, buffered)
1518 return changeset_printer(ui, repo, matchfn, opts, buffered)
1519
1519
1520 try:
1520 try:
1521 t = changeset_templater(ui, repo, matchfn, opts, tmpl, mapfile,
1521 t = changeset_templater(ui, repo, matchfn, opts, tmpl, mapfile,
1522 buffered)
1522 buffered)
1523 except SyntaxError as inst:
1523 except SyntaxError as inst:
1524 raise util.Abort(inst.args[0])
1524 raise util.Abort(inst.args[0])
1525 return t
1525 return t
1526
1526
1527 def showmarker(ui, marker):
1527 def showmarker(ui, marker):
1528 """utility function to display obsolescence marker in a readable way
1528 """utility function to display obsolescence marker in a readable way
1529
1529
1530 To be used by debug function."""
1530 To be used by debug function."""
1531 ui.write(hex(marker.precnode()))
1531 ui.write(hex(marker.precnode()))
1532 for repl in marker.succnodes():
1532 for repl in marker.succnodes():
1533 ui.write(' ')
1533 ui.write(' ')
1534 ui.write(hex(repl))
1534 ui.write(hex(repl))
1535 ui.write(' %X ' % marker.flags())
1535 ui.write(' %X ' % marker.flags())
1536 parents = marker.parentnodes()
1536 parents = marker.parentnodes()
1537 if parents is not None:
1537 if parents is not None:
1538 ui.write('{%s} ' % ', '.join(hex(p) for p in parents))
1538 ui.write('{%s} ' % ', '.join(hex(p) for p in parents))
1539 ui.write('(%s) ' % util.datestr(marker.date()))
1539 ui.write('(%s) ' % util.datestr(marker.date()))
1540 ui.write('{%s}' % (', '.join('%r: %r' % t for t in
1540 ui.write('{%s}' % (', '.join('%r: %r' % t for t in
1541 sorted(marker.metadata().items())
1541 sorted(marker.metadata().items())
1542 if t[0] != 'date')))
1542 if t[0] != 'date')))
1543 ui.write('\n')
1543 ui.write('\n')
1544
1544
1545 def finddate(ui, repo, date):
1545 def finddate(ui, repo, date):
1546 """Find the tipmost changeset that matches the given date spec"""
1546 """Find the tipmost changeset that matches the given date spec"""
1547
1547
1548 df = util.matchdate(date)
1548 df = util.matchdate(date)
1549 m = scmutil.matchall(repo)
1549 m = scmutil.matchall(repo)
1550 results = {}
1550 results = {}
1551
1551
1552 def prep(ctx, fns):
1552 def prep(ctx, fns):
1553 d = ctx.date()
1553 d = ctx.date()
1554 if df(d[0]):
1554 if df(d[0]):
1555 results[ctx.rev()] = d
1555 results[ctx.rev()] = d
1556
1556
1557 for ctx in walkchangerevs(repo, m, {'rev': None}, prep):
1557 for ctx in walkchangerevs(repo, m, {'rev': None}, prep):
1558 rev = ctx.rev()
1558 rev = ctx.rev()
1559 if rev in results:
1559 if rev in results:
1560 ui.status(_("found revision %s from %s\n") %
1560 ui.status(_("found revision %s from %s\n") %
1561 (rev, util.datestr(results[rev])))
1561 (rev, util.datestr(results[rev])))
1562 return str(rev)
1562 return str(rev)
1563
1563
1564 raise util.Abort(_("revision matching date not found"))
1564 raise util.Abort(_("revision matching date not found"))
1565
1565
1566 def increasingwindows(windowsize=8, sizelimit=512):
1566 def increasingwindows(windowsize=8, sizelimit=512):
1567 while True:
1567 while True:
1568 yield windowsize
1568 yield windowsize
1569 if windowsize < sizelimit:
1569 if windowsize < sizelimit:
1570 windowsize *= 2
1570 windowsize *= 2
1571
1571
1572 class FileWalkError(Exception):
1572 class FileWalkError(Exception):
1573 pass
1573 pass
1574
1574
1575 def walkfilerevs(repo, match, follow, revs, fncache):
1575 def walkfilerevs(repo, match, follow, revs, fncache):
1576 '''Walks the file history for the matched files.
1576 '''Walks the file history for the matched files.
1577
1577
1578 Returns the changeset revs that are involved in the file history.
1578 Returns the changeset revs that are involved in the file history.
1579
1579
1580 Throws FileWalkError if the file history can't be walked using
1580 Throws FileWalkError if the file history can't be walked using
1581 filelogs alone.
1581 filelogs alone.
1582 '''
1582 '''
1583 wanted = set()
1583 wanted = set()
1584 copies = []
1584 copies = []
1585 minrev, maxrev = min(revs), max(revs)
1585 minrev, maxrev = min(revs), max(revs)
1586 def filerevgen(filelog, last):
1586 def filerevgen(filelog, last):
1587 """
1587 """
1588 Only files, no patterns. Check the history of each file.
1588 Only files, no patterns. Check the history of each file.
1589
1589
1590 Examines filelog entries within minrev, maxrev linkrev range
1590 Examines filelog entries within minrev, maxrev linkrev range
1591 Returns an iterator yielding (linkrev, parentlinkrevs, copied)
1591 Returns an iterator yielding (linkrev, parentlinkrevs, copied)
1592 tuples in backwards order
1592 tuples in backwards order
1593 """
1593 """
1594 cl_count = len(repo)
1594 cl_count = len(repo)
1595 revs = []
1595 revs = []
1596 for j in xrange(0, last + 1):
1596 for j in xrange(0, last + 1):
1597 linkrev = filelog.linkrev(j)
1597 linkrev = filelog.linkrev(j)
1598 if linkrev < minrev:
1598 if linkrev < minrev:
1599 continue
1599 continue
1600 # only yield rev for which we have the changelog, it can
1600 # only yield rev for which we have the changelog, it can
1601 # happen while doing "hg log" during a pull or commit
1601 # happen while doing "hg log" during a pull or commit
1602 if linkrev >= cl_count:
1602 if linkrev >= cl_count:
1603 break
1603 break
1604
1604
1605 parentlinkrevs = []
1605 parentlinkrevs = []
1606 for p in filelog.parentrevs(j):
1606 for p in filelog.parentrevs(j):
1607 if p != nullrev:
1607 if p != nullrev:
1608 parentlinkrevs.append(filelog.linkrev(p))
1608 parentlinkrevs.append(filelog.linkrev(p))
1609 n = filelog.node(j)
1609 n = filelog.node(j)
1610 revs.append((linkrev, parentlinkrevs,
1610 revs.append((linkrev, parentlinkrevs,
1611 follow and filelog.renamed(n)))
1611 follow and filelog.renamed(n)))
1612
1612
1613 return reversed(revs)
1613 return reversed(revs)
1614 def iterfiles():
1614 def iterfiles():
1615 pctx = repo['.']
1615 pctx = repo['.']
1616 for filename in match.files():
1616 for filename in match.files():
1617 if follow:
1617 if follow:
1618 if filename not in pctx:
1618 if filename not in pctx:
1619 raise util.Abort(_('cannot follow file not in parent '
1619 raise util.Abort(_('cannot follow file not in parent '
1620 'revision: "%s"') % filename)
1620 'revision: "%s"') % filename)
1621 yield filename, pctx[filename].filenode()
1621 yield filename, pctx[filename].filenode()
1622 else:
1622 else:
1623 yield filename, None
1623 yield filename, None
1624 for filename_node in copies:
1624 for filename_node in copies:
1625 yield filename_node
1625 yield filename_node
1626
1626
1627 for file_, node in iterfiles():
1627 for file_, node in iterfiles():
1628 filelog = repo.file(file_)
1628 filelog = repo.file(file_)
1629 if not len(filelog):
1629 if not len(filelog):
1630 if node is None:
1630 if node is None:
1631 # A zero count may be a directory or deleted file, so
1631 # A zero count may be a directory or deleted file, so
1632 # try to find matching entries on the slow path.
1632 # try to find matching entries on the slow path.
1633 if follow:
1633 if follow:
1634 raise util.Abort(
1634 raise util.Abort(
1635 _('cannot follow nonexistent file: "%s"') % file_)
1635 _('cannot follow nonexistent file: "%s"') % file_)
1636 raise FileWalkError("Cannot walk via filelog")
1636 raise FileWalkError("Cannot walk via filelog")
1637 else:
1637 else:
1638 continue
1638 continue
1639
1639
1640 if node is None:
1640 if node is None:
1641 last = len(filelog) - 1
1641 last = len(filelog) - 1
1642 else:
1642 else:
1643 last = filelog.rev(node)
1643 last = filelog.rev(node)
1644
1644
1645 # keep track of all ancestors of the file
1645 # keep track of all ancestors of the file
1646 ancestors = set([filelog.linkrev(last)])
1646 ancestors = set([filelog.linkrev(last)])
1647
1647
1648 # iterate from latest to oldest revision
1648 # iterate from latest to oldest revision
1649 for rev, flparentlinkrevs, copied in filerevgen(filelog, last):
1649 for rev, flparentlinkrevs, copied in filerevgen(filelog, last):
1650 if not follow:
1650 if not follow:
1651 if rev > maxrev:
1651 if rev > maxrev:
1652 continue
1652 continue
1653 else:
1653 else:
1654 # Note that last might not be the first interesting
1654 # Note that last might not be the first interesting
1655 # rev to us:
1655 # rev to us:
1656 # if the file has been changed after maxrev, we'll
1656 # if the file has been changed after maxrev, we'll
1657 # have linkrev(last) > maxrev, and we still need
1657 # have linkrev(last) > maxrev, and we still need
1658 # to explore the file graph
1658 # to explore the file graph
1659 if rev not in ancestors:
1659 if rev not in ancestors:
1660 continue
1660 continue
1661 # XXX insert 1327 fix here
1661 # XXX insert 1327 fix here
1662 if flparentlinkrevs:
1662 if flparentlinkrevs:
1663 ancestors.update(flparentlinkrevs)
1663 ancestors.update(flparentlinkrevs)
1664
1664
1665 fncache.setdefault(rev, []).append(file_)
1665 fncache.setdefault(rev, []).append(file_)
1666 wanted.add(rev)
1666 wanted.add(rev)
1667 if copied:
1667 if copied:
1668 copies.append(copied)
1668 copies.append(copied)
1669
1669
1670 return wanted
1670 return wanted
1671
1671
1672 class _followfilter(object):
1672 class _followfilter(object):
1673 def __init__(self, repo, onlyfirst=False):
1673 def __init__(self, repo, onlyfirst=False):
1674 self.repo = repo
1674 self.repo = repo
1675 self.startrev = nullrev
1675 self.startrev = nullrev
1676 self.roots = set()
1676 self.roots = set()
1677 self.onlyfirst = onlyfirst
1677 self.onlyfirst = onlyfirst
1678
1678
1679 def match(self, rev):
1679 def match(self, rev):
1680 def realparents(rev):
1680 def realparents(rev):
1681 if self.onlyfirst:
1681 if self.onlyfirst:
1682 return self.repo.changelog.parentrevs(rev)[0:1]
1682 return self.repo.changelog.parentrevs(rev)[0:1]
1683 else:
1683 else:
1684 return filter(lambda x: x != nullrev,
1684 return filter(lambda x: x != nullrev,
1685 self.repo.changelog.parentrevs(rev))
1685 self.repo.changelog.parentrevs(rev))
1686
1686
1687 if self.startrev == nullrev:
1687 if self.startrev == nullrev:
1688 self.startrev = rev
1688 self.startrev = rev
1689 return True
1689 return True
1690
1690
1691 if rev > self.startrev:
1691 if rev > self.startrev:
1692 # forward: all descendants
1692 # forward: all descendants
1693 if not self.roots:
1693 if not self.roots:
1694 self.roots.add(self.startrev)
1694 self.roots.add(self.startrev)
1695 for parent in realparents(rev):
1695 for parent in realparents(rev):
1696 if parent in self.roots:
1696 if parent in self.roots:
1697 self.roots.add(rev)
1697 self.roots.add(rev)
1698 return True
1698 return True
1699 else:
1699 else:
1700 # backwards: all parents
1700 # backwards: all parents
1701 if not self.roots:
1701 if not self.roots:
1702 self.roots.update(realparents(self.startrev))
1702 self.roots.update(realparents(self.startrev))
1703 if rev in self.roots:
1703 if rev in self.roots:
1704 self.roots.remove(rev)
1704 self.roots.remove(rev)
1705 self.roots.update(realparents(rev))
1705 self.roots.update(realparents(rev))
1706 return True
1706 return True
1707
1707
1708 return False
1708 return False
1709
1709
1710 def walkchangerevs(repo, match, opts, prepare):
1710 def walkchangerevs(repo, match, opts, prepare):
1711 '''Iterate over files and the revs in which they changed.
1711 '''Iterate over files and the revs in which they changed.
1712
1712
1713 Callers most commonly need to iterate backwards over the history
1713 Callers most commonly need to iterate backwards over the history
1714 in which they are interested. Doing so has awful (quadratic-looking)
1714 in which they are interested. Doing so has awful (quadratic-looking)
1715 performance, so we use iterators in a "windowed" way.
1715 performance, so we use iterators in a "windowed" way.
1716
1716
1717 We walk a window of revisions in the desired order. Within the
1717 We walk a window of revisions in the desired order. Within the
1718 window, we first walk forwards to gather data, then in the desired
1718 window, we first walk forwards to gather data, then in the desired
1719 order (usually backwards) to display it.
1719 order (usually backwards) to display it.
1720
1720
1721 This function returns an iterator yielding contexts. Before
1721 This function returns an iterator yielding contexts. Before
1722 yielding each context, the iterator will first call the prepare
1722 yielding each context, the iterator will first call the prepare
1723 function on each context in the window in forward order.'''
1723 function on each context in the window in forward order.'''
1724
1724
1725 follow = opts.get('follow') or opts.get('follow_first')
1725 follow = opts.get('follow') or opts.get('follow_first')
1726 revs = _logrevs(repo, opts)
1726 revs = _logrevs(repo, opts)
1727 if not revs:
1727 if not revs:
1728 return []
1728 return []
1729 wanted = set()
1729 wanted = set()
1730 slowpath = match.anypats() or ((match.isexact() or match.prefix()) and
1730 slowpath = match.anypats() or ((match.isexact() or match.prefix()) and
1731 opts.get('removed'))
1731 opts.get('removed'))
1732 fncache = {}
1732 fncache = {}
1733 change = repo.changectx
1733 change = repo.changectx
1734
1734
1735 # First step is to fill wanted, the set of revisions that we want to yield.
1735 # First step is to fill wanted, the set of revisions that we want to yield.
1736 # When it does not induce extra cost, we also fill fncache for revisions in
1736 # When it does not induce extra cost, we also fill fncache for revisions in
1737 # wanted: a cache of filenames that were changed (ctx.files()) and that
1737 # wanted: a cache of filenames that were changed (ctx.files()) and that
1738 # match the file filtering conditions.
1738 # match the file filtering conditions.
1739
1739
1740 if match.always():
1740 if match.always():
1741 # No files, no patterns. Display all revs.
1741 # No files, no patterns. Display all revs.
1742 wanted = revs
1742 wanted = revs
1743 elif not slowpath:
1743 elif not slowpath:
1744 # We only have to read through the filelog to find wanted revisions
1744 # We only have to read through the filelog to find wanted revisions
1745
1745
1746 try:
1746 try:
1747 wanted = walkfilerevs(repo, match, follow, revs, fncache)
1747 wanted = walkfilerevs(repo, match, follow, revs, fncache)
1748 except FileWalkError:
1748 except FileWalkError:
1749 slowpath = True
1749 slowpath = True
1750
1750
1751 # We decided to fall back to the slowpath because at least one
1751 # We decided to fall back to the slowpath because at least one
1752 # of the paths was not a file. Check to see if at least one of them
1752 # of the paths was not a file. Check to see if at least one of them
1753 # existed in history, otherwise simply return
1753 # existed in history, otherwise simply return
1754 for path in match.files():
1754 for path in match.files():
1755 if path == '.' or path in repo.store:
1755 if path == '.' or path in repo.store:
1756 break
1756 break
1757 else:
1757 else:
1758 return []
1758 return []
1759
1759
1760 if slowpath:
1760 if slowpath:
1761 # We have to read the changelog to match filenames against
1761 # We have to read the changelog to match filenames against
1762 # changed files
1762 # changed files
1763
1763
1764 if follow:
1764 if follow:
1765 raise util.Abort(_('can only follow copies/renames for explicit '
1765 raise util.Abort(_('can only follow copies/renames for explicit '
1766 'filenames'))
1766 'filenames'))
1767
1767
1768 # The slow path checks files modified in every changeset.
1768 # The slow path checks files modified in every changeset.
1769 # This is really slow on large repos, so compute the set lazily.
1769 # This is really slow on large repos, so compute the set lazily.
1770 class lazywantedset(object):
1770 class lazywantedset(object):
1771 def __init__(self):
1771 def __init__(self):
1772 self.set = set()
1772 self.set = set()
1773 self.revs = set(revs)
1773 self.revs = set(revs)
1774
1774
1775 # No need to worry about locality here because it will be accessed
1775 # No need to worry about locality here because it will be accessed
1776 # in the same order as the increasing window below.
1776 # in the same order as the increasing window below.
1777 def __contains__(self, value):
1777 def __contains__(self, value):
1778 if value in self.set:
1778 if value in self.set:
1779 return True
1779 return True
1780 elif not value in self.revs:
1780 elif not value in self.revs:
1781 return False
1781 return False
1782 else:
1782 else:
1783 self.revs.discard(value)
1783 self.revs.discard(value)
1784 ctx = change(value)
1784 ctx = change(value)
1785 matches = filter(match, ctx.files())
1785 matches = filter(match, ctx.files())
1786 if matches:
1786 if matches:
1787 fncache[value] = matches
1787 fncache[value] = matches
1788 self.set.add(value)
1788 self.set.add(value)
1789 return True
1789 return True
1790 return False
1790 return False
1791
1791
1792 def discard(self, value):
1792 def discard(self, value):
1793 self.revs.discard(value)
1793 self.revs.discard(value)
1794 self.set.discard(value)
1794 self.set.discard(value)
1795
1795
1796 wanted = lazywantedset()
1796 wanted = lazywantedset()
1797
1797
1798 # it might be worthwhile to do this in the iterator if the rev range
1798 # it might be worthwhile to do this in the iterator if the rev range
1799 # is descending and the prune args are all within that range
1799 # is descending and the prune args are all within that range
1800 for rev in opts.get('prune', ()):
1800 for rev in opts.get('prune', ()):
1801 rev = repo[rev].rev()
1801 rev = repo[rev].rev()
1802 ff = _followfilter(repo)
1802 ff = _followfilter(repo)
1803 stop = min(revs[0], revs[-1])
1803 stop = min(revs[0], revs[-1])
1804 for x in xrange(rev, stop - 1, -1):
1804 for x in xrange(rev, stop - 1, -1):
1805 if ff.match(x):
1805 if ff.match(x):
1806 wanted = wanted - [x]
1806 wanted = wanted - [x]
1807
1807
1808 # Now that wanted is correctly initialized, we can iterate over the
1808 # Now that wanted is correctly initialized, we can iterate over the
1809 # revision range, yielding only revisions in wanted.
1809 # revision range, yielding only revisions in wanted.
1810 def iterate():
1810 def iterate():
1811 if follow and match.always():
1811 if follow and match.always():
1812 ff = _followfilter(repo, onlyfirst=opts.get('follow_first'))
1812 ff = _followfilter(repo, onlyfirst=opts.get('follow_first'))
1813 def want(rev):
1813 def want(rev):
1814 return ff.match(rev) and rev in wanted
1814 return ff.match(rev) and rev in wanted
1815 else:
1815 else:
1816 def want(rev):
1816 def want(rev):
1817 return rev in wanted
1817 return rev in wanted
1818
1818
1819 it = iter(revs)
1819 it = iter(revs)
1820 stopiteration = False
1820 stopiteration = False
1821 for windowsize in increasingwindows():
1821 for windowsize in increasingwindows():
1822 nrevs = []
1822 nrevs = []
1823 for i in xrange(windowsize):
1823 for i in xrange(windowsize):
1824 rev = next(it, None)
1824 rev = next(it, None)
1825 if rev is None:
1825 if rev is None:
1826 stopiteration = True
1826 stopiteration = True
1827 break
1827 break
1828 elif want(rev):
1828 elif want(rev):
1829 nrevs.append(rev)
1829 nrevs.append(rev)
1830 for rev in sorted(nrevs):
1830 for rev in sorted(nrevs):
1831 fns = fncache.get(rev)
1831 fns = fncache.get(rev)
1832 ctx = change(rev)
1832 ctx = change(rev)
1833 if not fns:
1833 if not fns:
1834 def fns_generator():
1834 def fns_generator():
1835 for f in ctx.files():
1835 for f in ctx.files():
1836 if match(f):
1836 if match(f):
1837 yield f
1837 yield f
1838 fns = fns_generator()
1838 fns = fns_generator()
1839 prepare(ctx, fns)
1839 prepare(ctx, fns)
1840 for rev in nrevs:
1840 for rev in nrevs:
1841 yield change(rev)
1841 yield change(rev)
1842
1842
1843 if stopiteration:
1843 if stopiteration:
1844 break
1844 break
1845
1845
1846 return iterate()
1846 return iterate()
1847
1847
1848 def _makefollowlogfilematcher(repo, files, followfirst):
1848 def _makefollowlogfilematcher(repo, files, followfirst):
1849 # When displaying a revision with --patch --follow FILE, we have
1849 # When displaying a revision with --patch --follow FILE, we have
1850 # to know which file of the revision must be diffed. With
1850 # to know which file of the revision must be diffed. With
1851 # --follow, we want the names of the ancestors of FILE in the
1851 # --follow, we want the names of the ancestors of FILE in the
1852 # revision, stored in "fcache". "fcache" is populated by
1852 # revision, stored in "fcache". "fcache" is populated by
1853 # reproducing the graph traversal already done by --follow revset
1853 # reproducing the graph traversal already done by --follow revset
1854 # and relating linkrevs to file names (which is not "correct" but
1854 # and relating linkrevs to file names (which is not "correct" but
1855 # good enough).
1855 # good enough).
1856 fcache = {}
1856 fcache = {}
1857 fcacheready = [False]
1857 fcacheready = [False]
1858 pctx = repo['.']
1858 pctx = repo['.']
1859
1859
1860 def populate():
1860 def populate():
1861 for fn in files:
1861 for fn in files:
1862 for i in ((pctx[fn],), pctx[fn].ancestors(followfirst=followfirst)):
1862 for i in ((pctx[fn],), pctx[fn].ancestors(followfirst=followfirst)):
1863 for c in i:
1863 for c in i:
1864 fcache.setdefault(c.linkrev(), set()).add(c.path())
1864 fcache.setdefault(c.linkrev(), set()).add(c.path())
1865
1865
1866 def filematcher(rev):
1866 def filematcher(rev):
1867 if not fcacheready[0]:
1867 if not fcacheready[0]:
1868 # Lazy initialization
1868 # Lazy initialization
1869 fcacheready[0] = True
1869 fcacheready[0] = True
1870 populate()
1870 populate()
1871 return scmutil.matchfiles(repo, fcache.get(rev, []))
1871 return scmutil.matchfiles(repo, fcache.get(rev, []))
1872
1872
1873 return filematcher
1873 return filematcher
1874
1874
1875 def _makenofollowlogfilematcher(repo, pats, opts):
1875 def _makenofollowlogfilematcher(repo, pats, opts):
1876 '''hook for extensions to override the filematcher for non-follow cases'''
1876 '''hook for extensions to override the filematcher for non-follow cases'''
1877 return None
1877 return None
1878
1878
1879 def _makelogrevset(repo, pats, opts, revs):
1879 def _makelogrevset(repo, pats, opts, revs):
1880 """Return (expr, filematcher) where expr is a revset string built
1880 """Return (expr, filematcher) where expr is a revset string built
1881 from log options and file patterns or None. If --stat or --patch
1881 from log options and file patterns or None. If --stat or --patch
1882 are not passed filematcher is None. Otherwise it is a callable
1882 are not passed filematcher is None. Otherwise it is a callable
1883 taking a revision number and returning a match objects filtering
1883 taking a revision number and returning a match objects filtering
1884 the files to be detailed when displaying the revision.
1884 the files to be detailed when displaying the revision.
1885 """
1885 """
1886 opt2revset = {
1886 opt2revset = {
1887 'no_merges': ('not merge()', None),
1887 'no_merges': ('not merge()', None),
1888 'only_merges': ('merge()', None),
1888 'only_merges': ('merge()', None),
1889 '_ancestors': ('ancestors(%(val)s)', None),
1889 '_ancestors': ('ancestors(%(val)s)', None),
1890 '_fancestors': ('_firstancestors(%(val)s)', None),
1890 '_fancestors': ('_firstancestors(%(val)s)', None),
1891 '_descendants': ('descendants(%(val)s)', None),
1891 '_descendants': ('descendants(%(val)s)', None),
1892 '_fdescendants': ('_firstdescendants(%(val)s)', None),
1892 '_fdescendants': ('_firstdescendants(%(val)s)', None),
1893 '_matchfiles': ('_matchfiles(%(val)s)', None),
1893 '_matchfiles': ('_matchfiles(%(val)s)', None),
1894 'date': ('date(%(val)r)', None),
1894 'date': ('date(%(val)r)', None),
1895 'branch': ('branch(%(val)r)', ' or '),
1895 'branch': ('branch(%(val)r)', ' or '),
1896 '_patslog': ('filelog(%(val)r)', ' or '),
1896 '_patslog': ('filelog(%(val)r)', ' or '),
1897 '_patsfollow': ('follow(%(val)r)', ' or '),
1897 '_patsfollow': ('follow(%(val)r)', ' or '),
1898 '_patsfollowfirst': ('_followfirst(%(val)r)', ' or '),
1898 '_patsfollowfirst': ('_followfirst(%(val)r)', ' or '),
1899 'keyword': ('keyword(%(val)r)', ' or '),
1899 'keyword': ('keyword(%(val)r)', ' or '),
1900 'prune': ('not (%(val)r or ancestors(%(val)r))', ' and '),
1900 'prune': ('not (%(val)r or ancestors(%(val)r))', ' and '),
1901 'user': ('user(%(val)r)', ' or '),
1901 'user': ('user(%(val)r)', ' or '),
1902 }
1902 }
1903
1903
1904 opts = dict(opts)
1904 opts = dict(opts)
1905 # follow or not follow?
1905 # follow or not follow?
1906 follow = opts.get('follow') or opts.get('follow_first')
1906 follow = opts.get('follow') or opts.get('follow_first')
1907 if opts.get('follow_first'):
1907 if opts.get('follow_first'):
1908 followfirst = 1
1908 followfirst = 1
1909 else:
1909 else:
1910 followfirst = 0
1910 followfirst = 0
1911 # --follow with FILE behavior depends on revs...
1911 # --follow with FILE behavior depends on revs...
1912 it = iter(revs)
1912 it = iter(revs)
1913 startrev = it.next()
1913 startrev = it.next()
1914 followdescendants = startrev < next(it, startrev)
1914 followdescendants = startrev < next(it, startrev)
1915
1915
1916 # branch and only_branch are really aliases and must be handled at
1916 # branch and only_branch are really aliases and must be handled at
1917 # the same time
1917 # the same time
1918 opts['branch'] = opts.get('branch', []) + opts.get('only_branch', [])
1918 opts['branch'] = opts.get('branch', []) + opts.get('only_branch', [])
1919 opts['branch'] = [repo.lookupbranch(b) for b in opts['branch']]
1919 opts['branch'] = [repo.lookupbranch(b) for b in opts['branch']]
1920 # pats/include/exclude are passed to match.match() directly in
1920 # pats/include/exclude are passed to match.match() directly in
1921 # _matchfiles() revset but walkchangerevs() builds its matcher with
1921 # _matchfiles() revset but walkchangerevs() builds its matcher with
1922 # scmutil.match(). The difference is input pats are globbed on
1922 # scmutil.match(). The difference is input pats are globbed on
1923 # platforms without shell expansion (windows).
1923 # platforms without shell expansion (windows).
1924 wctx = repo[None]
1924 wctx = repo[None]
1925 match, pats = scmutil.matchandpats(wctx, pats, opts)
1925 match, pats = scmutil.matchandpats(wctx, pats, opts)
1926 slowpath = match.anypats() or ((match.isexact() or match.prefix()) and
1926 slowpath = match.anypats() or ((match.isexact() or match.prefix()) and
1927 opts.get('removed'))
1927 opts.get('removed'))
1928 if not slowpath:
1928 if not slowpath:
1929 for f in match.files():
1929 for f in match.files():
1930 if follow and f not in wctx:
1930 if follow and f not in wctx:
1931 # If the file exists, it may be a directory, so let it
1931 # If the file exists, it may be a directory, so let it
1932 # take the slow path.
1932 # take the slow path.
1933 if os.path.exists(repo.wjoin(f)):
1933 if os.path.exists(repo.wjoin(f)):
1934 slowpath = True
1934 slowpath = True
1935 continue
1935 continue
1936 else:
1936 else:
1937 raise util.Abort(_('cannot follow file not in parent '
1937 raise util.Abort(_('cannot follow file not in parent '
1938 'revision: "%s"') % f)
1938 'revision: "%s"') % f)
1939 filelog = repo.file(f)
1939 filelog = repo.file(f)
1940 if not filelog:
1940 if not filelog:
1941 # A zero count may be a directory or deleted file, so
1941 # A zero count may be a directory or deleted file, so
1942 # try to find matching entries on the slow path.
1942 # try to find matching entries on the slow path.
1943 if follow:
1943 if follow:
1944 raise util.Abort(
1944 raise util.Abort(
1945 _('cannot follow nonexistent file: "%s"') % f)
1945 _('cannot follow nonexistent file: "%s"') % f)
1946 slowpath = True
1946 slowpath = True
1947
1947
1948 # We decided to fall back to the slowpath because at least one
1948 # We decided to fall back to the slowpath because at least one
1949 # of the paths was not a file. Check to see if at least one of them
1949 # of the paths was not a file. Check to see if at least one of them
1950 # existed in history - in that case, we'll continue down the
1950 # existed in history - in that case, we'll continue down the
1951 # slowpath; otherwise, we can turn off the slowpath
1951 # slowpath; otherwise, we can turn off the slowpath
1952 if slowpath:
1952 if slowpath:
1953 for path in match.files():
1953 for path in match.files():
1954 if path == '.' or path in repo.store:
1954 if path == '.' or path in repo.store:
1955 break
1955 break
1956 else:
1956 else:
1957 slowpath = False
1957 slowpath = False
1958
1958
1959 fpats = ('_patsfollow', '_patsfollowfirst')
1959 fpats = ('_patsfollow', '_patsfollowfirst')
1960 fnopats = (('_ancestors', '_fancestors'),
1960 fnopats = (('_ancestors', '_fancestors'),
1961 ('_descendants', '_fdescendants'))
1961 ('_descendants', '_fdescendants'))
1962 if slowpath:
1962 if slowpath:
1963 # See walkchangerevs() slow path.
1963 # See walkchangerevs() slow path.
1964 #
1964 #
1965 # pats/include/exclude cannot be represented as separate
1965 # pats/include/exclude cannot be represented as separate
1966 # revset expressions as their filtering logic applies at file
1966 # revset expressions as their filtering logic applies at file
1967 # level. For instance "-I a -X a" matches a revision touching
1967 # level. For instance "-I a -X a" matches a revision touching
1968 # "a" and "b" while "file(a) and not file(b)" does
1968 # "a" and "b" while "file(a) and not file(b)" does
1969 # not. Besides, filesets are evaluated against the working
1969 # not. Besides, filesets are evaluated against the working
1970 # directory.
1970 # directory.
1971 matchargs = ['r:', 'd:relpath']
1971 matchargs = ['r:', 'd:relpath']
1972 for p in pats:
1972 for p in pats:
1973 matchargs.append('p:' + p)
1973 matchargs.append('p:' + p)
1974 for p in opts.get('include', []):
1974 for p in opts.get('include', []):
1975 matchargs.append('i:' + p)
1975 matchargs.append('i:' + p)
1976 for p in opts.get('exclude', []):
1976 for p in opts.get('exclude', []):
1977 matchargs.append('x:' + p)
1977 matchargs.append('x:' + p)
1978 matchargs = ','.join(('%r' % p) for p in matchargs)
1978 matchargs = ','.join(('%r' % p) for p in matchargs)
1979 opts['_matchfiles'] = matchargs
1979 opts['_matchfiles'] = matchargs
1980 if follow:
1980 if follow:
1981 opts[fnopats[0][followfirst]] = '.'
1981 opts[fnopats[0][followfirst]] = '.'
1982 else:
1982 else:
1983 if follow:
1983 if follow:
1984 if pats:
1984 if pats:
1985 # follow() revset interprets its file argument as a
1985 # follow() revset interprets its file argument as a
1986 # manifest entry, so use match.files(), not pats.
1986 # manifest entry, so use match.files(), not pats.
1987 opts[fpats[followfirst]] = list(match.files())
1987 opts[fpats[followfirst]] = list(match.files())
1988 else:
1988 else:
1989 op = fnopats[followdescendants][followfirst]
1989 op = fnopats[followdescendants][followfirst]
1990 opts[op] = 'rev(%d)' % startrev
1990 opts[op] = 'rev(%d)' % startrev
1991 else:
1991 else:
1992 opts['_patslog'] = list(pats)
1992 opts['_patslog'] = list(pats)
1993
1993
1994 filematcher = None
1994 filematcher = None
1995 if opts.get('patch') or opts.get('stat'):
1995 if opts.get('patch') or opts.get('stat'):
1996 # When following files, track renames via a special matcher.
1996 # When following files, track renames via a special matcher.
1997 # If we're forced to take the slowpath it means we're following
1997 # If we're forced to take the slowpath it means we're following
1998 # at least one pattern/directory, so don't bother with rename tracking.
1998 # at least one pattern/directory, so don't bother with rename tracking.
1999 if follow and not match.always() and not slowpath:
1999 if follow and not match.always() and not slowpath:
2000 # _makefollowlogfilematcher expects its files argument to be
2000 # _makefollowlogfilematcher expects its files argument to be
2001 # relative to the repo root, so use match.files(), not pats.
2001 # relative to the repo root, so use match.files(), not pats.
2002 filematcher = _makefollowlogfilematcher(repo, match.files(),
2002 filematcher = _makefollowlogfilematcher(repo, match.files(),
2003 followfirst)
2003 followfirst)
2004 else:
2004 else:
2005 filematcher = _makenofollowlogfilematcher(repo, pats, opts)
2005 filematcher = _makenofollowlogfilematcher(repo, pats, opts)
2006 if filematcher is None:
2006 if filematcher is None:
2007 filematcher = lambda rev: match
2007 filematcher = lambda rev: match
2008
2008
2009 expr = []
2009 expr = []
2010 for op, val in sorted(opts.iteritems()):
2010 for op, val in sorted(opts.iteritems()):
2011 if not val:
2011 if not val:
2012 continue
2012 continue
2013 if op not in opt2revset:
2013 if op not in opt2revset:
2014 continue
2014 continue
2015 revop, andor = opt2revset[op]
2015 revop, andor = opt2revset[op]
2016 if '%(val)' not in revop:
2016 if '%(val)' not in revop:
2017 expr.append(revop)
2017 expr.append(revop)
2018 else:
2018 else:
2019 if not isinstance(val, list):
2019 if not isinstance(val, list):
2020 e = revop % {'val': val}
2020 e = revop % {'val': val}
2021 else:
2021 else:
2022 e = '(' + andor.join((revop % {'val': v}) for v in val) + ')'
2022 e = '(' + andor.join((revop % {'val': v}) for v in val) + ')'
2023 expr.append(e)
2023 expr.append(e)
2024
2024
2025 if expr:
2025 if expr:
2026 expr = '(' + ' and '.join(expr) + ')'
2026 expr = '(' + ' and '.join(expr) + ')'
2027 else:
2027 else:
2028 expr = None
2028 expr = None
2029 return expr, filematcher
2029 return expr, filematcher
2030
2030
2031 def _logrevs(repo, opts):
2031 def _logrevs(repo, opts):
2032 # Default --rev value depends on --follow but --follow behavior
2032 # Default --rev value depends on --follow but --follow behavior
2033 # depends on revisions resolved from --rev...
2033 # depends on revisions resolved from --rev...
2034 follow = opts.get('follow') or opts.get('follow_first')
2034 follow = opts.get('follow') or opts.get('follow_first')
2035 if opts.get('rev'):
2035 if opts.get('rev'):
2036 revs = scmutil.revrange(repo, opts['rev'])
2036 revs = scmutil.revrange(repo, opts['rev'])
2037 elif follow and repo.dirstate.p1() == nullid:
2037 elif follow and repo.dirstate.p1() == nullid:
2038 revs = revset.baseset()
2038 revs = revset.baseset()
2039 elif follow:
2039 elif follow:
2040 revs = repo.revs('reverse(:.)')
2040 revs = repo.revs('reverse(:.)')
2041 else:
2041 else:
2042 revs = revset.spanset(repo)
2042 revs = revset.spanset(repo)
2043 revs.reverse()
2043 revs.reverse()
2044 return revs
2044 return revs
2045
2045
2046 def getgraphlogrevs(repo, pats, opts):
2046 def getgraphlogrevs(repo, pats, opts):
2047 """Return (revs, expr, filematcher) where revs is an iterable of
2047 """Return (revs, expr, filematcher) where revs is an iterable of
2048 revision numbers, expr is a revset string built from log options
2048 revision numbers, expr is a revset string built from log options
2049 and file patterns or None, and used to filter 'revs'. If --stat or
2049 and file patterns or None, and used to filter 'revs'. If --stat or
2050 --patch are not passed filematcher is None. Otherwise it is a
2050 --patch are not passed filematcher is None. Otherwise it is a
2051 callable taking a revision number and returning a match objects
2051 callable taking a revision number and returning a match objects
2052 filtering the files to be detailed when displaying the revision.
2052 filtering the files to be detailed when displaying the revision.
2053 """
2053 """
2054 limit = loglimit(opts)
2054 limit = loglimit(opts)
2055 revs = _logrevs(repo, opts)
2055 revs = _logrevs(repo, opts)
2056 if not revs:
2056 if not revs:
2057 return revset.baseset(), None, None
2057 return revset.baseset(), None, None
2058 expr, filematcher = _makelogrevset(repo, pats, opts, revs)
2058 expr, filematcher = _makelogrevset(repo, pats, opts, revs)
2059 if opts.get('rev'):
2059 if opts.get('rev'):
2060 # User-specified revs might be unsorted, but don't sort before
2060 # User-specified revs might be unsorted, but don't sort before
2061 # _makelogrevset because it might depend on the order of revs
2061 # _makelogrevset because it might depend on the order of revs
2062 revs.sort(reverse=True)
2062 revs.sort(reverse=True)
2063 if expr:
2063 if expr:
2064 # Revset matchers often operate faster on revisions in changelog
2064 # Revset matchers often operate faster on revisions in changelog
2065 # order, because most filters deal with the changelog.
2065 # order, because most filters deal with the changelog.
2066 revs.reverse()
2066 revs.reverse()
2067 matcher = revset.match(repo.ui, expr)
2067 matcher = revset.match(repo.ui, expr)
2068 # Revset matches can reorder revisions. "A or B" typically returns
2068 # Revset matches can reorder revisions. "A or B" typically returns
2069 # returns the revision matching A then the revision matching B. Sort
2069 # returns the revision matching A then the revision matching B. Sort
2070 # again to fix that.
2070 # again to fix that.
2071 revs = matcher(repo, revs)
2071 revs = matcher(repo, revs)
2072 revs.sort(reverse=True)
2072 revs.sort(reverse=True)
2073 if limit is not None:
2073 if limit is not None:
2074 limitedrevs = []
2074 limitedrevs = []
2075 for idx, rev in enumerate(revs):
2075 for idx, rev in enumerate(revs):
2076 if idx >= limit:
2076 if idx >= limit:
2077 break
2077 break
2078 limitedrevs.append(rev)
2078 limitedrevs.append(rev)
2079 revs = revset.baseset(limitedrevs)
2079 revs = revset.baseset(limitedrevs)
2080
2080
2081 return revs, expr, filematcher
2081 return revs, expr, filematcher
2082
2082
2083 def getlogrevs(repo, pats, opts):
2083 def getlogrevs(repo, pats, opts):
2084 """Return (revs, expr, filematcher) where revs is an iterable of
2084 """Return (revs, expr, filematcher) where revs is an iterable of
2085 revision numbers, expr is a revset string built from log options
2085 revision numbers, expr is a revset string built from log options
2086 and file patterns or None, and used to filter 'revs'. If --stat or
2086 and file patterns or None, and used to filter 'revs'. If --stat or
2087 --patch are not passed filematcher is None. Otherwise it is a
2087 --patch are not passed filematcher is None. Otherwise it is a
2088 callable taking a revision number and returning a match objects
2088 callable taking a revision number and returning a match objects
2089 filtering the files to be detailed when displaying the revision.
2089 filtering the files to be detailed when displaying the revision.
2090 """
2090 """
2091 limit = loglimit(opts)
2091 limit = loglimit(opts)
2092 revs = _logrevs(repo, opts)
2092 revs = _logrevs(repo, opts)
2093 if not revs:
2093 if not revs:
2094 return revset.baseset([]), None, None
2094 return revset.baseset([]), None, None
2095 expr, filematcher = _makelogrevset(repo, pats, opts, revs)
2095 expr, filematcher = _makelogrevset(repo, pats, opts, revs)
2096 if expr:
2096 if expr:
2097 # Revset matchers often operate faster on revisions in changelog
2097 # Revset matchers often operate faster on revisions in changelog
2098 # order, because most filters deal with the changelog.
2098 # order, because most filters deal with the changelog.
2099 if not opts.get('rev'):
2099 if not opts.get('rev'):
2100 revs.reverse()
2100 revs.reverse()
2101 matcher = revset.match(repo.ui, expr)
2101 matcher = revset.match(repo.ui, expr)
2102 # Revset matches can reorder revisions. "A or B" typically returns
2102 # Revset matches can reorder revisions. "A or B" typically returns
2103 # returns the revision matching A then the revision matching B. Sort
2103 # returns the revision matching A then the revision matching B. Sort
2104 # again to fix that.
2104 # again to fix that.
2105 revs = matcher(repo, revs)
2105 revs = matcher(repo, revs)
2106 if not opts.get('rev'):
2106 if not opts.get('rev'):
2107 revs.sort(reverse=True)
2107 revs.sort(reverse=True)
2108 if limit is not None:
2108 if limit is not None:
2109 limitedrevs = []
2109 limitedrevs = []
2110 for idx, r in enumerate(revs):
2110 for idx, r in enumerate(revs):
2111 if limit <= idx:
2111 if limit <= idx:
2112 break
2112 break
2113 limitedrevs.append(r)
2113 limitedrevs.append(r)
2114 revs = revset.baseset(limitedrevs)
2114 revs = revset.baseset(limitedrevs)
2115
2115
2116 return revs, expr, filematcher
2116 return revs, expr, filematcher
2117
2117
2118 def displaygraph(ui, dag, displayer, showparents, edgefn, getrenamed=None,
2118 def displaygraph(ui, dag, displayer, showparents, edgefn, getrenamed=None,
2119 filematcher=None):
2119 filematcher=None):
2120 seen, state = [], graphmod.asciistate()
2120 seen, state = [], graphmod.asciistate()
2121 for rev, type, ctx, parents in dag:
2121 for rev, type, ctx, parents in dag:
2122 char = 'o'
2122 char = 'o'
2123 if ctx.node() in showparents:
2123 if ctx.node() in showparents:
2124 char = '@'
2124 char = '@'
2125 elif ctx.obsolete():
2125 elif ctx.obsolete():
2126 char = 'x'
2126 char = 'x'
2127 elif ctx.closesbranch():
2127 elif ctx.closesbranch():
2128 char = '_'
2128 char = '_'
2129 copies = None
2129 copies = None
2130 if getrenamed and ctx.rev():
2130 if getrenamed and ctx.rev():
2131 copies = []
2131 copies = []
2132 for fn in ctx.files():
2132 for fn in ctx.files():
2133 rename = getrenamed(fn, ctx.rev())
2133 rename = getrenamed(fn, ctx.rev())
2134 if rename:
2134 if rename:
2135 copies.append((fn, rename[0]))
2135 copies.append((fn, rename[0]))
2136 revmatchfn = None
2136 revmatchfn = None
2137 if filematcher is not None:
2137 if filematcher is not None:
2138 revmatchfn = filematcher(ctx.rev())
2138 revmatchfn = filematcher(ctx.rev())
2139 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
2139 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
2140 lines = displayer.hunk.pop(rev).split('\n')
2140 lines = displayer.hunk.pop(rev).split('\n')
2141 if not lines[-1]:
2141 if not lines[-1]:
2142 del lines[-1]
2142 del lines[-1]
2143 displayer.flush(ctx)
2143 displayer.flush(ctx)
2144 edges = edgefn(type, char, lines, seen, rev, parents)
2144 edges = edgefn(type, char, lines, seen, rev, parents)
2145 for type, char, lines, coldata in edges:
2145 for type, char, lines, coldata in edges:
2146 graphmod.ascii(ui, state, type, char, lines, coldata)
2146 graphmod.ascii(ui, state, type, char, lines, coldata)
2147 displayer.close()
2147 displayer.close()
2148
2148
2149 def graphlog(ui, repo, *pats, **opts):
2149 def graphlog(ui, repo, *pats, **opts):
2150 # Parameters are identical to log command ones
2150 # Parameters are identical to log command ones
2151 revs, expr, filematcher = getgraphlogrevs(repo, pats, opts)
2151 revs, expr, filematcher = getgraphlogrevs(repo, pats, opts)
2152 revdag = graphmod.dagwalker(repo, revs)
2152 revdag = graphmod.dagwalker(repo, revs)
2153
2153
2154 getrenamed = None
2154 getrenamed = None
2155 if opts.get('copies'):
2155 if opts.get('copies'):
2156 endrev = None
2156 endrev = None
2157 if opts.get('rev'):
2157 if opts.get('rev'):
2158 endrev = scmutil.revrange(repo, opts.get('rev')).max() + 1
2158 endrev = scmutil.revrange(repo, opts.get('rev')).max() + 1
2159 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
2159 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
2160 displayer = show_changeset(ui, repo, opts, buffered=True)
2160 displayer = show_changeset(ui, repo, opts, buffered=True)
2161 showparents = [ctx.node() for ctx in repo[None].parents()]
2161 showparents = [ctx.node() for ctx in repo[None].parents()]
2162 displaygraph(ui, revdag, displayer, showparents,
2162 displaygraph(ui, revdag, displayer, showparents,
2163 graphmod.asciiedges, getrenamed, filematcher)
2163 graphmod.asciiedges, getrenamed, filematcher)
2164
2164
2165 def checkunsupportedgraphflags(pats, opts):
2165 def checkunsupportedgraphflags(pats, opts):
2166 for op in ["newest_first"]:
2166 for op in ["newest_first"]:
2167 if op in opts and opts[op]:
2167 if op in opts and opts[op]:
2168 raise util.Abort(_("-G/--graph option is incompatible with --%s")
2168 raise util.Abort(_("-G/--graph option is incompatible with --%s")
2169 % op.replace("_", "-"))
2169 % op.replace("_", "-"))
2170
2170
2171 def graphrevs(repo, nodes, opts):
2171 def graphrevs(repo, nodes, opts):
2172 limit = loglimit(opts)
2172 limit = loglimit(opts)
2173 nodes.reverse()
2173 nodes.reverse()
2174 if limit is not None:
2174 if limit is not None:
2175 nodes = nodes[:limit]
2175 nodes = nodes[:limit]
2176 return graphmod.nodes(repo, nodes)
2176 return graphmod.nodes(repo, nodes)
2177
2177
2178 def add(ui, repo, match, prefix, explicitonly, **opts):
2178 def add(ui, repo, match, prefix, explicitonly, **opts):
2179 join = lambda f: os.path.join(prefix, f)
2179 join = lambda f: os.path.join(prefix, f)
2180 bad = []
2180 bad = []
2181
2181
2182 badfn = lambda x, y: bad.append(x) or match.bad(x, y)
2182 badfn = lambda x, y: bad.append(x) or match.bad(x, y)
2183 names = []
2183 names = []
2184 wctx = repo[None]
2184 wctx = repo[None]
2185 cca = None
2185 cca = None
2186 abort, warn = scmutil.checkportabilityalert(ui)
2186 abort, warn = scmutil.checkportabilityalert(ui)
2187 if abort or warn:
2187 if abort or warn:
2188 cca = scmutil.casecollisionauditor(ui, abort, repo.dirstate)
2188 cca = scmutil.casecollisionauditor(ui, abort, repo.dirstate)
2189
2189
2190 badmatch = matchmod.badmatch(match, badfn)
2190 badmatch = matchmod.badmatch(match, badfn)
2191 dirstate = repo.dirstate
2191 dirstate = repo.dirstate
2192 # We don't want to just call wctx.walk here, since it would return a lot of
2192 # We don't want to just call wctx.walk here, since it would return a lot of
2193 # clean files, which we aren't interested in and takes time.
2193 # clean files, which we aren't interested in and takes time.
2194 for f in sorted(dirstate.walk(badmatch, sorted(wctx.substate),
2194 for f in sorted(dirstate.walk(badmatch, sorted(wctx.substate),
2195 True, False, full=False)):
2195 True, False, full=False)):
2196 exact = match.exact(f)
2196 exact = match.exact(f)
2197 if exact or not explicitonly and f not in wctx and repo.wvfs.lexists(f):
2197 if exact or not explicitonly and f not in wctx and repo.wvfs.lexists(f):
2198 if cca:
2198 if cca:
2199 cca(f)
2199 cca(f)
2200 names.append(f)
2200 names.append(f)
2201 if ui.verbose or not exact:
2201 if ui.verbose or not exact:
2202 ui.status(_('adding %s\n') % match.rel(f))
2202 ui.status(_('adding %s\n') % match.rel(f))
2203
2203
2204 for subpath in sorted(wctx.substate):
2204 for subpath in sorted(wctx.substate):
2205 sub = wctx.sub(subpath)
2205 sub = wctx.sub(subpath)
2206 try:
2206 try:
2207 submatch = matchmod.narrowmatcher(subpath, match)
2207 submatch = matchmod.narrowmatcher(subpath, match)
2208 if opts.get('subrepos'):
2208 if opts.get('subrepos'):
2209 bad.extend(sub.add(ui, submatch, prefix, False, **opts))
2209 bad.extend(sub.add(ui, submatch, prefix, False, **opts))
2210 else:
2210 else:
2211 bad.extend(sub.add(ui, submatch, prefix, True, **opts))
2211 bad.extend(sub.add(ui, submatch, prefix, True, **opts))
2212 except error.LookupError:
2212 except error.LookupError:
2213 ui.status(_("skipping missing subrepository: %s\n")
2213 ui.status(_("skipping missing subrepository: %s\n")
2214 % join(subpath))
2214 % join(subpath))
2215
2215
2216 if not opts.get('dry_run'):
2216 if not opts.get('dry_run'):
2217 rejected = wctx.add(names, prefix)
2217 rejected = wctx.add(names, prefix)
2218 bad.extend(f for f in rejected if f in match.files())
2218 bad.extend(f for f in rejected if f in match.files())
2219 return bad
2219 return bad
2220
2220
2221 def forget(ui, repo, match, prefix, explicitonly):
2221 def forget(ui, repo, match, prefix, explicitonly):
2222 join = lambda f: os.path.join(prefix, f)
2222 join = lambda f: os.path.join(prefix, f)
2223 bad = []
2223 bad = []
2224 badfn = lambda x, y: bad.append(x) or match.bad(x, y)
2224 badfn = lambda x, y: bad.append(x) or match.bad(x, y)
2225 wctx = repo[None]
2225 wctx = repo[None]
2226 forgot = []
2226 forgot = []
2227
2227
2228 s = repo.status(match=matchmod.badmatch(match, badfn), clean=True)
2228 s = repo.status(match=matchmod.badmatch(match, badfn), clean=True)
2229 forget = sorted(s[0] + s[1] + s[3] + s[6])
2229 forget = sorted(s[0] + s[1] + s[3] + s[6])
2230 if explicitonly:
2230 if explicitonly:
2231 forget = [f for f in forget if match.exact(f)]
2231 forget = [f for f in forget if match.exact(f)]
2232
2232
2233 for subpath in sorted(wctx.substate):
2233 for subpath in sorted(wctx.substate):
2234 sub = wctx.sub(subpath)
2234 sub = wctx.sub(subpath)
2235 try:
2235 try:
2236 submatch = matchmod.narrowmatcher(subpath, match)
2236 submatch = matchmod.narrowmatcher(subpath, match)
2237 subbad, subforgot = sub.forget(submatch, prefix)
2237 subbad, subforgot = sub.forget(submatch, prefix)
2238 bad.extend([subpath + '/' + f for f in subbad])
2238 bad.extend([subpath + '/' + f for f in subbad])
2239 forgot.extend([subpath + '/' + f for f in subforgot])
2239 forgot.extend([subpath + '/' + f for f in subforgot])
2240 except error.LookupError:
2240 except error.LookupError:
2241 ui.status(_("skipping missing subrepository: %s\n")
2241 ui.status(_("skipping missing subrepository: %s\n")
2242 % join(subpath))
2242 % join(subpath))
2243
2243
2244 if not explicitonly:
2244 if not explicitonly:
2245 for f in match.files():
2245 for f in match.files():
2246 if f not in repo.dirstate and not repo.wvfs.isdir(f):
2246 if f not in repo.dirstate and not repo.wvfs.isdir(f):
2247 if f not in forgot:
2247 if f not in forgot:
2248 if repo.wvfs.exists(f):
2248 if repo.wvfs.exists(f):
2249 # Don't complain if the exact case match wasn't given.
2249 # Don't complain if the exact case match wasn't given.
2250 # But don't do this until after checking 'forgot', so
2250 # But don't do this until after checking 'forgot', so
2251 # that subrepo files aren't normalized, and this op is
2251 # that subrepo files aren't normalized, and this op is
2252 # purely from data cached by the status walk above.
2252 # purely from data cached by the status walk above.
2253 if repo.dirstate.normalize(f) in repo.dirstate:
2253 if repo.dirstate.normalize(f) in repo.dirstate:
2254 continue
2254 continue
2255 ui.warn(_('not removing %s: '
2255 ui.warn(_('not removing %s: '
2256 'file is already untracked\n')
2256 'file is already untracked\n')
2257 % match.rel(f))
2257 % match.rel(f))
2258 bad.append(f)
2258 bad.append(f)
2259
2259
2260 for f in forget:
2260 for f in forget:
2261 if ui.verbose or not match.exact(f):
2261 if ui.verbose or not match.exact(f):
2262 ui.status(_('removing %s\n') % match.rel(f))
2262 ui.status(_('removing %s\n') % match.rel(f))
2263
2263
2264 rejected = wctx.forget(forget, prefix)
2264 rejected = wctx.forget(forget, prefix)
2265 bad.extend(f for f in rejected if f in match.files())
2265 bad.extend(f for f in rejected if f in match.files())
2266 forgot.extend(f for f in forget if f not in rejected)
2266 forgot.extend(f for f in forget if f not in rejected)
2267 return bad, forgot
2267 return bad, forgot
2268
2268
2269 def files(ui, ctx, m, fm, fmt, subrepos):
2269 def files(ui, ctx, m, fm, fmt, subrepos):
2270 rev = ctx.rev()
2270 rev = ctx.rev()
2271 ret = 1
2271 ret = 1
2272 ds = ctx.repo().dirstate
2272 ds = ctx.repo().dirstate
2273
2273
2274 for f in ctx.matches(m):
2274 for f in ctx.matches(m):
2275 if rev is None and ds[f] == 'r':
2275 if rev is None and ds[f] == 'r':
2276 continue
2276 continue
2277 fm.startitem()
2277 fm.startitem()
2278 if ui.verbose:
2278 if ui.verbose:
2279 fc = ctx[f]
2279 fc = ctx[f]
2280 fm.write('size flags', '% 10d % 1s ', fc.size(), fc.flags())
2280 fm.write('size flags', '% 10d % 1s ', fc.size(), fc.flags())
2281 fm.data(abspath=f)
2281 fm.data(abspath=f)
2282 fm.write('path', fmt, m.rel(f))
2282 fm.write('path', fmt, m.rel(f))
2283 ret = 0
2283 ret = 0
2284
2284
2285 for subpath in sorted(ctx.substate):
2285 for subpath in sorted(ctx.substate):
2286 def matchessubrepo(subpath):
2286 def matchessubrepo(subpath):
2287 return (m.always() or m.exact(subpath)
2287 return (m.always() or m.exact(subpath)
2288 or any(f.startswith(subpath + '/') for f in m.files()))
2288 or any(f.startswith(subpath + '/') for f in m.files()))
2289
2289
2290 if subrepos or matchessubrepo(subpath):
2290 if subrepos or matchessubrepo(subpath):
2291 sub = ctx.sub(subpath)
2291 sub = ctx.sub(subpath)
2292 try:
2292 try:
2293 submatch = matchmod.narrowmatcher(subpath, m)
2293 submatch = matchmod.narrowmatcher(subpath, m)
2294 if sub.printfiles(ui, submatch, fm, fmt, subrepos) == 0:
2294 if sub.printfiles(ui, submatch, fm, fmt, subrepos) == 0:
2295 ret = 0
2295 ret = 0
2296 except error.LookupError:
2296 except error.LookupError:
2297 ui.status(_("skipping missing subrepository: %s\n")
2297 ui.status(_("skipping missing subrepository: %s\n")
2298 % m.abs(subpath))
2298 % m.abs(subpath))
2299
2299
2300 return ret
2300 return ret
2301
2301
2302 def remove(ui, repo, m, prefix, after, force, subrepos):
2302 def remove(ui, repo, m, prefix, after, force, subrepos):
2303 join = lambda f: os.path.join(prefix, f)
2303 join = lambda f: os.path.join(prefix, f)
2304 ret = 0
2304 ret = 0
2305 s = repo.status(match=m, clean=True)
2305 s = repo.status(match=m, clean=True)
2306 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
2306 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
2307
2307
2308 wctx = repo[None]
2308 wctx = repo[None]
2309
2309
2310 for subpath in sorted(wctx.substate):
2310 for subpath in sorted(wctx.substate):
2311 def matchessubrepo(matcher, subpath):
2311 def matchessubrepo(matcher, subpath):
2312 if matcher.exact(subpath):
2312 if matcher.exact(subpath):
2313 return True
2313 return True
2314 for f in matcher.files():
2314 for f in matcher.files():
2315 if f.startswith(subpath):
2315 if f.startswith(subpath):
2316 return True
2316 return True
2317 return False
2317 return False
2318
2318
2319 if subrepos or matchessubrepo(m, subpath):
2319 if subrepos or matchessubrepo(m, subpath):
2320 sub = wctx.sub(subpath)
2320 sub = wctx.sub(subpath)
2321 try:
2321 try:
2322 submatch = matchmod.narrowmatcher(subpath, m)
2322 submatch = matchmod.narrowmatcher(subpath, m)
2323 if sub.removefiles(submatch, prefix, after, force, subrepos):
2323 if sub.removefiles(submatch, prefix, after, force, subrepos):
2324 ret = 1
2324 ret = 1
2325 except error.LookupError:
2325 except error.LookupError:
2326 ui.status(_("skipping missing subrepository: %s\n")
2326 ui.status(_("skipping missing subrepository: %s\n")
2327 % join(subpath))
2327 % join(subpath))
2328
2328
2329 # warn about failure to delete explicit files/dirs
2329 # warn about failure to delete explicit files/dirs
2330 deleteddirs = util.dirs(deleted)
2330 deleteddirs = util.dirs(deleted)
2331 for f in m.files():
2331 for f in m.files():
2332 def insubrepo():
2332 def insubrepo():
2333 for subpath in wctx.substate:
2333 for subpath in wctx.substate:
2334 if f.startswith(subpath):
2334 if f.startswith(subpath):
2335 return True
2335 return True
2336 return False
2336 return False
2337
2337
2338 isdir = f in deleteddirs or wctx.hasdir(f)
2338 isdir = f in deleteddirs or wctx.hasdir(f)
2339 if f in repo.dirstate or isdir or f == '.' or insubrepo():
2339 if f in repo.dirstate or isdir or f == '.' or insubrepo():
2340 continue
2340 continue
2341
2341
2342 if repo.wvfs.exists(f):
2342 if repo.wvfs.exists(f):
2343 if repo.wvfs.isdir(f):
2343 if repo.wvfs.isdir(f):
2344 ui.warn(_('not removing %s: no tracked files\n')
2344 ui.warn(_('not removing %s: no tracked files\n')
2345 % m.rel(f))
2345 % m.rel(f))
2346 else:
2346 else:
2347 ui.warn(_('not removing %s: file is untracked\n')
2347 ui.warn(_('not removing %s: file is untracked\n')
2348 % m.rel(f))
2348 % m.rel(f))
2349 # missing files will generate a warning elsewhere
2349 # missing files will generate a warning elsewhere
2350 ret = 1
2350 ret = 1
2351
2351
2352 if force:
2352 if force:
2353 list = modified + deleted + clean + added
2353 list = modified + deleted + clean + added
2354 elif after:
2354 elif after:
2355 list = deleted
2355 list = deleted
2356 for f in modified + added + clean:
2356 for f in modified + added + clean:
2357 ui.warn(_('not removing %s: file still exists\n') % m.rel(f))
2357 ui.warn(_('not removing %s: file still exists\n') % m.rel(f))
2358 ret = 1
2358 ret = 1
2359 else:
2359 else:
2360 list = deleted + clean
2360 list = deleted + clean
2361 for f in modified:
2361 for f in modified:
2362 ui.warn(_('not removing %s: file is modified (use -f'
2362 ui.warn(_('not removing %s: file is modified (use -f'
2363 ' to force removal)\n') % m.rel(f))
2363 ' to force removal)\n') % m.rel(f))
2364 ret = 1
2364 ret = 1
2365 for f in added:
2365 for f in added:
2366 ui.warn(_('not removing %s: file has been marked for add'
2366 ui.warn(_('not removing %s: file has been marked for add'
2367 ' (use forget to undo)\n') % m.rel(f))
2367 ' (use forget to undo)\n') % m.rel(f))
2368 ret = 1
2368 ret = 1
2369
2369
2370 for f in sorted(list):
2370 for f in sorted(list):
2371 if ui.verbose or not m.exact(f):
2371 if ui.verbose or not m.exact(f):
2372 ui.status(_('removing %s\n') % m.rel(f))
2372 ui.status(_('removing %s\n') % m.rel(f))
2373
2373
2374 wlock = repo.wlock()
2374 wlock = repo.wlock()
2375 try:
2375 try:
2376 if not after:
2376 if not after:
2377 for f in list:
2377 for f in list:
2378 if f in added:
2378 if f in added:
2379 continue # we never unlink added files on remove
2379 continue # we never unlink added files on remove
2380 util.unlinkpath(repo.wjoin(f), ignoremissing=True)
2380 util.unlinkpath(repo.wjoin(f), ignoremissing=True)
2381 repo[None].forget(list)
2381 repo[None].forget(list)
2382 finally:
2382 finally:
2383 wlock.release()
2383 wlock.release()
2384
2384
2385 return ret
2385 return ret
2386
2386
2387 def cat(ui, repo, ctx, matcher, prefix, **opts):
2387 def cat(ui, repo, ctx, matcher, prefix, **opts):
2388 err = 1
2388 err = 1
2389
2389
2390 def write(path):
2390 def write(path):
2391 fp = makefileobj(repo, opts.get('output'), ctx.node(),
2391 fp = makefileobj(repo, opts.get('output'), ctx.node(),
2392 pathname=os.path.join(prefix, path))
2392 pathname=os.path.join(prefix, path))
2393 data = ctx[path].data()
2393 data = ctx[path].data()
2394 if opts.get('decode'):
2394 if opts.get('decode'):
2395 data = repo.wwritedata(path, data)
2395 data = repo.wwritedata(path, data)
2396 fp.write(data)
2396 fp.write(data)
2397 fp.close()
2397 fp.close()
2398
2398
2399 # Automation often uses hg cat on single files, so special case it
2399 # Automation often uses hg cat on single files, so special case it
2400 # for performance to avoid the cost of parsing the manifest.
2400 # for performance to avoid the cost of parsing the manifest.
2401 if len(matcher.files()) == 1 and not matcher.anypats():
2401 if len(matcher.files()) == 1 and not matcher.anypats():
2402 file = matcher.files()[0]
2402 file = matcher.files()[0]
2403 mf = repo.manifest
2403 mf = repo.manifest
2404 mfnode = ctx.manifestnode()
2404 mfnode = ctx.manifestnode()
2405 if mfnode and mf.find(mfnode, file)[0]:
2405 if mfnode and mf.find(mfnode, file)[0]:
2406 write(file)
2406 write(file)
2407 return 0
2407 return 0
2408
2408
2409 # Don't warn about "missing" files that are really in subrepos
2409 # Don't warn about "missing" files that are really in subrepos
2410 def badfn(path, msg):
2410 def badfn(path, msg):
2411 for subpath in ctx.substate:
2411 for subpath in ctx.substate:
2412 if path.startswith(subpath):
2412 if path.startswith(subpath):
2413 return
2413 return
2414 matcher.bad(path, msg)
2414 matcher.bad(path, msg)
2415
2415
2416 for abs in ctx.walk(matchmod.badmatch(matcher, badfn)):
2416 for abs in ctx.walk(matchmod.badmatch(matcher, badfn)):
2417 write(abs)
2417 write(abs)
2418 err = 0
2418 err = 0
2419
2419
2420 for subpath in sorted(ctx.substate):
2420 for subpath in sorted(ctx.substate):
2421 sub = ctx.sub(subpath)
2421 sub = ctx.sub(subpath)
2422 try:
2422 try:
2423 submatch = matchmod.narrowmatcher(subpath, matcher)
2423 submatch = matchmod.narrowmatcher(subpath, matcher)
2424
2424
2425 if not sub.cat(submatch, os.path.join(prefix, sub._path),
2425 if not sub.cat(submatch, os.path.join(prefix, sub._path),
2426 **opts):
2426 **opts):
2427 err = 0
2427 err = 0
2428 except error.RepoLookupError:
2428 except error.RepoLookupError:
2429 ui.status(_("skipping missing subrepository: %s\n")
2429 ui.status(_("skipping missing subrepository: %s\n")
2430 % os.path.join(prefix, subpath))
2430 % os.path.join(prefix, subpath))
2431
2431
2432 return err
2432 return err
2433
2433
2434 def commit(ui, repo, commitfunc, pats, opts):
2434 def commit(ui, repo, commitfunc, pats, opts):
2435 '''commit the specified files or all outstanding changes'''
2435 '''commit the specified files or all outstanding changes'''
2436 date = opts.get('date')
2436 date = opts.get('date')
2437 if date:
2437 if date:
2438 opts['date'] = util.parsedate(date)
2438 opts['date'] = util.parsedate(date)
2439 message = logmessage(ui, opts)
2439 message = logmessage(ui, opts)
2440 matcher = scmutil.match(repo[None], pats, opts)
2440 matcher = scmutil.match(repo[None], pats, opts)
2441
2441
2442 # extract addremove carefully -- this function can be called from a command
2442 # extract addremove carefully -- this function can be called from a command
2443 # that doesn't support addremove
2443 # that doesn't support addremove
2444 if opts.get('addremove'):
2444 if opts.get('addremove'):
2445 if scmutil.addremove(repo, matcher, "", opts) != 0:
2445 if scmutil.addremove(repo, matcher, "", opts) != 0:
2446 raise util.Abort(
2446 raise util.Abort(
2447 _("failed to mark all new/missing files as added/removed"))
2447 _("failed to mark all new/missing files as added/removed"))
2448
2448
2449 return commitfunc(ui, repo, message, matcher, opts)
2449 return commitfunc(ui, repo, message, matcher, opts)
2450
2450
2451 def amend(ui, repo, commitfunc, old, extra, pats, opts):
2451 def amend(ui, repo, commitfunc, old, extra, pats, opts):
2452 # avoid cycle context -> subrepo -> cmdutil
2452 # avoid cycle context -> subrepo -> cmdutil
2453 import context
2453 import context
2454
2454
2455 # amend will reuse the existing user if not specified, but the obsolete
2455 # amend will reuse the existing user if not specified, but the obsolete
2456 # marker creation requires that the current user's name is specified.
2456 # marker creation requires that the current user's name is specified.
2457 if obsolete.isenabled(repo, obsolete.createmarkersopt):
2457 if obsolete.isenabled(repo, obsolete.createmarkersopt):
2458 ui.username() # raise exception if username not set
2458 ui.username() # raise exception if username not set
2459
2459
2460 ui.note(_('amending changeset %s\n') % old)
2460 ui.note(_('amending changeset %s\n') % old)
2461 base = old.p1()
2461 base = old.p1()
2462 createmarkers = obsolete.isenabled(repo, obsolete.createmarkersopt)
2462 createmarkers = obsolete.isenabled(repo, obsolete.createmarkersopt)
2463
2463
2464 wlock = dsguard = lock = newid = None
2464 wlock = dsguard = lock = newid = None
2465 try:
2465 try:
2466 wlock = repo.wlock()
2466 wlock = repo.wlock()
2467 dsguard = dirstateguard(repo, 'amend')
2467 dsguard = dirstateguard(repo, 'amend')
2468 lock = repo.lock()
2468 lock = repo.lock()
2469 tr = repo.transaction('amend')
2469 tr = repo.transaction('amend')
2470 try:
2470 try:
2471 # See if we got a message from -m or -l, if not, open the editor
2471 # See if we got a message from -m or -l, if not, open the editor
2472 # with the message of the changeset to amend
2472 # with the message of the changeset to amend
2473 message = logmessage(ui, opts)
2473 message = logmessage(ui, opts)
2474 # ensure logfile does not conflict with later enforcement of the
2474 # ensure logfile does not conflict with later enforcement of the
2475 # message. potential logfile content has been processed by
2475 # message. potential logfile content has been processed by
2476 # `logmessage` anyway.
2476 # `logmessage` anyway.
2477 opts.pop('logfile')
2477 opts.pop('logfile')
2478 # First, do a regular commit to record all changes in the working
2478 # First, do a regular commit to record all changes in the working
2479 # directory (if there are any)
2479 # directory (if there are any)
2480 ui.callhooks = False
2480 ui.callhooks = False
2481 activebookmark = repo._activebookmark
2481 activebookmark = repo._activebookmark
2482 try:
2482 try:
2483 repo._activebookmark = None
2483 repo._activebookmark = None
2484 opts['message'] = 'temporary amend commit for %s' % old
2484 opts['message'] = 'temporary amend commit for %s' % old
2485 node = commit(ui, repo, commitfunc, pats, opts)
2485 node = commit(ui, repo, commitfunc, pats, opts)
2486 finally:
2486 finally:
2487 repo._activebookmark = activebookmark
2487 repo._activebookmark = activebookmark
2488 ui.callhooks = True
2488 ui.callhooks = True
2489 ctx = repo[node]
2489 ctx = repo[node]
2490
2490
2491 # Participating changesets:
2491 # Participating changesets:
2492 #
2492 #
2493 # node/ctx o - new (intermediate) commit that contains changes
2493 # node/ctx o - new (intermediate) commit that contains changes
2494 # | from working dir to go into amending commit
2494 # | from working dir to go into amending commit
2495 # | (or a workingctx if there were no changes)
2495 # | (or a workingctx if there were no changes)
2496 # |
2496 # |
2497 # old o - changeset to amend
2497 # old o - changeset to amend
2498 # |
2498 # |
2499 # base o - parent of amending changeset
2499 # base o - parent of amending changeset
2500
2500
2501 # Update extra dict from amended commit (e.g. to preserve graft
2501 # Update extra dict from amended commit (e.g. to preserve graft
2502 # source)
2502 # source)
2503 extra.update(old.extra())
2503 extra.update(old.extra())
2504
2504
2505 # Also update it from the intermediate commit or from the wctx
2505 # Also update it from the intermediate commit or from the wctx
2506 extra.update(ctx.extra())
2506 extra.update(ctx.extra())
2507
2507
2508 if len(old.parents()) > 1:
2508 if len(old.parents()) > 1:
2509 # ctx.files() isn't reliable for merges, so fall back to the
2509 # ctx.files() isn't reliable for merges, so fall back to the
2510 # slower repo.status() method
2510 # slower repo.status() method
2511 files = set([fn for st in repo.status(base, old)[:3]
2511 files = set([fn for st in repo.status(base, old)[:3]
2512 for fn in st])
2512 for fn in st])
2513 else:
2513 else:
2514 files = set(old.files())
2514 files = set(old.files())
2515
2515
2516 # Second, we use either the commit we just did, or if there were no
2516 # Second, we use either the commit we just did, or if there were no
2517 # changes the parent of the working directory as the version of the
2517 # changes the parent of the working directory as the version of the
2518 # files in the final amend commit
2518 # files in the final amend commit
2519 if node:
2519 if node:
2520 ui.note(_('copying changeset %s to %s\n') % (ctx, base))
2520 ui.note(_('copying changeset %s to %s\n') % (ctx, base))
2521
2521
2522 user = ctx.user()
2522 user = ctx.user()
2523 date = ctx.date()
2523 date = ctx.date()
2524 # Recompute copies (avoid recording a -> b -> a)
2524 # Recompute copies (avoid recording a -> b -> a)
2525 copied = copies.pathcopies(base, ctx)
2525 copied = copies.pathcopies(base, ctx)
2526 if old.p2:
2526 if old.p2:
2527 copied.update(copies.pathcopies(old.p2(), ctx))
2527 copied.update(copies.pathcopies(old.p2(), ctx))
2528
2528
2529 # Prune files which were reverted by the updates: if old
2529 # Prune files which were reverted by the updates: if old
2530 # introduced file X and our intermediate commit, node,
2530 # introduced file X and our intermediate commit, node,
2531 # renamed that file, then those two files are the same and
2531 # renamed that file, then those two files are the same and
2532 # we can discard X from our list of files. Likewise if X
2532 # we can discard X from our list of files. Likewise if X
2533 # was deleted, it's no longer relevant
2533 # was deleted, it's no longer relevant
2534 files.update(ctx.files())
2534 files.update(ctx.files())
2535
2535
2536 def samefile(f):
2536 def samefile(f):
2537 if f in ctx.manifest():
2537 if f in ctx.manifest():
2538 a = ctx.filectx(f)
2538 a = ctx.filectx(f)
2539 if f in base.manifest():
2539 if f in base.manifest():
2540 b = base.filectx(f)
2540 b = base.filectx(f)
2541 return (not a.cmp(b)
2541 return (not a.cmp(b)
2542 and a.flags() == b.flags())
2542 and a.flags() == b.flags())
2543 else:
2543 else:
2544 return False
2544 return False
2545 else:
2545 else:
2546 return f not in base.manifest()
2546 return f not in base.manifest()
2547 files = [f for f in files if not samefile(f)]
2547 files = [f for f in files if not samefile(f)]
2548
2548
2549 def filectxfn(repo, ctx_, path):
2549 def filectxfn(repo, ctx_, path):
2550 try:
2550 try:
2551 fctx = ctx[path]
2551 fctx = ctx[path]
2552 flags = fctx.flags()
2552 flags = fctx.flags()
2553 mctx = context.memfilectx(repo,
2553 mctx = context.memfilectx(repo,
2554 fctx.path(), fctx.data(),
2554 fctx.path(), fctx.data(),
2555 islink='l' in flags,
2555 islink='l' in flags,
2556 isexec='x' in flags,
2556 isexec='x' in flags,
2557 copied=copied.get(path))
2557 copied=copied.get(path))
2558 return mctx
2558 return mctx
2559 except KeyError:
2559 except KeyError:
2560 return None
2560 return None
2561 else:
2561 else:
2562 ui.note(_('copying changeset %s to %s\n') % (old, base))
2562 ui.note(_('copying changeset %s to %s\n') % (old, base))
2563
2563
2564 # Use version of files as in the old cset
2564 # Use version of files as in the old cset
2565 def filectxfn(repo, ctx_, path):
2565 def filectxfn(repo, ctx_, path):
2566 try:
2566 try:
2567 return old.filectx(path)
2567 return old.filectx(path)
2568 except KeyError:
2568 except KeyError:
2569 return None
2569 return None
2570
2570
2571 user = opts.get('user') or old.user()
2571 user = opts.get('user') or old.user()
2572 date = opts.get('date') or old.date()
2572 date = opts.get('date') or old.date()
2573 editform = mergeeditform(old, 'commit.amend')
2573 editform = mergeeditform(old, 'commit.amend')
2574 editor = getcommiteditor(editform=editform, **opts)
2574 editor = getcommiteditor(editform=editform, **opts)
2575 if not message:
2575 if not message:
2576 editor = getcommiteditor(edit=True, editform=editform)
2576 editor = getcommiteditor(edit=True, editform=editform)
2577 message = old.description()
2577 message = old.description()
2578
2578
2579 pureextra = extra.copy()
2579 pureextra = extra.copy()
2580 extra['amend_source'] = old.hex()
2580 extra['amend_source'] = old.hex()
2581
2581
2582 new = context.memctx(repo,
2582 new = context.memctx(repo,
2583 parents=[base.node(), old.p2().node()],
2583 parents=[base.node(), old.p2().node()],
2584 text=message,
2584 text=message,
2585 files=files,
2585 files=files,
2586 filectxfn=filectxfn,
2586 filectxfn=filectxfn,
2587 user=user,
2587 user=user,
2588 date=date,
2588 date=date,
2589 extra=extra,
2589 extra=extra,
2590 editor=editor)
2590 editor=editor)
2591
2591
2592 newdesc = changelog.stripdesc(new.description())
2592 newdesc = changelog.stripdesc(new.description())
2593 if ((not node)
2593 if ((not node)
2594 and newdesc == old.description()
2594 and newdesc == old.description()
2595 and user == old.user()
2595 and user == old.user()
2596 and date == old.date()
2596 and date == old.date()
2597 and pureextra == old.extra()):
2597 and pureextra == old.extra()):
2598 # nothing changed. continuing here would create a new node
2598 # nothing changed. continuing here would create a new node
2599 # anyway because of the amend_source noise.
2599 # anyway because of the amend_source noise.
2600 #
2600 #
2601 # This not what we expect from amend.
2601 # This not what we expect from amend.
2602 return old.node()
2602 return old.node()
2603
2603
2604 ph = repo.ui.config('phases', 'new-commit', phases.draft)
2604 ph = repo.ui.config('phases', 'new-commit', phases.draft)
2605 try:
2605 try:
2606 if opts.get('secret'):
2606 if opts.get('secret'):
2607 commitphase = 'secret'
2607 commitphase = 'secret'
2608 else:
2608 else:
2609 commitphase = old.phase()
2609 commitphase = old.phase()
2610 repo.ui.setconfig('phases', 'new-commit', commitphase, 'amend')
2610 repo.ui.setconfig('phases', 'new-commit', commitphase, 'amend')
2611 newid = repo.commitctx(new)
2611 newid = repo.commitctx(new)
2612 finally:
2612 finally:
2613 repo.ui.setconfig('phases', 'new-commit', ph, 'amend')
2613 repo.ui.setconfig('phases', 'new-commit', ph, 'amend')
2614 if newid != old.node():
2614 if newid != old.node():
2615 # Reroute the working copy parent to the new changeset
2615 # Reroute the working copy parent to the new changeset
2616 repo.setparents(newid, nullid)
2616 repo.setparents(newid, nullid)
2617
2617
2618 # Move bookmarks from old parent to amend commit
2618 # Move bookmarks from old parent to amend commit
2619 bms = repo.nodebookmarks(old.node())
2619 bms = repo.nodebookmarks(old.node())
2620 if bms:
2620 if bms:
2621 marks = repo._bookmarks
2621 marks = repo._bookmarks
2622 for bm in bms:
2622 for bm in bms:
2623 ui.debug('moving bookmarks %r from %s to %s\n' %
2623 ui.debug('moving bookmarks %r from %s to %s\n' %
2624 (marks, old.hex(), hex(newid)))
2624 (marks, old.hex(), hex(newid)))
2625 marks[bm] = newid
2625 marks[bm] = newid
2626 marks.recordchange(tr)
2626 marks.recordchange(tr)
2627 #commit the whole amend process
2627 #commit the whole amend process
2628 if createmarkers:
2628 if createmarkers:
2629 # mark the new changeset as successor of the rewritten one
2629 # mark the new changeset as successor of the rewritten one
2630 new = repo[newid]
2630 new = repo[newid]
2631 obs = [(old, (new,))]
2631 obs = [(old, (new,))]
2632 if node:
2632 if node:
2633 obs.append((ctx, ()))
2633 obs.append((ctx, ()))
2634
2634
2635 obsolete.createmarkers(repo, obs)
2635 obsolete.createmarkers(repo, obs)
2636 tr.close()
2636 tr.close()
2637 finally:
2637 finally:
2638 tr.release()
2638 tr.release()
2639 dsguard.close()
2639 dsguard.close()
2640 if not createmarkers and newid != old.node():
2640 if not createmarkers and newid != old.node():
2641 # Strip the intermediate commit (if there was one) and the amended
2641 # Strip the intermediate commit (if there was one) and the amended
2642 # commit
2642 # commit
2643 if node:
2643 if node:
2644 ui.note(_('stripping intermediate changeset %s\n') % ctx)
2644 ui.note(_('stripping intermediate changeset %s\n') % ctx)
2645 ui.note(_('stripping amended changeset %s\n') % old)
2645 ui.note(_('stripping amended changeset %s\n') % old)
2646 repair.strip(ui, repo, old.node(), topic='amend-backup')
2646 repair.strip(ui, repo, old.node(), topic='amend-backup')
2647 finally:
2647 finally:
2648 lockmod.release(lock, dsguard, wlock)
2648 lockmod.release(lock, dsguard, wlock)
2649 return newid
2649 return newid
2650
2650
2651 def commiteditor(repo, ctx, subs, editform=''):
2651 def commiteditor(repo, ctx, subs, editform=''):
2652 if ctx.description():
2652 if ctx.description():
2653 return ctx.description()
2653 return ctx.description()
2654 return commitforceeditor(repo, ctx, subs, editform=editform)
2654 return commitforceeditor(repo, ctx, subs, editform=editform)
2655
2655
2656 def commitforceeditor(repo, ctx, subs, finishdesc=None, extramsg=None,
2656 def commitforceeditor(repo, ctx, subs, finishdesc=None, extramsg=None,
2657 editform=''):
2657 editform=''):
2658 if not extramsg:
2658 if not extramsg:
2659 extramsg = _("Leave message empty to abort commit.")
2659 extramsg = _("Leave message empty to abort commit.")
2660
2660
2661 forms = [e for e in editform.split('.') if e]
2661 forms = [e for e in editform.split('.') if e]
2662 forms.insert(0, 'changeset')
2662 forms.insert(0, 'changeset')
2663 while forms:
2663 while forms:
2664 tmpl = repo.ui.config('committemplate', '.'.join(forms))
2664 tmpl = repo.ui.config('committemplate', '.'.join(forms))
2665 if tmpl:
2665 if tmpl:
2666 committext = buildcommittemplate(repo, ctx, subs, extramsg, tmpl)
2666 committext = buildcommittemplate(repo, ctx, subs, extramsg, tmpl)
2667 break
2667 break
2668 forms.pop()
2668 forms.pop()
2669 else:
2669 else:
2670 committext = buildcommittext(repo, ctx, subs, extramsg)
2670 committext = buildcommittext(repo, ctx, subs, extramsg)
2671
2671
2672 # run editor in the repository root
2672 # run editor in the repository root
2673 olddir = os.getcwd()
2673 olddir = os.getcwd()
2674 os.chdir(repo.root)
2674 os.chdir(repo.root)
2675 text = repo.ui.edit(committext, ctx.user(), ctx.extra(), editform=editform)
2675 text = repo.ui.edit(committext, ctx.user(), ctx.extra(), editform=editform)
2676 text = re.sub("(?m)^HG:.*(\n|$)", "", text)
2676 text = re.sub("(?m)^HG:.*(\n|$)", "", text)
2677 os.chdir(olddir)
2677 os.chdir(olddir)
2678
2678
2679 if finishdesc:
2679 if finishdesc:
2680 text = finishdesc(text)
2680 text = finishdesc(text)
2681 if not text.strip():
2681 if not text.strip():
2682 raise util.Abort(_("empty commit message"))
2682 raise util.Abort(_("empty commit message"))
2683
2683
2684 return text
2684 return text
2685
2685
2686 def buildcommittemplate(repo, ctx, subs, extramsg, tmpl):
2686 def buildcommittemplate(repo, ctx, subs, extramsg, tmpl):
2687 ui = repo.ui
2687 ui = repo.ui
2688 tmpl, mapfile = gettemplate(ui, tmpl, None)
2688 tmpl, mapfile = gettemplate(ui, tmpl, None)
2689
2689
2690 try:
2690 try:
2691 t = changeset_templater(ui, repo, None, {}, tmpl, mapfile, False)
2691 t = changeset_templater(ui, repo, None, {}, tmpl, mapfile, False)
2692 except SyntaxError as inst:
2692 except SyntaxError as inst:
2693 raise util.Abort(inst.args[0])
2693 raise util.Abort(inst.args[0])
2694
2694
2695 for k, v in repo.ui.configitems('committemplate'):
2695 for k, v in repo.ui.configitems('committemplate'):
2696 if k != 'changeset':
2696 if k != 'changeset':
2697 t.t.cache[k] = v
2697 t.t.cache[k] = v
2698
2698
2699 if not extramsg:
2699 if not extramsg:
2700 extramsg = '' # ensure that extramsg is string
2700 extramsg = '' # ensure that extramsg is string
2701
2701
2702 ui.pushbuffer()
2702 ui.pushbuffer()
2703 t.show(ctx, extramsg=extramsg)
2703 t.show(ctx, extramsg=extramsg)
2704 return ui.popbuffer()
2704 return ui.popbuffer()
2705
2705
2706 def hgprefix(msg):
2706 def hgprefix(msg):
2707 return "\n".join(["HG: %s" % a for a in msg.split("\n") if a])
2707 return "\n".join(["HG: %s" % a for a in msg.split("\n") if a])
2708
2708
2709 def buildcommittext(repo, ctx, subs, extramsg):
2709 def buildcommittext(repo, ctx, subs, extramsg):
2710 edittext = []
2710 edittext = []
2711 modified, added, removed = ctx.modified(), ctx.added(), ctx.removed()
2711 modified, added, removed = ctx.modified(), ctx.added(), ctx.removed()
2712 if ctx.description():
2712 if ctx.description():
2713 edittext.append(ctx.description())
2713 edittext.append(ctx.description())
2714 edittext.append("")
2714 edittext.append("")
2715 edittext.append("") # Empty line between message and comments.
2715 edittext.append("") # Empty line between message and comments.
2716 edittext.append(hgprefix(_("Enter commit message."
2716 edittext.append(hgprefix(_("Enter commit message."
2717 " Lines beginning with 'HG:' are removed.")))
2717 " Lines beginning with 'HG:' are removed.")))
2718 edittext.append(hgprefix(extramsg))
2718 edittext.append(hgprefix(extramsg))
2719 edittext.append("HG: --")
2719 edittext.append("HG: --")
2720 edittext.append(hgprefix(_("user: %s") % ctx.user()))
2720 edittext.append(hgprefix(_("user: %s") % ctx.user()))
2721 if ctx.p2():
2721 if ctx.p2():
2722 edittext.append(hgprefix(_("branch merge")))
2722 edittext.append(hgprefix(_("branch merge")))
2723 if ctx.branch():
2723 if ctx.branch():
2724 edittext.append(hgprefix(_("branch '%s'") % ctx.branch()))
2724 edittext.append(hgprefix(_("branch '%s'") % ctx.branch()))
2725 if bookmarks.isactivewdirparent(repo):
2725 if bookmarks.isactivewdirparent(repo):
2726 edittext.append(hgprefix(_("bookmark '%s'") % repo._activebookmark))
2726 edittext.append(hgprefix(_("bookmark '%s'") % repo._activebookmark))
2727 edittext.extend([hgprefix(_("subrepo %s") % s) for s in subs])
2727 edittext.extend([hgprefix(_("subrepo %s") % s) for s in subs])
2728 edittext.extend([hgprefix(_("added %s") % f) for f in added])
2728 edittext.extend([hgprefix(_("added %s") % f) for f in added])
2729 edittext.extend([hgprefix(_("changed %s") % f) for f in modified])
2729 edittext.extend([hgprefix(_("changed %s") % f) for f in modified])
2730 edittext.extend([hgprefix(_("removed %s") % f) for f in removed])
2730 edittext.extend([hgprefix(_("removed %s") % f) for f in removed])
2731 if not added and not modified and not removed:
2731 if not added and not modified and not removed:
2732 edittext.append(hgprefix(_("no files changed")))
2732 edittext.append(hgprefix(_("no files changed")))
2733 edittext.append("")
2733 edittext.append("")
2734
2734
2735 return "\n".join(edittext)
2735 return "\n".join(edittext)
2736
2736
2737 def commitstatus(repo, node, branch, bheads=None, opts=None):
2737 def commitstatus(repo, node, branch, bheads=None, opts=None):
2738 if opts is None:
2738 if opts is None:
2739 opts = {}
2739 opts = {}
2740 ctx = repo[node]
2740 ctx = repo[node]
2741 parents = ctx.parents()
2741 parents = ctx.parents()
2742
2742
2743 if (not opts.get('amend') and bheads and node not in bheads and not
2743 if (not opts.get('amend') and bheads and node not in bheads and not
2744 [x for x in parents if x.node() in bheads and x.branch() == branch]):
2744 [x for x in parents if x.node() in bheads and x.branch() == branch]):
2745 repo.ui.status(_('created new head\n'))
2745 repo.ui.status(_('created new head\n'))
2746 # The message is not printed for initial roots. For the other
2746 # The message is not printed for initial roots. For the other
2747 # changesets, it is printed in the following situations:
2747 # changesets, it is printed in the following situations:
2748 #
2748 #
2749 # Par column: for the 2 parents with ...
2749 # Par column: for the 2 parents with ...
2750 # N: null or no parent
2750 # N: null or no parent
2751 # B: parent is on another named branch
2751 # B: parent is on another named branch
2752 # C: parent is a regular non head changeset
2752 # C: parent is a regular non head changeset
2753 # H: parent was a branch head of the current branch
2753 # H: parent was a branch head of the current branch
2754 # Msg column: whether we print "created new head" message
2754 # Msg column: whether we print "created new head" message
2755 # In the following, it is assumed that there already exists some
2755 # In the following, it is assumed that there already exists some
2756 # initial branch heads of the current branch, otherwise nothing is
2756 # initial branch heads of the current branch, otherwise nothing is
2757 # printed anyway.
2757 # printed anyway.
2758 #
2758 #
2759 # Par Msg Comment
2759 # Par Msg Comment
2760 # N N y additional topo root
2760 # N N y additional topo root
2761 #
2761 #
2762 # B N y additional branch root
2762 # B N y additional branch root
2763 # C N y additional topo head
2763 # C N y additional topo head
2764 # H N n usual case
2764 # H N n usual case
2765 #
2765 #
2766 # B B y weird additional branch root
2766 # B B y weird additional branch root
2767 # C B y branch merge
2767 # C B y branch merge
2768 # H B n merge with named branch
2768 # H B n merge with named branch
2769 #
2769 #
2770 # C C y additional head from merge
2770 # C C y additional head from merge
2771 # C H n merge with a head
2771 # C H n merge with a head
2772 #
2772 #
2773 # H H n head merge: head count decreases
2773 # H H n head merge: head count decreases
2774
2774
2775 if not opts.get('close_branch'):
2775 if not opts.get('close_branch'):
2776 for r in parents:
2776 for r in parents:
2777 if r.closesbranch() and r.branch() == branch:
2777 if r.closesbranch() and r.branch() == branch:
2778 repo.ui.status(_('reopening closed branch head %d\n') % r)
2778 repo.ui.status(_('reopening closed branch head %d\n') % r)
2779
2779
2780 if repo.ui.debugflag:
2780 if repo.ui.debugflag:
2781 repo.ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
2781 repo.ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
2782 elif repo.ui.verbose:
2782 elif repo.ui.verbose:
2783 repo.ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
2783 repo.ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
2784
2784
2785 def revert(ui, repo, ctx, parents, *pats, **opts):
2785 def revert(ui, repo, ctx, parents, *pats, **opts):
2786 parent, p2 = parents
2786 parent, p2 = parents
2787 node = ctx.node()
2787 node = ctx.node()
2788
2788
2789 mf = ctx.manifest()
2789 mf = ctx.manifest()
2790 if node == p2:
2790 if node == p2:
2791 parent = p2
2791 parent = p2
2792 if node == parent:
2792 if node == parent:
2793 pmf = mf
2793 pmf = mf
2794 else:
2794 else:
2795 pmf = None
2795 pmf = None
2796
2796
2797 # need all matching names in dirstate and manifest of target rev,
2797 # need all matching names in dirstate and manifest of target rev,
2798 # so have to walk both. do not print errors if files exist in one
2798 # so have to walk both. do not print errors if files exist in one
2799 # but not other. in both cases, filesets should be evaluated against
2799 # but not other. in both cases, filesets should be evaluated against
2800 # workingctx to get consistent result (issue4497). this means 'set:**'
2800 # workingctx to get consistent result (issue4497). this means 'set:**'
2801 # cannot be used to select missing files from target rev.
2801 # cannot be used to select missing files from target rev.
2802
2802
2803 # `names` is a mapping for all elements in working copy and target revision
2803 # `names` is a mapping for all elements in working copy and target revision
2804 # The mapping is in the form:
2804 # The mapping is in the form:
2805 # <asb path in repo> -> (<path from CWD>, <exactly specified by matcher?>)
2805 # <asb path in repo> -> (<path from CWD>, <exactly specified by matcher?>)
2806 names = {}
2806 names = {}
2807
2807
2808 wlock = repo.wlock()
2808 wlock = repo.wlock()
2809 try:
2809 try:
2810 ## filling of the `names` mapping
2810 ## filling of the `names` mapping
2811 # walk dirstate to fill `names`
2811 # walk dirstate to fill `names`
2812
2812
2813 interactive = opts.get('interactive', False)
2813 interactive = opts.get('interactive', False)
2814 wctx = repo[None]
2814 wctx = repo[None]
2815 m = scmutil.match(wctx, pats, opts)
2815 m = scmutil.match(wctx, pats, opts)
2816
2816
2817 # we'll need this later
2817 # we'll need this later
2818 targetsubs = sorted(s for s in wctx.substate if m(s))
2818 targetsubs = sorted(s for s in wctx.substate if m(s))
2819
2819
2820 if not m.always():
2820 if not m.always():
2821 for abs in repo.walk(matchmod.badmatch(m, lambda x, y: False)):
2821 for abs in repo.walk(matchmod.badmatch(m, lambda x, y: False)):
2822 names[abs] = m.rel(abs), m.exact(abs)
2822 names[abs] = m.rel(abs), m.exact(abs)
2823
2823
2824 # walk target manifest to fill `names`
2824 # walk target manifest to fill `names`
2825
2825
2826 def badfn(path, msg):
2826 def badfn(path, msg):
2827 if path in names:
2827 if path in names:
2828 return
2828 return
2829 if path in ctx.substate:
2829 if path in ctx.substate:
2830 return
2830 return
2831 path_ = path + '/'
2831 path_ = path + '/'
2832 for f in names:
2832 for f in names:
2833 if f.startswith(path_):
2833 if f.startswith(path_):
2834 return
2834 return
2835 ui.warn("%s: %s\n" % (m.rel(path), msg))
2835 ui.warn("%s: %s\n" % (m.rel(path), msg))
2836
2836
2837 for abs in ctx.walk(matchmod.badmatch(m, badfn)):
2837 for abs in ctx.walk(matchmod.badmatch(m, badfn)):
2838 if abs not in names:
2838 if abs not in names:
2839 names[abs] = m.rel(abs), m.exact(abs)
2839 names[abs] = m.rel(abs), m.exact(abs)
2840
2840
2841 # Find status of all file in `names`.
2841 # Find status of all file in `names`.
2842 m = scmutil.matchfiles(repo, names)
2842 m = scmutil.matchfiles(repo, names)
2843
2843
2844 changes = repo.status(node1=node, match=m,
2844 changes = repo.status(node1=node, match=m,
2845 unknown=True, ignored=True, clean=True)
2845 unknown=True, ignored=True, clean=True)
2846 else:
2846 else:
2847 changes = repo.status(node1=node, match=m)
2847 changes = repo.status(node1=node, match=m)
2848 for kind in changes:
2848 for kind in changes:
2849 for abs in kind:
2849 for abs in kind:
2850 names[abs] = m.rel(abs), m.exact(abs)
2850 names[abs] = m.rel(abs), m.exact(abs)
2851
2851
2852 m = scmutil.matchfiles(repo, names)
2852 m = scmutil.matchfiles(repo, names)
2853
2853
2854 modified = set(changes.modified)
2854 modified = set(changes.modified)
2855 added = set(changes.added)
2855 added = set(changes.added)
2856 removed = set(changes.removed)
2856 removed = set(changes.removed)
2857 _deleted = set(changes.deleted)
2857 _deleted = set(changes.deleted)
2858 unknown = set(changes.unknown)
2858 unknown = set(changes.unknown)
2859 unknown.update(changes.ignored)
2859 unknown.update(changes.ignored)
2860 clean = set(changes.clean)
2860 clean = set(changes.clean)
2861 modadded = set()
2861 modadded = set()
2862
2862
2863 # split between files known in target manifest and the others
2863 # split between files known in target manifest and the others
2864 smf = set(mf)
2864 smf = set(mf)
2865
2865
2866 # determine the exact nature of the deleted changesets
2866 # determine the exact nature of the deleted changesets
2867 deladded = _deleted - smf
2867 deladded = _deleted - smf
2868 deleted = _deleted - deladded
2868 deleted = _deleted - deladded
2869
2869
2870 # We need to account for the state of the file in the dirstate,
2870 # We need to account for the state of the file in the dirstate,
2871 # even when we revert against something else than parent. This will
2871 # even when we revert against something else than parent. This will
2872 # slightly alter the behavior of revert (doing back up or not, delete
2872 # slightly alter the behavior of revert (doing back up or not, delete
2873 # or just forget etc).
2873 # or just forget etc).
2874 if parent == node:
2874 if parent == node:
2875 dsmodified = modified
2875 dsmodified = modified
2876 dsadded = added
2876 dsadded = added
2877 dsremoved = removed
2877 dsremoved = removed
2878 # store all local modifications, useful later for rename detection
2878 # store all local modifications, useful later for rename detection
2879 localchanges = dsmodified | dsadded
2879 localchanges = dsmodified | dsadded
2880 modified, added, removed = set(), set(), set()
2880 modified, added, removed = set(), set(), set()
2881 else:
2881 else:
2882 changes = repo.status(node1=parent, match=m)
2882 changes = repo.status(node1=parent, match=m)
2883 dsmodified = set(changes.modified)
2883 dsmodified = set(changes.modified)
2884 dsadded = set(changes.added)
2884 dsadded = set(changes.added)
2885 dsremoved = set(changes.removed)
2885 dsremoved = set(changes.removed)
2886 # store all local modifications, useful later for rename detection
2886 # store all local modifications, useful later for rename detection
2887 localchanges = dsmodified | dsadded
2887 localchanges = dsmodified | dsadded
2888
2888
2889 # only take into account for removes between wc and target
2889 # only take into account for removes between wc and target
2890 clean |= dsremoved - removed
2890 clean |= dsremoved - removed
2891 dsremoved &= removed
2891 dsremoved &= removed
2892 # distinct between dirstate remove and other
2892 # distinct between dirstate remove and other
2893 removed -= dsremoved
2893 removed -= dsremoved
2894
2894
2895 modadded = added & dsmodified
2895 modadded = added & dsmodified
2896 added -= modadded
2896 added -= modadded
2897
2897
2898 # tell newly modified apart.
2898 # tell newly modified apart.
2899 dsmodified &= modified
2899 dsmodified &= modified
2900 dsmodified |= modified & dsadded # dirstate added may needs backup
2900 dsmodified |= modified & dsadded # dirstate added may needs backup
2901 modified -= dsmodified
2901 modified -= dsmodified
2902
2902
2903 # We need to wait for some post-processing to update this set
2903 # We need to wait for some post-processing to update this set
2904 # before making the distinction. The dirstate will be used for
2904 # before making the distinction. The dirstate will be used for
2905 # that purpose.
2905 # that purpose.
2906 dsadded = added
2906 dsadded = added
2907
2907
2908 # in case of merge, files that are actually added can be reported as
2908 # in case of merge, files that are actually added can be reported as
2909 # modified, we need to post process the result
2909 # modified, we need to post process the result
2910 if p2 != nullid:
2910 if p2 != nullid:
2911 if pmf is None:
2911 if pmf is None:
2912 # only need parent manifest in the merge case,
2912 # only need parent manifest in the merge case,
2913 # so do not read by default
2913 # so do not read by default
2914 pmf = repo[parent].manifest()
2914 pmf = repo[parent].manifest()
2915 mergeadd = dsmodified - set(pmf)
2915 mergeadd = dsmodified - set(pmf)
2916 dsadded |= mergeadd
2916 dsadded |= mergeadd
2917 dsmodified -= mergeadd
2917 dsmodified -= mergeadd
2918
2918
2919 # if f is a rename, update `names` to also revert the source
2919 # if f is a rename, update `names` to also revert the source
2920 cwd = repo.getcwd()
2920 cwd = repo.getcwd()
2921 for f in localchanges:
2921 for f in localchanges:
2922 src = repo.dirstate.copied(f)
2922 src = repo.dirstate.copied(f)
2923 # XXX should we check for rename down to target node?
2923 # XXX should we check for rename down to target node?
2924 if src and src not in names and repo.dirstate[src] == 'r':
2924 if src and src not in names and repo.dirstate[src] == 'r':
2925 dsremoved.add(src)
2925 dsremoved.add(src)
2926 names[src] = (repo.pathto(src, cwd), True)
2926 names[src] = (repo.pathto(src, cwd), True)
2927
2927
2928 # distinguish between file to forget and the other
2928 # distinguish between file to forget and the other
2929 added = set()
2929 added = set()
2930 for abs in dsadded:
2930 for abs in dsadded:
2931 if repo.dirstate[abs] != 'a':
2931 if repo.dirstate[abs] != 'a':
2932 added.add(abs)
2932 added.add(abs)
2933 dsadded -= added
2933 dsadded -= added
2934
2934
2935 for abs in deladded:
2935 for abs in deladded:
2936 if repo.dirstate[abs] == 'a':
2936 if repo.dirstate[abs] == 'a':
2937 dsadded.add(abs)
2937 dsadded.add(abs)
2938 deladded -= dsadded
2938 deladded -= dsadded
2939
2939
2940 # For files marked as removed, we check if an unknown file is present at
2940 # For files marked as removed, we check if an unknown file is present at
2941 # the same path. If a such file exists it may need to be backed up.
2941 # the same path. If a such file exists it may need to be backed up.
2942 # Making the distinction at this stage helps have simpler backup
2942 # Making the distinction at this stage helps have simpler backup
2943 # logic.
2943 # logic.
2944 removunk = set()
2944 removunk = set()
2945 for abs in removed:
2945 for abs in removed:
2946 target = repo.wjoin(abs)
2946 target = repo.wjoin(abs)
2947 if os.path.lexists(target):
2947 if os.path.lexists(target):
2948 removunk.add(abs)
2948 removunk.add(abs)
2949 removed -= removunk
2949 removed -= removunk
2950
2950
2951 dsremovunk = set()
2951 dsremovunk = set()
2952 for abs in dsremoved:
2952 for abs in dsremoved:
2953 target = repo.wjoin(abs)
2953 target = repo.wjoin(abs)
2954 if os.path.lexists(target):
2954 if os.path.lexists(target):
2955 dsremovunk.add(abs)
2955 dsremovunk.add(abs)
2956 dsremoved -= dsremovunk
2956 dsremoved -= dsremovunk
2957
2957
2958 # action to be actually performed by revert
2958 # action to be actually performed by revert
2959 # (<list of file>, message>) tuple
2959 # (<list of file>, message>) tuple
2960 actions = {'revert': ([], _('reverting %s\n')),
2960 actions = {'revert': ([], _('reverting %s\n')),
2961 'add': ([], _('adding %s\n')),
2961 'add': ([], _('adding %s\n')),
2962 'remove': ([], _('removing %s\n')),
2962 'remove': ([], _('removing %s\n')),
2963 'drop': ([], _('removing %s\n')),
2963 'drop': ([], _('removing %s\n')),
2964 'forget': ([], _('forgetting %s\n')),
2964 'forget': ([], _('forgetting %s\n')),
2965 'undelete': ([], _('undeleting %s\n')),
2965 'undelete': ([], _('undeleting %s\n')),
2966 'noop': (None, _('no changes needed to %s\n')),
2966 'noop': (None, _('no changes needed to %s\n')),
2967 'unknown': (None, _('file not managed: %s\n')),
2967 'unknown': (None, _('file not managed: %s\n')),
2968 }
2968 }
2969
2969
2970 # "constant" that convey the backup strategy.
2970 # "constant" that convey the backup strategy.
2971 # All set to `discard` if `no-backup` is set do avoid checking
2971 # All set to `discard` if `no-backup` is set do avoid checking
2972 # no_backup lower in the code.
2972 # no_backup lower in the code.
2973 # These values are ordered for comparison purposes
2973 # These values are ordered for comparison purposes
2974 backup = 2 # unconditionally do backup
2974 backup = 2 # unconditionally do backup
2975 check = 1 # check if the existing file differs from target
2975 check = 1 # check if the existing file differs from target
2976 discard = 0 # never do backup
2976 discard = 0 # never do backup
2977 if opts.get('no_backup'):
2977 if opts.get('no_backup'):
2978 backup = check = discard
2978 backup = check = discard
2979
2979
2980 backupanddel = actions['remove']
2980 backupanddel = actions['remove']
2981 if not opts.get('no_backup'):
2981 if not opts.get('no_backup'):
2982 backupanddel = actions['drop']
2982 backupanddel = actions['drop']
2983
2983
2984 disptable = (
2984 disptable = (
2985 # dispatch table:
2985 # dispatch table:
2986 # file state
2986 # file state
2987 # action
2987 # action
2988 # make backup
2988 # make backup
2989
2989
2990 ## Sets that results that will change file on disk
2990 ## Sets that results that will change file on disk
2991 # Modified compared to target, no local change
2991 # Modified compared to target, no local change
2992 (modified, actions['revert'], discard),
2992 (modified, actions['revert'], discard),
2993 # Modified compared to target, but local file is deleted
2993 # Modified compared to target, but local file is deleted
2994 (deleted, actions['revert'], discard),
2994 (deleted, actions['revert'], discard),
2995 # Modified compared to target, local change
2995 # Modified compared to target, local change
2996 (dsmodified, actions['revert'], backup),
2996 (dsmodified, actions['revert'], backup),
2997 # Added since target
2997 # Added since target
2998 (added, actions['remove'], discard),
2998 (added, actions['remove'], discard),
2999 # Added in working directory
2999 # Added in working directory
3000 (dsadded, actions['forget'], discard),
3000 (dsadded, actions['forget'], discard),
3001 # Added since target, have local modification
3001 # Added since target, have local modification
3002 (modadded, backupanddel, backup),
3002 (modadded, backupanddel, backup),
3003 # Added since target but file is missing in working directory
3003 # Added since target but file is missing in working directory
3004 (deladded, actions['drop'], discard),
3004 (deladded, actions['drop'], discard),
3005 # Removed since target, before working copy parent
3005 # Removed since target, before working copy parent
3006 (removed, actions['add'], discard),
3006 (removed, actions['add'], discard),
3007 # Same as `removed` but an unknown file exists at the same path
3007 # Same as `removed` but an unknown file exists at the same path
3008 (removunk, actions['add'], check),
3008 (removunk, actions['add'], check),
3009 # Removed since targe, marked as such in working copy parent
3009 # Removed since targe, marked as such in working copy parent
3010 (dsremoved, actions['undelete'], discard),
3010 (dsremoved, actions['undelete'], discard),
3011 # Same as `dsremoved` but an unknown file exists at the same path
3011 # Same as `dsremoved` but an unknown file exists at the same path
3012 (dsremovunk, actions['undelete'], check),
3012 (dsremovunk, actions['undelete'], check),
3013 ## the following sets does not result in any file changes
3013 ## the following sets does not result in any file changes
3014 # File with no modification
3014 # File with no modification
3015 (clean, actions['noop'], discard),
3015 (clean, actions['noop'], discard),
3016 # Existing file, not tracked anywhere
3016 # Existing file, not tracked anywhere
3017 (unknown, actions['unknown'], discard),
3017 (unknown, actions['unknown'], discard),
3018 )
3018 )
3019
3019
3020 for abs, (rel, exact) in sorted(names.items()):
3020 for abs, (rel, exact) in sorted(names.items()):
3021 # target file to be touch on disk (relative to cwd)
3021 # target file to be touch on disk (relative to cwd)
3022 target = repo.wjoin(abs)
3022 target = repo.wjoin(abs)
3023 # search the entry in the dispatch table.
3023 # search the entry in the dispatch table.
3024 # if the file is in any of these sets, it was touched in the working
3024 # if the file is in any of these sets, it was touched in the working
3025 # directory parent and we are sure it needs to be reverted.
3025 # directory parent and we are sure it needs to be reverted.
3026 for table, (xlist, msg), dobackup in disptable:
3026 for table, (xlist, msg), dobackup in disptable:
3027 if abs not in table:
3027 if abs not in table:
3028 continue
3028 continue
3029 if xlist is not None:
3029 if xlist is not None:
3030 xlist.append(abs)
3030 xlist.append(abs)
3031 if dobackup and (backup <= dobackup
3031 if dobackup and (backup <= dobackup
3032 or wctx[abs].cmp(ctx[abs])):
3032 or wctx[abs].cmp(ctx[abs])):
3033 bakname = "%s.orig" % rel
3033 bakname = "%s.orig" % rel
3034 ui.note(_('saving current version of %s as %s\n') %
3034 ui.note(_('saving current version of %s as %s\n') %
3035 (rel, bakname))
3035 (rel, bakname))
3036 if not opts.get('dry_run'):
3036 if not opts.get('dry_run'):
3037 if interactive:
3037 if interactive:
3038 util.copyfile(target, bakname)
3038 util.copyfile(target, bakname)
3039 else:
3039 else:
3040 util.rename(target, bakname)
3040 util.rename(target, bakname)
3041 if ui.verbose or not exact:
3041 if ui.verbose or not exact:
3042 if not isinstance(msg, basestring):
3042 if not isinstance(msg, basestring):
3043 msg = msg(abs)
3043 msg = msg(abs)
3044 ui.status(msg % rel)
3044 ui.status(msg % rel)
3045 elif exact:
3045 elif exact:
3046 ui.warn(msg % rel)
3046 ui.warn(msg % rel)
3047 break
3047 break
3048
3048
3049 if not opts.get('dry_run'):
3049 if not opts.get('dry_run'):
3050 needdata = ('revert', 'add', 'undelete')
3050 needdata = ('revert', 'add', 'undelete')
3051 _revertprefetch(repo, ctx, *[actions[name][0] for name in needdata])
3051 _revertprefetch(repo, ctx, *[actions[name][0] for name in needdata])
3052 _performrevert(repo, parents, ctx, actions, interactive)
3052 _performrevert(repo, parents, ctx, actions, interactive)
3053
3053
3054 if targetsubs:
3054 if targetsubs:
3055 # Revert the subrepos on the revert list
3055 # Revert the subrepos on the revert list
3056 for sub in targetsubs:
3056 for sub in targetsubs:
3057 try:
3057 try:
3058 wctx.sub(sub).revert(ctx.substate[sub], *pats, **opts)
3058 wctx.sub(sub).revert(ctx.substate[sub], *pats, **opts)
3059 except KeyError:
3059 except KeyError:
3060 raise util.Abort("subrepository '%s' does not exist in %s!"
3060 raise util.Abort("subrepository '%s' does not exist in %s!"
3061 % (sub, short(ctx.node())))
3061 % (sub, short(ctx.node())))
3062 finally:
3062 finally:
3063 wlock.release()
3063 wlock.release()
3064
3064
3065 def _revertprefetch(repo, ctx, *files):
3065 def _revertprefetch(repo, ctx, *files):
3066 """Let extension changing the storage layer prefetch content"""
3066 """Let extension changing the storage layer prefetch content"""
3067 pass
3067 pass
3068
3068
3069 def _performrevert(repo, parents, ctx, actions, interactive=False):
3069 def _performrevert(repo, parents, ctx, actions, interactive=False):
3070 """function that actually perform all the actions computed for revert
3070 """function that actually perform all the actions computed for revert
3071
3071
3072 This is an independent function to let extension to plug in and react to
3072 This is an independent function to let extension to plug in and react to
3073 the imminent revert.
3073 the imminent revert.
3074
3074
3075 Make sure you have the working directory locked when calling this function.
3075 Make sure you have the working directory locked when calling this function.
3076 """
3076 """
3077 parent, p2 = parents
3077 parent, p2 = parents
3078 node = ctx.node()
3078 node = ctx.node()
3079 def checkout(f):
3079 def checkout(f):
3080 fc = ctx[f]
3080 fc = ctx[f]
3081 repo.wwrite(f, fc.data(), fc.flags())
3081 repo.wwrite(f, fc.data(), fc.flags())
3082
3082
3083 audit_path = pathutil.pathauditor(repo.root)
3083 audit_path = pathutil.pathauditor(repo.root)
3084 for f in actions['forget'][0]:
3084 for f in actions['forget'][0]:
3085 repo.dirstate.drop(f)
3085 repo.dirstate.drop(f)
3086 for f in actions['remove'][0]:
3086 for f in actions['remove'][0]:
3087 audit_path(f)
3087 audit_path(f)
3088 try:
3088 try:
3089 util.unlinkpath(repo.wjoin(f))
3089 util.unlinkpath(repo.wjoin(f))
3090 except OSError:
3090 except OSError:
3091 pass
3091 pass
3092 repo.dirstate.remove(f)
3092 repo.dirstate.remove(f)
3093 for f in actions['drop'][0]:
3093 for f in actions['drop'][0]:
3094 audit_path(f)
3094 audit_path(f)
3095 repo.dirstate.remove(f)
3095 repo.dirstate.remove(f)
3096
3096
3097 normal = None
3097 normal = None
3098 if node == parent:
3098 if node == parent:
3099 # We're reverting to our parent. If possible, we'd like status
3099 # We're reverting to our parent. If possible, we'd like status
3100 # to report the file as clean. We have to use normallookup for
3100 # to report the file as clean. We have to use normallookup for
3101 # merges to avoid losing information about merged/dirty files.
3101 # merges to avoid losing information about merged/dirty files.
3102 if p2 != nullid:
3102 if p2 != nullid:
3103 normal = repo.dirstate.normallookup
3103 normal = repo.dirstate.normallookup
3104 else:
3104 else:
3105 normal = repo.dirstate.normal
3105 normal = repo.dirstate.normal
3106
3106
3107 newlyaddedandmodifiedfiles = set()
3107 newlyaddedandmodifiedfiles = set()
3108 if interactive:
3108 if interactive:
3109 # Prompt the user for changes to revert
3109 # Prompt the user for changes to revert
3110 torevert = [repo.wjoin(f) for f in actions['revert'][0]]
3110 torevert = [repo.wjoin(f) for f in actions['revert'][0]]
3111 m = scmutil.match(ctx, torevert, {})
3111 m = scmutil.match(ctx, torevert, {})
3112 diffopts = patch.difffeatureopts(repo.ui, whitespace=True)
3112 diffopts = patch.difffeatureopts(repo.ui, whitespace=True)
3113 diffopts.nodates = True
3113 diffopts.nodates = True
3114 diffopts.git = True
3114 diffopts.git = True
3115 reversehunks = repo.ui.configbool('experimental',
3115 reversehunks = repo.ui.configbool('experimental',
3116 'revertalternateinteractivemode',
3116 'revertalternateinteractivemode',
3117 True)
3117 True)
3118 if reversehunks:
3118 if reversehunks:
3119 diff = patch.diff(repo, ctx.node(), None, m, opts=diffopts)
3119 diff = patch.diff(repo, ctx.node(), None, m, opts=diffopts)
3120 else:
3120 else:
3121 diff = patch.diff(repo, None, ctx.node(), m, opts=diffopts)
3121 diff = patch.diff(repo, None, ctx.node(), m, opts=diffopts)
3122 originalchunks = patch.parsepatch(diff)
3122 originalchunks = patch.parsepatch(diff)
3123
3123
3124 try:
3124 try:
3125
3125
3126 chunks = recordfilter(repo.ui, originalchunks)
3126 chunks = recordfilter(repo.ui, originalchunks)
3127 if reversehunks:
3127 if reversehunks:
3128 chunks = patch.reversehunks(chunks)
3128 chunks = patch.reversehunks(chunks)
3129
3129
3130 except patch.PatchError as err:
3130 except patch.PatchError as err:
3131 raise util.Abort(_('error parsing patch: %s') % err)
3131 raise util.Abort(_('error parsing patch: %s') % err)
3132
3132
3133 newlyaddedandmodifiedfiles = newandmodified(chunks, originalchunks)
3133 newlyaddedandmodifiedfiles = newandmodified(chunks, originalchunks)
3134 # Apply changes
3134 # Apply changes
3135 fp = cStringIO.StringIO()
3135 fp = cStringIO.StringIO()
3136 for c in chunks:
3136 for c in chunks:
3137 c.write(fp)
3137 c.write(fp)
3138 dopatch = fp.tell()
3138 dopatch = fp.tell()
3139 fp.seek(0)
3139 fp.seek(0)
3140 if dopatch:
3140 if dopatch:
3141 try:
3141 try:
3142 patch.internalpatch(repo.ui, repo, fp, 1, eolmode=None)
3142 patch.internalpatch(repo.ui, repo, fp, 1, eolmode=None)
3143 except patch.PatchError as err:
3143 except patch.PatchError as err:
3144 raise util.Abort(str(err))
3144 raise util.Abort(str(err))
3145 del fp
3145 del fp
3146 else:
3146 else:
3147 for f in actions['revert'][0]:
3147 for f in actions['revert'][0]:
3148 checkout(f)
3148 checkout(f)
3149 if normal:
3149 if normal:
3150 normal(f)
3150 normal(f)
3151
3151
3152 for f in actions['add'][0]:
3152 for f in actions['add'][0]:
3153 # Don't checkout modified files, they are already created by the diff
3153 # Don't checkout modified files, they are already created by the diff
3154 if f not in newlyaddedandmodifiedfiles:
3154 if f not in newlyaddedandmodifiedfiles:
3155 checkout(f)
3155 checkout(f)
3156 repo.dirstate.add(f)
3156 repo.dirstate.add(f)
3157
3157
3158 normal = repo.dirstate.normallookup
3158 normal = repo.dirstate.normallookup
3159 if node == parent and p2 == nullid:
3159 if node == parent and p2 == nullid:
3160 normal = repo.dirstate.normal
3160 normal = repo.dirstate.normal
3161 for f in actions['undelete'][0]:
3161 for f in actions['undelete'][0]:
3162 checkout(f)
3162 checkout(f)
3163 normal(f)
3163 normal(f)
3164
3164
3165 copied = copies.pathcopies(repo[parent], ctx)
3165 copied = copies.pathcopies(repo[parent], ctx)
3166
3166
3167 for f in actions['add'][0] + actions['undelete'][0] + actions['revert'][0]:
3167 for f in actions['add'][0] + actions['undelete'][0] + actions['revert'][0]:
3168 if f in copied:
3168 if f in copied:
3169 repo.dirstate.copy(copied[f], f)
3169 repo.dirstate.copy(copied[f], f)
3170
3170
3171 def command(table):
3171 def command(table):
3172 """Returns a function object to be used as a decorator for making commands.
3172 """Returns a function object to be used as a decorator for making commands.
3173
3173
3174 This function receives a command table as its argument. The table should
3174 This function receives a command table as its argument. The table should
3175 be a dict.
3175 be a dict.
3176
3176
3177 The returned function can be used as a decorator for adding commands
3177 The returned function can be used as a decorator for adding commands
3178 to that command table. This function accepts multiple arguments to define
3178 to that command table. This function accepts multiple arguments to define
3179 a command.
3179 a command.
3180
3180
3181 The first argument is the command name.
3181 The first argument is the command name.
3182
3182
3183 The options argument is an iterable of tuples defining command arguments.
3183 The options argument is an iterable of tuples defining command arguments.
3184 See ``mercurial.fancyopts.fancyopts()`` for the format of each tuple.
3184 See ``mercurial.fancyopts.fancyopts()`` for the format of each tuple.
3185
3185
3186 The synopsis argument defines a short, one line summary of how to use the
3186 The synopsis argument defines a short, one line summary of how to use the
3187 command. This shows up in the help output.
3187 command. This shows up in the help output.
3188
3188
3189 The norepo argument defines whether the command does not require a
3189 The norepo argument defines whether the command does not require a
3190 local repository. Most commands operate against a repository, thus the
3190 local repository. Most commands operate against a repository, thus the
3191 default is False.
3191 default is False.
3192
3192
3193 The optionalrepo argument defines whether the command optionally requires
3193 The optionalrepo argument defines whether the command optionally requires
3194 a local repository.
3194 a local repository.
3195
3195
3196 The inferrepo argument defines whether to try to find a repository from the
3196 The inferrepo argument defines whether to try to find a repository from the
3197 command line arguments. If True, arguments will be examined for potential
3197 command line arguments. If True, arguments will be examined for potential
3198 repository locations. See ``findrepo()``. If a repository is found, it
3198 repository locations. See ``findrepo()``. If a repository is found, it
3199 will be used.
3199 will be used.
3200 """
3200 """
3201 def cmd(name, options=(), synopsis=None, norepo=False, optionalrepo=False,
3201 def cmd(name, options=(), synopsis=None, norepo=False, optionalrepo=False,
3202 inferrepo=False):
3202 inferrepo=False):
3203 def decorator(func):
3203 def decorator(func):
3204 if synopsis:
3204 if synopsis:
3205 table[name] = func, list(options), synopsis
3205 table[name] = func, list(options), synopsis
3206 else:
3206 else:
3207 table[name] = func, list(options)
3207 table[name] = func, list(options)
3208
3208
3209 if norepo:
3209 if norepo:
3210 # Avoid import cycle.
3210 # Avoid import cycle.
3211 import commands
3211 import commands
3212 commands.norepo += ' %s' % ' '.join(parsealiases(name))
3212 commands.norepo += ' %s' % ' '.join(parsealiases(name))
3213
3213
3214 if optionalrepo:
3214 if optionalrepo:
3215 import commands
3215 import commands
3216 commands.optionalrepo += ' %s' % ' '.join(parsealiases(name))
3216 commands.optionalrepo += ' %s' % ' '.join(parsealiases(name))
3217
3217
3218 if inferrepo:
3218 if inferrepo:
3219 import commands
3219 import commands
3220 commands.inferrepo += ' %s' % ' '.join(parsealiases(name))
3220 commands.inferrepo += ' %s' % ' '.join(parsealiases(name))
3221
3221
3222 return func
3222 return func
3223 return decorator
3223 return decorator
3224
3224
3225 return cmd
3225 return cmd
3226
3226
3227 # a list of (ui, repo, otherpeer, opts, missing) functions called by
3227 # a list of (ui, repo, otherpeer, opts, missing) functions called by
3228 # commands.outgoing. "missing" is "missing" of the result of
3228 # commands.outgoing. "missing" is "missing" of the result of
3229 # "findcommonoutgoing()"
3229 # "findcommonoutgoing()"
3230 outgoinghooks = util.hooks()
3230 outgoinghooks = util.hooks()
3231
3231
3232 # a list of (ui, repo) functions called by commands.summary
3232 # a list of (ui, repo) functions called by commands.summary
3233 summaryhooks = util.hooks()
3233 summaryhooks = util.hooks()
3234
3234
3235 # a list of (ui, repo, opts, changes) functions called by commands.summary.
3235 # a list of (ui, repo, opts, changes) functions called by commands.summary.
3236 #
3236 #
3237 # functions should return tuple of booleans below, if 'changes' is None:
3237 # functions should return tuple of booleans below, if 'changes' is None:
3238 # (whether-incomings-are-needed, whether-outgoings-are-needed)
3238 # (whether-incomings-are-needed, whether-outgoings-are-needed)
3239 #
3239 #
3240 # otherwise, 'changes' is a tuple of tuples below:
3240 # otherwise, 'changes' is a tuple of tuples below:
3241 # - (sourceurl, sourcebranch, sourcepeer, incoming)
3241 # - (sourceurl, sourcebranch, sourcepeer, incoming)
3242 # - (desturl, destbranch, destpeer, outgoing)
3242 # - (desturl, destbranch, destpeer, outgoing)
3243 summaryremotehooks = util.hooks()
3243 summaryremotehooks = util.hooks()
3244
3244
3245 # A list of state files kept by multistep operations like graft.
3245 # A list of state files kept by multistep operations like graft.
3246 # Since graft cannot be aborted, it is considered 'clearable' by update.
3246 # Since graft cannot be aborted, it is considered 'clearable' by update.
3247 # note: bisect is intentionally excluded
3247 # note: bisect is intentionally excluded
3248 # (state file, clearable, allowcommit, error, hint)
3248 # (state file, clearable, allowcommit, error, hint)
3249 unfinishedstates = [
3249 unfinishedstates = [
3250 ('graftstate', True, False, _('graft in progress'),
3250 ('graftstate', True, False, _('graft in progress'),
3251 _("use 'hg graft --continue' or 'hg update' to abort")),
3251 _("use 'hg graft --continue' or 'hg update' to abort")),
3252 ('updatestate', True, False, _('last update was interrupted'),
3252 ('updatestate', True, False, _('last update was interrupted'),
3253 _("use 'hg update' to get a consistent checkout"))
3253 _("use 'hg update' to get a consistent checkout"))
3254 ]
3254 ]
3255
3255
3256 def checkunfinished(repo, commit=False):
3256 def checkunfinished(repo, commit=False):
3257 '''Look for an unfinished multistep operation, like graft, and abort
3257 '''Look for an unfinished multistep operation, like graft, and abort
3258 if found. It's probably good to check this right before
3258 if found. It's probably good to check this right before
3259 bailifchanged().
3259 bailifchanged().
3260 '''
3260 '''
3261 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3261 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3262 if commit and allowcommit:
3262 if commit and allowcommit:
3263 continue
3263 continue
3264 if repo.vfs.exists(f):
3264 if repo.vfs.exists(f):
3265 raise util.Abort(msg, hint=hint)
3265 raise util.Abort(msg, hint=hint)
3266
3266
3267 def clearunfinished(repo):
3267 def clearunfinished(repo):
3268 '''Check for unfinished operations (as above), and clear the ones
3268 '''Check for unfinished operations (as above), and clear the ones
3269 that are clearable.
3269 that are clearable.
3270 '''
3270 '''
3271 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3271 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3272 if not clearable and repo.vfs.exists(f):
3272 if not clearable and repo.vfs.exists(f):
3273 raise util.Abort(msg, hint=hint)
3273 raise util.Abort(msg, hint=hint)
3274 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3274 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3275 if clearable and repo.vfs.exists(f):
3275 if clearable and repo.vfs.exists(f):
3276 util.unlink(repo.join(f))
3276 util.unlink(repo.join(f))
3277
3277
3278 class dirstateguard(object):
3278 class dirstateguard(object):
3279 '''Restore dirstate at unexpected failure.
3279 '''Restore dirstate at unexpected failure.
3280
3280
3281 At the construction, this class does:
3281 At the construction, this class does:
3282
3282
3283 - write current ``repo.dirstate`` out, and
3283 - write current ``repo.dirstate`` out, and
3284 - save ``.hg/dirstate`` into the backup file
3284 - save ``.hg/dirstate`` into the backup file
3285
3285
3286 This restores ``.hg/dirstate`` from backup file, if ``release()``
3286 This restores ``.hg/dirstate`` from backup file, if ``release()``
3287 is invoked before ``close()``.
3287 is invoked before ``close()``.
3288
3288
3289 This just removes the backup file at ``close()`` before ``release()``.
3289 This just removes the backup file at ``close()`` before ``release()``.
3290 '''
3290 '''
3291
3291
3292 def __init__(self, repo, name):
3292 def __init__(self, repo, name):
3293 repo.dirstate.write()
3293 repo.dirstate.write()
3294 self._repo = repo
3294 self._repo = repo
3295 self._filename = 'dirstate.backup.%s.%d' % (name, id(self))
3295 self._filename = 'dirstate.backup.%s.%d' % (name, id(self))
3296 repo.vfs.write(self._filename, repo.vfs.tryread('dirstate'))
3296 repo.vfs.write(self._filename, repo.vfs.tryread('dirstate'))
3297 self._active = True
3297 self._active = True
3298 self._closed = False
3298 self._closed = False
3299
3299
3300 def __del__(self):
3300 def __del__(self):
3301 if self._active: # still active
3301 if self._active: # still active
3302 # this may occur, even if this class is used correctly:
3302 # this may occur, even if this class is used correctly:
3303 # for example, releasing other resources like transaction
3303 # for example, releasing other resources like transaction
3304 # may raise exception before ``dirstateguard.release`` in
3304 # may raise exception before ``dirstateguard.release`` in
3305 # ``release(tr, ....)``.
3305 # ``release(tr, ....)``.
3306 self._abort()
3306 self._abort()
3307
3307
3308 def close(self):
3308 def close(self):
3309 if not self._active: # already inactivated
3309 if not self._active: # already inactivated
3310 msg = (_("can't close already inactivated backup: %s")
3310 msg = (_("can't close already inactivated backup: %s")
3311 % self._filename)
3311 % self._filename)
3312 raise util.Abort(msg)
3312 raise util.Abort(msg)
3313
3313
3314 self._repo.vfs.unlink(self._filename)
3314 self._repo.vfs.unlink(self._filename)
3315 self._active = False
3315 self._active = False
3316 self._closed = True
3316 self._closed = True
3317
3317
3318 def _abort(self):
3318 def _abort(self):
3319 # this "invalidate()" prevents "wlock.release()" from writing
3319 # this "invalidate()" prevents "wlock.release()" from writing
3320 # changes of dirstate out after restoring to original status
3320 # changes of dirstate out after restoring to original status
3321 self._repo.dirstate.invalidate()
3321 self._repo.dirstate.invalidate()
3322
3322
3323 self._repo.vfs.rename(self._filename, 'dirstate')
3323 self._repo.vfs.rename(self._filename, 'dirstate')
3324 self._active = False
3324 self._active = False
3325
3325
3326 def release(self):
3326 def release(self):
3327 if not self._closed:
3327 if not self._closed:
3328 if not self._active: # already inactivated
3328 if not self._active: # already inactivated
3329 msg = (_("can't release already inactivated backup: %s")
3329 msg = (_("can't release already inactivated backup: %s")
3330 % self._filename)
3330 % self._filename)
3331 raise util.Abort(msg)
3331 raise util.Abort(msg)
3332 self._abort()
3332 self._abort()
3333
3334 def parsebundletype(bundletype):
3335 """return the internal bundle type to use from a user input
3336
3337 This is parsing user specified bundle type as accepted in:
3338
3339 'hg bundle --type TYPE'.
3340 """
3341 btypes = {'none': 'HG10UN',
3342 'bzip2': 'HG10BZ',
3343 'gzip': 'HG10GZ',
3344 'bundle2': 'HG20'}
3345 bundletype = btypes.get(bundletype)
3346 if bundletype not in changegroup.bundletypes:
3347 raise util.Abort(_('unknown bundle type specified with --type'))
3348 return bundletype
3349
@@ -1,6642 +1,6636 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 node import hex, bin, nullid, nullrev, short
8 from node import hex, bin, nullid, nullrev, short
9 from lock import release
9 from lock import release
10 from i18n import _
10 from i18n import _
11 import os, re, difflib, time, tempfile, errno, shlex
11 import os, re, difflib, time, tempfile, errno, shlex
12 import sys, socket
12 import sys, socket
13 import hg, scmutil, util, revlog, copies, error, bookmarks
13 import hg, scmutil, util, revlog, copies, error, bookmarks
14 import patch, help, encoding, templatekw, discovery
14 import patch, help, encoding, templatekw, discovery
15 import archival, changegroup, cmdutil, hbisect
15 import archival, changegroup, cmdutil, hbisect
16 import sshserver, hgweb
16 import sshserver, hgweb
17 import extensions
17 import extensions
18 from hgweb import server as hgweb_server
18 from hgweb import server as hgweb_server
19 import merge as mergemod
19 import merge as mergemod
20 import minirst, revset, fileset
20 import minirst, revset, fileset
21 import dagparser, context, simplemerge, graphmod, copies
21 import dagparser, context, simplemerge, graphmod, copies
22 import random, operator
22 import random, operator
23 import setdiscovery, treediscovery, dagutil, pvec, localrepo
23 import setdiscovery, treediscovery, dagutil, pvec, localrepo
24 import phases, obsolete, exchange, bundle2, repair, lock as lockmod
24 import phases, obsolete, exchange, bundle2, repair, lock as lockmod
25 import ui as uimod
25 import ui as uimod
26
26
27 table = {}
27 table = {}
28
28
29 command = cmdutil.command(table)
29 command = cmdutil.command(table)
30
30
31 # Space delimited list of commands that don't require local repositories.
31 # Space delimited list of commands that don't require local repositories.
32 # This should be populated by passing norepo=True into the @command decorator.
32 # This should be populated by passing norepo=True into the @command decorator.
33 norepo = ''
33 norepo = ''
34 # Space delimited list of commands that optionally require local repositories.
34 # Space delimited list of commands that optionally require local repositories.
35 # This should be populated by passing optionalrepo=True into the @command
35 # This should be populated by passing optionalrepo=True into the @command
36 # decorator.
36 # decorator.
37 optionalrepo = ''
37 optionalrepo = ''
38 # Space delimited list of commands that will examine arguments looking for
38 # Space delimited list of commands that will examine arguments looking for
39 # a repository. This should be populated by passing inferrepo=True into the
39 # a repository. This should be populated by passing inferrepo=True into the
40 # @command decorator.
40 # @command decorator.
41 inferrepo = ''
41 inferrepo = ''
42
42
43 # label constants
43 # label constants
44 # until 3.5, bookmarks.current was the advertised name, not
44 # until 3.5, bookmarks.current was the advertised name, not
45 # bookmarks.active, so we must use both to avoid breaking old
45 # bookmarks.active, so we must use both to avoid breaking old
46 # custom styles
46 # custom styles
47 activebookmarklabel = 'bookmarks.active bookmarks.current'
47 activebookmarklabel = 'bookmarks.active bookmarks.current'
48
48
49 # common command options
49 # common command options
50
50
51 globalopts = [
51 globalopts = [
52 ('R', 'repository', '',
52 ('R', 'repository', '',
53 _('repository root directory or name of overlay bundle file'),
53 _('repository root directory or name of overlay bundle file'),
54 _('REPO')),
54 _('REPO')),
55 ('', 'cwd', '',
55 ('', 'cwd', '',
56 _('change working directory'), _('DIR')),
56 _('change working directory'), _('DIR')),
57 ('y', 'noninteractive', None,
57 ('y', 'noninteractive', None,
58 _('do not prompt, automatically pick the first choice for all prompts')),
58 _('do not prompt, automatically pick the first choice for all prompts')),
59 ('q', 'quiet', None, _('suppress output')),
59 ('q', 'quiet', None, _('suppress output')),
60 ('v', 'verbose', None, _('enable additional output')),
60 ('v', 'verbose', None, _('enable additional output')),
61 ('', 'config', [],
61 ('', 'config', [],
62 _('set/override config option (use \'section.name=value\')'),
62 _('set/override config option (use \'section.name=value\')'),
63 _('CONFIG')),
63 _('CONFIG')),
64 ('', 'debug', None, _('enable debugging output')),
64 ('', 'debug', None, _('enable debugging output')),
65 ('', 'debugger', None, _('start debugger')),
65 ('', 'debugger', None, _('start debugger')),
66 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
66 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
67 _('ENCODE')),
67 _('ENCODE')),
68 ('', 'encodingmode', encoding.encodingmode,
68 ('', 'encodingmode', encoding.encodingmode,
69 _('set the charset encoding mode'), _('MODE')),
69 _('set the charset encoding mode'), _('MODE')),
70 ('', 'traceback', None, _('always print a traceback on exception')),
70 ('', 'traceback', None, _('always print a traceback on exception')),
71 ('', 'time', None, _('time how long the command takes')),
71 ('', 'time', None, _('time how long the command takes')),
72 ('', 'profile', None, _('print command execution profile')),
72 ('', 'profile', None, _('print command execution profile')),
73 ('', 'version', None, _('output version information and exit')),
73 ('', 'version', None, _('output version information and exit')),
74 ('h', 'help', None, _('display help and exit')),
74 ('h', 'help', None, _('display help and exit')),
75 ('', 'hidden', False, _('consider hidden changesets')),
75 ('', 'hidden', False, _('consider hidden changesets')),
76 ]
76 ]
77
77
78 dryrunopts = [('n', 'dry-run', None,
78 dryrunopts = [('n', 'dry-run', None,
79 _('do not perform actions, just print output'))]
79 _('do not perform actions, just print output'))]
80
80
81 remoteopts = [
81 remoteopts = [
82 ('e', 'ssh', '',
82 ('e', 'ssh', '',
83 _('specify ssh command to use'), _('CMD')),
83 _('specify ssh command to use'), _('CMD')),
84 ('', 'remotecmd', '',
84 ('', 'remotecmd', '',
85 _('specify hg command to run on the remote side'), _('CMD')),
85 _('specify hg command to run on the remote side'), _('CMD')),
86 ('', 'insecure', None,
86 ('', 'insecure', None,
87 _('do not verify server certificate (ignoring web.cacerts config)')),
87 _('do not verify server certificate (ignoring web.cacerts config)')),
88 ]
88 ]
89
89
90 walkopts = [
90 walkopts = [
91 ('I', 'include', [],
91 ('I', 'include', [],
92 _('include names matching the given patterns'), _('PATTERN')),
92 _('include names matching the given patterns'), _('PATTERN')),
93 ('X', 'exclude', [],
93 ('X', 'exclude', [],
94 _('exclude names matching the given patterns'), _('PATTERN')),
94 _('exclude names matching the given patterns'), _('PATTERN')),
95 ]
95 ]
96
96
97 commitopts = [
97 commitopts = [
98 ('m', 'message', '',
98 ('m', 'message', '',
99 _('use text as commit message'), _('TEXT')),
99 _('use text as commit message'), _('TEXT')),
100 ('l', 'logfile', '',
100 ('l', 'logfile', '',
101 _('read commit message from file'), _('FILE')),
101 _('read commit message from file'), _('FILE')),
102 ]
102 ]
103
103
104 commitopts2 = [
104 commitopts2 = [
105 ('d', 'date', '',
105 ('d', 'date', '',
106 _('record the specified date as commit date'), _('DATE')),
106 _('record the specified date as commit date'), _('DATE')),
107 ('u', 'user', '',
107 ('u', 'user', '',
108 _('record the specified user as committer'), _('USER')),
108 _('record the specified user as committer'), _('USER')),
109 ]
109 ]
110
110
111 # hidden for now
111 # hidden for now
112 formatteropts = [
112 formatteropts = [
113 ('T', 'template', '',
113 ('T', 'template', '',
114 _('display with template (EXPERIMENTAL)'), _('TEMPLATE')),
114 _('display with template (EXPERIMENTAL)'), _('TEMPLATE')),
115 ]
115 ]
116
116
117 templateopts = [
117 templateopts = [
118 ('', 'style', '',
118 ('', 'style', '',
119 _('display using template map file (DEPRECATED)'), _('STYLE')),
119 _('display using template map file (DEPRECATED)'), _('STYLE')),
120 ('T', 'template', '',
120 ('T', 'template', '',
121 _('display with template'), _('TEMPLATE')),
121 _('display with template'), _('TEMPLATE')),
122 ]
122 ]
123
123
124 logopts = [
124 logopts = [
125 ('p', 'patch', None, _('show patch')),
125 ('p', 'patch', None, _('show patch')),
126 ('g', 'git', None, _('use git extended diff format')),
126 ('g', 'git', None, _('use git extended diff format')),
127 ('l', 'limit', '',
127 ('l', 'limit', '',
128 _('limit number of changes displayed'), _('NUM')),
128 _('limit number of changes displayed'), _('NUM')),
129 ('M', 'no-merges', None, _('do not show merges')),
129 ('M', 'no-merges', None, _('do not show merges')),
130 ('', 'stat', None, _('output diffstat-style summary of changes')),
130 ('', 'stat', None, _('output diffstat-style summary of changes')),
131 ('G', 'graph', None, _("show the revision DAG")),
131 ('G', 'graph', None, _("show the revision DAG")),
132 ] + templateopts
132 ] + templateopts
133
133
134 diffopts = [
134 diffopts = [
135 ('a', 'text', None, _('treat all files as text')),
135 ('a', 'text', None, _('treat all files as text')),
136 ('g', 'git', None, _('use git extended diff format')),
136 ('g', 'git', None, _('use git extended diff format')),
137 ('', 'nodates', None, _('omit dates from diff headers'))
137 ('', 'nodates', None, _('omit dates from diff headers'))
138 ]
138 ]
139
139
140 diffwsopts = [
140 diffwsopts = [
141 ('w', 'ignore-all-space', None,
141 ('w', 'ignore-all-space', None,
142 _('ignore white space when comparing lines')),
142 _('ignore white space when comparing lines')),
143 ('b', 'ignore-space-change', None,
143 ('b', 'ignore-space-change', None,
144 _('ignore changes in the amount of white space')),
144 _('ignore changes in the amount of white space')),
145 ('B', 'ignore-blank-lines', None,
145 ('B', 'ignore-blank-lines', None,
146 _('ignore changes whose lines are all blank')),
146 _('ignore changes whose lines are all blank')),
147 ]
147 ]
148
148
149 diffopts2 = [
149 diffopts2 = [
150 ('', 'noprefix', None, _('omit a/ and b/ prefixes from filenames')),
150 ('', 'noprefix', None, _('omit a/ and b/ prefixes from filenames')),
151 ('p', 'show-function', None, _('show which function each change is in')),
151 ('p', 'show-function', None, _('show which function each change is in')),
152 ('', 'reverse', None, _('produce a diff that undoes the changes')),
152 ('', 'reverse', None, _('produce a diff that undoes the changes')),
153 ] + diffwsopts + [
153 ] + diffwsopts + [
154 ('U', 'unified', '',
154 ('U', 'unified', '',
155 _('number of lines of context to show'), _('NUM')),
155 _('number of lines of context to show'), _('NUM')),
156 ('', 'stat', None, _('output diffstat-style summary of changes')),
156 ('', 'stat', None, _('output diffstat-style summary of changes')),
157 ('', 'root', '', _('produce diffs relative to subdirectory'), _('DIR')),
157 ('', 'root', '', _('produce diffs relative to subdirectory'), _('DIR')),
158 ]
158 ]
159
159
160 mergetoolopts = [
160 mergetoolopts = [
161 ('t', 'tool', '', _('specify merge tool')),
161 ('t', 'tool', '', _('specify merge tool')),
162 ]
162 ]
163
163
164 similarityopts = [
164 similarityopts = [
165 ('s', 'similarity', '',
165 ('s', 'similarity', '',
166 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
166 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
167 ]
167 ]
168
168
169 subrepoopts = [
169 subrepoopts = [
170 ('S', 'subrepos', None,
170 ('S', 'subrepos', None,
171 _('recurse into subrepositories'))
171 _('recurse into subrepositories'))
172 ]
172 ]
173
173
174 # Commands start here, listed alphabetically
174 # Commands start here, listed alphabetically
175
175
176 @command('^add',
176 @command('^add',
177 walkopts + subrepoopts + dryrunopts,
177 walkopts + subrepoopts + dryrunopts,
178 _('[OPTION]... [FILE]...'),
178 _('[OPTION]... [FILE]...'),
179 inferrepo=True)
179 inferrepo=True)
180 def add(ui, repo, *pats, **opts):
180 def add(ui, repo, *pats, **opts):
181 """add the specified files on the next commit
181 """add the specified files on the next commit
182
182
183 Schedule files to be version controlled and added to the
183 Schedule files to be version controlled and added to the
184 repository.
184 repository.
185
185
186 The files will be added to the repository at the next commit. To
186 The files will be added to the repository at the next commit. To
187 undo an add before that, see :hg:`forget`.
187 undo an add before that, see :hg:`forget`.
188
188
189 If no names are given, add all files to the repository.
189 If no names are given, add all files to the repository.
190
190
191 .. container:: verbose
191 .. container:: verbose
192
192
193 An example showing how new (unknown) files are added
193 An example showing how new (unknown) files are added
194 automatically by :hg:`add`::
194 automatically by :hg:`add`::
195
195
196 $ ls
196 $ ls
197 foo.c
197 foo.c
198 $ hg status
198 $ hg status
199 ? foo.c
199 ? foo.c
200 $ hg add
200 $ hg add
201 adding foo.c
201 adding foo.c
202 $ hg status
202 $ hg status
203 A foo.c
203 A foo.c
204
204
205 Returns 0 if all files are successfully added.
205 Returns 0 if all files are successfully added.
206 """
206 """
207
207
208 m = scmutil.match(repo[None], pats, opts)
208 m = scmutil.match(repo[None], pats, opts)
209 rejected = cmdutil.add(ui, repo, m, "", False, **opts)
209 rejected = cmdutil.add(ui, repo, m, "", False, **opts)
210 return rejected and 1 or 0
210 return rejected and 1 or 0
211
211
212 @command('addremove',
212 @command('addremove',
213 similarityopts + subrepoopts + walkopts + dryrunopts,
213 similarityopts + subrepoopts + walkopts + dryrunopts,
214 _('[OPTION]... [FILE]...'),
214 _('[OPTION]... [FILE]...'),
215 inferrepo=True)
215 inferrepo=True)
216 def addremove(ui, repo, *pats, **opts):
216 def addremove(ui, repo, *pats, **opts):
217 """add all new files, delete all missing files
217 """add all new files, delete all missing files
218
218
219 Add all new files and remove all missing files from the
219 Add all new files and remove all missing files from the
220 repository.
220 repository.
221
221
222 New files are ignored if they match any of the patterns in
222 New files are ignored if they match any of the patterns in
223 ``.hgignore``. As with add, these changes take effect at the next
223 ``.hgignore``. As with add, these changes take effect at the next
224 commit.
224 commit.
225
225
226 Use the -s/--similarity option to detect renamed files. This
226 Use the -s/--similarity option to detect renamed files. This
227 option takes a percentage between 0 (disabled) and 100 (files must
227 option takes a percentage between 0 (disabled) and 100 (files must
228 be identical) as its parameter. With a parameter greater than 0,
228 be identical) as its parameter. With a parameter greater than 0,
229 this compares every removed file with every added file and records
229 this compares every removed file with every added file and records
230 those similar enough as renames. Detecting renamed files this way
230 those similar enough as renames. Detecting renamed files this way
231 can be expensive. After using this option, :hg:`status -C` can be
231 can be expensive. After using this option, :hg:`status -C` can be
232 used to check which files were identified as moved or renamed. If
232 used to check which files were identified as moved or renamed. If
233 not specified, -s/--similarity defaults to 100 and only renames of
233 not specified, -s/--similarity defaults to 100 and only renames of
234 identical files are detected.
234 identical files are detected.
235
235
236 Returns 0 if all files are successfully added.
236 Returns 0 if all files are successfully added.
237 """
237 """
238 try:
238 try:
239 sim = float(opts.get('similarity') or 100)
239 sim = float(opts.get('similarity') or 100)
240 except ValueError:
240 except ValueError:
241 raise util.Abort(_('similarity must be a number'))
241 raise util.Abort(_('similarity must be a number'))
242 if sim < 0 or sim > 100:
242 if sim < 0 or sim > 100:
243 raise util.Abort(_('similarity must be between 0 and 100'))
243 raise util.Abort(_('similarity must be between 0 and 100'))
244 matcher = scmutil.match(repo[None], pats, opts)
244 matcher = scmutil.match(repo[None], pats, opts)
245 return scmutil.addremove(repo, matcher, "", opts, similarity=sim / 100.0)
245 return scmutil.addremove(repo, matcher, "", opts, similarity=sim / 100.0)
246
246
247 @command('^annotate|blame',
247 @command('^annotate|blame',
248 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
248 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
249 ('', 'follow', None,
249 ('', 'follow', None,
250 _('follow copies/renames and list the filename (DEPRECATED)')),
250 _('follow copies/renames and list the filename (DEPRECATED)')),
251 ('', 'no-follow', None, _("don't follow copies and renames")),
251 ('', 'no-follow', None, _("don't follow copies and renames")),
252 ('a', 'text', None, _('treat all files as text')),
252 ('a', 'text', None, _('treat all files as text')),
253 ('u', 'user', None, _('list the author (long with -v)')),
253 ('u', 'user', None, _('list the author (long with -v)')),
254 ('f', 'file', None, _('list the filename')),
254 ('f', 'file', None, _('list the filename')),
255 ('d', 'date', None, _('list the date (short with -q)')),
255 ('d', 'date', None, _('list the date (short with -q)')),
256 ('n', 'number', None, _('list the revision number (default)')),
256 ('n', 'number', None, _('list the revision number (default)')),
257 ('c', 'changeset', None, _('list the changeset')),
257 ('c', 'changeset', None, _('list the changeset')),
258 ('l', 'line-number', None, _('show line number at the first appearance'))
258 ('l', 'line-number', None, _('show line number at the first appearance'))
259 ] + diffwsopts + walkopts + formatteropts,
259 ] + diffwsopts + walkopts + formatteropts,
260 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'),
260 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'),
261 inferrepo=True)
261 inferrepo=True)
262 def annotate(ui, repo, *pats, **opts):
262 def annotate(ui, repo, *pats, **opts):
263 """show changeset information by line for each file
263 """show changeset information by line for each file
264
264
265 List changes in files, showing the revision id responsible for
265 List changes in files, showing the revision id responsible for
266 each line
266 each line
267
267
268 This command is useful for discovering when a change was made and
268 This command is useful for discovering when a change was made and
269 by whom.
269 by whom.
270
270
271 Without the -a/--text option, annotate will avoid processing files
271 Without the -a/--text option, annotate will avoid processing files
272 it detects as binary. With -a, annotate will annotate the file
272 it detects as binary. With -a, annotate will annotate the file
273 anyway, although the results will probably be neither useful
273 anyway, although the results will probably be neither useful
274 nor desirable.
274 nor desirable.
275
275
276 Returns 0 on success.
276 Returns 0 on success.
277 """
277 """
278 if not pats:
278 if not pats:
279 raise util.Abort(_('at least one filename or pattern is required'))
279 raise util.Abort(_('at least one filename or pattern is required'))
280
280
281 if opts.get('follow'):
281 if opts.get('follow'):
282 # --follow is deprecated and now just an alias for -f/--file
282 # --follow is deprecated and now just an alias for -f/--file
283 # to mimic the behavior of Mercurial before version 1.5
283 # to mimic the behavior of Mercurial before version 1.5
284 opts['file'] = True
284 opts['file'] = True
285
285
286 ctx = scmutil.revsingle(repo, opts.get('rev'))
286 ctx = scmutil.revsingle(repo, opts.get('rev'))
287
287
288 fm = ui.formatter('annotate', opts)
288 fm = ui.formatter('annotate', opts)
289 if ui.quiet:
289 if ui.quiet:
290 datefunc = util.shortdate
290 datefunc = util.shortdate
291 else:
291 else:
292 datefunc = util.datestr
292 datefunc = util.datestr
293 if ctx.rev() is None:
293 if ctx.rev() is None:
294 def hexfn(node):
294 def hexfn(node):
295 if node is None:
295 if node is None:
296 return None
296 return None
297 else:
297 else:
298 return fm.hexfunc(node)
298 return fm.hexfunc(node)
299 if opts.get('changeset'):
299 if opts.get('changeset'):
300 # omit "+" suffix which is appended to node hex
300 # omit "+" suffix which is appended to node hex
301 def formatrev(rev):
301 def formatrev(rev):
302 if rev is None:
302 if rev is None:
303 return '%d' % ctx.p1().rev()
303 return '%d' % ctx.p1().rev()
304 else:
304 else:
305 return '%d' % rev
305 return '%d' % rev
306 else:
306 else:
307 def formatrev(rev):
307 def formatrev(rev):
308 if rev is None:
308 if rev is None:
309 return '%d+' % ctx.p1().rev()
309 return '%d+' % ctx.p1().rev()
310 else:
310 else:
311 return '%d ' % rev
311 return '%d ' % rev
312 def formathex(hex):
312 def formathex(hex):
313 if hex is None:
313 if hex is None:
314 return '%s+' % fm.hexfunc(ctx.p1().node())
314 return '%s+' % fm.hexfunc(ctx.p1().node())
315 else:
315 else:
316 return '%s ' % hex
316 return '%s ' % hex
317 else:
317 else:
318 hexfn = fm.hexfunc
318 hexfn = fm.hexfunc
319 formatrev = formathex = str
319 formatrev = formathex = str
320
320
321 opmap = [('user', ' ', lambda x: x[0].user(), ui.shortuser),
321 opmap = [('user', ' ', lambda x: x[0].user(), ui.shortuser),
322 ('number', ' ', lambda x: x[0].rev(), formatrev),
322 ('number', ' ', lambda x: x[0].rev(), formatrev),
323 ('changeset', ' ', lambda x: hexfn(x[0].node()), formathex),
323 ('changeset', ' ', lambda x: hexfn(x[0].node()), formathex),
324 ('date', ' ', lambda x: x[0].date(), util.cachefunc(datefunc)),
324 ('date', ' ', lambda x: x[0].date(), util.cachefunc(datefunc)),
325 ('file', ' ', lambda x: x[0].path(), str),
325 ('file', ' ', lambda x: x[0].path(), str),
326 ('line_number', ':', lambda x: x[1], str),
326 ('line_number', ':', lambda x: x[1], str),
327 ]
327 ]
328 fieldnamemap = {'number': 'rev', 'changeset': 'node'}
328 fieldnamemap = {'number': 'rev', 'changeset': 'node'}
329
329
330 if (not opts.get('user') and not opts.get('changeset')
330 if (not opts.get('user') and not opts.get('changeset')
331 and not opts.get('date') and not opts.get('file')):
331 and not opts.get('date') and not opts.get('file')):
332 opts['number'] = True
332 opts['number'] = True
333
333
334 linenumber = opts.get('line_number') is not None
334 linenumber = opts.get('line_number') is not None
335 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
335 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
336 raise util.Abort(_('at least one of -n/-c is required for -l'))
336 raise util.Abort(_('at least one of -n/-c is required for -l'))
337
337
338 if fm:
338 if fm:
339 def makefunc(get, fmt):
339 def makefunc(get, fmt):
340 return get
340 return get
341 else:
341 else:
342 def makefunc(get, fmt):
342 def makefunc(get, fmt):
343 return lambda x: fmt(get(x))
343 return lambda x: fmt(get(x))
344 funcmap = [(makefunc(get, fmt), sep) for op, sep, get, fmt in opmap
344 funcmap = [(makefunc(get, fmt), sep) for op, sep, get, fmt in opmap
345 if opts.get(op)]
345 if opts.get(op)]
346 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
346 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
347 fields = ' '.join(fieldnamemap.get(op, op) for op, sep, get, fmt in opmap
347 fields = ' '.join(fieldnamemap.get(op, op) for op, sep, get, fmt in opmap
348 if opts.get(op))
348 if opts.get(op))
349
349
350 def bad(x, y):
350 def bad(x, y):
351 raise util.Abort("%s: %s" % (x, y))
351 raise util.Abort("%s: %s" % (x, y))
352
352
353 m = scmutil.match(ctx, pats, opts, badfn=bad)
353 m = scmutil.match(ctx, pats, opts, badfn=bad)
354
354
355 follow = not opts.get('no_follow')
355 follow = not opts.get('no_follow')
356 diffopts = patch.difffeatureopts(ui, opts, section='annotate',
356 diffopts = patch.difffeatureopts(ui, opts, section='annotate',
357 whitespace=True)
357 whitespace=True)
358 for abs in ctx.walk(m):
358 for abs in ctx.walk(m):
359 fctx = ctx[abs]
359 fctx = ctx[abs]
360 if not opts.get('text') and util.binary(fctx.data()):
360 if not opts.get('text') and util.binary(fctx.data()):
361 fm.plain(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
361 fm.plain(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
362 continue
362 continue
363
363
364 lines = fctx.annotate(follow=follow, linenumber=linenumber,
364 lines = fctx.annotate(follow=follow, linenumber=linenumber,
365 diffopts=diffopts)
365 diffopts=diffopts)
366 formats = []
366 formats = []
367 pieces = []
367 pieces = []
368
368
369 for f, sep in funcmap:
369 for f, sep in funcmap:
370 l = [f(n) for n, dummy in lines]
370 l = [f(n) for n, dummy in lines]
371 if l:
371 if l:
372 if fm:
372 if fm:
373 formats.append(['%s' for x in l])
373 formats.append(['%s' for x in l])
374 else:
374 else:
375 sizes = [encoding.colwidth(x) for x in l]
375 sizes = [encoding.colwidth(x) for x in l]
376 ml = max(sizes)
376 ml = max(sizes)
377 formats.append([sep + ' ' * (ml - w) + '%s' for w in sizes])
377 formats.append([sep + ' ' * (ml - w) + '%s' for w in sizes])
378 pieces.append(l)
378 pieces.append(l)
379
379
380 for f, p, l in zip(zip(*formats), zip(*pieces), lines):
380 for f, p, l in zip(zip(*formats), zip(*pieces), lines):
381 fm.startitem()
381 fm.startitem()
382 fm.write(fields, "".join(f), *p)
382 fm.write(fields, "".join(f), *p)
383 fm.write('line', ": %s", l[1])
383 fm.write('line', ": %s", l[1])
384
384
385 if lines and not lines[-1][1].endswith('\n'):
385 if lines and not lines[-1][1].endswith('\n'):
386 fm.plain('\n')
386 fm.plain('\n')
387
387
388 fm.end()
388 fm.end()
389
389
390 @command('archive',
390 @command('archive',
391 [('', 'no-decode', None, _('do not pass files through decoders')),
391 [('', 'no-decode', None, _('do not pass files through decoders')),
392 ('p', 'prefix', '', _('directory prefix for files in archive'),
392 ('p', 'prefix', '', _('directory prefix for files in archive'),
393 _('PREFIX')),
393 _('PREFIX')),
394 ('r', 'rev', '', _('revision to distribute'), _('REV')),
394 ('r', 'rev', '', _('revision to distribute'), _('REV')),
395 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
395 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
396 ] + subrepoopts + walkopts,
396 ] + subrepoopts + walkopts,
397 _('[OPTION]... DEST'))
397 _('[OPTION]... DEST'))
398 def archive(ui, repo, dest, **opts):
398 def archive(ui, repo, dest, **opts):
399 '''create an unversioned archive of a repository revision
399 '''create an unversioned archive of a repository revision
400
400
401 By default, the revision used is the parent of the working
401 By default, the revision used is the parent of the working
402 directory; use -r/--rev to specify a different revision.
402 directory; use -r/--rev to specify a different revision.
403
403
404 The archive type is automatically detected based on file
404 The archive type is automatically detected based on file
405 extension (or override using -t/--type).
405 extension (or override using -t/--type).
406
406
407 .. container:: verbose
407 .. container:: verbose
408
408
409 Examples:
409 Examples:
410
410
411 - create a zip file containing the 1.0 release::
411 - create a zip file containing the 1.0 release::
412
412
413 hg archive -r 1.0 project-1.0.zip
413 hg archive -r 1.0 project-1.0.zip
414
414
415 - create a tarball excluding .hg files::
415 - create a tarball excluding .hg files::
416
416
417 hg archive project.tar.gz -X ".hg*"
417 hg archive project.tar.gz -X ".hg*"
418
418
419 Valid types are:
419 Valid types are:
420
420
421 :``files``: a directory full of files (default)
421 :``files``: a directory full of files (default)
422 :``tar``: tar archive, uncompressed
422 :``tar``: tar archive, uncompressed
423 :``tbz2``: tar archive, compressed using bzip2
423 :``tbz2``: tar archive, compressed using bzip2
424 :``tgz``: tar archive, compressed using gzip
424 :``tgz``: tar archive, compressed using gzip
425 :``uzip``: zip archive, uncompressed
425 :``uzip``: zip archive, uncompressed
426 :``zip``: zip archive, compressed using deflate
426 :``zip``: zip archive, compressed using deflate
427
427
428 The exact name of the destination archive or directory is given
428 The exact name of the destination archive or directory is given
429 using a format string; see :hg:`help export` for details.
429 using a format string; see :hg:`help export` for details.
430
430
431 Each member added to an archive file has a directory prefix
431 Each member added to an archive file has a directory prefix
432 prepended. Use -p/--prefix to specify a format string for the
432 prepended. Use -p/--prefix to specify a format string for the
433 prefix. The default is the basename of the archive, with suffixes
433 prefix. The default is the basename of the archive, with suffixes
434 removed.
434 removed.
435
435
436 Returns 0 on success.
436 Returns 0 on success.
437 '''
437 '''
438
438
439 ctx = scmutil.revsingle(repo, opts.get('rev'))
439 ctx = scmutil.revsingle(repo, opts.get('rev'))
440 if not ctx:
440 if not ctx:
441 raise util.Abort(_('no working directory: please specify a revision'))
441 raise util.Abort(_('no working directory: please specify a revision'))
442 node = ctx.node()
442 node = ctx.node()
443 dest = cmdutil.makefilename(repo, dest, node)
443 dest = cmdutil.makefilename(repo, dest, node)
444 if os.path.realpath(dest) == repo.root:
444 if os.path.realpath(dest) == repo.root:
445 raise util.Abort(_('repository root cannot be destination'))
445 raise util.Abort(_('repository root cannot be destination'))
446
446
447 kind = opts.get('type') or archival.guesskind(dest) or 'files'
447 kind = opts.get('type') or archival.guesskind(dest) or 'files'
448 prefix = opts.get('prefix')
448 prefix = opts.get('prefix')
449
449
450 if dest == '-':
450 if dest == '-':
451 if kind == 'files':
451 if kind == 'files':
452 raise util.Abort(_('cannot archive plain files to stdout'))
452 raise util.Abort(_('cannot archive plain files to stdout'))
453 dest = cmdutil.makefileobj(repo, dest)
453 dest = cmdutil.makefileobj(repo, dest)
454 if not prefix:
454 if not prefix:
455 prefix = os.path.basename(repo.root) + '-%h'
455 prefix = os.path.basename(repo.root) + '-%h'
456
456
457 prefix = cmdutil.makefilename(repo, prefix, node)
457 prefix = cmdutil.makefilename(repo, prefix, node)
458 matchfn = scmutil.match(ctx, [], opts)
458 matchfn = scmutil.match(ctx, [], opts)
459 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
459 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
460 matchfn, prefix, subrepos=opts.get('subrepos'))
460 matchfn, prefix, subrepos=opts.get('subrepos'))
461
461
462 @command('backout',
462 @command('backout',
463 [('', 'merge', None, _('merge with old dirstate parent after backout')),
463 [('', 'merge', None, _('merge with old dirstate parent after backout')),
464 ('', 'commit', None, _('commit if no conflicts were encountered')),
464 ('', 'commit', None, _('commit if no conflicts were encountered')),
465 ('', 'parent', '',
465 ('', 'parent', '',
466 _('parent to choose when backing out merge (DEPRECATED)'), _('REV')),
466 _('parent to choose when backing out merge (DEPRECATED)'), _('REV')),
467 ('r', 'rev', '', _('revision to backout'), _('REV')),
467 ('r', 'rev', '', _('revision to backout'), _('REV')),
468 ('e', 'edit', False, _('invoke editor on commit messages')),
468 ('e', 'edit', False, _('invoke editor on commit messages')),
469 ] + mergetoolopts + walkopts + commitopts + commitopts2,
469 ] + mergetoolopts + walkopts + commitopts + commitopts2,
470 _('[OPTION]... [-r] REV'))
470 _('[OPTION]... [-r] REV'))
471 def backout(ui, repo, node=None, rev=None, commit=False, **opts):
471 def backout(ui, repo, node=None, rev=None, commit=False, **opts):
472 '''reverse effect of earlier changeset
472 '''reverse effect of earlier changeset
473
473
474 Prepare a new changeset with the effect of REV undone in the
474 Prepare a new changeset with the effect of REV undone in the
475 current working directory.
475 current working directory.
476
476
477 If REV is the parent of the working directory, then this new changeset
477 If REV is the parent of the working directory, then this new changeset
478 is committed automatically. Otherwise, hg needs to merge the
478 is committed automatically. Otherwise, hg needs to merge the
479 changes and the merged result is left uncommitted.
479 changes and the merged result is left uncommitted.
480
480
481 .. note::
481 .. note::
482
482
483 backout cannot be used to fix either an unwanted or
483 backout cannot be used to fix either an unwanted or
484 incorrect merge.
484 incorrect merge.
485
485
486 .. container:: verbose
486 .. container:: verbose
487
487
488 By default, the pending changeset will have one parent,
488 By default, the pending changeset will have one parent,
489 maintaining a linear history. With --merge, the pending
489 maintaining a linear history. With --merge, the pending
490 changeset will instead have two parents: the old parent of the
490 changeset will instead have two parents: the old parent of the
491 working directory and a new child of REV that simply undoes REV.
491 working directory and a new child of REV that simply undoes REV.
492
492
493 Before version 1.7, the behavior without --merge was equivalent
493 Before version 1.7, the behavior without --merge was equivalent
494 to specifying --merge followed by :hg:`update --clean .` to
494 to specifying --merge followed by :hg:`update --clean .` to
495 cancel the merge and leave the child of REV as a head to be
495 cancel the merge and leave the child of REV as a head to be
496 merged separately.
496 merged separately.
497
497
498 See :hg:`help dates` for a list of formats valid for -d/--date.
498 See :hg:`help dates` for a list of formats valid for -d/--date.
499
499
500 See :hg:`help revert` for a way to restore files to the state
500 See :hg:`help revert` for a way to restore files to the state
501 of another revision.
501 of another revision.
502
502
503 Returns 0 on success, 1 if nothing to backout or there are unresolved
503 Returns 0 on success, 1 if nothing to backout or there are unresolved
504 files.
504 files.
505 '''
505 '''
506 if rev and node:
506 if rev and node:
507 raise util.Abort(_("please specify just one revision"))
507 raise util.Abort(_("please specify just one revision"))
508
508
509 if not rev:
509 if not rev:
510 rev = node
510 rev = node
511
511
512 if not rev:
512 if not rev:
513 raise util.Abort(_("please specify a revision to backout"))
513 raise util.Abort(_("please specify a revision to backout"))
514
514
515 date = opts.get('date')
515 date = opts.get('date')
516 if date:
516 if date:
517 opts['date'] = util.parsedate(date)
517 opts['date'] = util.parsedate(date)
518
518
519 cmdutil.checkunfinished(repo)
519 cmdutil.checkunfinished(repo)
520 cmdutil.bailifchanged(repo)
520 cmdutil.bailifchanged(repo)
521 node = scmutil.revsingle(repo, rev).node()
521 node = scmutil.revsingle(repo, rev).node()
522
522
523 op1, op2 = repo.dirstate.parents()
523 op1, op2 = repo.dirstate.parents()
524 if not repo.changelog.isancestor(node, op1):
524 if not repo.changelog.isancestor(node, op1):
525 raise util.Abort(_('cannot backout change that is not an ancestor'))
525 raise util.Abort(_('cannot backout change that is not an ancestor'))
526
526
527 p1, p2 = repo.changelog.parents(node)
527 p1, p2 = repo.changelog.parents(node)
528 if p1 == nullid:
528 if p1 == nullid:
529 raise util.Abort(_('cannot backout a change with no parents'))
529 raise util.Abort(_('cannot backout a change with no parents'))
530 if p2 != nullid:
530 if p2 != nullid:
531 if not opts.get('parent'):
531 if not opts.get('parent'):
532 raise util.Abort(_('cannot backout a merge changeset'))
532 raise util.Abort(_('cannot backout a merge changeset'))
533 p = repo.lookup(opts['parent'])
533 p = repo.lookup(opts['parent'])
534 if p not in (p1, p2):
534 if p not in (p1, p2):
535 raise util.Abort(_('%s is not a parent of %s') %
535 raise util.Abort(_('%s is not a parent of %s') %
536 (short(p), short(node)))
536 (short(p), short(node)))
537 parent = p
537 parent = p
538 else:
538 else:
539 if opts.get('parent'):
539 if opts.get('parent'):
540 raise util.Abort(_('cannot use --parent on non-merge changeset'))
540 raise util.Abort(_('cannot use --parent on non-merge changeset'))
541 parent = p1
541 parent = p1
542
542
543 # the backout should appear on the same branch
543 # the backout should appear on the same branch
544 wlock = repo.wlock()
544 wlock = repo.wlock()
545 try:
545 try:
546 branch = repo.dirstate.branch()
546 branch = repo.dirstate.branch()
547 bheads = repo.branchheads(branch)
547 bheads = repo.branchheads(branch)
548 rctx = scmutil.revsingle(repo, hex(parent))
548 rctx = scmutil.revsingle(repo, hex(parent))
549 if not opts.get('merge') and op1 != node:
549 if not opts.get('merge') and op1 != node:
550 try:
550 try:
551 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
551 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
552 'backout')
552 'backout')
553 repo.dirstate.beginparentchange()
553 repo.dirstate.beginparentchange()
554 stats = mergemod.update(repo, parent, True, True, False,
554 stats = mergemod.update(repo, parent, True, True, False,
555 node, False)
555 node, False)
556 repo.setparents(op1, op2)
556 repo.setparents(op1, op2)
557 repo.dirstate.endparentchange()
557 repo.dirstate.endparentchange()
558 hg._showstats(repo, stats)
558 hg._showstats(repo, stats)
559 if stats[3]:
559 if stats[3]:
560 repo.ui.status(_("use 'hg resolve' to retry unresolved "
560 repo.ui.status(_("use 'hg resolve' to retry unresolved "
561 "file merges\n"))
561 "file merges\n"))
562 return 1
562 return 1
563 elif not commit:
563 elif not commit:
564 msg = _("changeset %s backed out, "
564 msg = _("changeset %s backed out, "
565 "don't forget to commit.\n")
565 "don't forget to commit.\n")
566 ui.status(msg % short(node))
566 ui.status(msg % short(node))
567 return 0
567 return 0
568 finally:
568 finally:
569 ui.setconfig('ui', 'forcemerge', '', '')
569 ui.setconfig('ui', 'forcemerge', '', '')
570 else:
570 else:
571 hg.clean(repo, node, show_stats=False)
571 hg.clean(repo, node, show_stats=False)
572 repo.dirstate.setbranch(branch)
572 repo.dirstate.setbranch(branch)
573 cmdutil.revert(ui, repo, rctx, repo.dirstate.parents())
573 cmdutil.revert(ui, repo, rctx, repo.dirstate.parents())
574
574
575
575
576 def commitfunc(ui, repo, message, match, opts):
576 def commitfunc(ui, repo, message, match, opts):
577 editform = 'backout'
577 editform = 'backout'
578 e = cmdutil.getcommiteditor(editform=editform, **opts)
578 e = cmdutil.getcommiteditor(editform=editform, **opts)
579 if not message:
579 if not message:
580 # we don't translate commit messages
580 # we don't translate commit messages
581 message = "Backed out changeset %s" % short(node)
581 message = "Backed out changeset %s" % short(node)
582 e = cmdutil.getcommiteditor(edit=True, editform=editform)
582 e = cmdutil.getcommiteditor(edit=True, editform=editform)
583 return repo.commit(message, opts.get('user'), opts.get('date'),
583 return repo.commit(message, opts.get('user'), opts.get('date'),
584 match, editor=e)
584 match, editor=e)
585 newnode = cmdutil.commit(ui, repo, commitfunc, [], opts)
585 newnode = cmdutil.commit(ui, repo, commitfunc, [], opts)
586 if not newnode:
586 if not newnode:
587 ui.status(_("nothing changed\n"))
587 ui.status(_("nothing changed\n"))
588 return 1
588 return 1
589 cmdutil.commitstatus(repo, newnode, branch, bheads)
589 cmdutil.commitstatus(repo, newnode, branch, bheads)
590
590
591 def nice(node):
591 def nice(node):
592 return '%d:%s' % (repo.changelog.rev(node), short(node))
592 return '%d:%s' % (repo.changelog.rev(node), short(node))
593 ui.status(_('changeset %s backs out changeset %s\n') %
593 ui.status(_('changeset %s backs out changeset %s\n') %
594 (nice(repo.changelog.tip()), nice(node)))
594 (nice(repo.changelog.tip()), nice(node)))
595 if opts.get('merge') and op1 != node:
595 if opts.get('merge') and op1 != node:
596 hg.clean(repo, op1, show_stats=False)
596 hg.clean(repo, op1, show_stats=False)
597 ui.status(_('merging with changeset %s\n')
597 ui.status(_('merging with changeset %s\n')
598 % nice(repo.changelog.tip()))
598 % nice(repo.changelog.tip()))
599 try:
599 try:
600 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
600 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
601 'backout')
601 'backout')
602 return hg.merge(repo, hex(repo.changelog.tip()))
602 return hg.merge(repo, hex(repo.changelog.tip()))
603 finally:
603 finally:
604 ui.setconfig('ui', 'forcemerge', '', '')
604 ui.setconfig('ui', 'forcemerge', '', '')
605 finally:
605 finally:
606 wlock.release()
606 wlock.release()
607 return 0
607 return 0
608
608
609 @command('bisect',
609 @command('bisect',
610 [('r', 'reset', False, _('reset bisect state')),
610 [('r', 'reset', False, _('reset bisect state')),
611 ('g', 'good', False, _('mark changeset good')),
611 ('g', 'good', False, _('mark changeset good')),
612 ('b', 'bad', False, _('mark changeset bad')),
612 ('b', 'bad', False, _('mark changeset bad')),
613 ('s', 'skip', False, _('skip testing changeset')),
613 ('s', 'skip', False, _('skip testing changeset')),
614 ('e', 'extend', False, _('extend the bisect range')),
614 ('e', 'extend', False, _('extend the bisect range')),
615 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
615 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
616 ('U', 'noupdate', False, _('do not update to target'))],
616 ('U', 'noupdate', False, _('do not update to target'))],
617 _("[-gbsr] [-U] [-c CMD] [REV]"))
617 _("[-gbsr] [-U] [-c CMD] [REV]"))
618 def bisect(ui, repo, rev=None, extra=None, command=None,
618 def bisect(ui, repo, rev=None, extra=None, command=None,
619 reset=None, good=None, bad=None, skip=None, extend=None,
619 reset=None, good=None, bad=None, skip=None, extend=None,
620 noupdate=None):
620 noupdate=None):
621 """subdivision search of changesets
621 """subdivision search of changesets
622
622
623 This command helps to find changesets which introduce problems. To
623 This command helps to find changesets which introduce problems. To
624 use, mark the earliest changeset you know exhibits the problem as
624 use, mark the earliest changeset you know exhibits the problem as
625 bad, then mark the latest changeset which is free from the problem
625 bad, then mark the latest changeset which is free from the problem
626 as good. Bisect will update your working directory to a revision
626 as good. Bisect will update your working directory to a revision
627 for testing (unless the -U/--noupdate option is specified). Once
627 for testing (unless the -U/--noupdate option is specified). Once
628 you have performed tests, mark the working directory as good or
628 you have performed tests, mark the working directory as good or
629 bad, and bisect will either update to another candidate changeset
629 bad, and bisect will either update to another candidate changeset
630 or announce that it has found the bad revision.
630 or announce that it has found the bad revision.
631
631
632 As a shortcut, you can also use the revision argument to mark a
632 As a shortcut, you can also use the revision argument to mark a
633 revision as good or bad without checking it out first.
633 revision as good or bad without checking it out first.
634
634
635 If you supply a command, it will be used for automatic bisection.
635 If you supply a command, it will be used for automatic bisection.
636 The environment variable HG_NODE will contain the ID of the
636 The environment variable HG_NODE will contain the ID of the
637 changeset being tested. The exit status of the command will be
637 changeset being tested. The exit status of the command will be
638 used to mark revisions as good or bad: status 0 means good, 125
638 used to mark revisions as good or bad: status 0 means good, 125
639 means to skip the revision, 127 (command not found) will abort the
639 means to skip the revision, 127 (command not found) will abort the
640 bisection, and any other non-zero exit status means the revision
640 bisection, and any other non-zero exit status means the revision
641 is bad.
641 is bad.
642
642
643 .. container:: verbose
643 .. container:: verbose
644
644
645 Some examples:
645 Some examples:
646
646
647 - start a bisection with known bad revision 34, and good revision 12::
647 - start a bisection with known bad revision 34, and good revision 12::
648
648
649 hg bisect --bad 34
649 hg bisect --bad 34
650 hg bisect --good 12
650 hg bisect --good 12
651
651
652 - advance the current bisection by marking current revision as good or
652 - advance the current bisection by marking current revision as good or
653 bad::
653 bad::
654
654
655 hg bisect --good
655 hg bisect --good
656 hg bisect --bad
656 hg bisect --bad
657
657
658 - mark the current revision, or a known revision, to be skipped (e.g. if
658 - mark the current revision, or a known revision, to be skipped (e.g. if
659 that revision is not usable because of another issue)::
659 that revision is not usable because of another issue)::
660
660
661 hg bisect --skip
661 hg bisect --skip
662 hg bisect --skip 23
662 hg bisect --skip 23
663
663
664 - skip all revisions that do not touch directories ``foo`` or ``bar``::
664 - skip all revisions that do not touch directories ``foo`` or ``bar``::
665
665
666 hg bisect --skip "!( file('path:foo') & file('path:bar') )"
666 hg bisect --skip "!( file('path:foo') & file('path:bar') )"
667
667
668 - forget the current bisection::
668 - forget the current bisection::
669
669
670 hg bisect --reset
670 hg bisect --reset
671
671
672 - use 'make && make tests' to automatically find the first broken
672 - use 'make && make tests' to automatically find the first broken
673 revision::
673 revision::
674
674
675 hg bisect --reset
675 hg bisect --reset
676 hg bisect --bad 34
676 hg bisect --bad 34
677 hg bisect --good 12
677 hg bisect --good 12
678 hg bisect --command "make && make tests"
678 hg bisect --command "make && make tests"
679
679
680 - see all changesets whose states are already known in the current
680 - see all changesets whose states are already known in the current
681 bisection::
681 bisection::
682
682
683 hg log -r "bisect(pruned)"
683 hg log -r "bisect(pruned)"
684
684
685 - see the changeset currently being bisected (especially useful
685 - see the changeset currently being bisected (especially useful
686 if running with -U/--noupdate)::
686 if running with -U/--noupdate)::
687
687
688 hg log -r "bisect(current)"
688 hg log -r "bisect(current)"
689
689
690 - see all changesets that took part in the current bisection::
690 - see all changesets that took part in the current bisection::
691
691
692 hg log -r "bisect(range)"
692 hg log -r "bisect(range)"
693
693
694 - you can even get a nice graph::
694 - you can even get a nice graph::
695
695
696 hg log --graph -r "bisect(range)"
696 hg log --graph -r "bisect(range)"
697
697
698 See :hg:`help revsets` for more about the `bisect()` keyword.
698 See :hg:`help revsets` for more about the `bisect()` keyword.
699
699
700 Returns 0 on success.
700 Returns 0 on success.
701 """
701 """
702 def extendbisectrange(nodes, good):
702 def extendbisectrange(nodes, good):
703 # bisect is incomplete when it ends on a merge node and
703 # bisect is incomplete when it ends on a merge node and
704 # one of the parent was not checked.
704 # one of the parent was not checked.
705 parents = repo[nodes[0]].parents()
705 parents = repo[nodes[0]].parents()
706 if len(parents) > 1:
706 if len(parents) > 1:
707 if good:
707 if good:
708 side = state['bad']
708 side = state['bad']
709 else:
709 else:
710 side = state['good']
710 side = state['good']
711 num = len(set(i.node() for i in parents) & set(side))
711 num = len(set(i.node() for i in parents) & set(side))
712 if num == 1:
712 if num == 1:
713 return parents[0].ancestor(parents[1])
713 return parents[0].ancestor(parents[1])
714 return None
714 return None
715
715
716 def print_result(nodes, good):
716 def print_result(nodes, good):
717 displayer = cmdutil.show_changeset(ui, repo, {})
717 displayer = cmdutil.show_changeset(ui, repo, {})
718 if len(nodes) == 1:
718 if len(nodes) == 1:
719 # narrowed it down to a single revision
719 # narrowed it down to a single revision
720 if good:
720 if good:
721 ui.write(_("The first good revision is:\n"))
721 ui.write(_("The first good revision is:\n"))
722 else:
722 else:
723 ui.write(_("The first bad revision is:\n"))
723 ui.write(_("The first bad revision is:\n"))
724 displayer.show(repo[nodes[0]])
724 displayer.show(repo[nodes[0]])
725 extendnode = extendbisectrange(nodes, good)
725 extendnode = extendbisectrange(nodes, good)
726 if extendnode is not None:
726 if extendnode is not None:
727 ui.write(_('Not all ancestors of this changeset have been'
727 ui.write(_('Not all ancestors of this changeset have been'
728 ' checked.\nUse bisect --extend to continue the '
728 ' checked.\nUse bisect --extend to continue the '
729 'bisection from\nthe common ancestor, %s.\n')
729 'bisection from\nthe common ancestor, %s.\n')
730 % extendnode)
730 % extendnode)
731 else:
731 else:
732 # multiple possible revisions
732 # multiple possible revisions
733 if good:
733 if good:
734 ui.write(_("Due to skipped revisions, the first "
734 ui.write(_("Due to skipped revisions, the first "
735 "good revision could be any of:\n"))
735 "good revision could be any of:\n"))
736 else:
736 else:
737 ui.write(_("Due to skipped revisions, the first "
737 ui.write(_("Due to skipped revisions, the first "
738 "bad revision could be any of:\n"))
738 "bad revision could be any of:\n"))
739 for n in nodes:
739 for n in nodes:
740 displayer.show(repo[n])
740 displayer.show(repo[n])
741 displayer.close()
741 displayer.close()
742
742
743 def check_state(state, interactive=True):
743 def check_state(state, interactive=True):
744 if not state['good'] or not state['bad']:
744 if not state['good'] or not state['bad']:
745 if (good or bad or skip or reset) and interactive:
745 if (good or bad or skip or reset) and interactive:
746 return
746 return
747 if not state['good']:
747 if not state['good']:
748 raise util.Abort(_('cannot bisect (no known good revisions)'))
748 raise util.Abort(_('cannot bisect (no known good revisions)'))
749 else:
749 else:
750 raise util.Abort(_('cannot bisect (no known bad revisions)'))
750 raise util.Abort(_('cannot bisect (no known bad revisions)'))
751 return True
751 return True
752
752
753 # backward compatibility
753 # backward compatibility
754 if rev in "good bad reset init".split():
754 if rev in "good bad reset init".split():
755 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
755 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
756 cmd, rev, extra = rev, extra, None
756 cmd, rev, extra = rev, extra, None
757 if cmd == "good":
757 if cmd == "good":
758 good = True
758 good = True
759 elif cmd == "bad":
759 elif cmd == "bad":
760 bad = True
760 bad = True
761 else:
761 else:
762 reset = True
762 reset = True
763 elif extra or good + bad + skip + reset + extend + bool(command) > 1:
763 elif extra or good + bad + skip + reset + extend + bool(command) > 1:
764 raise util.Abort(_('incompatible arguments'))
764 raise util.Abort(_('incompatible arguments'))
765
765
766 cmdutil.checkunfinished(repo)
766 cmdutil.checkunfinished(repo)
767
767
768 if reset:
768 if reset:
769 p = repo.join("bisect.state")
769 p = repo.join("bisect.state")
770 if os.path.exists(p):
770 if os.path.exists(p):
771 os.unlink(p)
771 os.unlink(p)
772 return
772 return
773
773
774 state = hbisect.load_state(repo)
774 state = hbisect.load_state(repo)
775
775
776 if command:
776 if command:
777 changesets = 1
777 changesets = 1
778 if noupdate:
778 if noupdate:
779 try:
779 try:
780 node = state['current'][0]
780 node = state['current'][0]
781 except LookupError:
781 except LookupError:
782 raise util.Abort(_('current bisect revision is unknown - '
782 raise util.Abort(_('current bisect revision is unknown - '
783 'start a new bisect to fix'))
783 'start a new bisect to fix'))
784 else:
784 else:
785 node, p2 = repo.dirstate.parents()
785 node, p2 = repo.dirstate.parents()
786 if p2 != nullid:
786 if p2 != nullid:
787 raise util.Abort(_('current bisect revision is a merge'))
787 raise util.Abort(_('current bisect revision is a merge'))
788 try:
788 try:
789 while changesets:
789 while changesets:
790 # update state
790 # update state
791 state['current'] = [node]
791 state['current'] = [node]
792 hbisect.save_state(repo, state)
792 hbisect.save_state(repo, state)
793 status = ui.system(command, environ={'HG_NODE': hex(node)})
793 status = ui.system(command, environ={'HG_NODE': hex(node)})
794 if status == 125:
794 if status == 125:
795 transition = "skip"
795 transition = "skip"
796 elif status == 0:
796 elif status == 0:
797 transition = "good"
797 transition = "good"
798 # status < 0 means process was killed
798 # status < 0 means process was killed
799 elif status == 127:
799 elif status == 127:
800 raise util.Abort(_("failed to execute %s") % command)
800 raise util.Abort(_("failed to execute %s") % command)
801 elif status < 0:
801 elif status < 0:
802 raise util.Abort(_("%s killed") % command)
802 raise util.Abort(_("%s killed") % command)
803 else:
803 else:
804 transition = "bad"
804 transition = "bad"
805 ctx = scmutil.revsingle(repo, rev, node)
805 ctx = scmutil.revsingle(repo, rev, node)
806 rev = None # clear for future iterations
806 rev = None # clear for future iterations
807 state[transition].append(ctx.node())
807 state[transition].append(ctx.node())
808 ui.status(_('changeset %d:%s: %s\n') % (ctx, ctx, transition))
808 ui.status(_('changeset %d:%s: %s\n') % (ctx, ctx, transition))
809 check_state(state, interactive=False)
809 check_state(state, interactive=False)
810 # bisect
810 # bisect
811 nodes, changesets, bgood = hbisect.bisect(repo.changelog, state)
811 nodes, changesets, bgood = hbisect.bisect(repo.changelog, state)
812 # update to next check
812 # update to next check
813 node = nodes[0]
813 node = nodes[0]
814 if not noupdate:
814 if not noupdate:
815 cmdutil.bailifchanged(repo)
815 cmdutil.bailifchanged(repo)
816 hg.clean(repo, node, show_stats=False)
816 hg.clean(repo, node, show_stats=False)
817 finally:
817 finally:
818 state['current'] = [node]
818 state['current'] = [node]
819 hbisect.save_state(repo, state)
819 hbisect.save_state(repo, state)
820 print_result(nodes, bgood)
820 print_result(nodes, bgood)
821 return
821 return
822
822
823 # update state
823 # update state
824
824
825 if rev:
825 if rev:
826 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
826 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
827 else:
827 else:
828 nodes = [repo.lookup('.')]
828 nodes = [repo.lookup('.')]
829
829
830 if good or bad or skip:
830 if good or bad or skip:
831 if good:
831 if good:
832 state['good'] += nodes
832 state['good'] += nodes
833 elif bad:
833 elif bad:
834 state['bad'] += nodes
834 state['bad'] += nodes
835 elif skip:
835 elif skip:
836 state['skip'] += nodes
836 state['skip'] += nodes
837 hbisect.save_state(repo, state)
837 hbisect.save_state(repo, state)
838
838
839 if not check_state(state):
839 if not check_state(state):
840 return
840 return
841
841
842 # actually bisect
842 # actually bisect
843 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
843 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
844 if extend:
844 if extend:
845 if not changesets:
845 if not changesets:
846 extendnode = extendbisectrange(nodes, good)
846 extendnode = extendbisectrange(nodes, good)
847 if extendnode is not None:
847 if extendnode is not None:
848 ui.write(_("Extending search to changeset %d:%s\n")
848 ui.write(_("Extending search to changeset %d:%s\n")
849 % (extendnode.rev(), extendnode))
849 % (extendnode.rev(), extendnode))
850 state['current'] = [extendnode.node()]
850 state['current'] = [extendnode.node()]
851 hbisect.save_state(repo, state)
851 hbisect.save_state(repo, state)
852 if noupdate:
852 if noupdate:
853 return
853 return
854 cmdutil.bailifchanged(repo)
854 cmdutil.bailifchanged(repo)
855 return hg.clean(repo, extendnode.node())
855 return hg.clean(repo, extendnode.node())
856 raise util.Abort(_("nothing to extend"))
856 raise util.Abort(_("nothing to extend"))
857
857
858 if changesets == 0:
858 if changesets == 0:
859 print_result(nodes, good)
859 print_result(nodes, good)
860 else:
860 else:
861 assert len(nodes) == 1 # only a single node can be tested next
861 assert len(nodes) == 1 # only a single node can be tested next
862 node = nodes[0]
862 node = nodes[0]
863 # compute the approximate number of remaining tests
863 # compute the approximate number of remaining tests
864 tests, size = 0, 2
864 tests, size = 0, 2
865 while size <= changesets:
865 while size <= changesets:
866 tests, size = tests + 1, size * 2
866 tests, size = tests + 1, size * 2
867 rev = repo.changelog.rev(node)
867 rev = repo.changelog.rev(node)
868 ui.write(_("Testing changeset %d:%s "
868 ui.write(_("Testing changeset %d:%s "
869 "(%d changesets remaining, ~%d tests)\n")
869 "(%d changesets remaining, ~%d tests)\n")
870 % (rev, short(node), changesets, tests))
870 % (rev, short(node), changesets, tests))
871 state['current'] = [node]
871 state['current'] = [node]
872 hbisect.save_state(repo, state)
872 hbisect.save_state(repo, state)
873 if not noupdate:
873 if not noupdate:
874 cmdutil.bailifchanged(repo)
874 cmdutil.bailifchanged(repo)
875 return hg.clean(repo, node)
875 return hg.clean(repo, node)
876
876
877 @command('bookmarks|bookmark',
877 @command('bookmarks|bookmark',
878 [('f', 'force', False, _('force')),
878 [('f', 'force', False, _('force')),
879 ('r', 'rev', '', _('revision'), _('REV')),
879 ('r', 'rev', '', _('revision'), _('REV')),
880 ('d', 'delete', False, _('delete a given bookmark')),
880 ('d', 'delete', False, _('delete a given bookmark')),
881 ('m', 'rename', '', _('rename a given bookmark'), _('OLD')),
881 ('m', 'rename', '', _('rename a given bookmark'), _('OLD')),
882 ('i', 'inactive', False, _('mark a bookmark inactive')),
882 ('i', 'inactive', False, _('mark a bookmark inactive')),
883 ] + formatteropts,
883 ] + formatteropts,
884 _('hg bookmarks [OPTIONS]... [NAME]...'))
884 _('hg bookmarks [OPTIONS]... [NAME]...'))
885 def bookmark(ui, repo, *names, **opts):
885 def bookmark(ui, repo, *names, **opts):
886 '''create a new bookmark or list existing bookmarks
886 '''create a new bookmark or list existing bookmarks
887
887
888 Bookmarks are labels on changesets to help track lines of development.
888 Bookmarks are labels on changesets to help track lines of development.
889 Bookmarks are unversioned and can be moved, renamed and deleted.
889 Bookmarks are unversioned and can be moved, renamed and deleted.
890 Deleting or moving a bookmark has no effect on the associated changesets.
890 Deleting or moving a bookmark has no effect on the associated changesets.
891
891
892 Creating or updating to a bookmark causes it to be marked as 'active'.
892 Creating or updating to a bookmark causes it to be marked as 'active'.
893 The active bookmark is indicated with a '*'.
893 The active bookmark is indicated with a '*'.
894 When a commit is made, the active bookmark will advance to the new commit.
894 When a commit is made, the active bookmark will advance to the new commit.
895 A plain :hg:`update` will also advance an active bookmark, if possible.
895 A plain :hg:`update` will also advance an active bookmark, if possible.
896 Updating away from a bookmark will cause it to be deactivated.
896 Updating away from a bookmark will cause it to be deactivated.
897
897
898 Bookmarks can be pushed and pulled between repositories (see
898 Bookmarks can be pushed and pulled between repositories (see
899 :hg:`help push` and :hg:`help pull`). If a shared bookmark has
899 :hg:`help push` and :hg:`help pull`). If a shared bookmark has
900 diverged, a new 'divergent bookmark' of the form 'name@path' will
900 diverged, a new 'divergent bookmark' of the form 'name@path' will
901 be created. Using :hg:`merge` will resolve the divergence.
901 be created. Using :hg:`merge` will resolve the divergence.
902
902
903 A bookmark named '@' has the special property that :hg:`clone` will
903 A bookmark named '@' has the special property that :hg:`clone` will
904 check it out by default if it exists.
904 check it out by default if it exists.
905
905
906 .. container:: verbose
906 .. container:: verbose
907
907
908 Examples:
908 Examples:
909
909
910 - create an active bookmark for a new line of development::
910 - create an active bookmark for a new line of development::
911
911
912 hg book new-feature
912 hg book new-feature
913
913
914 - create an inactive bookmark as a place marker::
914 - create an inactive bookmark as a place marker::
915
915
916 hg book -i reviewed
916 hg book -i reviewed
917
917
918 - create an inactive bookmark on another changeset::
918 - create an inactive bookmark on another changeset::
919
919
920 hg book -r .^ tested
920 hg book -r .^ tested
921
921
922 - rename bookmark turkey to dinner::
922 - rename bookmark turkey to dinner::
923
923
924 hg book -m turkey dinner
924 hg book -m turkey dinner
925
925
926 - move the '@' bookmark from another branch::
926 - move the '@' bookmark from another branch::
927
927
928 hg book -f @
928 hg book -f @
929 '''
929 '''
930 force = opts.get('force')
930 force = opts.get('force')
931 rev = opts.get('rev')
931 rev = opts.get('rev')
932 delete = opts.get('delete')
932 delete = opts.get('delete')
933 rename = opts.get('rename')
933 rename = opts.get('rename')
934 inactive = opts.get('inactive')
934 inactive = opts.get('inactive')
935
935
936 def checkformat(mark):
936 def checkformat(mark):
937 mark = mark.strip()
937 mark = mark.strip()
938 if not mark:
938 if not mark:
939 raise util.Abort(_("bookmark names cannot consist entirely of "
939 raise util.Abort(_("bookmark names cannot consist entirely of "
940 "whitespace"))
940 "whitespace"))
941 scmutil.checknewlabel(repo, mark, 'bookmark')
941 scmutil.checknewlabel(repo, mark, 'bookmark')
942 return mark
942 return mark
943
943
944 def checkconflict(repo, mark, cur, force=False, target=None):
944 def checkconflict(repo, mark, cur, force=False, target=None):
945 if mark in marks and not force:
945 if mark in marks and not force:
946 if target:
946 if target:
947 if marks[mark] == target and target == cur:
947 if marks[mark] == target and target == cur:
948 # re-activating a bookmark
948 # re-activating a bookmark
949 return
949 return
950 anc = repo.changelog.ancestors([repo[target].rev()])
950 anc = repo.changelog.ancestors([repo[target].rev()])
951 bmctx = repo[marks[mark]]
951 bmctx = repo[marks[mark]]
952 divs = [repo[b].node() for b in marks
952 divs = [repo[b].node() for b in marks
953 if b.split('@', 1)[0] == mark.split('@', 1)[0]]
953 if b.split('@', 1)[0] == mark.split('@', 1)[0]]
954
954
955 # allow resolving a single divergent bookmark even if moving
955 # allow resolving a single divergent bookmark even if moving
956 # the bookmark across branches when a revision is specified
956 # the bookmark across branches when a revision is specified
957 # that contains a divergent bookmark
957 # that contains a divergent bookmark
958 if bmctx.rev() not in anc and target in divs:
958 if bmctx.rev() not in anc and target in divs:
959 bookmarks.deletedivergent(repo, [target], mark)
959 bookmarks.deletedivergent(repo, [target], mark)
960 return
960 return
961
961
962 deletefrom = [b for b in divs
962 deletefrom = [b for b in divs
963 if repo[b].rev() in anc or b == target]
963 if repo[b].rev() in anc or b == target]
964 bookmarks.deletedivergent(repo, deletefrom, mark)
964 bookmarks.deletedivergent(repo, deletefrom, mark)
965 if bookmarks.validdest(repo, bmctx, repo[target]):
965 if bookmarks.validdest(repo, bmctx, repo[target]):
966 ui.status(_("moving bookmark '%s' forward from %s\n") %
966 ui.status(_("moving bookmark '%s' forward from %s\n") %
967 (mark, short(bmctx.node())))
967 (mark, short(bmctx.node())))
968 return
968 return
969 raise util.Abort(_("bookmark '%s' already exists "
969 raise util.Abort(_("bookmark '%s' already exists "
970 "(use -f to force)") % mark)
970 "(use -f to force)") % mark)
971 if ((mark in repo.branchmap() or mark == repo.dirstate.branch())
971 if ((mark in repo.branchmap() or mark == repo.dirstate.branch())
972 and not force):
972 and not force):
973 raise util.Abort(
973 raise util.Abort(
974 _("a bookmark cannot have the name of an existing branch"))
974 _("a bookmark cannot have the name of an existing branch"))
975
975
976 if delete and rename:
976 if delete and rename:
977 raise util.Abort(_("--delete and --rename are incompatible"))
977 raise util.Abort(_("--delete and --rename are incompatible"))
978 if delete and rev:
978 if delete and rev:
979 raise util.Abort(_("--rev is incompatible with --delete"))
979 raise util.Abort(_("--rev is incompatible with --delete"))
980 if rename and rev:
980 if rename and rev:
981 raise util.Abort(_("--rev is incompatible with --rename"))
981 raise util.Abort(_("--rev is incompatible with --rename"))
982 if not names and (delete or rev):
982 if not names and (delete or rev):
983 raise util.Abort(_("bookmark name required"))
983 raise util.Abort(_("bookmark name required"))
984
984
985 if delete or rename or names or inactive:
985 if delete or rename or names or inactive:
986 wlock = lock = tr = None
986 wlock = lock = tr = None
987 try:
987 try:
988 wlock = repo.wlock()
988 wlock = repo.wlock()
989 lock = repo.lock()
989 lock = repo.lock()
990 cur = repo.changectx('.').node()
990 cur = repo.changectx('.').node()
991 marks = repo._bookmarks
991 marks = repo._bookmarks
992 if delete:
992 if delete:
993 tr = repo.transaction('bookmark')
993 tr = repo.transaction('bookmark')
994 for mark in names:
994 for mark in names:
995 if mark not in marks:
995 if mark not in marks:
996 raise util.Abort(_("bookmark '%s' does not exist") %
996 raise util.Abort(_("bookmark '%s' does not exist") %
997 mark)
997 mark)
998 if mark == repo._activebookmark:
998 if mark == repo._activebookmark:
999 bookmarks.deactivate(repo)
999 bookmarks.deactivate(repo)
1000 del marks[mark]
1000 del marks[mark]
1001
1001
1002 elif rename:
1002 elif rename:
1003 tr = repo.transaction('bookmark')
1003 tr = repo.transaction('bookmark')
1004 if not names:
1004 if not names:
1005 raise util.Abort(_("new bookmark name required"))
1005 raise util.Abort(_("new bookmark name required"))
1006 elif len(names) > 1:
1006 elif len(names) > 1:
1007 raise util.Abort(_("only one new bookmark name allowed"))
1007 raise util.Abort(_("only one new bookmark name allowed"))
1008 mark = checkformat(names[0])
1008 mark = checkformat(names[0])
1009 if rename not in marks:
1009 if rename not in marks:
1010 raise util.Abort(_("bookmark '%s' does not exist") % rename)
1010 raise util.Abort(_("bookmark '%s' does not exist") % rename)
1011 checkconflict(repo, mark, cur, force)
1011 checkconflict(repo, mark, cur, force)
1012 marks[mark] = marks[rename]
1012 marks[mark] = marks[rename]
1013 if repo._activebookmark == rename and not inactive:
1013 if repo._activebookmark == rename and not inactive:
1014 bookmarks.activate(repo, mark)
1014 bookmarks.activate(repo, mark)
1015 del marks[rename]
1015 del marks[rename]
1016 elif names:
1016 elif names:
1017 tr = repo.transaction('bookmark')
1017 tr = repo.transaction('bookmark')
1018 newact = None
1018 newact = None
1019 for mark in names:
1019 for mark in names:
1020 mark = checkformat(mark)
1020 mark = checkformat(mark)
1021 if newact is None:
1021 if newact is None:
1022 newact = mark
1022 newact = mark
1023 if inactive and mark == repo._activebookmark:
1023 if inactive and mark == repo._activebookmark:
1024 bookmarks.deactivate(repo)
1024 bookmarks.deactivate(repo)
1025 return
1025 return
1026 tgt = cur
1026 tgt = cur
1027 if rev:
1027 if rev:
1028 tgt = scmutil.revsingle(repo, rev).node()
1028 tgt = scmutil.revsingle(repo, rev).node()
1029 checkconflict(repo, mark, cur, force, tgt)
1029 checkconflict(repo, mark, cur, force, tgt)
1030 marks[mark] = tgt
1030 marks[mark] = tgt
1031 if not inactive and cur == marks[newact] and not rev:
1031 if not inactive and cur == marks[newact] and not rev:
1032 bookmarks.activate(repo, newact)
1032 bookmarks.activate(repo, newact)
1033 elif cur != tgt and newact == repo._activebookmark:
1033 elif cur != tgt and newact == repo._activebookmark:
1034 bookmarks.deactivate(repo)
1034 bookmarks.deactivate(repo)
1035 elif inactive:
1035 elif inactive:
1036 if len(marks) == 0:
1036 if len(marks) == 0:
1037 ui.status(_("no bookmarks set\n"))
1037 ui.status(_("no bookmarks set\n"))
1038 elif not repo._activebookmark:
1038 elif not repo._activebookmark:
1039 ui.status(_("no active bookmark\n"))
1039 ui.status(_("no active bookmark\n"))
1040 else:
1040 else:
1041 bookmarks.deactivate(repo)
1041 bookmarks.deactivate(repo)
1042 if tr is not None:
1042 if tr is not None:
1043 marks.recordchange(tr)
1043 marks.recordchange(tr)
1044 tr.close()
1044 tr.close()
1045 finally:
1045 finally:
1046 lockmod.release(tr, lock, wlock)
1046 lockmod.release(tr, lock, wlock)
1047 else: # show bookmarks
1047 else: # show bookmarks
1048 fm = ui.formatter('bookmarks', opts)
1048 fm = ui.formatter('bookmarks', opts)
1049 hexfn = fm.hexfunc
1049 hexfn = fm.hexfunc
1050 marks = repo._bookmarks
1050 marks = repo._bookmarks
1051 if len(marks) == 0 and not fm:
1051 if len(marks) == 0 and not fm:
1052 ui.status(_("no bookmarks set\n"))
1052 ui.status(_("no bookmarks set\n"))
1053 for bmark, n in sorted(marks.iteritems()):
1053 for bmark, n in sorted(marks.iteritems()):
1054 active = repo._activebookmark
1054 active = repo._activebookmark
1055 if bmark == active:
1055 if bmark == active:
1056 prefix, label = '*', activebookmarklabel
1056 prefix, label = '*', activebookmarklabel
1057 else:
1057 else:
1058 prefix, label = ' ', ''
1058 prefix, label = ' ', ''
1059
1059
1060 fm.startitem()
1060 fm.startitem()
1061 if not ui.quiet:
1061 if not ui.quiet:
1062 fm.plain(' %s ' % prefix, label=label)
1062 fm.plain(' %s ' % prefix, label=label)
1063 fm.write('bookmark', '%s', bmark, label=label)
1063 fm.write('bookmark', '%s', bmark, label=label)
1064 pad = " " * (25 - encoding.colwidth(bmark))
1064 pad = " " * (25 - encoding.colwidth(bmark))
1065 fm.condwrite(not ui.quiet, 'rev node', pad + ' %d:%s',
1065 fm.condwrite(not ui.quiet, 'rev node', pad + ' %d:%s',
1066 repo.changelog.rev(n), hexfn(n), label=label)
1066 repo.changelog.rev(n), hexfn(n), label=label)
1067 fm.data(active=(bmark == active))
1067 fm.data(active=(bmark == active))
1068 fm.plain('\n')
1068 fm.plain('\n')
1069 fm.end()
1069 fm.end()
1070
1070
1071 @command('branch',
1071 @command('branch',
1072 [('f', 'force', None,
1072 [('f', 'force', None,
1073 _('set branch name even if it shadows an existing branch')),
1073 _('set branch name even if it shadows an existing branch')),
1074 ('C', 'clean', None, _('reset branch name to parent branch name'))],
1074 ('C', 'clean', None, _('reset branch name to parent branch name'))],
1075 _('[-fC] [NAME]'))
1075 _('[-fC] [NAME]'))
1076 def branch(ui, repo, label=None, **opts):
1076 def branch(ui, repo, label=None, **opts):
1077 """set or show the current branch name
1077 """set or show the current branch name
1078
1078
1079 .. note::
1079 .. note::
1080
1080
1081 Branch names are permanent and global. Use :hg:`bookmark` to create a
1081 Branch names are permanent and global. Use :hg:`bookmark` to create a
1082 light-weight bookmark instead. See :hg:`help glossary` for more
1082 light-weight bookmark instead. See :hg:`help glossary` for more
1083 information about named branches and bookmarks.
1083 information about named branches and bookmarks.
1084
1084
1085 With no argument, show the current branch name. With one argument,
1085 With no argument, show the current branch name. With one argument,
1086 set the working directory branch name (the branch will not exist
1086 set the working directory branch name (the branch will not exist
1087 in the repository until the next commit). Standard practice
1087 in the repository until the next commit). Standard practice
1088 recommends that primary development take place on the 'default'
1088 recommends that primary development take place on the 'default'
1089 branch.
1089 branch.
1090
1090
1091 Unless -f/--force is specified, branch will not let you set a
1091 Unless -f/--force is specified, branch will not let you set a
1092 branch name that already exists.
1092 branch name that already exists.
1093
1093
1094 Use -C/--clean to reset the working directory branch to that of
1094 Use -C/--clean to reset the working directory branch to that of
1095 the parent of the working directory, negating a previous branch
1095 the parent of the working directory, negating a previous branch
1096 change.
1096 change.
1097
1097
1098 Use the command :hg:`update` to switch to an existing branch. Use
1098 Use the command :hg:`update` to switch to an existing branch. Use
1099 :hg:`commit --close-branch` to mark this branch head as closed.
1099 :hg:`commit --close-branch` to mark this branch head as closed.
1100 When all heads of the branch are closed, the branch will be
1100 When all heads of the branch are closed, the branch will be
1101 considered closed.
1101 considered closed.
1102
1102
1103 Returns 0 on success.
1103 Returns 0 on success.
1104 """
1104 """
1105 if label:
1105 if label:
1106 label = label.strip()
1106 label = label.strip()
1107
1107
1108 if not opts.get('clean') and not label:
1108 if not opts.get('clean') and not label:
1109 ui.write("%s\n" % repo.dirstate.branch())
1109 ui.write("%s\n" % repo.dirstate.branch())
1110 return
1110 return
1111
1111
1112 wlock = repo.wlock()
1112 wlock = repo.wlock()
1113 try:
1113 try:
1114 if opts.get('clean'):
1114 if opts.get('clean'):
1115 label = repo[None].p1().branch()
1115 label = repo[None].p1().branch()
1116 repo.dirstate.setbranch(label)
1116 repo.dirstate.setbranch(label)
1117 ui.status(_('reset working directory to branch %s\n') % label)
1117 ui.status(_('reset working directory to branch %s\n') % label)
1118 elif label:
1118 elif label:
1119 if not opts.get('force') and label in repo.branchmap():
1119 if not opts.get('force') and label in repo.branchmap():
1120 if label not in [p.branch() for p in repo.parents()]:
1120 if label not in [p.branch() for p in repo.parents()]:
1121 raise util.Abort(_('a branch of the same name already'
1121 raise util.Abort(_('a branch of the same name already'
1122 ' exists'),
1122 ' exists'),
1123 # i18n: "it" refers to an existing branch
1123 # i18n: "it" refers to an existing branch
1124 hint=_("use 'hg update' to switch to it"))
1124 hint=_("use 'hg update' to switch to it"))
1125 scmutil.checknewlabel(repo, label, 'branch')
1125 scmutil.checknewlabel(repo, label, 'branch')
1126 repo.dirstate.setbranch(label)
1126 repo.dirstate.setbranch(label)
1127 ui.status(_('marked working directory as branch %s\n') % label)
1127 ui.status(_('marked working directory as branch %s\n') % label)
1128
1128
1129 # find any open named branches aside from default
1129 # find any open named branches aside from default
1130 others = [n for n, h, t, c in repo.branchmap().iterbranches()
1130 others = [n for n, h, t, c in repo.branchmap().iterbranches()
1131 if n != "default" and not c]
1131 if n != "default" and not c]
1132 if not others:
1132 if not others:
1133 ui.status(_('(branches are permanent and global, '
1133 ui.status(_('(branches are permanent and global, '
1134 'did you want a bookmark?)\n'))
1134 'did you want a bookmark?)\n'))
1135 finally:
1135 finally:
1136 wlock.release()
1136 wlock.release()
1137
1137
1138 @command('branches',
1138 @command('branches',
1139 [('a', 'active', False,
1139 [('a', 'active', False,
1140 _('show only branches that have unmerged heads (DEPRECATED)')),
1140 _('show only branches that have unmerged heads (DEPRECATED)')),
1141 ('c', 'closed', False, _('show normal and closed branches')),
1141 ('c', 'closed', False, _('show normal and closed branches')),
1142 ] + formatteropts,
1142 ] + formatteropts,
1143 _('[-ac]'))
1143 _('[-ac]'))
1144 def branches(ui, repo, active=False, closed=False, **opts):
1144 def branches(ui, repo, active=False, closed=False, **opts):
1145 """list repository named branches
1145 """list repository named branches
1146
1146
1147 List the repository's named branches, indicating which ones are
1147 List the repository's named branches, indicating which ones are
1148 inactive. If -c/--closed is specified, also list branches which have
1148 inactive. If -c/--closed is specified, also list branches which have
1149 been marked closed (see :hg:`commit --close-branch`).
1149 been marked closed (see :hg:`commit --close-branch`).
1150
1150
1151 Use the command :hg:`update` to switch to an existing branch.
1151 Use the command :hg:`update` to switch to an existing branch.
1152
1152
1153 Returns 0.
1153 Returns 0.
1154 """
1154 """
1155
1155
1156 fm = ui.formatter('branches', opts)
1156 fm = ui.formatter('branches', opts)
1157 hexfunc = fm.hexfunc
1157 hexfunc = fm.hexfunc
1158
1158
1159 allheads = set(repo.heads())
1159 allheads = set(repo.heads())
1160 branches = []
1160 branches = []
1161 for tag, heads, tip, isclosed in repo.branchmap().iterbranches():
1161 for tag, heads, tip, isclosed in repo.branchmap().iterbranches():
1162 isactive = not isclosed and bool(set(heads) & allheads)
1162 isactive = not isclosed and bool(set(heads) & allheads)
1163 branches.append((tag, repo[tip], isactive, not isclosed))
1163 branches.append((tag, repo[tip], isactive, not isclosed))
1164 branches.sort(key=lambda i: (i[2], i[1].rev(), i[0], i[3]),
1164 branches.sort(key=lambda i: (i[2], i[1].rev(), i[0], i[3]),
1165 reverse=True)
1165 reverse=True)
1166
1166
1167 for tag, ctx, isactive, isopen in branches:
1167 for tag, ctx, isactive, isopen in branches:
1168 if active and not isactive:
1168 if active and not isactive:
1169 continue
1169 continue
1170 if isactive:
1170 if isactive:
1171 label = 'branches.active'
1171 label = 'branches.active'
1172 notice = ''
1172 notice = ''
1173 elif not isopen:
1173 elif not isopen:
1174 if not closed:
1174 if not closed:
1175 continue
1175 continue
1176 label = 'branches.closed'
1176 label = 'branches.closed'
1177 notice = _(' (closed)')
1177 notice = _(' (closed)')
1178 else:
1178 else:
1179 label = 'branches.inactive'
1179 label = 'branches.inactive'
1180 notice = _(' (inactive)')
1180 notice = _(' (inactive)')
1181 current = (tag == repo.dirstate.branch())
1181 current = (tag == repo.dirstate.branch())
1182 if current:
1182 if current:
1183 label = 'branches.current'
1183 label = 'branches.current'
1184
1184
1185 fm.startitem()
1185 fm.startitem()
1186 fm.write('branch', '%s', tag, label=label)
1186 fm.write('branch', '%s', tag, label=label)
1187 rev = ctx.rev()
1187 rev = ctx.rev()
1188 padsize = max(31 - len(str(rev)) - encoding.colwidth(tag), 0)
1188 padsize = max(31 - len(str(rev)) - encoding.colwidth(tag), 0)
1189 fmt = ' ' * padsize + ' %d:%s'
1189 fmt = ' ' * padsize + ' %d:%s'
1190 fm.condwrite(not ui.quiet, 'rev node', fmt, rev, hexfunc(ctx.node()),
1190 fm.condwrite(not ui.quiet, 'rev node', fmt, rev, hexfunc(ctx.node()),
1191 label='log.changeset changeset.%s' % ctx.phasestr())
1191 label='log.changeset changeset.%s' % ctx.phasestr())
1192 fm.data(active=isactive, closed=not isopen, current=current)
1192 fm.data(active=isactive, closed=not isopen, current=current)
1193 if not ui.quiet:
1193 if not ui.quiet:
1194 fm.plain(notice)
1194 fm.plain(notice)
1195 fm.plain('\n')
1195 fm.plain('\n')
1196 fm.end()
1196 fm.end()
1197
1197
1198 @command('bundle',
1198 @command('bundle',
1199 [('f', 'force', None, _('run even when the destination is unrelated')),
1199 [('f', 'force', None, _('run even when the destination is unrelated')),
1200 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
1200 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
1201 _('REV')),
1201 _('REV')),
1202 ('b', 'branch', [], _('a specific branch you would like to bundle'),
1202 ('b', 'branch', [], _('a specific branch you would like to bundle'),
1203 _('BRANCH')),
1203 _('BRANCH')),
1204 ('', 'base', [],
1204 ('', 'base', [],
1205 _('a base changeset assumed to be available at the destination'),
1205 _('a base changeset assumed to be available at the destination'),
1206 _('REV')),
1206 _('REV')),
1207 ('a', 'all', None, _('bundle all changesets in the repository')),
1207 ('a', 'all', None, _('bundle all changesets in the repository')),
1208 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
1208 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
1209 ] + remoteopts,
1209 ] + remoteopts,
1210 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
1210 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
1211 def bundle(ui, repo, fname, dest=None, **opts):
1211 def bundle(ui, repo, fname, dest=None, **opts):
1212 """create a changegroup file
1212 """create a changegroup file
1213
1213
1214 Generate a compressed changegroup file collecting changesets not
1214 Generate a compressed changegroup file collecting changesets not
1215 known to be in another repository.
1215 known to be in another repository.
1216
1216
1217 If you omit the destination repository, then hg assumes the
1217 If you omit the destination repository, then hg assumes the
1218 destination will have all the nodes you specify with --base
1218 destination will have all the nodes you specify with --base
1219 parameters. To create a bundle containing all changesets, use
1219 parameters. To create a bundle containing all changesets, use
1220 -a/--all (or --base null).
1220 -a/--all (or --base null).
1221
1221
1222 You can change compression method with the -t/--type option.
1222 You can change compression method with the -t/--type option.
1223 The available compression methods are: none, bzip2, and
1223 The available compression methods are: none, bzip2, and
1224 gzip (by default, bundles are compressed using bzip2).
1224 gzip (by default, bundles are compressed using bzip2).
1225
1225
1226 The bundle file can then be transferred using conventional means
1226 The bundle file can then be transferred using conventional means
1227 and applied to another repository with the unbundle or pull
1227 and applied to another repository with the unbundle or pull
1228 command. This is useful when direct push and pull are not
1228 command. This is useful when direct push and pull are not
1229 available or when exporting an entire repository is undesirable.
1229 available or when exporting an entire repository is undesirable.
1230
1230
1231 Applying bundles preserves all changeset contents including
1231 Applying bundles preserves all changeset contents including
1232 permissions, copy/rename information, and revision history.
1232 permissions, copy/rename information, and revision history.
1233
1233
1234 Returns 0 on success, 1 if no changes found.
1234 Returns 0 on success, 1 if no changes found.
1235 """
1235 """
1236 revs = None
1236 revs = None
1237 if 'rev' in opts:
1237 if 'rev' in opts:
1238 revs = scmutil.revrange(repo, opts['rev'])
1238 revs = scmutil.revrange(repo, opts['rev'])
1239
1239
1240 bundletype = opts.get('type', 'bzip2').lower()
1240 bundletype = opts.get('type', 'bzip2').lower()
1241 btypes = {'none': 'HG10UN',
1241 bundletype = cmdutil.parsebundletype(bundletype)
1242 'bzip2': 'HG10BZ',
1243 'gzip': 'HG10GZ',
1244 'bundle2': 'HG20'}
1245 bundletype = btypes.get(bundletype)
1246 if bundletype not in changegroup.bundletypes:
1247 raise util.Abort(_('unknown bundle type specified with --type'))
1248
1242
1249 if opts.get('all'):
1243 if opts.get('all'):
1250 base = ['null']
1244 base = ['null']
1251 else:
1245 else:
1252 base = scmutil.revrange(repo, opts.get('base'))
1246 base = scmutil.revrange(repo, opts.get('base'))
1253 # TODO: get desired bundlecaps from command line.
1247 # TODO: get desired bundlecaps from command line.
1254 bundlecaps = None
1248 bundlecaps = None
1255 if base:
1249 if base:
1256 if dest:
1250 if dest:
1257 raise util.Abort(_("--base is incompatible with specifying "
1251 raise util.Abort(_("--base is incompatible with specifying "
1258 "a destination"))
1252 "a destination"))
1259 common = [repo.lookup(rev) for rev in base]
1253 common = [repo.lookup(rev) for rev in base]
1260 heads = revs and map(repo.lookup, revs) or revs
1254 heads = revs and map(repo.lookup, revs) or revs
1261 cg = changegroup.getchangegroup(repo, 'bundle', heads=heads,
1255 cg = changegroup.getchangegroup(repo, 'bundle', heads=heads,
1262 common=common, bundlecaps=bundlecaps)
1256 common=common, bundlecaps=bundlecaps)
1263 outgoing = None
1257 outgoing = None
1264 else:
1258 else:
1265 dest = ui.expandpath(dest or 'default-push', dest or 'default')
1259 dest = ui.expandpath(dest or 'default-push', dest or 'default')
1266 dest, branches = hg.parseurl(dest, opts.get('branch'))
1260 dest, branches = hg.parseurl(dest, opts.get('branch'))
1267 other = hg.peer(repo, opts, dest)
1261 other = hg.peer(repo, opts, dest)
1268 revs, checkout = hg.addbranchrevs(repo, repo, branches, revs)
1262 revs, checkout = hg.addbranchrevs(repo, repo, branches, revs)
1269 heads = revs and map(repo.lookup, revs) or revs
1263 heads = revs and map(repo.lookup, revs) or revs
1270 outgoing = discovery.findcommonoutgoing(repo, other,
1264 outgoing = discovery.findcommonoutgoing(repo, other,
1271 onlyheads=heads,
1265 onlyheads=heads,
1272 force=opts.get('force'),
1266 force=opts.get('force'),
1273 portable=True)
1267 portable=True)
1274 cg = changegroup.getlocalchangegroup(repo, 'bundle', outgoing,
1268 cg = changegroup.getlocalchangegroup(repo, 'bundle', outgoing,
1275 bundlecaps)
1269 bundlecaps)
1276 if not cg:
1270 if not cg:
1277 scmutil.nochangesfound(ui, repo, outgoing and outgoing.excluded)
1271 scmutil.nochangesfound(ui, repo, outgoing and outgoing.excluded)
1278 return 1
1272 return 1
1279
1273
1280 changegroup.writebundle(ui, cg, fname, bundletype)
1274 changegroup.writebundle(ui, cg, fname, bundletype)
1281
1275
1282 @command('cat',
1276 @command('cat',
1283 [('o', 'output', '',
1277 [('o', 'output', '',
1284 _('print output to file with formatted name'), _('FORMAT')),
1278 _('print output to file with formatted name'), _('FORMAT')),
1285 ('r', 'rev', '', _('print the given revision'), _('REV')),
1279 ('r', 'rev', '', _('print the given revision'), _('REV')),
1286 ('', 'decode', None, _('apply any matching decode filter')),
1280 ('', 'decode', None, _('apply any matching decode filter')),
1287 ] + walkopts,
1281 ] + walkopts,
1288 _('[OPTION]... FILE...'),
1282 _('[OPTION]... FILE...'),
1289 inferrepo=True)
1283 inferrepo=True)
1290 def cat(ui, repo, file1, *pats, **opts):
1284 def cat(ui, repo, file1, *pats, **opts):
1291 """output the current or given revision of files
1285 """output the current or given revision of files
1292
1286
1293 Print the specified files as they were at the given revision. If
1287 Print the specified files as they were at the given revision. If
1294 no revision is given, the parent of the working directory is used.
1288 no revision is given, the parent of the working directory is used.
1295
1289
1296 Output may be to a file, in which case the name of the file is
1290 Output may be to a file, in which case the name of the file is
1297 given using a format string. The formatting rules as follows:
1291 given using a format string. The formatting rules as follows:
1298
1292
1299 :``%%``: literal "%" character
1293 :``%%``: literal "%" character
1300 :``%s``: basename of file being printed
1294 :``%s``: basename of file being printed
1301 :``%d``: dirname of file being printed, or '.' if in repository root
1295 :``%d``: dirname of file being printed, or '.' if in repository root
1302 :``%p``: root-relative path name of file being printed
1296 :``%p``: root-relative path name of file being printed
1303 :``%H``: changeset hash (40 hexadecimal digits)
1297 :``%H``: changeset hash (40 hexadecimal digits)
1304 :``%R``: changeset revision number
1298 :``%R``: changeset revision number
1305 :``%h``: short-form changeset hash (12 hexadecimal digits)
1299 :``%h``: short-form changeset hash (12 hexadecimal digits)
1306 :``%r``: zero-padded changeset revision number
1300 :``%r``: zero-padded changeset revision number
1307 :``%b``: basename of the exporting repository
1301 :``%b``: basename of the exporting repository
1308
1302
1309 Returns 0 on success.
1303 Returns 0 on success.
1310 """
1304 """
1311 ctx = scmutil.revsingle(repo, opts.get('rev'))
1305 ctx = scmutil.revsingle(repo, opts.get('rev'))
1312 m = scmutil.match(ctx, (file1,) + pats, opts)
1306 m = scmutil.match(ctx, (file1,) + pats, opts)
1313
1307
1314 return cmdutil.cat(ui, repo, ctx, m, '', **opts)
1308 return cmdutil.cat(ui, repo, ctx, m, '', **opts)
1315
1309
1316 @command('^clone',
1310 @command('^clone',
1317 [('U', 'noupdate', None, _('the clone will include an empty working '
1311 [('U', 'noupdate', None, _('the clone will include an empty working '
1318 'directory (only a repository)')),
1312 'directory (only a repository)')),
1319 ('u', 'updaterev', '', _('revision, tag or branch to check out'), _('REV')),
1313 ('u', 'updaterev', '', _('revision, tag or branch to check out'), _('REV')),
1320 ('r', 'rev', [], _('include the specified changeset'), _('REV')),
1314 ('r', 'rev', [], _('include the specified changeset'), _('REV')),
1321 ('b', 'branch', [], _('clone only the specified branch'), _('BRANCH')),
1315 ('b', 'branch', [], _('clone only the specified branch'), _('BRANCH')),
1322 ('', 'pull', None, _('use pull protocol to copy metadata')),
1316 ('', 'pull', None, _('use pull protocol to copy metadata')),
1323 ('', 'uncompressed', None, _('use uncompressed transfer (fast over LAN)')),
1317 ('', 'uncompressed', None, _('use uncompressed transfer (fast over LAN)')),
1324 ] + remoteopts,
1318 ] + remoteopts,
1325 _('[OPTION]... SOURCE [DEST]'),
1319 _('[OPTION]... SOURCE [DEST]'),
1326 norepo=True)
1320 norepo=True)
1327 def clone(ui, source, dest=None, **opts):
1321 def clone(ui, source, dest=None, **opts):
1328 """make a copy of an existing repository
1322 """make a copy of an existing repository
1329
1323
1330 Create a copy of an existing repository in a new directory.
1324 Create a copy of an existing repository in a new directory.
1331
1325
1332 If no destination directory name is specified, it defaults to the
1326 If no destination directory name is specified, it defaults to the
1333 basename of the source.
1327 basename of the source.
1334
1328
1335 The location of the source is added to the new repository's
1329 The location of the source is added to the new repository's
1336 ``.hg/hgrc`` file, as the default to be used for future pulls.
1330 ``.hg/hgrc`` file, as the default to be used for future pulls.
1337
1331
1338 Only local paths and ``ssh://`` URLs are supported as
1332 Only local paths and ``ssh://`` URLs are supported as
1339 destinations. For ``ssh://`` destinations, no working directory or
1333 destinations. For ``ssh://`` destinations, no working directory or
1340 ``.hg/hgrc`` will be created on the remote side.
1334 ``.hg/hgrc`` will be created on the remote side.
1341
1335
1342 To pull only a subset of changesets, specify one or more revisions
1336 To pull only a subset of changesets, specify one or more revisions
1343 identifiers with -r/--rev or branches with -b/--branch. The
1337 identifiers with -r/--rev or branches with -b/--branch. The
1344 resulting clone will contain only the specified changesets and
1338 resulting clone will contain only the specified changesets and
1345 their ancestors. These options (or 'clone src#rev dest') imply
1339 their ancestors. These options (or 'clone src#rev dest') imply
1346 --pull, even for local source repositories. Note that specifying a
1340 --pull, even for local source repositories. Note that specifying a
1347 tag will include the tagged changeset but not the changeset
1341 tag will include the tagged changeset but not the changeset
1348 containing the tag.
1342 containing the tag.
1349
1343
1350 If the source repository has a bookmark called '@' set, that
1344 If the source repository has a bookmark called '@' set, that
1351 revision will be checked out in the new repository by default.
1345 revision will be checked out in the new repository by default.
1352
1346
1353 To check out a particular version, use -u/--update, or
1347 To check out a particular version, use -u/--update, or
1354 -U/--noupdate to create a clone with no working directory.
1348 -U/--noupdate to create a clone with no working directory.
1355
1349
1356 .. container:: verbose
1350 .. container:: verbose
1357
1351
1358 For efficiency, hardlinks are used for cloning whenever the
1352 For efficiency, hardlinks are used for cloning whenever the
1359 source and destination are on the same filesystem (note this
1353 source and destination are on the same filesystem (note this
1360 applies only to the repository data, not to the working
1354 applies only to the repository data, not to the working
1361 directory). Some filesystems, such as AFS, implement hardlinking
1355 directory). Some filesystems, such as AFS, implement hardlinking
1362 incorrectly, but do not report errors. In these cases, use the
1356 incorrectly, but do not report errors. In these cases, use the
1363 --pull option to avoid hardlinking.
1357 --pull option to avoid hardlinking.
1364
1358
1365 In some cases, you can clone repositories and the working
1359 In some cases, you can clone repositories and the working
1366 directory using full hardlinks with ::
1360 directory using full hardlinks with ::
1367
1361
1368 $ cp -al REPO REPOCLONE
1362 $ cp -al REPO REPOCLONE
1369
1363
1370 This is the fastest way to clone, but it is not always safe. The
1364 This is the fastest way to clone, but it is not always safe. The
1371 operation is not atomic (making sure REPO is not modified during
1365 operation is not atomic (making sure REPO is not modified during
1372 the operation is up to you) and you have to make sure your
1366 the operation is up to you) and you have to make sure your
1373 editor breaks hardlinks (Emacs and most Linux Kernel tools do
1367 editor breaks hardlinks (Emacs and most Linux Kernel tools do
1374 so). Also, this is not compatible with certain extensions that
1368 so). Also, this is not compatible with certain extensions that
1375 place their metadata under the .hg directory, such as mq.
1369 place their metadata under the .hg directory, such as mq.
1376
1370
1377 Mercurial will update the working directory to the first applicable
1371 Mercurial will update the working directory to the first applicable
1378 revision from this list:
1372 revision from this list:
1379
1373
1380 a) null if -U or the source repository has no changesets
1374 a) null if -U or the source repository has no changesets
1381 b) if -u . and the source repository is local, the first parent of
1375 b) if -u . and the source repository is local, the first parent of
1382 the source repository's working directory
1376 the source repository's working directory
1383 c) the changeset specified with -u (if a branch name, this means the
1377 c) the changeset specified with -u (if a branch name, this means the
1384 latest head of that branch)
1378 latest head of that branch)
1385 d) the changeset specified with -r
1379 d) the changeset specified with -r
1386 e) the tipmost head specified with -b
1380 e) the tipmost head specified with -b
1387 f) the tipmost head specified with the url#branch source syntax
1381 f) the tipmost head specified with the url#branch source syntax
1388 g) the revision marked with the '@' bookmark, if present
1382 g) the revision marked with the '@' bookmark, if present
1389 h) the tipmost head of the default branch
1383 h) the tipmost head of the default branch
1390 i) tip
1384 i) tip
1391
1385
1392 Examples:
1386 Examples:
1393
1387
1394 - clone a remote repository to a new directory named hg/::
1388 - clone a remote repository to a new directory named hg/::
1395
1389
1396 hg clone http://selenic.com/hg
1390 hg clone http://selenic.com/hg
1397
1391
1398 - create a lightweight local clone::
1392 - create a lightweight local clone::
1399
1393
1400 hg clone project/ project-feature/
1394 hg clone project/ project-feature/
1401
1395
1402 - 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)::
1403
1397
1404 hg clone ssh://user@server//home/projects/alpha/
1398 hg clone ssh://user@server//home/projects/alpha/
1405
1399
1406 - do a high-speed clone over a LAN while checking out a
1400 - do a high-speed clone over a LAN while checking out a
1407 specified version::
1401 specified version::
1408
1402
1409 hg clone --uncompressed http://server/repo -u 1.5
1403 hg clone --uncompressed http://server/repo -u 1.5
1410
1404
1411 - create a repository without changesets after a particular revision::
1405 - create a repository without changesets after a particular revision::
1412
1406
1413 hg clone -r 04e544 experimental/ good/
1407 hg clone -r 04e544 experimental/ good/
1414
1408
1415 - clone (and track) a particular named branch::
1409 - clone (and track) a particular named branch::
1416
1410
1417 hg clone http://selenic.com/hg#stable
1411 hg clone http://selenic.com/hg#stable
1418
1412
1419 See :hg:`help urls` for details on specifying URLs.
1413 See :hg:`help urls` for details on specifying URLs.
1420
1414
1421 Returns 0 on success.
1415 Returns 0 on success.
1422 """
1416 """
1423 if opts.get('noupdate') and opts.get('updaterev'):
1417 if opts.get('noupdate') and opts.get('updaterev'):
1424 raise util.Abort(_("cannot specify both --noupdate and --updaterev"))
1418 raise util.Abort(_("cannot specify both --noupdate and --updaterev"))
1425
1419
1426 r = hg.clone(ui, opts, source, dest,
1420 r = hg.clone(ui, opts, source, dest,
1427 pull=opts.get('pull'),
1421 pull=opts.get('pull'),
1428 stream=opts.get('uncompressed'),
1422 stream=opts.get('uncompressed'),
1429 rev=opts.get('rev'),
1423 rev=opts.get('rev'),
1430 update=opts.get('updaterev') or not opts.get('noupdate'),
1424 update=opts.get('updaterev') or not opts.get('noupdate'),
1431 branch=opts.get('branch'),
1425 branch=opts.get('branch'),
1432 shareopts=opts.get('shareopts'))
1426 shareopts=opts.get('shareopts'))
1433
1427
1434 return r is None
1428 return r is None
1435
1429
1436 @command('^commit|ci',
1430 @command('^commit|ci',
1437 [('A', 'addremove', None,
1431 [('A', 'addremove', None,
1438 _('mark new/missing files as added/removed before committing')),
1432 _('mark new/missing files as added/removed before committing')),
1439 ('', 'close-branch', None,
1433 ('', 'close-branch', None,
1440 _('mark a branch head as closed')),
1434 _('mark a branch head as closed')),
1441 ('', 'amend', None, _('amend the parent of the working directory')),
1435 ('', 'amend', None, _('amend the parent of the working directory')),
1442 ('s', 'secret', None, _('use the secret phase for committing')),
1436 ('s', 'secret', None, _('use the secret phase for committing')),
1443 ('e', 'edit', None, _('invoke editor on commit messages')),
1437 ('e', 'edit', None, _('invoke editor on commit messages')),
1444 ('i', 'interactive', None, _('use interactive mode')),
1438 ('i', 'interactive', None, _('use interactive mode')),
1445 ] + walkopts + commitopts + commitopts2 + subrepoopts,
1439 ] + walkopts + commitopts + commitopts2 + subrepoopts,
1446 _('[OPTION]... [FILE]...'),
1440 _('[OPTION]... [FILE]...'),
1447 inferrepo=True)
1441 inferrepo=True)
1448 def commit(ui, repo, *pats, **opts):
1442 def commit(ui, repo, *pats, **opts):
1449 """commit the specified files or all outstanding changes
1443 """commit the specified files or all outstanding changes
1450
1444
1451 Commit changes to the given files into the repository. Unlike a
1445 Commit changes to the given files into the repository. Unlike a
1452 centralized SCM, this operation is a local operation. See
1446 centralized SCM, this operation is a local operation. See
1453 :hg:`push` for a way to actively distribute your changes.
1447 :hg:`push` for a way to actively distribute your changes.
1454
1448
1455 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`
1456 will be committed.
1450 will be committed.
1457
1451
1458 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
1459 filenames or -I/-X filters.
1453 filenames or -I/-X filters.
1460
1454
1461 If no commit message is specified, Mercurial starts your
1455 If no commit message is specified, Mercurial starts your
1462 configured editor where you can enter a message. In case your
1456 configured editor where you can enter a message. In case your
1463 commit fails, you will find a backup of your message in
1457 commit fails, you will find a backup of your message in
1464 ``.hg/last-message.txt``.
1458 ``.hg/last-message.txt``.
1465
1459
1466 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
1467 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
1468 will be considered closed and no longer listed.
1462 will be considered closed and no longer listed.
1469
1463
1470 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
1471 working directory with a new commit that contains the changes
1465 working directory with a new commit that contains the changes
1472 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`,
1473 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
1474 ``.hg/strip-backup`` (see :hg:`help bundle` and :hg:`help unbundle`
1468 ``.hg/strip-backup`` (see :hg:`help bundle` and :hg:`help unbundle`
1475 on how to restore it).
1469 on how to restore it).
1476
1470
1477 Message, user and date are taken from the amended commit unless
1471 Message, user and date are taken from the amended commit unless
1478 specified. When a message isn't specified on the command line,
1472 specified. When a message isn't specified on the command line,
1479 the editor will open with the message of the amended commit.
1473 the editor will open with the message of the amended commit.
1480
1474
1481 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`)
1482 or changesets that have children.
1476 or changesets that have children.
1483
1477
1484 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.
1485
1479
1486 Returns 0 on success, 1 if nothing changed.
1480 Returns 0 on success, 1 if nothing changed.
1487 """
1481 """
1488 if opts.get('interactive'):
1482 if opts.get('interactive'):
1489 opts.pop('interactive')
1483 opts.pop('interactive')
1490 cmdutil.dorecord(ui, repo, commit, None, False,
1484 cmdutil.dorecord(ui, repo, commit, None, False,
1491 cmdutil.recordfilter, *pats, **opts)
1485 cmdutil.recordfilter, *pats, **opts)
1492 return
1486 return
1493
1487
1494 if opts.get('subrepos'):
1488 if opts.get('subrepos'):
1495 if opts.get('amend'):
1489 if opts.get('amend'):
1496 raise util.Abort(_('cannot amend with --subrepos'))
1490 raise util.Abort(_('cannot amend with --subrepos'))
1497 # Let --subrepos on the command line override config setting.
1491 # Let --subrepos on the command line override config setting.
1498 ui.setconfig('ui', 'commitsubrepos', True, 'commit')
1492 ui.setconfig('ui', 'commitsubrepos', True, 'commit')
1499
1493
1500 cmdutil.checkunfinished(repo, commit=True)
1494 cmdutil.checkunfinished(repo, commit=True)
1501
1495
1502 branch = repo[None].branch()
1496 branch = repo[None].branch()
1503 bheads = repo.branchheads(branch)
1497 bheads = repo.branchheads(branch)
1504
1498
1505 extra = {}
1499 extra = {}
1506 if opts.get('close_branch'):
1500 if opts.get('close_branch'):
1507 extra['close'] = 1
1501 extra['close'] = 1
1508
1502
1509 if not bheads:
1503 if not bheads:
1510 raise util.Abort(_('can only close branch heads'))
1504 raise util.Abort(_('can only close branch heads'))
1511 elif opts.get('amend'):
1505 elif opts.get('amend'):
1512 if repo.parents()[0].p1().branch() != branch and \
1506 if repo.parents()[0].p1().branch() != branch and \
1513 repo.parents()[0].p2().branch() != branch:
1507 repo.parents()[0].p2().branch() != branch:
1514 raise util.Abort(_('can only close branch heads'))
1508 raise util.Abort(_('can only close branch heads'))
1515
1509
1516 if opts.get('amend'):
1510 if opts.get('amend'):
1517 if ui.configbool('ui', 'commitsubrepos'):
1511 if ui.configbool('ui', 'commitsubrepos'):
1518 raise util.Abort(_('cannot amend with ui.commitsubrepos enabled'))
1512 raise util.Abort(_('cannot amend with ui.commitsubrepos enabled'))
1519
1513
1520 old = repo['.']
1514 old = repo['.']
1521 if not old.mutable():
1515 if not old.mutable():
1522 raise util.Abort(_('cannot amend public changesets'))
1516 raise util.Abort(_('cannot amend public changesets'))
1523 if len(repo[None].parents()) > 1:
1517 if len(repo[None].parents()) > 1:
1524 raise util.Abort(_('cannot amend while merging'))
1518 raise util.Abort(_('cannot amend while merging'))
1525 allowunstable = obsolete.isenabled(repo, obsolete.allowunstableopt)
1519 allowunstable = obsolete.isenabled(repo, obsolete.allowunstableopt)
1526 if not allowunstable and old.children():
1520 if not allowunstable and old.children():
1527 raise util.Abort(_('cannot amend changeset with children'))
1521 raise util.Abort(_('cannot amend changeset with children'))
1528
1522
1529 # commitfunc is used only for temporary amend commit by cmdutil.amend
1523 # commitfunc is used only for temporary amend commit by cmdutil.amend
1530 def commitfunc(ui, repo, message, match, opts):
1524 def commitfunc(ui, repo, message, match, opts):
1531 return repo.commit(message,
1525 return repo.commit(message,
1532 opts.get('user') or old.user(),
1526 opts.get('user') or old.user(),
1533 opts.get('date') or old.date(),
1527 opts.get('date') or old.date(),
1534 match,
1528 match,
1535 extra=extra)
1529 extra=extra)
1536
1530
1537 node = cmdutil.amend(ui, repo, commitfunc, old, extra, pats, opts)
1531 node = cmdutil.amend(ui, repo, commitfunc, old, extra, pats, opts)
1538 if node == old.node():
1532 if node == old.node():
1539 ui.status(_("nothing changed\n"))
1533 ui.status(_("nothing changed\n"))
1540 return 1
1534 return 1
1541 else:
1535 else:
1542 def commitfunc(ui, repo, message, match, opts):
1536 def commitfunc(ui, repo, message, match, opts):
1543 backup = ui.backupconfig('phases', 'new-commit')
1537 backup = ui.backupconfig('phases', 'new-commit')
1544 baseui = repo.baseui
1538 baseui = repo.baseui
1545 basebackup = baseui.backupconfig('phases', 'new-commit')
1539 basebackup = baseui.backupconfig('phases', 'new-commit')
1546 try:
1540 try:
1547 if opts.get('secret'):
1541 if opts.get('secret'):
1548 ui.setconfig('phases', 'new-commit', 'secret', 'commit')
1542 ui.setconfig('phases', 'new-commit', 'secret', 'commit')
1549 # Propagate to subrepos
1543 # Propagate to subrepos
1550 baseui.setconfig('phases', 'new-commit', 'secret', 'commit')
1544 baseui.setconfig('phases', 'new-commit', 'secret', 'commit')
1551
1545
1552 editform = cmdutil.mergeeditform(repo[None], 'commit.normal')
1546 editform = cmdutil.mergeeditform(repo[None], 'commit.normal')
1553 editor = cmdutil.getcommiteditor(editform=editform, **opts)
1547 editor = cmdutil.getcommiteditor(editform=editform, **opts)
1554 return repo.commit(message, opts.get('user'), opts.get('date'),
1548 return repo.commit(message, opts.get('user'), opts.get('date'),
1555 match,
1549 match,
1556 editor=editor,
1550 editor=editor,
1557 extra=extra)
1551 extra=extra)
1558 finally:
1552 finally:
1559 ui.restoreconfig(backup)
1553 ui.restoreconfig(backup)
1560 repo.baseui.restoreconfig(basebackup)
1554 repo.baseui.restoreconfig(basebackup)
1561
1555
1562
1556
1563 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1557 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1564
1558
1565 if not node:
1559 if not node:
1566 stat = repo.status(match=scmutil.match(repo[None], pats, opts))
1560 stat = repo.status(match=scmutil.match(repo[None], pats, opts))
1567 if stat[3]:
1561 if stat[3]:
1568 ui.status(_("nothing changed (%d missing files, see "
1562 ui.status(_("nothing changed (%d missing files, see "
1569 "'hg status')\n") % len(stat[3]))
1563 "'hg status')\n") % len(stat[3]))
1570 else:
1564 else:
1571 ui.status(_("nothing changed\n"))
1565 ui.status(_("nothing changed\n"))
1572 return 1
1566 return 1
1573
1567
1574 cmdutil.commitstatus(repo, node, branch, bheads, opts)
1568 cmdutil.commitstatus(repo, node, branch, bheads, opts)
1575
1569
1576 @command('config|showconfig|debugconfig',
1570 @command('config|showconfig|debugconfig',
1577 [('u', 'untrusted', None, _('show untrusted configuration options')),
1571 [('u', 'untrusted', None, _('show untrusted configuration options')),
1578 ('e', 'edit', None, _('edit user config')),
1572 ('e', 'edit', None, _('edit user config')),
1579 ('l', 'local', None, _('edit repository config')),
1573 ('l', 'local', None, _('edit repository config')),
1580 ('g', 'global', None, _('edit global config'))],
1574 ('g', 'global', None, _('edit global config'))],
1581 _('[-u] [NAME]...'),
1575 _('[-u] [NAME]...'),
1582 optionalrepo=True)
1576 optionalrepo=True)
1583 def config(ui, repo, *values, **opts):
1577 def config(ui, repo, *values, **opts):
1584 """show combined config settings from all hgrc files
1578 """show combined config settings from all hgrc files
1585
1579
1586 With no arguments, print names and values of all config items.
1580 With no arguments, print names and values of all config items.
1587
1581
1588 With one argument of the form section.name, print just the value
1582 With one argument of the form section.name, print just the value
1589 of that config item.
1583 of that config item.
1590
1584
1591 With multiple arguments, print names and values of all config
1585 With multiple arguments, print names and values of all config
1592 items with matching section names.
1586 items with matching section names.
1593
1587
1594 With --edit, start an editor on the user-level config file. With
1588 With --edit, start an editor on the user-level config file. With
1595 --global, edit the system-wide config file. With --local, edit the
1589 --global, edit the system-wide config file. With --local, edit the
1596 repository-level config file.
1590 repository-level config file.
1597
1591
1598 With --debug, the source (filename and line number) is printed
1592 With --debug, the source (filename and line number) is printed
1599 for each config item.
1593 for each config item.
1600
1594
1601 See :hg:`help config` for more information about config files.
1595 See :hg:`help config` for more information about config files.
1602
1596
1603 Returns 0 on success, 1 if NAME does not exist.
1597 Returns 0 on success, 1 if NAME does not exist.
1604
1598
1605 """
1599 """
1606
1600
1607 if opts.get('edit') or opts.get('local') or opts.get('global'):
1601 if opts.get('edit') or opts.get('local') or opts.get('global'):
1608 if opts.get('local') and opts.get('global'):
1602 if opts.get('local') and opts.get('global'):
1609 raise util.Abort(_("can't use --local and --global together"))
1603 raise util.Abort(_("can't use --local and --global together"))
1610
1604
1611 if opts.get('local'):
1605 if opts.get('local'):
1612 if not repo:
1606 if not repo:
1613 raise util.Abort(_("can't use --local outside a repository"))
1607 raise util.Abort(_("can't use --local outside a repository"))
1614 paths = [repo.join('hgrc')]
1608 paths = [repo.join('hgrc')]
1615 elif opts.get('global'):
1609 elif opts.get('global'):
1616 paths = scmutil.systemrcpath()
1610 paths = scmutil.systemrcpath()
1617 else:
1611 else:
1618 paths = scmutil.userrcpath()
1612 paths = scmutil.userrcpath()
1619
1613
1620 for f in paths:
1614 for f in paths:
1621 if os.path.exists(f):
1615 if os.path.exists(f):
1622 break
1616 break
1623 else:
1617 else:
1624 if opts.get('global'):
1618 if opts.get('global'):
1625 samplehgrc = uimod.samplehgrcs['global']
1619 samplehgrc = uimod.samplehgrcs['global']
1626 elif opts.get('local'):
1620 elif opts.get('local'):
1627 samplehgrc = uimod.samplehgrcs['local']
1621 samplehgrc = uimod.samplehgrcs['local']
1628 else:
1622 else:
1629 samplehgrc = uimod.samplehgrcs['user']
1623 samplehgrc = uimod.samplehgrcs['user']
1630
1624
1631 f = paths[0]
1625 f = paths[0]
1632 fp = open(f, "w")
1626 fp = open(f, "w")
1633 fp.write(samplehgrc)
1627 fp.write(samplehgrc)
1634 fp.close()
1628 fp.close()
1635
1629
1636 editor = ui.geteditor()
1630 editor = ui.geteditor()
1637 ui.system("%s \"%s\"" % (editor, f),
1631 ui.system("%s \"%s\"" % (editor, f),
1638 onerr=util.Abort, errprefix=_("edit failed"))
1632 onerr=util.Abort, errprefix=_("edit failed"))
1639 return
1633 return
1640
1634
1641 for f in scmutil.rcpath():
1635 for f in scmutil.rcpath():
1642 ui.debug('read config from: %s\n' % f)
1636 ui.debug('read config from: %s\n' % f)
1643 untrusted = bool(opts.get('untrusted'))
1637 untrusted = bool(opts.get('untrusted'))
1644 if values:
1638 if values:
1645 sections = [v for v in values if '.' not in v]
1639 sections = [v for v in values if '.' not in v]
1646 items = [v for v in values if '.' in v]
1640 items = [v for v in values if '.' in v]
1647 if len(items) > 1 or items and sections:
1641 if len(items) > 1 or items and sections:
1648 raise util.Abort(_('only one config item permitted'))
1642 raise util.Abort(_('only one config item permitted'))
1649 matched = False
1643 matched = False
1650 for section, name, value in ui.walkconfig(untrusted=untrusted):
1644 for section, name, value in ui.walkconfig(untrusted=untrusted):
1651 value = str(value).replace('\n', '\\n')
1645 value = str(value).replace('\n', '\\n')
1652 sectname = section + '.' + name
1646 sectname = section + '.' + name
1653 if values:
1647 if values:
1654 for v in values:
1648 for v in values:
1655 if v == section:
1649 if v == section:
1656 ui.debug('%s: ' %
1650 ui.debug('%s: ' %
1657 ui.configsource(section, name, untrusted))
1651 ui.configsource(section, name, untrusted))
1658 ui.write('%s=%s\n' % (sectname, value))
1652 ui.write('%s=%s\n' % (sectname, value))
1659 matched = True
1653 matched = True
1660 elif v == sectname:
1654 elif v == sectname:
1661 ui.debug('%s: ' %
1655 ui.debug('%s: ' %
1662 ui.configsource(section, name, untrusted))
1656 ui.configsource(section, name, untrusted))
1663 ui.write(value, '\n')
1657 ui.write(value, '\n')
1664 matched = True
1658 matched = True
1665 else:
1659 else:
1666 ui.debug('%s: ' %
1660 ui.debug('%s: ' %
1667 ui.configsource(section, name, untrusted))
1661 ui.configsource(section, name, untrusted))
1668 ui.write('%s=%s\n' % (sectname, value))
1662 ui.write('%s=%s\n' % (sectname, value))
1669 matched = True
1663 matched = True
1670 if matched:
1664 if matched:
1671 return 0
1665 return 0
1672 return 1
1666 return 1
1673
1667
1674 @command('copy|cp',
1668 @command('copy|cp',
1675 [('A', 'after', None, _('record a copy that has already occurred')),
1669 [('A', 'after', None, _('record a copy that has already occurred')),
1676 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1670 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1677 ] + walkopts + dryrunopts,
1671 ] + walkopts + dryrunopts,
1678 _('[OPTION]... [SOURCE]... DEST'))
1672 _('[OPTION]... [SOURCE]... DEST'))
1679 def copy(ui, repo, *pats, **opts):
1673 def copy(ui, repo, *pats, **opts):
1680 """mark files as copied for the next commit
1674 """mark files as copied for the next commit
1681
1675
1682 Mark dest as having copies of source files. If dest is a
1676 Mark dest as having copies of source files. If dest is a
1683 directory, copies are put in that directory. If dest is a file,
1677 directory, copies are put in that directory. If dest is a file,
1684 the source must be a single file.
1678 the source must be a single file.
1685
1679
1686 By default, this command copies the contents of files as they
1680 By default, this command copies the contents of files as they
1687 exist in the working directory. If invoked with -A/--after, the
1681 exist in the working directory. If invoked with -A/--after, the
1688 operation is recorded, but no copying is performed.
1682 operation is recorded, but no copying is performed.
1689
1683
1690 This command takes effect with the next commit. To undo a copy
1684 This command takes effect with the next commit. To undo a copy
1691 before that, see :hg:`revert`.
1685 before that, see :hg:`revert`.
1692
1686
1693 Returns 0 on success, 1 if errors are encountered.
1687 Returns 0 on success, 1 if errors are encountered.
1694 """
1688 """
1695 wlock = repo.wlock(False)
1689 wlock = repo.wlock(False)
1696 try:
1690 try:
1697 return cmdutil.copy(ui, repo, pats, opts)
1691 return cmdutil.copy(ui, repo, pats, opts)
1698 finally:
1692 finally:
1699 wlock.release()
1693 wlock.release()
1700
1694
1701 @command('debugancestor', [], _('[INDEX] REV1 REV2'), optionalrepo=True)
1695 @command('debugancestor', [], _('[INDEX] REV1 REV2'), optionalrepo=True)
1702 def debugancestor(ui, repo, *args):
1696 def debugancestor(ui, repo, *args):
1703 """find the ancestor revision of two revisions in a given index"""
1697 """find the ancestor revision of two revisions in a given index"""
1704 if len(args) == 3:
1698 if len(args) == 3:
1705 index, rev1, rev2 = args
1699 index, rev1, rev2 = args
1706 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), index)
1700 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), index)
1707 lookup = r.lookup
1701 lookup = r.lookup
1708 elif len(args) == 2:
1702 elif len(args) == 2:
1709 if not repo:
1703 if not repo:
1710 raise util.Abort(_("there is no Mercurial repository here "
1704 raise util.Abort(_("there is no Mercurial repository here "
1711 "(.hg not found)"))
1705 "(.hg not found)"))
1712 rev1, rev2 = args
1706 rev1, rev2 = args
1713 r = repo.changelog
1707 r = repo.changelog
1714 lookup = repo.lookup
1708 lookup = repo.lookup
1715 else:
1709 else:
1716 raise util.Abort(_('either two or three arguments required'))
1710 raise util.Abort(_('either two or three arguments required'))
1717 a = r.ancestor(lookup(rev1), lookup(rev2))
1711 a = r.ancestor(lookup(rev1), lookup(rev2))
1718 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
1712 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
1719
1713
1720 @command('debugbuilddag',
1714 @command('debugbuilddag',
1721 [('m', 'mergeable-file', None, _('add single file mergeable changes')),
1715 [('m', 'mergeable-file', None, _('add single file mergeable changes')),
1722 ('o', 'overwritten-file', None, _('add single file all revs overwrite')),
1716 ('o', 'overwritten-file', None, _('add single file all revs overwrite')),
1723 ('n', 'new-file', None, _('add new file at each rev'))],
1717 ('n', 'new-file', None, _('add new file at each rev'))],
1724 _('[OPTION]... [TEXT]'))
1718 _('[OPTION]... [TEXT]'))
1725 def debugbuilddag(ui, repo, text=None,
1719 def debugbuilddag(ui, repo, text=None,
1726 mergeable_file=False,
1720 mergeable_file=False,
1727 overwritten_file=False,
1721 overwritten_file=False,
1728 new_file=False):
1722 new_file=False):
1729 """builds a repo with a given DAG from scratch in the current empty repo
1723 """builds a repo with a given DAG from scratch in the current empty repo
1730
1724
1731 The description of the DAG is read from stdin if not given on the
1725 The description of the DAG is read from stdin if not given on the
1732 command line.
1726 command line.
1733
1727
1734 Elements:
1728 Elements:
1735
1729
1736 - "+n" is a linear run of n nodes based on the current default parent
1730 - "+n" is a linear run of n nodes based on the current default parent
1737 - "." is a single node based on the current default parent
1731 - "." is a single node based on the current default parent
1738 - "$" resets the default parent to null (implied at the start);
1732 - "$" resets the default parent to null (implied at the start);
1739 otherwise the default parent is always the last node created
1733 otherwise the default parent is always the last node created
1740 - "<p" sets the default parent to the backref p
1734 - "<p" sets the default parent to the backref p
1741 - "*p" is a fork at parent p, which is a backref
1735 - "*p" is a fork at parent p, which is a backref
1742 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
1736 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
1743 - "/p2" is a merge of the preceding node and p2
1737 - "/p2" is a merge of the preceding node and p2
1744 - ":tag" defines a local tag for the preceding node
1738 - ":tag" defines a local tag for the preceding node
1745 - "@branch" sets the named branch for subsequent nodes
1739 - "@branch" sets the named branch for subsequent nodes
1746 - "#...\\n" is a comment up to the end of the line
1740 - "#...\\n" is a comment up to the end of the line
1747
1741
1748 Whitespace between the above elements is ignored.
1742 Whitespace between the above elements is ignored.
1749
1743
1750 A backref is either
1744 A backref is either
1751
1745
1752 - a number n, which references the node curr-n, where curr is the current
1746 - a number n, which references the node curr-n, where curr is the current
1753 node, or
1747 node, or
1754 - the name of a local tag you placed earlier using ":tag", or
1748 - the name of a local tag you placed earlier using ":tag", or
1755 - empty to denote the default parent.
1749 - empty to denote the default parent.
1756
1750
1757 All string valued-elements are either strictly alphanumeric, or must
1751 All string valued-elements are either strictly alphanumeric, or must
1758 be enclosed in double quotes ("..."), with "\\" as escape character.
1752 be enclosed in double quotes ("..."), with "\\" as escape character.
1759 """
1753 """
1760
1754
1761 if text is None:
1755 if text is None:
1762 ui.status(_("reading DAG from stdin\n"))
1756 ui.status(_("reading DAG from stdin\n"))
1763 text = ui.fin.read()
1757 text = ui.fin.read()
1764
1758
1765 cl = repo.changelog
1759 cl = repo.changelog
1766 if len(cl) > 0:
1760 if len(cl) > 0:
1767 raise util.Abort(_('repository is not empty'))
1761 raise util.Abort(_('repository is not empty'))
1768
1762
1769 # determine number of revs in DAG
1763 # determine number of revs in DAG
1770 total = 0
1764 total = 0
1771 for type, data in dagparser.parsedag(text):
1765 for type, data in dagparser.parsedag(text):
1772 if type == 'n':
1766 if type == 'n':
1773 total += 1
1767 total += 1
1774
1768
1775 if mergeable_file:
1769 if mergeable_file:
1776 linesperrev = 2
1770 linesperrev = 2
1777 # make a file with k lines per rev
1771 # make a file with k lines per rev
1778 initialmergedlines = [str(i) for i in xrange(0, total * linesperrev)]
1772 initialmergedlines = [str(i) for i in xrange(0, total * linesperrev)]
1779 initialmergedlines.append("")
1773 initialmergedlines.append("")
1780
1774
1781 tags = []
1775 tags = []
1782
1776
1783 lock = tr = None
1777 lock = tr = None
1784 try:
1778 try:
1785 lock = repo.lock()
1779 lock = repo.lock()
1786 tr = repo.transaction("builddag")
1780 tr = repo.transaction("builddag")
1787
1781
1788 at = -1
1782 at = -1
1789 atbranch = 'default'
1783 atbranch = 'default'
1790 nodeids = []
1784 nodeids = []
1791 id = 0
1785 id = 0
1792 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1786 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1793 for type, data in dagparser.parsedag(text):
1787 for type, data in dagparser.parsedag(text):
1794 if type == 'n':
1788 if type == 'n':
1795 ui.note(('node %s\n' % str(data)))
1789 ui.note(('node %s\n' % str(data)))
1796 id, ps = data
1790 id, ps = data
1797
1791
1798 files = []
1792 files = []
1799 fctxs = {}
1793 fctxs = {}
1800
1794
1801 p2 = None
1795 p2 = None
1802 if mergeable_file:
1796 if mergeable_file:
1803 fn = "mf"
1797 fn = "mf"
1804 p1 = repo[ps[0]]
1798 p1 = repo[ps[0]]
1805 if len(ps) > 1:
1799 if len(ps) > 1:
1806 p2 = repo[ps[1]]
1800 p2 = repo[ps[1]]
1807 pa = p1.ancestor(p2)
1801 pa = p1.ancestor(p2)
1808 base, local, other = [x[fn].data() for x in (pa, p1,
1802 base, local, other = [x[fn].data() for x in (pa, p1,
1809 p2)]
1803 p2)]
1810 m3 = simplemerge.Merge3Text(base, local, other)
1804 m3 = simplemerge.Merge3Text(base, local, other)
1811 ml = [l.strip() for l in m3.merge_lines()]
1805 ml = [l.strip() for l in m3.merge_lines()]
1812 ml.append("")
1806 ml.append("")
1813 elif at > 0:
1807 elif at > 0:
1814 ml = p1[fn].data().split("\n")
1808 ml = p1[fn].data().split("\n")
1815 else:
1809 else:
1816 ml = initialmergedlines
1810 ml = initialmergedlines
1817 ml[id * linesperrev] += " r%i" % id
1811 ml[id * linesperrev] += " r%i" % id
1818 mergedtext = "\n".join(ml)
1812 mergedtext = "\n".join(ml)
1819 files.append(fn)
1813 files.append(fn)
1820 fctxs[fn] = context.memfilectx(repo, fn, mergedtext)
1814 fctxs[fn] = context.memfilectx(repo, fn, mergedtext)
1821
1815
1822 if overwritten_file:
1816 if overwritten_file:
1823 fn = "of"
1817 fn = "of"
1824 files.append(fn)
1818 files.append(fn)
1825 fctxs[fn] = context.memfilectx(repo, fn, "r%i\n" % id)
1819 fctxs[fn] = context.memfilectx(repo, fn, "r%i\n" % id)
1826
1820
1827 if new_file:
1821 if new_file:
1828 fn = "nf%i" % id
1822 fn = "nf%i" % id
1829 files.append(fn)
1823 files.append(fn)
1830 fctxs[fn] = context.memfilectx(repo, fn, "r%i\n" % id)
1824 fctxs[fn] = context.memfilectx(repo, fn, "r%i\n" % id)
1831 if len(ps) > 1:
1825 if len(ps) > 1:
1832 if not p2:
1826 if not p2:
1833 p2 = repo[ps[1]]
1827 p2 = repo[ps[1]]
1834 for fn in p2:
1828 for fn in p2:
1835 if fn.startswith("nf"):
1829 if fn.startswith("nf"):
1836 files.append(fn)
1830 files.append(fn)
1837 fctxs[fn] = p2[fn]
1831 fctxs[fn] = p2[fn]
1838
1832
1839 def fctxfn(repo, cx, path):
1833 def fctxfn(repo, cx, path):
1840 return fctxs.get(path)
1834 return fctxs.get(path)
1841
1835
1842 if len(ps) == 0 or ps[0] < 0:
1836 if len(ps) == 0 or ps[0] < 0:
1843 pars = [None, None]
1837 pars = [None, None]
1844 elif len(ps) == 1:
1838 elif len(ps) == 1:
1845 pars = [nodeids[ps[0]], None]
1839 pars = [nodeids[ps[0]], None]
1846 else:
1840 else:
1847 pars = [nodeids[p] for p in ps]
1841 pars = [nodeids[p] for p in ps]
1848 cx = context.memctx(repo, pars, "r%i" % id, files, fctxfn,
1842 cx = context.memctx(repo, pars, "r%i" % id, files, fctxfn,
1849 date=(id, 0),
1843 date=(id, 0),
1850 user="debugbuilddag",
1844 user="debugbuilddag",
1851 extra={'branch': atbranch})
1845 extra={'branch': atbranch})
1852 nodeid = repo.commitctx(cx)
1846 nodeid = repo.commitctx(cx)
1853 nodeids.append(nodeid)
1847 nodeids.append(nodeid)
1854 at = id
1848 at = id
1855 elif type == 'l':
1849 elif type == 'l':
1856 id, name = data
1850 id, name = data
1857 ui.note(('tag %s\n' % name))
1851 ui.note(('tag %s\n' % name))
1858 tags.append("%s %s\n" % (hex(repo.changelog.node(id)), name))
1852 tags.append("%s %s\n" % (hex(repo.changelog.node(id)), name))
1859 elif type == 'a':
1853 elif type == 'a':
1860 ui.note(('branch %s\n' % data))
1854 ui.note(('branch %s\n' % data))
1861 atbranch = data
1855 atbranch = data
1862 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1856 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1863 tr.close()
1857 tr.close()
1864
1858
1865 if tags:
1859 if tags:
1866 repo.vfs.write("localtags", "".join(tags))
1860 repo.vfs.write("localtags", "".join(tags))
1867 finally:
1861 finally:
1868 ui.progress(_('building'), None)
1862 ui.progress(_('building'), None)
1869 release(tr, lock)
1863 release(tr, lock)
1870
1864
1871 @command('debugbundle',
1865 @command('debugbundle',
1872 [('a', 'all', None, _('show all details'))],
1866 [('a', 'all', None, _('show all details'))],
1873 _('FILE'),
1867 _('FILE'),
1874 norepo=True)
1868 norepo=True)
1875 def debugbundle(ui, bundlepath, all=None, **opts):
1869 def debugbundle(ui, bundlepath, all=None, **opts):
1876 """lists the contents of a bundle"""
1870 """lists the contents of a bundle"""
1877 f = hg.openpath(ui, bundlepath)
1871 f = hg.openpath(ui, bundlepath)
1878 try:
1872 try:
1879 gen = exchange.readbundle(ui, f, bundlepath)
1873 gen = exchange.readbundle(ui, f, bundlepath)
1880 if isinstance(gen, bundle2.unbundle20):
1874 if isinstance(gen, bundle2.unbundle20):
1881 return _debugbundle2(ui, gen, all=all, **opts)
1875 return _debugbundle2(ui, gen, all=all, **opts)
1882 if all:
1876 if all:
1883 ui.write(("format: id, p1, p2, cset, delta base, len(delta)\n"))
1877 ui.write(("format: id, p1, p2, cset, delta base, len(delta)\n"))
1884
1878
1885 def showchunks(named):
1879 def showchunks(named):
1886 ui.write("\n%s\n" % named)
1880 ui.write("\n%s\n" % named)
1887 chain = None
1881 chain = None
1888 while True:
1882 while True:
1889 chunkdata = gen.deltachunk(chain)
1883 chunkdata = gen.deltachunk(chain)
1890 if not chunkdata:
1884 if not chunkdata:
1891 break
1885 break
1892 node = chunkdata['node']
1886 node = chunkdata['node']
1893 p1 = chunkdata['p1']
1887 p1 = chunkdata['p1']
1894 p2 = chunkdata['p2']
1888 p2 = chunkdata['p2']
1895 cs = chunkdata['cs']
1889 cs = chunkdata['cs']
1896 deltabase = chunkdata['deltabase']
1890 deltabase = chunkdata['deltabase']
1897 delta = chunkdata['delta']
1891 delta = chunkdata['delta']
1898 ui.write("%s %s %s %s %s %s\n" %
1892 ui.write("%s %s %s %s %s %s\n" %
1899 (hex(node), hex(p1), hex(p2),
1893 (hex(node), hex(p1), hex(p2),
1900 hex(cs), hex(deltabase), len(delta)))
1894 hex(cs), hex(deltabase), len(delta)))
1901 chain = node
1895 chain = node
1902
1896
1903 chunkdata = gen.changelogheader()
1897 chunkdata = gen.changelogheader()
1904 showchunks("changelog")
1898 showchunks("changelog")
1905 chunkdata = gen.manifestheader()
1899 chunkdata = gen.manifestheader()
1906 showchunks("manifest")
1900 showchunks("manifest")
1907 while True:
1901 while True:
1908 chunkdata = gen.filelogheader()
1902 chunkdata = gen.filelogheader()
1909 if not chunkdata:
1903 if not chunkdata:
1910 break
1904 break
1911 fname = chunkdata['filename']
1905 fname = chunkdata['filename']
1912 showchunks(fname)
1906 showchunks(fname)
1913 else:
1907 else:
1914 if isinstance(gen, bundle2.unbundle20):
1908 if isinstance(gen, bundle2.unbundle20):
1915 raise util.Abort(_('use debugbundle2 for this file'))
1909 raise util.Abort(_('use debugbundle2 for this file'))
1916 chunkdata = gen.changelogheader()
1910 chunkdata = gen.changelogheader()
1917 chain = None
1911 chain = None
1918 while True:
1912 while True:
1919 chunkdata = gen.deltachunk(chain)
1913 chunkdata = gen.deltachunk(chain)
1920 if not chunkdata:
1914 if not chunkdata:
1921 break
1915 break
1922 node = chunkdata['node']
1916 node = chunkdata['node']
1923 ui.write("%s\n" % hex(node))
1917 ui.write("%s\n" % hex(node))
1924 chain = node
1918 chain = node
1925 finally:
1919 finally:
1926 f.close()
1920 f.close()
1927
1921
1928 def _debugbundle2(ui, gen, **opts):
1922 def _debugbundle2(ui, gen, **opts):
1929 """lists the contents of a bundle2"""
1923 """lists the contents of a bundle2"""
1930 if not isinstance(gen, bundle2.unbundle20):
1924 if not isinstance(gen, bundle2.unbundle20):
1931 raise util.Abort(_('not a bundle2 file'))
1925 raise util.Abort(_('not a bundle2 file'))
1932 ui.write(('Stream params: %s\n' % repr(gen.params)))
1926 ui.write(('Stream params: %s\n' % repr(gen.params)))
1933 for part in gen.iterparts():
1927 for part in gen.iterparts():
1934 ui.write('%s -- %r\n' % (part.type, repr(part.params)))
1928 ui.write('%s -- %r\n' % (part.type, repr(part.params)))
1935 if part.type == 'changegroup':
1929 if part.type == 'changegroup':
1936 version = part.params.get('version', '01')
1930 version = part.params.get('version', '01')
1937 cg = changegroup.packermap[version][1](part, 'UN')
1931 cg = changegroup.packermap[version][1](part, 'UN')
1938 chunkdata = cg.changelogheader()
1932 chunkdata = cg.changelogheader()
1939 chain = None
1933 chain = None
1940 while True:
1934 while True:
1941 chunkdata = cg.deltachunk(chain)
1935 chunkdata = cg.deltachunk(chain)
1942 if not chunkdata:
1936 if not chunkdata:
1943 break
1937 break
1944 node = chunkdata['node']
1938 node = chunkdata['node']
1945 ui.write(" %s\n" % hex(node))
1939 ui.write(" %s\n" % hex(node))
1946 chain = node
1940 chain = node
1947
1941
1948 @command('debugcheckstate', [], '')
1942 @command('debugcheckstate', [], '')
1949 def debugcheckstate(ui, repo):
1943 def debugcheckstate(ui, repo):
1950 """validate the correctness of the current dirstate"""
1944 """validate the correctness of the current dirstate"""
1951 parent1, parent2 = repo.dirstate.parents()
1945 parent1, parent2 = repo.dirstate.parents()
1952 m1 = repo[parent1].manifest()
1946 m1 = repo[parent1].manifest()
1953 m2 = repo[parent2].manifest()
1947 m2 = repo[parent2].manifest()
1954 errors = 0
1948 errors = 0
1955 for f in repo.dirstate:
1949 for f in repo.dirstate:
1956 state = repo.dirstate[f]
1950 state = repo.dirstate[f]
1957 if state in "nr" and f not in m1:
1951 if state in "nr" and f not in m1:
1958 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
1952 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
1959 errors += 1
1953 errors += 1
1960 if state in "a" and f in m1:
1954 if state in "a" and f in m1:
1961 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
1955 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
1962 errors += 1
1956 errors += 1
1963 if state in "m" and f not in m1 and f not in m2:
1957 if state in "m" and f not in m1 and f not in m2:
1964 ui.warn(_("%s in state %s, but not in either manifest\n") %
1958 ui.warn(_("%s in state %s, but not in either manifest\n") %
1965 (f, state))
1959 (f, state))
1966 errors += 1
1960 errors += 1
1967 for f in m1:
1961 for f in m1:
1968 state = repo.dirstate[f]
1962 state = repo.dirstate[f]
1969 if state not in "nrm":
1963 if state not in "nrm":
1970 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
1964 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
1971 errors += 1
1965 errors += 1
1972 if errors:
1966 if errors:
1973 error = _(".hg/dirstate inconsistent with current parent's manifest")
1967 error = _(".hg/dirstate inconsistent with current parent's manifest")
1974 raise util.Abort(error)
1968 raise util.Abort(error)
1975
1969
1976 @command('debugcommands', [], _('[COMMAND]'), norepo=True)
1970 @command('debugcommands', [], _('[COMMAND]'), norepo=True)
1977 def debugcommands(ui, cmd='', *args):
1971 def debugcommands(ui, cmd='', *args):
1978 """list all available commands and options"""
1972 """list all available commands and options"""
1979 for cmd, vals in sorted(table.iteritems()):
1973 for cmd, vals in sorted(table.iteritems()):
1980 cmd = cmd.split('|')[0].strip('^')
1974 cmd = cmd.split('|')[0].strip('^')
1981 opts = ', '.join([i[1] for i in vals[1]])
1975 opts = ', '.join([i[1] for i in vals[1]])
1982 ui.write('%s: %s\n' % (cmd, opts))
1976 ui.write('%s: %s\n' % (cmd, opts))
1983
1977
1984 @command('debugcomplete',
1978 @command('debugcomplete',
1985 [('o', 'options', None, _('show the command options'))],
1979 [('o', 'options', None, _('show the command options'))],
1986 _('[-o] CMD'),
1980 _('[-o] CMD'),
1987 norepo=True)
1981 norepo=True)
1988 def debugcomplete(ui, cmd='', **opts):
1982 def debugcomplete(ui, cmd='', **opts):
1989 """returns the completion list associated with the given command"""
1983 """returns the completion list associated with the given command"""
1990
1984
1991 if opts.get('options'):
1985 if opts.get('options'):
1992 options = []
1986 options = []
1993 otables = [globalopts]
1987 otables = [globalopts]
1994 if cmd:
1988 if cmd:
1995 aliases, entry = cmdutil.findcmd(cmd, table, False)
1989 aliases, entry = cmdutil.findcmd(cmd, table, False)
1996 otables.append(entry[1])
1990 otables.append(entry[1])
1997 for t in otables:
1991 for t in otables:
1998 for o in t:
1992 for o in t:
1999 if "(DEPRECATED)" in o[3]:
1993 if "(DEPRECATED)" in o[3]:
2000 continue
1994 continue
2001 if o[0]:
1995 if o[0]:
2002 options.append('-%s' % o[0])
1996 options.append('-%s' % o[0])
2003 options.append('--%s' % o[1])
1997 options.append('--%s' % o[1])
2004 ui.write("%s\n" % "\n".join(options))
1998 ui.write("%s\n" % "\n".join(options))
2005 return
1999 return
2006
2000
2007 cmdlist, unused_allcmds = cmdutil.findpossible(cmd, table)
2001 cmdlist, unused_allcmds = cmdutil.findpossible(cmd, table)
2008 if ui.verbose:
2002 if ui.verbose:
2009 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
2003 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
2010 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
2004 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
2011
2005
2012 @command('debugdag',
2006 @command('debugdag',
2013 [('t', 'tags', None, _('use tags as labels')),
2007 [('t', 'tags', None, _('use tags as labels')),
2014 ('b', 'branches', None, _('annotate with branch names')),
2008 ('b', 'branches', None, _('annotate with branch names')),
2015 ('', 'dots', None, _('use dots for runs')),
2009 ('', 'dots', None, _('use dots for runs')),
2016 ('s', 'spaces', None, _('separate elements by spaces'))],
2010 ('s', 'spaces', None, _('separate elements by spaces'))],
2017 _('[OPTION]... [FILE [REV]...]'),
2011 _('[OPTION]... [FILE [REV]...]'),
2018 optionalrepo=True)
2012 optionalrepo=True)
2019 def debugdag(ui, repo, file_=None, *revs, **opts):
2013 def debugdag(ui, repo, file_=None, *revs, **opts):
2020 """format the changelog or an index DAG as a concise textual description
2014 """format the changelog or an index DAG as a concise textual description
2021
2015
2022 If you pass a revlog index, the revlog's DAG is emitted. If you list
2016 If you pass a revlog index, the revlog's DAG is emitted. If you list
2023 revision numbers, they get labeled in the output as rN.
2017 revision numbers, they get labeled in the output as rN.
2024
2018
2025 Otherwise, the changelog DAG of the current repo is emitted.
2019 Otherwise, the changelog DAG of the current repo is emitted.
2026 """
2020 """
2027 spaces = opts.get('spaces')
2021 spaces = opts.get('spaces')
2028 dots = opts.get('dots')
2022 dots = opts.get('dots')
2029 if file_:
2023 if file_:
2030 rlog = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
2024 rlog = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
2031 revs = set((int(r) for r in revs))
2025 revs = set((int(r) for r in revs))
2032 def events():
2026 def events():
2033 for r in rlog:
2027 for r in rlog:
2034 yield 'n', (r, list(p for p in rlog.parentrevs(r)
2028 yield 'n', (r, list(p for p in rlog.parentrevs(r)
2035 if p != -1))
2029 if p != -1))
2036 if r in revs:
2030 if r in revs:
2037 yield 'l', (r, "r%i" % r)
2031 yield 'l', (r, "r%i" % r)
2038 elif repo:
2032 elif repo:
2039 cl = repo.changelog
2033 cl = repo.changelog
2040 tags = opts.get('tags')
2034 tags = opts.get('tags')
2041 branches = opts.get('branches')
2035 branches = opts.get('branches')
2042 if tags:
2036 if tags:
2043 labels = {}
2037 labels = {}
2044 for l, n in repo.tags().items():
2038 for l, n in repo.tags().items():
2045 labels.setdefault(cl.rev(n), []).append(l)
2039 labels.setdefault(cl.rev(n), []).append(l)
2046 def events():
2040 def events():
2047 b = "default"
2041 b = "default"
2048 for r in cl:
2042 for r in cl:
2049 if branches:
2043 if branches:
2050 newb = cl.read(cl.node(r))[5]['branch']
2044 newb = cl.read(cl.node(r))[5]['branch']
2051 if newb != b:
2045 if newb != b:
2052 yield 'a', newb
2046 yield 'a', newb
2053 b = newb
2047 b = newb
2054 yield 'n', (r, list(p for p in cl.parentrevs(r)
2048 yield 'n', (r, list(p for p in cl.parentrevs(r)
2055 if p != -1))
2049 if p != -1))
2056 if tags:
2050 if tags:
2057 ls = labels.get(r)
2051 ls = labels.get(r)
2058 if ls:
2052 if ls:
2059 for l in ls:
2053 for l in ls:
2060 yield 'l', (r, l)
2054 yield 'l', (r, l)
2061 else:
2055 else:
2062 raise util.Abort(_('need repo for changelog dag'))
2056 raise util.Abort(_('need repo for changelog dag'))
2063
2057
2064 for line in dagparser.dagtextlines(events(),
2058 for line in dagparser.dagtextlines(events(),
2065 addspaces=spaces,
2059 addspaces=spaces,
2066 wraplabels=True,
2060 wraplabels=True,
2067 wrapannotations=True,
2061 wrapannotations=True,
2068 wrapnonlinear=dots,
2062 wrapnonlinear=dots,
2069 usedots=dots,
2063 usedots=dots,
2070 maxlinewidth=70):
2064 maxlinewidth=70):
2071 ui.write(line)
2065 ui.write(line)
2072 ui.write("\n")
2066 ui.write("\n")
2073
2067
2074 @command('debugdata',
2068 @command('debugdata',
2075 [('c', 'changelog', False, _('open changelog')),
2069 [('c', 'changelog', False, _('open changelog')),
2076 ('m', 'manifest', False, _('open manifest')),
2070 ('m', 'manifest', False, _('open manifest')),
2077 ('', 'dir', False, _('open directory manifest'))],
2071 ('', 'dir', False, _('open directory manifest'))],
2078 _('-c|-m|FILE REV'))
2072 _('-c|-m|FILE REV'))
2079 def debugdata(ui, repo, file_, rev=None, **opts):
2073 def debugdata(ui, repo, file_, rev=None, **opts):
2080 """dump the contents of a data file revision"""
2074 """dump the contents of a data file revision"""
2081 if opts.get('changelog') or opts.get('manifest'):
2075 if opts.get('changelog') or opts.get('manifest'):
2082 file_, rev = None, file_
2076 file_, rev = None, file_
2083 elif rev is None:
2077 elif rev is None:
2084 raise error.CommandError('debugdata', _('invalid arguments'))
2078 raise error.CommandError('debugdata', _('invalid arguments'))
2085 r = cmdutil.openrevlog(repo, 'debugdata', file_, opts)
2079 r = cmdutil.openrevlog(repo, 'debugdata', file_, opts)
2086 try:
2080 try:
2087 ui.write(r.revision(r.lookup(rev)))
2081 ui.write(r.revision(r.lookup(rev)))
2088 except KeyError:
2082 except KeyError:
2089 raise util.Abort(_('invalid revision identifier %s') % rev)
2083 raise util.Abort(_('invalid revision identifier %s') % rev)
2090
2084
2091 @command('debugdate',
2085 @command('debugdate',
2092 [('e', 'extended', None, _('try extended date formats'))],
2086 [('e', 'extended', None, _('try extended date formats'))],
2093 _('[-e] DATE [RANGE]'),
2087 _('[-e] DATE [RANGE]'),
2094 norepo=True, optionalrepo=True)
2088 norepo=True, optionalrepo=True)
2095 def debugdate(ui, date, range=None, **opts):
2089 def debugdate(ui, date, range=None, **opts):
2096 """parse and display a date"""
2090 """parse and display a date"""
2097 if opts["extended"]:
2091 if opts["extended"]:
2098 d = util.parsedate(date, util.extendeddateformats)
2092 d = util.parsedate(date, util.extendeddateformats)
2099 else:
2093 else:
2100 d = util.parsedate(date)
2094 d = util.parsedate(date)
2101 ui.write(("internal: %s %s\n") % d)
2095 ui.write(("internal: %s %s\n") % d)
2102 ui.write(("standard: %s\n") % util.datestr(d))
2096 ui.write(("standard: %s\n") % util.datestr(d))
2103 if range:
2097 if range:
2104 m = util.matchdate(range)
2098 m = util.matchdate(range)
2105 ui.write(("match: %s\n") % m(d[0]))
2099 ui.write(("match: %s\n") % m(d[0]))
2106
2100
2107 @command('debugdiscovery',
2101 @command('debugdiscovery',
2108 [('', 'old', None, _('use old-style discovery')),
2102 [('', 'old', None, _('use old-style discovery')),
2109 ('', 'nonheads', None,
2103 ('', 'nonheads', None,
2110 _('use old-style discovery with non-heads included')),
2104 _('use old-style discovery with non-heads included')),
2111 ] + remoteopts,
2105 ] + remoteopts,
2112 _('[-l REV] [-r REV] [-b BRANCH]... [OTHER]'))
2106 _('[-l REV] [-r REV] [-b BRANCH]... [OTHER]'))
2113 def debugdiscovery(ui, repo, remoteurl="default", **opts):
2107 def debugdiscovery(ui, repo, remoteurl="default", **opts):
2114 """runs the changeset discovery protocol in isolation"""
2108 """runs the changeset discovery protocol in isolation"""
2115 remoteurl, branches = hg.parseurl(ui.expandpath(remoteurl),
2109 remoteurl, branches = hg.parseurl(ui.expandpath(remoteurl),
2116 opts.get('branch'))
2110 opts.get('branch'))
2117 remote = hg.peer(repo, opts, remoteurl)
2111 remote = hg.peer(repo, opts, remoteurl)
2118 ui.status(_('comparing with %s\n') % util.hidepassword(remoteurl))
2112 ui.status(_('comparing with %s\n') % util.hidepassword(remoteurl))
2119
2113
2120 # make sure tests are repeatable
2114 # make sure tests are repeatable
2121 random.seed(12323)
2115 random.seed(12323)
2122
2116
2123 def doit(localheads, remoteheads, remote=remote):
2117 def doit(localheads, remoteheads, remote=remote):
2124 if opts.get('old'):
2118 if opts.get('old'):
2125 if localheads:
2119 if localheads:
2126 raise util.Abort('cannot use localheads with old style '
2120 raise util.Abort('cannot use localheads with old style '
2127 'discovery')
2121 'discovery')
2128 if not util.safehasattr(remote, 'branches'):
2122 if not util.safehasattr(remote, 'branches'):
2129 # enable in-client legacy support
2123 # enable in-client legacy support
2130 remote = localrepo.locallegacypeer(remote.local())
2124 remote = localrepo.locallegacypeer(remote.local())
2131 common, _in, hds = treediscovery.findcommonincoming(repo, remote,
2125 common, _in, hds = treediscovery.findcommonincoming(repo, remote,
2132 force=True)
2126 force=True)
2133 common = set(common)
2127 common = set(common)
2134 if not opts.get('nonheads'):
2128 if not opts.get('nonheads'):
2135 ui.write(("unpruned common: %s\n") %
2129 ui.write(("unpruned common: %s\n") %
2136 " ".join(sorted(short(n) for n in common)))
2130 " ".join(sorted(short(n) for n in common)))
2137 dag = dagutil.revlogdag(repo.changelog)
2131 dag = dagutil.revlogdag(repo.changelog)
2138 all = dag.ancestorset(dag.internalizeall(common))
2132 all = dag.ancestorset(dag.internalizeall(common))
2139 common = dag.externalizeall(dag.headsetofconnecteds(all))
2133 common = dag.externalizeall(dag.headsetofconnecteds(all))
2140 else:
2134 else:
2141 common, any, hds = setdiscovery.findcommonheads(ui, repo, remote)
2135 common, any, hds = setdiscovery.findcommonheads(ui, repo, remote)
2142 common = set(common)
2136 common = set(common)
2143 rheads = set(hds)
2137 rheads = set(hds)
2144 lheads = set(repo.heads())
2138 lheads = set(repo.heads())
2145 ui.write(("common heads: %s\n") %
2139 ui.write(("common heads: %s\n") %
2146 " ".join(sorted(short(n) for n in common)))
2140 " ".join(sorted(short(n) for n in common)))
2147 if lheads <= common:
2141 if lheads <= common:
2148 ui.write(("local is subset\n"))
2142 ui.write(("local is subset\n"))
2149 elif rheads <= common:
2143 elif rheads <= common:
2150 ui.write(("remote is subset\n"))
2144 ui.write(("remote is subset\n"))
2151
2145
2152 serverlogs = opts.get('serverlog')
2146 serverlogs = opts.get('serverlog')
2153 if serverlogs:
2147 if serverlogs:
2154 for filename in serverlogs:
2148 for filename in serverlogs:
2155 logfile = open(filename, 'r')
2149 logfile = open(filename, 'r')
2156 try:
2150 try:
2157 line = logfile.readline()
2151 line = logfile.readline()
2158 while line:
2152 while line:
2159 parts = line.strip().split(';')
2153 parts = line.strip().split(';')
2160 op = parts[1]
2154 op = parts[1]
2161 if op == 'cg':
2155 if op == 'cg':
2162 pass
2156 pass
2163 elif op == 'cgss':
2157 elif op == 'cgss':
2164 doit(parts[2].split(' '), parts[3].split(' '))
2158 doit(parts[2].split(' '), parts[3].split(' '))
2165 elif op == 'unb':
2159 elif op == 'unb':
2166 doit(parts[3].split(' '), parts[2].split(' '))
2160 doit(parts[3].split(' '), parts[2].split(' '))
2167 line = logfile.readline()
2161 line = logfile.readline()
2168 finally:
2162 finally:
2169 logfile.close()
2163 logfile.close()
2170
2164
2171 else:
2165 else:
2172 remoterevs, _checkout = hg.addbranchrevs(repo, remote, branches,
2166 remoterevs, _checkout = hg.addbranchrevs(repo, remote, branches,
2173 opts.get('remote_head'))
2167 opts.get('remote_head'))
2174 localrevs = opts.get('local_head')
2168 localrevs = opts.get('local_head')
2175 doit(localrevs, remoterevs)
2169 doit(localrevs, remoterevs)
2176
2170
2177 @command('debugextensions', formatteropts, [], norepo=True)
2171 @command('debugextensions', formatteropts, [], norepo=True)
2178 def debugextensions(ui, **opts):
2172 def debugextensions(ui, **opts):
2179 '''show information about active extensions'''
2173 '''show information about active extensions'''
2180 exts = extensions.extensions(ui)
2174 exts = extensions.extensions(ui)
2181 fm = ui.formatter('debugextensions', opts)
2175 fm = ui.formatter('debugextensions', opts)
2182 for extname, extmod in sorted(exts, key=operator.itemgetter(0)):
2176 for extname, extmod in sorted(exts, key=operator.itemgetter(0)):
2183 extsource = extmod.__file__
2177 extsource = extmod.__file__
2184 exttestedwith = getattr(extmod, 'testedwith', None)
2178 exttestedwith = getattr(extmod, 'testedwith', None)
2185 if exttestedwith is not None:
2179 if exttestedwith is not None:
2186 exttestedwith = exttestedwith.split()
2180 exttestedwith = exttestedwith.split()
2187 extbuglink = getattr(extmod, 'buglink', None)
2181 extbuglink = getattr(extmod, 'buglink', None)
2188
2182
2189 fm.startitem()
2183 fm.startitem()
2190
2184
2191 if ui.quiet or ui.verbose:
2185 if ui.quiet or ui.verbose:
2192 fm.write('name', '%s\n', extname)
2186 fm.write('name', '%s\n', extname)
2193 else:
2187 else:
2194 fm.write('name', '%s', extname)
2188 fm.write('name', '%s', extname)
2195 if not exttestedwith:
2189 if not exttestedwith:
2196 fm.plain(_(' (untested!)\n'))
2190 fm.plain(_(' (untested!)\n'))
2197 else:
2191 else:
2198 if exttestedwith == ['internal'] or \
2192 if exttestedwith == ['internal'] or \
2199 util.version() in exttestedwith:
2193 util.version() in exttestedwith:
2200 fm.plain('\n')
2194 fm.plain('\n')
2201 else:
2195 else:
2202 lasttestedversion = exttestedwith[-1]
2196 lasttestedversion = exttestedwith[-1]
2203 fm.plain(' (%s!)\n' % lasttestedversion)
2197 fm.plain(' (%s!)\n' % lasttestedversion)
2204
2198
2205 fm.condwrite(ui.verbose and extsource, 'source',
2199 fm.condwrite(ui.verbose and extsource, 'source',
2206 _(' location: %s\n'), extsource or "")
2200 _(' location: %s\n'), extsource or "")
2207
2201
2208 fm.condwrite(ui.verbose and exttestedwith, 'testedwith',
2202 fm.condwrite(ui.verbose and exttestedwith, 'testedwith',
2209 _(' tested with: %s\n'), ' '.join(exttestedwith or []))
2203 _(' tested with: %s\n'), ' '.join(exttestedwith or []))
2210
2204
2211 fm.condwrite(ui.verbose and extbuglink, 'buglink',
2205 fm.condwrite(ui.verbose and extbuglink, 'buglink',
2212 _(' bug reporting: %s\n'), extbuglink or "")
2206 _(' bug reporting: %s\n'), extbuglink or "")
2213
2207
2214 fm.end()
2208 fm.end()
2215
2209
2216 @command('debugfileset',
2210 @command('debugfileset',
2217 [('r', 'rev', '', _('apply the filespec on this revision'), _('REV'))],
2211 [('r', 'rev', '', _('apply the filespec on this revision'), _('REV'))],
2218 _('[-r REV] FILESPEC'))
2212 _('[-r REV] FILESPEC'))
2219 def debugfileset(ui, repo, expr, **opts):
2213 def debugfileset(ui, repo, expr, **opts):
2220 '''parse and apply a fileset specification'''
2214 '''parse and apply a fileset specification'''
2221 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
2215 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
2222 if ui.verbose:
2216 if ui.verbose:
2223 tree = fileset.parse(expr)
2217 tree = fileset.parse(expr)
2224 ui.note(fileset.prettyformat(tree), "\n")
2218 ui.note(fileset.prettyformat(tree), "\n")
2225
2219
2226 for f in ctx.getfileset(expr):
2220 for f in ctx.getfileset(expr):
2227 ui.write("%s\n" % f)
2221 ui.write("%s\n" % f)
2228
2222
2229 @command('debugfsinfo', [], _('[PATH]'), norepo=True)
2223 @command('debugfsinfo', [], _('[PATH]'), norepo=True)
2230 def debugfsinfo(ui, path="."):
2224 def debugfsinfo(ui, path="."):
2231 """show information detected about current filesystem"""
2225 """show information detected about current filesystem"""
2232 util.writefile('.debugfsinfo', '')
2226 util.writefile('.debugfsinfo', '')
2233 ui.write(('exec: %s\n') % (util.checkexec(path) and 'yes' or 'no'))
2227 ui.write(('exec: %s\n') % (util.checkexec(path) and 'yes' or 'no'))
2234 ui.write(('symlink: %s\n') % (util.checklink(path) and 'yes' or 'no'))
2228 ui.write(('symlink: %s\n') % (util.checklink(path) and 'yes' or 'no'))
2235 ui.write(('hardlink: %s\n') % (util.checknlink(path) and 'yes' or 'no'))
2229 ui.write(('hardlink: %s\n') % (util.checknlink(path) and 'yes' or 'no'))
2236 ui.write(('case-sensitive: %s\n') % (util.checkcase('.debugfsinfo')
2230 ui.write(('case-sensitive: %s\n') % (util.checkcase('.debugfsinfo')
2237 and 'yes' or 'no'))
2231 and 'yes' or 'no'))
2238 os.unlink('.debugfsinfo')
2232 os.unlink('.debugfsinfo')
2239
2233
2240 @command('debuggetbundle',
2234 @command('debuggetbundle',
2241 [('H', 'head', [], _('id of head node'), _('ID')),
2235 [('H', 'head', [], _('id of head node'), _('ID')),
2242 ('C', 'common', [], _('id of common node'), _('ID')),
2236 ('C', 'common', [], _('id of common node'), _('ID')),
2243 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE'))],
2237 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE'))],
2244 _('REPO FILE [-H|-C ID]...'),
2238 _('REPO FILE [-H|-C ID]...'),
2245 norepo=True)
2239 norepo=True)
2246 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
2240 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
2247 """retrieves a bundle from a repo
2241 """retrieves a bundle from a repo
2248
2242
2249 Every ID must be a full-length hex node id string. Saves the bundle to the
2243 Every ID must be a full-length hex node id string. Saves the bundle to the
2250 given file.
2244 given file.
2251 """
2245 """
2252 repo = hg.peer(ui, opts, repopath)
2246 repo = hg.peer(ui, opts, repopath)
2253 if not repo.capable('getbundle'):
2247 if not repo.capable('getbundle'):
2254 raise util.Abort("getbundle() not supported by target repository")
2248 raise util.Abort("getbundle() not supported by target repository")
2255 args = {}
2249 args = {}
2256 if common:
2250 if common:
2257 args['common'] = [bin(s) for s in common]
2251 args['common'] = [bin(s) for s in common]
2258 if head:
2252 if head:
2259 args['heads'] = [bin(s) for s in head]
2253 args['heads'] = [bin(s) for s in head]
2260 # TODO: get desired bundlecaps from command line.
2254 # TODO: get desired bundlecaps from command line.
2261 args['bundlecaps'] = None
2255 args['bundlecaps'] = None
2262 bundle = repo.getbundle('debug', **args)
2256 bundle = repo.getbundle('debug', **args)
2263
2257
2264 bundletype = opts.get('type', 'bzip2').lower()
2258 bundletype = opts.get('type', 'bzip2').lower()
2265 btypes = {'none': 'HG10UN',
2259 btypes = {'none': 'HG10UN',
2266 'bzip2': 'HG10BZ',
2260 'bzip2': 'HG10BZ',
2267 'gzip': 'HG10GZ',
2261 'gzip': 'HG10GZ',
2268 'bundle2': 'HG20'}
2262 'bundle2': 'HG20'}
2269 bundletype = btypes.get(bundletype)
2263 bundletype = btypes.get(bundletype)
2270 if bundletype not in changegroup.bundletypes:
2264 if bundletype not in changegroup.bundletypes:
2271 raise util.Abort(_('unknown bundle type specified with --type'))
2265 raise util.Abort(_('unknown bundle type specified with --type'))
2272 changegroup.writebundle(ui, bundle, bundlepath, bundletype)
2266 changegroup.writebundle(ui, bundle, bundlepath, bundletype)
2273
2267
2274 @command('debugignore', [], '')
2268 @command('debugignore', [], '')
2275 def debugignore(ui, repo, *values, **opts):
2269 def debugignore(ui, repo, *values, **opts):
2276 """display the combined ignore pattern"""
2270 """display the combined ignore pattern"""
2277 ignore = repo.dirstate._ignore
2271 ignore = repo.dirstate._ignore
2278 includepat = getattr(ignore, 'includepat', None)
2272 includepat = getattr(ignore, 'includepat', None)
2279 if includepat is not None:
2273 if includepat is not None:
2280 ui.write("%s\n" % includepat)
2274 ui.write("%s\n" % includepat)
2281 else:
2275 else:
2282 raise util.Abort(_("no ignore patterns found"))
2276 raise util.Abort(_("no ignore patterns found"))
2283
2277
2284 @command('debugindex',
2278 @command('debugindex',
2285 [('c', 'changelog', False, _('open changelog')),
2279 [('c', 'changelog', False, _('open changelog')),
2286 ('m', 'manifest', False, _('open manifest')),
2280 ('m', 'manifest', False, _('open manifest')),
2287 ('', 'dir', False, _('open directory manifest')),
2281 ('', 'dir', False, _('open directory manifest')),
2288 ('f', 'format', 0, _('revlog format'), _('FORMAT'))],
2282 ('f', 'format', 0, _('revlog format'), _('FORMAT'))],
2289 _('[-f FORMAT] -c|-m|FILE'),
2283 _('[-f FORMAT] -c|-m|FILE'),
2290 optionalrepo=True)
2284 optionalrepo=True)
2291 def debugindex(ui, repo, file_=None, **opts):
2285 def debugindex(ui, repo, file_=None, **opts):
2292 """dump the contents of an index file"""
2286 """dump the contents of an index file"""
2293 r = cmdutil.openrevlog(repo, 'debugindex', file_, opts)
2287 r = cmdutil.openrevlog(repo, 'debugindex', file_, opts)
2294 format = opts.get('format', 0)
2288 format = opts.get('format', 0)
2295 if format not in (0, 1):
2289 if format not in (0, 1):
2296 raise util.Abort(_("unknown format %d") % format)
2290 raise util.Abort(_("unknown format %d") % format)
2297
2291
2298 generaldelta = r.version & revlog.REVLOGGENERALDELTA
2292 generaldelta = r.version & revlog.REVLOGGENERALDELTA
2299 if generaldelta:
2293 if generaldelta:
2300 basehdr = ' delta'
2294 basehdr = ' delta'
2301 else:
2295 else:
2302 basehdr = ' base'
2296 basehdr = ' base'
2303
2297
2304 if ui.debugflag:
2298 if ui.debugflag:
2305 shortfn = hex
2299 shortfn = hex
2306 else:
2300 else:
2307 shortfn = short
2301 shortfn = short
2308
2302
2309 # There might not be anything in r, so have a sane default
2303 # There might not be anything in r, so have a sane default
2310 idlen = 12
2304 idlen = 12
2311 for i in r:
2305 for i in r:
2312 idlen = len(shortfn(r.node(i)))
2306 idlen = len(shortfn(r.node(i)))
2313 break
2307 break
2314
2308
2315 if format == 0:
2309 if format == 0:
2316 ui.write(" rev offset length " + basehdr + " linkrev"
2310 ui.write(" rev offset length " + basehdr + " linkrev"
2317 " %s %s p2\n" % ("nodeid".ljust(idlen), "p1".ljust(idlen)))
2311 " %s %s p2\n" % ("nodeid".ljust(idlen), "p1".ljust(idlen)))
2318 elif format == 1:
2312 elif format == 1:
2319 ui.write(" rev flag offset length"
2313 ui.write(" rev flag offset length"
2320 " size " + basehdr + " link p1 p2"
2314 " size " + basehdr + " link p1 p2"
2321 " %s\n" % "nodeid".rjust(idlen))
2315 " %s\n" % "nodeid".rjust(idlen))
2322
2316
2323 for i in r:
2317 for i in r:
2324 node = r.node(i)
2318 node = r.node(i)
2325 if generaldelta:
2319 if generaldelta:
2326 base = r.deltaparent(i)
2320 base = r.deltaparent(i)
2327 else:
2321 else:
2328 base = r.chainbase(i)
2322 base = r.chainbase(i)
2329 if format == 0:
2323 if format == 0:
2330 try:
2324 try:
2331 pp = r.parents(node)
2325 pp = r.parents(node)
2332 except Exception:
2326 except Exception:
2333 pp = [nullid, nullid]
2327 pp = [nullid, nullid]
2334 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
2328 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
2335 i, r.start(i), r.length(i), base, r.linkrev(i),
2329 i, r.start(i), r.length(i), base, r.linkrev(i),
2336 shortfn(node), shortfn(pp[0]), shortfn(pp[1])))
2330 shortfn(node), shortfn(pp[0]), shortfn(pp[1])))
2337 elif format == 1:
2331 elif format == 1:
2338 pr = r.parentrevs(i)
2332 pr = r.parentrevs(i)
2339 ui.write("% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d % 6d %s\n" % (
2333 ui.write("% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d % 6d %s\n" % (
2340 i, r.flags(i), r.start(i), r.length(i), r.rawsize(i),
2334 i, r.flags(i), r.start(i), r.length(i), r.rawsize(i),
2341 base, r.linkrev(i), pr[0], pr[1], shortfn(node)))
2335 base, r.linkrev(i), pr[0], pr[1], shortfn(node)))
2342
2336
2343 @command('debugindexdot', [], _('FILE'), optionalrepo=True)
2337 @command('debugindexdot', [], _('FILE'), optionalrepo=True)
2344 def debugindexdot(ui, repo, file_):
2338 def debugindexdot(ui, repo, file_):
2345 """dump an index DAG as a graphviz dot file"""
2339 """dump an index DAG as a graphviz dot file"""
2346 r = None
2340 r = None
2347 if repo:
2341 if repo:
2348 filelog = repo.file(file_)
2342 filelog = repo.file(file_)
2349 if len(filelog):
2343 if len(filelog):
2350 r = filelog
2344 r = filelog
2351 if not r:
2345 if not r:
2352 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
2346 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
2353 ui.write(("digraph G {\n"))
2347 ui.write(("digraph G {\n"))
2354 for i in r:
2348 for i in r:
2355 node = r.node(i)
2349 node = r.node(i)
2356 pp = r.parents(node)
2350 pp = r.parents(node)
2357 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
2351 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
2358 if pp[1] != nullid:
2352 if pp[1] != nullid:
2359 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
2353 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
2360 ui.write("}\n")
2354 ui.write("}\n")
2361
2355
2362 @command('debuginstall', [], '', norepo=True)
2356 @command('debuginstall', [], '', norepo=True)
2363 def debuginstall(ui):
2357 def debuginstall(ui):
2364 '''test Mercurial installation
2358 '''test Mercurial installation
2365
2359
2366 Returns 0 on success.
2360 Returns 0 on success.
2367 '''
2361 '''
2368
2362
2369 def writetemp(contents):
2363 def writetemp(contents):
2370 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
2364 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
2371 f = os.fdopen(fd, "wb")
2365 f = os.fdopen(fd, "wb")
2372 f.write(contents)
2366 f.write(contents)
2373 f.close()
2367 f.close()
2374 return name
2368 return name
2375
2369
2376 problems = 0
2370 problems = 0
2377
2371
2378 # encoding
2372 # encoding
2379 ui.status(_("checking encoding (%s)...\n") % encoding.encoding)
2373 ui.status(_("checking encoding (%s)...\n") % encoding.encoding)
2380 try:
2374 try:
2381 encoding.fromlocal("test")
2375 encoding.fromlocal("test")
2382 except util.Abort as inst:
2376 except util.Abort as inst:
2383 ui.write(" %s\n" % inst)
2377 ui.write(" %s\n" % inst)
2384 ui.write(_(" (check that your locale is properly set)\n"))
2378 ui.write(_(" (check that your locale is properly set)\n"))
2385 problems += 1
2379 problems += 1
2386
2380
2387 # Python
2381 # Python
2388 ui.status(_("checking Python executable (%s)\n") % sys.executable)
2382 ui.status(_("checking Python executable (%s)\n") % sys.executable)
2389 ui.status(_("checking Python version (%s)\n")
2383 ui.status(_("checking Python version (%s)\n")
2390 % ("%s.%s.%s" % sys.version_info[:3]))
2384 % ("%s.%s.%s" % sys.version_info[:3]))
2391 ui.status(_("checking Python lib (%s)...\n")
2385 ui.status(_("checking Python lib (%s)...\n")
2392 % os.path.dirname(os.__file__))
2386 % os.path.dirname(os.__file__))
2393
2387
2394 # compiled modules
2388 # compiled modules
2395 ui.status(_("checking installed modules (%s)...\n")
2389 ui.status(_("checking installed modules (%s)...\n")
2396 % os.path.dirname(__file__))
2390 % os.path.dirname(__file__))
2397 try:
2391 try:
2398 import bdiff, mpatch, base85, osutil
2392 import bdiff, mpatch, base85, osutil
2399 dir(bdiff), dir(mpatch), dir(base85), dir(osutil) # quiet pyflakes
2393 dir(bdiff), dir(mpatch), dir(base85), dir(osutil) # quiet pyflakes
2400 except Exception as inst:
2394 except Exception as inst:
2401 ui.write(" %s\n" % inst)
2395 ui.write(" %s\n" % inst)
2402 ui.write(_(" One or more extensions could not be found"))
2396 ui.write(_(" One or more extensions could not be found"))
2403 ui.write(_(" (check that you compiled the extensions)\n"))
2397 ui.write(_(" (check that you compiled the extensions)\n"))
2404 problems += 1
2398 problems += 1
2405
2399
2406 # templates
2400 # templates
2407 import templater
2401 import templater
2408 p = templater.templatepaths()
2402 p = templater.templatepaths()
2409 ui.status(_("checking templates (%s)...\n") % ' '.join(p))
2403 ui.status(_("checking templates (%s)...\n") % ' '.join(p))
2410 if p:
2404 if p:
2411 m = templater.templatepath("map-cmdline.default")
2405 m = templater.templatepath("map-cmdline.default")
2412 if m:
2406 if m:
2413 # template found, check if it is working
2407 # template found, check if it is working
2414 try:
2408 try:
2415 templater.templater(m)
2409 templater.templater(m)
2416 except Exception as inst:
2410 except Exception as inst:
2417 ui.write(" %s\n" % inst)
2411 ui.write(" %s\n" % inst)
2418 p = None
2412 p = None
2419 else:
2413 else:
2420 ui.write(_(" template 'default' not found\n"))
2414 ui.write(_(" template 'default' not found\n"))
2421 p = None
2415 p = None
2422 else:
2416 else:
2423 ui.write(_(" no template directories found\n"))
2417 ui.write(_(" no template directories found\n"))
2424 if not p:
2418 if not p:
2425 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
2419 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
2426 problems += 1
2420 problems += 1
2427
2421
2428 # editor
2422 # editor
2429 ui.status(_("checking commit editor...\n"))
2423 ui.status(_("checking commit editor...\n"))
2430 editor = ui.geteditor()
2424 editor = ui.geteditor()
2431 editor = util.expandpath(editor)
2425 editor = util.expandpath(editor)
2432 cmdpath = util.findexe(shlex.split(editor)[0])
2426 cmdpath = util.findexe(shlex.split(editor)[0])
2433 if not cmdpath:
2427 if not cmdpath:
2434 if editor == 'vi':
2428 if editor == 'vi':
2435 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
2429 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
2436 ui.write(_(" (specify a commit editor in your configuration"
2430 ui.write(_(" (specify a commit editor in your configuration"
2437 " file)\n"))
2431 " file)\n"))
2438 else:
2432 else:
2439 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
2433 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
2440 ui.write(_(" (specify a commit editor in your configuration"
2434 ui.write(_(" (specify a commit editor in your configuration"
2441 " file)\n"))
2435 " file)\n"))
2442 problems += 1
2436 problems += 1
2443
2437
2444 # check username
2438 # check username
2445 ui.status(_("checking username...\n"))
2439 ui.status(_("checking username...\n"))
2446 try:
2440 try:
2447 ui.username()
2441 ui.username()
2448 except util.Abort as e:
2442 except util.Abort as e:
2449 ui.write(" %s\n" % e)
2443 ui.write(" %s\n" % e)
2450 ui.write(_(" (specify a username in your configuration file)\n"))
2444 ui.write(_(" (specify a username in your configuration file)\n"))
2451 problems += 1
2445 problems += 1
2452
2446
2453 if not problems:
2447 if not problems:
2454 ui.status(_("no problems detected\n"))
2448 ui.status(_("no problems detected\n"))
2455 else:
2449 else:
2456 ui.write(_("%s problems detected,"
2450 ui.write(_("%s problems detected,"
2457 " please check your install!\n") % problems)
2451 " please check your install!\n") % problems)
2458
2452
2459 return problems
2453 return problems
2460
2454
2461 @command('debugknown', [], _('REPO ID...'), norepo=True)
2455 @command('debugknown', [], _('REPO ID...'), norepo=True)
2462 def debugknown(ui, repopath, *ids, **opts):
2456 def debugknown(ui, repopath, *ids, **opts):
2463 """test whether node ids are known to a repo
2457 """test whether node ids are known to a repo
2464
2458
2465 Every ID must be a full-length hex node id string. Returns a list of 0s
2459 Every ID must be a full-length hex node id string. Returns a list of 0s
2466 and 1s indicating unknown/known.
2460 and 1s indicating unknown/known.
2467 """
2461 """
2468 repo = hg.peer(ui, opts, repopath)
2462 repo = hg.peer(ui, opts, repopath)
2469 if not repo.capable('known'):
2463 if not repo.capable('known'):
2470 raise util.Abort("known() not supported by target repository")
2464 raise util.Abort("known() not supported by target repository")
2471 flags = repo.known([bin(s) for s in ids])
2465 flags = repo.known([bin(s) for s in ids])
2472 ui.write("%s\n" % ("".join([f and "1" or "0" for f in flags])))
2466 ui.write("%s\n" % ("".join([f and "1" or "0" for f in flags])))
2473
2467
2474 @command('debuglabelcomplete', [], _('LABEL...'))
2468 @command('debuglabelcomplete', [], _('LABEL...'))
2475 def debuglabelcomplete(ui, repo, *args):
2469 def debuglabelcomplete(ui, repo, *args):
2476 '''backwards compatibility with old bash completion scripts (DEPRECATED)'''
2470 '''backwards compatibility with old bash completion scripts (DEPRECATED)'''
2477 debugnamecomplete(ui, repo, *args)
2471 debugnamecomplete(ui, repo, *args)
2478
2472
2479 @command('debugmergestate', [], '')
2473 @command('debugmergestate', [], '')
2480 def debugmergestate(ui, repo, *args):
2474 def debugmergestate(ui, repo, *args):
2481 """print merge state
2475 """print merge state
2482
2476
2483 Use --verbose to print out information about whether v1 or v2 merge state
2477 Use --verbose to print out information about whether v1 or v2 merge state
2484 was chosen."""
2478 was chosen."""
2485 def printrecords(version):
2479 def printrecords(version):
2486 ui.write(('* version %s records\n') % version)
2480 ui.write(('* version %s records\n') % version)
2487 if version == 1:
2481 if version == 1:
2488 records = v1records
2482 records = v1records
2489 else:
2483 else:
2490 records = v2records
2484 records = v2records
2491
2485
2492 for rtype, record in records:
2486 for rtype, record in records:
2493 # pretty print some record types
2487 # pretty print some record types
2494 if rtype == 'L':
2488 if rtype == 'L':
2495 ui.write(('local: %s\n') % record)
2489 ui.write(('local: %s\n') % record)
2496 elif rtype == 'O':
2490 elif rtype == 'O':
2497 ui.write(('other: %s\n') % record)
2491 ui.write(('other: %s\n') % record)
2498 elif rtype == 'F':
2492 elif rtype == 'F':
2499 r = record.split('\0')
2493 r = record.split('\0')
2500 f, state, hash, lfile, afile, anode, ofile = r[0:7]
2494 f, state, hash, lfile, afile, anode, ofile = r[0:7]
2501 if version == 1:
2495 if version == 1:
2502 onode = 'not stored in v1 format'
2496 onode = 'not stored in v1 format'
2503 flags = r[7]
2497 flags = r[7]
2504 else:
2498 else:
2505 onode, flags = r[7:9]
2499 onode, flags = r[7:9]
2506 ui.write(('file: %s (state "%s", hash %s)\n')
2500 ui.write(('file: %s (state "%s", hash %s)\n')
2507 % (f, state, hash))
2501 % (f, state, hash))
2508 ui.write((' local path: %s (flags "%s")\n') % (lfile, flags))
2502 ui.write((' local path: %s (flags "%s")\n') % (lfile, flags))
2509 ui.write((' ancestor path: %s (node %s)\n') % (afile, anode))
2503 ui.write((' ancestor path: %s (node %s)\n') % (afile, anode))
2510 ui.write((' other path: %s (node %s)\n') % (ofile, onode))
2504 ui.write((' other path: %s (node %s)\n') % (ofile, onode))
2511 else:
2505 else:
2512 ui.write(('unrecognized entry: %s\t%s\n')
2506 ui.write(('unrecognized entry: %s\t%s\n')
2513 % (rtype, record.replace('\0', '\t')))
2507 % (rtype, record.replace('\0', '\t')))
2514
2508
2515 ms = mergemod.mergestate(repo)
2509 ms = mergemod.mergestate(repo)
2516
2510
2517 # sort so that reasonable information is on top
2511 # sort so that reasonable information is on top
2518 v1records = ms._readrecordsv1()
2512 v1records = ms._readrecordsv1()
2519 v2records = ms._readrecordsv2()
2513 v2records = ms._readrecordsv2()
2520 order = 'LO'
2514 order = 'LO'
2521 def key(r):
2515 def key(r):
2522 idx = order.find(r[0])
2516 idx = order.find(r[0])
2523 if idx == -1:
2517 if idx == -1:
2524 return (1, r[1])
2518 return (1, r[1])
2525 else:
2519 else:
2526 return (0, idx)
2520 return (0, idx)
2527 v1records.sort(key=key)
2521 v1records.sort(key=key)
2528 v2records.sort(key=key)
2522 v2records.sort(key=key)
2529
2523
2530 if not v1records and not v2records:
2524 if not v1records and not v2records:
2531 ui.write(('no merge state found\n'))
2525 ui.write(('no merge state found\n'))
2532 elif not v2records:
2526 elif not v2records:
2533 ui.note(('no version 2 merge state\n'))
2527 ui.note(('no version 2 merge state\n'))
2534 printrecords(1)
2528 printrecords(1)
2535 elif ms._v1v2match(v1records, v2records):
2529 elif ms._v1v2match(v1records, v2records):
2536 ui.note(('v1 and v2 states match: using v2\n'))
2530 ui.note(('v1 and v2 states match: using v2\n'))
2537 printrecords(2)
2531 printrecords(2)
2538 else:
2532 else:
2539 ui.note(('v1 and v2 states mismatch: using v1\n'))
2533 ui.note(('v1 and v2 states mismatch: using v1\n'))
2540 printrecords(1)
2534 printrecords(1)
2541 if ui.verbose:
2535 if ui.verbose:
2542 printrecords(2)
2536 printrecords(2)
2543
2537
2544 @command('debugnamecomplete', [], _('NAME...'))
2538 @command('debugnamecomplete', [], _('NAME...'))
2545 def debugnamecomplete(ui, repo, *args):
2539 def debugnamecomplete(ui, repo, *args):
2546 '''complete "names" - tags, open branch names, bookmark names'''
2540 '''complete "names" - tags, open branch names, bookmark names'''
2547
2541
2548 names = set()
2542 names = set()
2549 # since we previously only listed open branches, we will handle that
2543 # since we previously only listed open branches, we will handle that
2550 # specially (after this for loop)
2544 # specially (after this for loop)
2551 for name, ns in repo.names.iteritems():
2545 for name, ns in repo.names.iteritems():
2552 if name != 'branches':
2546 if name != 'branches':
2553 names.update(ns.listnames(repo))
2547 names.update(ns.listnames(repo))
2554 names.update(tag for (tag, heads, tip, closed)
2548 names.update(tag for (tag, heads, tip, closed)
2555 in repo.branchmap().iterbranches() if not closed)
2549 in repo.branchmap().iterbranches() if not closed)
2556 completions = set()
2550 completions = set()
2557 if not args:
2551 if not args:
2558 args = ['']
2552 args = ['']
2559 for a in args:
2553 for a in args:
2560 completions.update(n for n in names if n.startswith(a))
2554 completions.update(n for n in names if n.startswith(a))
2561 ui.write('\n'.join(sorted(completions)))
2555 ui.write('\n'.join(sorted(completions)))
2562 ui.write('\n')
2556 ui.write('\n')
2563
2557
2564 @command('debuglocks',
2558 @command('debuglocks',
2565 [('L', 'force-lock', None, _('free the store lock (DANGEROUS)')),
2559 [('L', 'force-lock', None, _('free the store lock (DANGEROUS)')),
2566 ('W', 'force-wlock', None,
2560 ('W', 'force-wlock', None,
2567 _('free the working state lock (DANGEROUS)'))],
2561 _('free the working state lock (DANGEROUS)'))],
2568 _('[OPTION]...'))
2562 _('[OPTION]...'))
2569 def debuglocks(ui, repo, **opts):
2563 def debuglocks(ui, repo, **opts):
2570 """show or modify state of locks
2564 """show or modify state of locks
2571
2565
2572 By default, this command will show which locks are held. This
2566 By default, this command will show which locks are held. This
2573 includes the user and process holding the lock, the amount of time
2567 includes the user and process holding the lock, the amount of time
2574 the lock has been held, and the machine name where the process is
2568 the lock has been held, and the machine name where the process is
2575 running if it's not local.
2569 running if it's not local.
2576
2570
2577 Locks protect the integrity of Mercurial's data, so should be
2571 Locks protect the integrity of Mercurial's data, so should be
2578 treated with care. System crashes or other interruptions may cause
2572 treated with care. System crashes or other interruptions may cause
2579 locks to not be properly released, though Mercurial will usually
2573 locks to not be properly released, though Mercurial will usually
2580 detect and remove such stale locks automatically.
2574 detect and remove such stale locks automatically.
2581
2575
2582 However, detecting stale locks may not always be possible (for
2576 However, detecting stale locks may not always be possible (for
2583 instance, on a shared filesystem). Removing locks may also be
2577 instance, on a shared filesystem). Removing locks may also be
2584 blocked by filesystem permissions.
2578 blocked by filesystem permissions.
2585
2579
2586 Returns 0 if no locks are held.
2580 Returns 0 if no locks are held.
2587
2581
2588 """
2582 """
2589
2583
2590 if opts.get('force_lock'):
2584 if opts.get('force_lock'):
2591 repo.svfs.unlink('lock')
2585 repo.svfs.unlink('lock')
2592 if opts.get('force_wlock'):
2586 if opts.get('force_wlock'):
2593 repo.vfs.unlink('wlock')
2587 repo.vfs.unlink('wlock')
2594 if opts.get('force_lock') or opts.get('force_lock'):
2588 if opts.get('force_lock') or opts.get('force_lock'):
2595 return 0
2589 return 0
2596
2590
2597 now = time.time()
2591 now = time.time()
2598 held = 0
2592 held = 0
2599
2593
2600 def report(vfs, name, method):
2594 def report(vfs, name, method):
2601 # this causes stale locks to get reaped for more accurate reporting
2595 # this causes stale locks to get reaped for more accurate reporting
2602 try:
2596 try:
2603 l = method(False)
2597 l = method(False)
2604 except error.LockHeld:
2598 except error.LockHeld:
2605 l = None
2599 l = None
2606
2600
2607 if l:
2601 if l:
2608 l.release()
2602 l.release()
2609 else:
2603 else:
2610 try:
2604 try:
2611 stat = vfs.lstat(name)
2605 stat = vfs.lstat(name)
2612 age = now - stat.st_mtime
2606 age = now - stat.st_mtime
2613 user = util.username(stat.st_uid)
2607 user = util.username(stat.st_uid)
2614 locker = vfs.readlock(name)
2608 locker = vfs.readlock(name)
2615 if ":" in locker:
2609 if ":" in locker:
2616 host, pid = locker.split(':')
2610 host, pid = locker.split(':')
2617 if host == socket.gethostname():
2611 if host == socket.gethostname():
2618 locker = 'user %s, process %s' % (user, pid)
2612 locker = 'user %s, process %s' % (user, pid)
2619 else:
2613 else:
2620 locker = 'user %s, process %s, host %s' \
2614 locker = 'user %s, process %s, host %s' \
2621 % (user, pid, host)
2615 % (user, pid, host)
2622 ui.write("%-6s %s (%ds)\n" % (name + ":", locker, age))
2616 ui.write("%-6s %s (%ds)\n" % (name + ":", locker, age))
2623 return 1
2617 return 1
2624 except OSError as e:
2618 except OSError as e:
2625 if e.errno != errno.ENOENT:
2619 if e.errno != errno.ENOENT:
2626 raise
2620 raise
2627
2621
2628 ui.write("%-6s free\n" % (name + ":"))
2622 ui.write("%-6s free\n" % (name + ":"))
2629 return 0
2623 return 0
2630
2624
2631 held += report(repo.svfs, "lock", repo.lock)
2625 held += report(repo.svfs, "lock", repo.lock)
2632 held += report(repo.vfs, "wlock", repo.wlock)
2626 held += report(repo.vfs, "wlock", repo.wlock)
2633
2627
2634 return held
2628 return held
2635
2629
2636 @command('debugobsolete',
2630 @command('debugobsolete',
2637 [('', 'flags', 0, _('markers flag')),
2631 [('', 'flags', 0, _('markers flag')),
2638 ('', 'record-parents', False,
2632 ('', 'record-parents', False,
2639 _('record parent information for the precursor')),
2633 _('record parent information for the precursor')),
2640 ('r', 'rev', [], _('display markers relevant to REV')),
2634 ('r', 'rev', [], _('display markers relevant to REV')),
2641 ] + commitopts2,
2635 ] + commitopts2,
2642 _('[OBSOLETED [REPLACEMENT] [REPL... ]'))
2636 _('[OBSOLETED [REPLACEMENT] [REPL... ]'))
2643 def debugobsolete(ui, repo, precursor=None, *successors, **opts):
2637 def debugobsolete(ui, repo, precursor=None, *successors, **opts):
2644 """create arbitrary obsolete marker
2638 """create arbitrary obsolete marker
2645
2639
2646 With no arguments, displays the list of obsolescence markers."""
2640 With no arguments, displays the list of obsolescence markers."""
2647
2641
2648 def parsenodeid(s):
2642 def parsenodeid(s):
2649 try:
2643 try:
2650 # We do not use revsingle/revrange functions here to accept
2644 # We do not use revsingle/revrange functions here to accept
2651 # arbitrary node identifiers, possibly not present in the
2645 # arbitrary node identifiers, possibly not present in the
2652 # local repository.
2646 # local repository.
2653 n = bin(s)
2647 n = bin(s)
2654 if len(n) != len(nullid):
2648 if len(n) != len(nullid):
2655 raise TypeError()
2649 raise TypeError()
2656 return n
2650 return n
2657 except TypeError:
2651 except TypeError:
2658 raise util.Abort('changeset references must be full hexadecimal '
2652 raise util.Abort('changeset references must be full hexadecimal '
2659 'node identifiers')
2653 'node identifiers')
2660
2654
2661 if precursor is not None:
2655 if precursor is not None:
2662 if opts['rev']:
2656 if opts['rev']:
2663 raise util.Abort('cannot select revision when creating marker')
2657 raise util.Abort('cannot select revision when creating marker')
2664 metadata = {}
2658 metadata = {}
2665 metadata['user'] = opts['user'] or ui.username()
2659 metadata['user'] = opts['user'] or ui.username()
2666 succs = tuple(parsenodeid(succ) for succ in successors)
2660 succs = tuple(parsenodeid(succ) for succ in successors)
2667 l = repo.lock()
2661 l = repo.lock()
2668 try:
2662 try:
2669 tr = repo.transaction('debugobsolete')
2663 tr = repo.transaction('debugobsolete')
2670 try:
2664 try:
2671 date = opts.get('date')
2665 date = opts.get('date')
2672 if date:
2666 if date:
2673 date = util.parsedate(date)
2667 date = util.parsedate(date)
2674 else:
2668 else:
2675 date = None
2669 date = None
2676 prec = parsenodeid(precursor)
2670 prec = parsenodeid(precursor)
2677 parents = None
2671 parents = None
2678 if opts['record_parents']:
2672 if opts['record_parents']:
2679 if prec not in repo.unfiltered():
2673 if prec not in repo.unfiltered():
2680 raise util.Abort('cannot used --record-parents on '
2674 raise util.Abort('cannot used --record-parents on '
2681 'unknown changesets')
2675 'unknown changesets')
2682 parents = repo.unfiltered()[prec].parents()
2676 parents = repo.unfiltered()[prec].parents()
2683 parents = tuple(p.node() for p in parents)
2677 parents = tuple(p.node() for p in parents)
2684 repo.obsstore.create(tr, prec, succs, opts['flags'],
2678 repo.obsstore.create(tr, prec, succs, opts['flags'],
2685 parents=parents, date=date,
2679 parents=parents, date=date,
2686 metadata=metadata)
2680 metadata=metadata)
2687 tr.close()
2681 tr.close()
2688 except ValueError as exc:
2682 except ValueError as exc:
2689 raise util.Abort(_('bad obsmarker input: %s') % exc)
2683 raise util.Abort(_('bad obsmarker input: %s') % exc)
2690 finally:
2684 finally:
2691 tr.release()
2685 tr.release()
2692 finally:
2686 finally:
2693 l.release()
2687 l.release()
2694 else:
2688 else:
2695 if opts['rev']:
2689 if opts['rev']:
2696 revs = scmutil.revrange(repo, opts['rev'])
2690 revs = scmutil.revrange(repo, opts['rev'])
2697 nodes = [repo[r].node() for r in revs]
2691 nodes = [repo[r].node() for r in revs]
2698 markers = list(obsolete.getmarkers(repo, nodes=nodes))
2692 markers = list(obsolete.getmarkers(repo, nodes=nodes))
2699 markers.sort(key=lambda x: x._data)
2693 markers.sort(key=lambda x: x._data)
2700 else:
2694 else:
2701 markers = obsolete.getmarkers(repo)
2695 markers = obsolete.getmarkers(repo)
2702
2696
2703 for m in markers:
2697 for m in markers:
2704 cmdutil.showmarker(ui, m)
2698 cmdutil.showmarker(ui, m)
2705
2699
2706 @command('debugpathcomplete',
2700 @command('debugpathcomplete',
2707 [('f', 'full', None, _('complete an entire path')),
2701 [('f', 'full', None, _('complete an entire path')),
2708 ('n', 'normal', None, _('show only normal files')),
2702 ('n', 'normal', None, _('show only normal files')),
2709 ('a', 'added', None, _('show only added files')),
2703 ('a', 'added', None, _('show only added files')),
2710 ('r', 'removed', None, _('show only removed files'))],
2704 ('r', 'removed', None, _('show only removed files'))],
2711 _('FILESPEC...'))
2705 _('FILESPEC...'))
2712 def debugpathcomplete(ui, repo, *specs, **opts):
2706 def debugpathcomplete(ui, repo, *specs, **opts):
2713 '''complete part or all of a tracked path
2707 '''complete part or all of a tracked path
2714
2708
2715 This command supports shells that offer path name completion. It
2709 This command supports shells that offer path name completion. It
2716 currently completes only files already known to the dirstate.
2710 currently completes only files already known to the dirstate.
2717
2711
2718 Completion extends only to the next path segment unless
2712 Completion extends only to the next path segment unless
2719 --full is specified, in which case entire paths are used.'''
2713 --full is specified, in which case entire paths are used.'''
2720
2714
2721 def complete(path, acceptable):
2715 def complete(path, acceptable):
2722 dirstate = repo.dirstate
2716 dirstate = repo.dirstate
2723 spec = os.path.normpath(os.path.join(os.getcwd(), path))
2717 spec = os.path.normpath(os.path.join(os.getcwd(), path))
2724 rootdir = repo.root + os.sep
2718 rootdir = repo.root + os.sep
2725 if spec != repo.root and not spec.startswith(rootdir):
2719 if spec != repo.root and not spec.startswith(rootdir):
2726 return [], []
2720 return [], []
2727 if os.path.isdir(spec):
2721 if os.path.isdir(spec):
2728 spec += '/'
2722 spec += '/'
2729 spec = spec[len(rootdir):]
2723 spec = spec[len(rootdir):]
2730 fixpaths = os.sep != '/'
2724 fixpaths = os.sep != '/'
2731 if fixpaths:
2725 if fixpaths:
2732 spec = spec.replace(os.sep, '/')
2726 spec = spec.replace(os.sep, '/')
2733 speclen = len(spec)
2727 speclen = len(spec)
2734 fullpaths = opts['full']
2728 fullpaths = opts['full']
2735 files, dirs = set(), set()
2729 files, dirs = set(), set()
2736 adddir, addfile = dirs.add, files.add
2730 adddir, addfile = dirs.add, files.add
2737 for f, st in dirstate.iteritems():
2731 for f, st in dirstate.iteritems():
2738 if f.startswith(spec) and st[0] in acceptable:
2732 if f.startswith(spec) and st[0] in acceptable:
2739 if fixpaths:
2733 if fixpaths:
2740 f = f.replace('/', os.sep)
2734 f = f.replace('/', os.sep)
2741 if fullpaths:
2735 if fullpaths:
2742 addfile(f)
2736 addfile(f)
2743 continue
2737 continue
2744 s = f.find(os.sep, speclen)
2738 s = f.find(os.sep, speclen)
2745 if s >= 0:
2739 if s >= 0:
2746 adddir(f[:s])
2740 adddir(f[:s])
2747 else:
2741 else:
2748 addfile(f)
2742 addfile(f)
2749 return files, dirs
2743 return files, dirs
2750
2744
2751 acceptable = ''
2745 acceptable = ''
2752 if opts['normal']:
2746 if opts['normal']:
2753 acceptable += 'nm'
2747 acceptable += 'nm'
2754 if opts['added']:
2748 if opts['added']:
2755 acceptable += 'a'
2749 acceptable += 'a'
2756 if opts['removed']:
2750 if opts['removed']:
2757 acceptable += 'r'
2751 acceptable += 'r'
2758 cwd = repo.getcwd()
2752 cwd = repo.getcwd()
2759 if not specs:
2753 if not specs:
2760 specs = ['.']
2754 specs = ['.']
2761
2755
2762 files, dirs = set(), set()
2756 files, dirs = set(), set()
2763 for spec in specs:
2757 for spec in specs:
2764 f, d = complete(spec, acceptable or 'nmar')
2758 f, d = complete(spec, acceptable or 'nmar')
2765 files.update(f)
2759 files.update(f)
2766 dirs.update(d)
2760 dirs.update(d)
2767 files.update(dirs)
2761 files.update(dirs)
2768 ui.write('\n'.join(repo.pathto(p, cwd) for p in sorted(files)))
2762 ui.write('\n'.join(repo.pathto(p, cwd) for p in sorted(files)))
2769 ui.write('\n')
2763 ui.write('\n')
2770
2764
2771 @command('debugpushkey', [], _('REPO NAMESPACE [KEY OLD NEW]'), norepo=True)
2765 @command('debugpushkey', [], _('REPO NAMESPACE [KEY OLD NEW]'), norepo=True)
2772 def debugpushkey(ui, repopath, namespace, *keyinfo, **opts):
2766 def debugpushkey(ui, repopath, namespace, *keyinfo, **opts):
2773 '''access the pushkey key/value protocol
2767 '''access the pushkey key/value protocol
2774
2768
2775 With two args, list the keys in the given namespace.
2769 With two args, list the keys in the given namespace.
2776
2770
2777 With five args, set a key to new if it currently is set to old.
2771 With five args, set a key to new if it currently is set to old.
2778 Reports success or failure.
2772 Reports success or failure.
2779 '''
2773 '''
2780
2774
2781 target = hg.peer(ui, {}, repopath)
2775 target = hg.peer(ui, {}, repopath)
2782 if keyinfo:
2776 if keyinfo:
2783 key, old, new = keyinfo
2777 key, old, new = keyinfo
2784 r = target.pushkey(namespace, key, old, new)
2778 r = target.pushkey(namespace, key, old, new)
2785 ui.status(str(r) + '\n')
2779 ui.status(str(r) + '\n')
2786 return not r
2780 return not r
2787 else:
2781 else:
2788 for k, v in sorted(target.listkeys(namespace).iteritems()):
2782 for k, v in sorted(target.listkeys(namespace).iteritems()):
2789 ui.write("%s\t%s\n" % (k.encode('string-escape'),
2783 ui.write("%s\t%s\n" % (k.encode('string-escape'),
2790 v.encode('string-escape')))
2784 v.encode('string-escape')))
2791
2785
2792 @command('debugpvec', [], _('A B'))
2786 @command('debugpvec', [], _('A B'))
2793 def debugpvec(ui, repo, a, b=None):
2787 def debugpvec(ui, repo, a, b=None):
2794 ca = scmutil.revsingle(repo, a)
2788 ca = scmutil.revsingle(repo, a)
2795 cb = scmutil.revsingle(repo, b)
2789 cb = scmutil.revsingle(repo, b)
2796 pa = pvec.ctxpvec(ca)
2790 pa = pvec.ctxpvec(ca)
2797 pb = pvec.ctxpvec(cb)
2791 pb = pvec.ctxpvec(cb)
2798 if pa == pb:
2792 if pa == pb:
2799 rel = "="
2793 rel = "="
2800 elif pa > pb:
2794 elif pa > pb:
2801 rel = ">"
2795 rel = ">"
2802 elif pa < pb:
2796 elif pa < pb:
2803 rel = "<"
2797 rel = "<"
2804 elif pa | pb:
2798 elif pa | pb:
2805 rel = "|"
2799 rel = "|"
2806 ui.write(_("a: %s\n") % pa)
2800 ui.write(_("a: %s\n") % pa)
2807 ui.write(_("b: %s\n") % pb)
2801 ui.write(_("b: %s\n") % pb)
2808 ui.write(_("depth(a): %d depth(b): %d\n") % (pa._depth, pb._depth))
2802 ui.write(_("depth(a): %d depth(b): %d\n") % (pa._depth, pb._depth))
2809 ui.write(_("delta: %d hdist: %d distance: %d relation: %s\n") %
2803 ui.write(_("delta: %d hdist: %d distance: %d relation: %s\n") %
2810 (abs(pa._depth - pb._depth), pvec._hamming(pa._vec, pb._vec),
2804 (abs(pa._depth - pb._depth), pvec._hamming(pa._vec, pb._vec),
2811 pa.distance(pb), rel))
2805 pa.distance(pb), rel))
2812
2806
2813 @command('debugrebuilddirstate|debugrebuildstate',
2807 @command('debugrebuilddirstate|debugrebuildstate',
2814 [('r', 'rev', '', _('revision to rebuild to'), _('REV')),
2808 [('r', 'rev', '', _('revision to rebuild to'), _('REV')),
2815 ('', 'minimal', None, _('only rebuild files that are inconsistent with '
2809 ('', 'minimal', None, _('only rebuild files that are inconsistent with '
2816 'the working copy parent')),
2810 'the working copy parent')),
2817 ],
2811 ],
2818 _('[-r REV]'))
2812 _('[-r REV]'))
2819 def debugrebuilddirstate(ui, repo, rev, **opts):
2813 def debugrebuilddirstate(ui, repo, rev, **opts):
2820 """rebuild the dirstate as it would look like for the given revision
2814 """rebuild the dirstate as it would look like for the given revision
2821
2815
2822 If no revision is specified the first current parent will be used.
2816 If no revision is specified the first current parent will be used.
2823
2817
2824 The dirstate will be set to the files of the given revision.
2818 The dirstate will be set to the files of the given revision.
2825 The actual working directory content or existing dirstate
2819 The actual working directory content or existing dirstate
2826 information such as adds or removes is not considered.
2820 information such as adds or removes is not considered.
2827
2821
2828 ``minimal`` will only rebuild the dirstate status for files that claim to be
2822 ``minimal`` will only rebuild the dirstate status for files that claim to be
2829 tracked but are not in the parent manifest, or that exist in the parent
2823 tracked but are not in the parent manifest, or that exist in the parent
2830 manifest but are not in the dirstate. It will not change adds, removes, or
2824 manifest but are not in the dirstate. It will not change adds, removes, or
2831 modified files that are in the working copy parent.
2825 modified files that are in the working copy parent.
2832
2826
2833 One use of this command is to make the next :hg:`status` invocation
2827 One use of this command is to make the next :hg:`status` invocation
2834 check the actual file content.
2828 check the actual file content.
2835 """
2829 """
2836 ctx = scmutil.revsingle(repo, rev)
2830 ctx = scmutil.revsingle(repo, rev)
2837 wlock = repo.wlock()
2831 wlock = repo.wlock()
2838 try:
2832 try:
2839 dirstate = repo.dirstate
2833 dirstate = repo.dirstate
2840
2834
2841 # See command doc for what minimal does.
2835 # See command doc for what minimal does.
2842 if opts.get('minimal'):
2836 if opts.get('minimal'):
2843 dirstatefiles = set(dirstate)
2837 dirstatefiles = set(dirstate)
2844 ctxfiles = set(ctx.manifest().keys())
2838 ctxfiles = set(ctx.manifest().keys())
2845 for file in (dirstatefiles | ctxfiles):
2839 for file in (dirstatefiles | ctxfiles):
2846 indirstate = file in dirstatefiles
2840 indirstate = file in dirstatefiles
2847 inctx = file in ctxfiles
2841 inctx = file in ctxfiles
2848
2842
2849 if indirstate and not inctx and dirstate[file] != 'a':
2843 if indirstate and not inctx and dirstate[file] != 'a':
2850 dirstate.drop(file)
2844 dirstate.drop(file)
2851 elif inctx and not indirstate:
2845 elif inctx and not indirstate:
2852 dirstate.normallookup(file)
2846 dirstate.normallookup(file)
2853 else:
2847 else:
2854 dirstate.rebuild(ctx.node(), ctx.manifest())
2848 dirstate.rebuild(ctx.node(), ctx.manifest())
2855 finally:
2849 finally:
2856 wlock.release()
2850 wlock.release()
2857
2851
2858 @command('debugrebuildfncache', [], '')
2852 @command('debugrebuildfncache', [], '')
2859 def debugrebuildfncache(ui, repo):
2853 def debugrebuildfncache(ui, repo):
2860 """rebuild the fncache file"""
2854 """rebuild the fncache file"""
2861 repair.rebuildfncache(ui, repo)
2855 repair.rebuildfncache(ui, repo)
2862
2856
2863 @command('debugrename',
2857 @command('debugrename',
2864 [('r', 'rev', '', _('revision to debug'), _('REV'))],
2858 [('r', 'rev', '', _('revision to debug'), _('REV'))],
2865 _('[-r REV] FILE'))
2859 _('[-r REV] FILE'))
2866 def debugrename(ui, repo, file1, *pats, **opts):
2860 def debugrename(ui, repo, file1, *pats, **opts):
2867 """dump rename information"""
2861 """dump rename information"""
2868
2862
2869 ctx = scmutil.revsingle(repo, opts.get('rev'))
2863 ctx = scmutil.revsingle(repo, opts.get('rev'))
2870 m = scmutil.match(ctx, (file1,) + pats, opts)
2864 m = scmutil.match(ctx, (file1,) + pats, opts)
2871 for abs in ctx.walk(m):
2865 for abs in ctx.walk(m):
2872 fctx = ctx[abs]
2866 fctx = ctx[abs]
2873 o = fctx.filelog().renamed(fctx.filenode())
2867 o = fctx.filelog().renamed(fctx.filenode())
2874 rel = m.rel(abs)
2868 rel = m.rel(abs)
2875 if o:
2869 if o:
2876 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
2870 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
2877 else:
2871 else:
2878 ui.write(_("%s not renamed\n") % rel)
2872 ui.write(_("%s not renamed\n") % rel)
2879
2873
2880 @command('debugrevlog',
2874 @command('debugrevlog',
2881 [('c', 'changelog', False, _('open changelog')),
2875 [('c', 'changelog', False, _('open changelog')),
2882 ('m', 'manifest', False, _('open manifest')),
2876 ('m', 'manifest', False, _('open manifest')),
2883 ('', 'dir', False, _('open directory manifest')),
2877 ('', 'dir', False, _('open directory manifest')),
2884 ('d', 'dump', False, _('dump index data'))],
2878 ('d', 'dump', False, _('dump index data'))],
2885 _('-c|-m|FILE'),
2879 _('-c|-m|FILE'),
2886 optionalrepo=True)
2880 optionalrepo=True)
2887 def debugrevlog(ui, repo, file_=None, **opts):
2881 def debugrevlog(ui, repo, file_=None, **opts):
2888 """show data and statistics about a revlog"""
2882 """show data and statistics about a revlog"""
2889 r = cmdutil.openrevlog(repo, 'debugrevlog', file_, opts)
2883 r = cmdutil.openrevlog(repo, 'debugrevlog', file_, opts)
2890
2884
2891 if opts.get("dump"):
2885 if opts.get("dump"):
2892 numrevs = len(r)
2886 numrevs = len(r)
2893 ui.write("# rev p1rev p2rev start end deltastart base p1 p2"
2887 ui.write("# rev p1rev p2rev start end deltastart base p1 p2"
2894 " rawsize totalsize compression heads chainlen\n")
2888 " rawsize totalsize compression heads chainlen\n")
2895 ts = 0
2889 ts = 0
2896 heads = set()
2890 heads = set()
2897
2891
2898 for rev in xrange(numrevs):
2892 for rev in xrange(numrevs):
2899 dbase = r.deltaparent(rev)
2893 dbase = r.deltaparent(rev)
2900 if dbase == -1:
2894 if dbase == -1:
2901 dbase = rev
2895 dbase = rev
2902 cbase = r.chainbase(rev)
2896 cbase = r.chainbase(rev)
2903 clen = r.chainlen(rev)
2897 clen = r.chainlen(rev)
2904 p1, p2 = r.parentrevs(rev)
2898 p1, p2 = r.parentrevs(rev)
2905 rs = r.rawsize(rev)
2899 rs = r.rawsize(rev)
2906 ts = ts + rs
2900 ts = ts + rs
2907 heads -= set(r.parentrevs(rev))
2901 heads -= set(r.parentrevs(rev))
2908 heads.add(rev)
2902 heads.add(rev)
2909 ui.write("%5d %5d %5d %5d %5d %10d %4d %4d %4d %7d %9d "
2903 ui.write("%5d %5d %5d %5d %5d %10d %4d %4d %4d %7d %9d "
2910 "%11d %5d %8d\n" %
2904 "%11d %5d %8d\n" %
2911 (rev, p1, p2, r.start(rev), r.end(rev),
2905 (rev, p1, p2, r.start(rev), r.end(rev),
2912 r.start(dbase), r.start(cbase),
2906 r.start(dbase), r.start(cbase),
2913 r.start(p1), r.start(p2),
2907 r.start(p1), r.start(p2),
2914 rs, ts, ts / r.end(rev), len(heads), clen))
2908 rs, ts, ts / r.end(rev), len(heads), clen))
2915 return 0
2909 return 0
2916
2910
2917 v = r.version
2911 v = r.version
2918 format = v & 0xFFFF
2912 format = v & 0xFFFF
2919 flags = []
2913 flags = []
2920 gdelta = False
2914 gdelta = False
2921 if v & revlog.REVLOGNGINLINEDATA:
2915 if v & revlog.REVLOGNGINLINEDATA:
2922 flags.append('inline')
2916 flags.append('inline')
2923 if v & revlog.REVLOGGENERALDELTA:
2917 if v & revlog.REVLOGGENERALDELTA:
2924 gdelta = True
2918 gdelta = True
2925 flags.append('generaldelta')
2919 flags.append('generaldelta')
2926 if not flags:
2920 if not flags:
2927 flags = ['(none)']
2921 flags = ['(none)']
2928
2922
2929 nummerges = 0
2923 nummerges = 0
2930 numfull = 0
2924 numfull = 0
2931 numprev = 0
2925 numprev = 0
2932 nump1 = 0
2926 nump1 = 0
2933 nump2 = 0
2927 nump2 = 0
2934 numother = 0
2928 numother = 0
2935 nump1prev = 0
2929 nump1prev = 0
2936 nump2prev = 0
2930 nump2prev = 0
2937 chainlengths = []
2931 chainlengths = []
2938
2932
2939 datasize = [None, 0, 0L]
2933 datasize = [None, 0, 0L]
2940 fullsize = [None, 0, 0L]
2934 fullsize = [None, 0, 0L]
2941 deltasize = [None, 0, 0L]
2935 deltasize = [None, 0, 0L]
2942
2936
2943 def addsize(size, l):
2937 def addsize(size, l):
2944 if l[0] is None or size < l[0]:
2938 if l[0] is None or size < l[0]:
2945 l[0] = size
2939 l[0] = size
2946 if size > l[1]:
2940 if size > l[1]:
2947 l[1] = size
2941 l[1] = size
2948 l[2] += size
2942 l[2] += size
2949
2943
2950 numrevs = len(r)
2944 numrevs = len(r)
2951 for rev in xrange(numrevs):
2945 for rev in xrange(numrevs):
2952 p1, p2 = r.parentrevs(rev)
2946 p1, p2 = r.parentrevs(rev)
2953 delta = r.deltaparent(rev)
2947 delta = r.deltaparent(rev)
2954 if format > 0:
2948 if format > 0:
2955 addsize(r.rawsize(rev), datasize)
2949 addsize(r.rawsize(rev), datasize)
2956 if p2 != nullrev:
2950 if p2 != nullrev:
2957 nummerges += 1
2951 nummerges += 1
2958 size = r.length(rev)
2952 size = r.length(rev)
2959 if delta == nullrev:
2953 if delta == nullrev:
2960 chainlengths.append(0)
2954 chainlengths.append(0)
2961 numfull += 1
2955 numfull += 1
2962 addsize(size, fullsize)
2956 addsize(size, fullsize)
2963 else:
2957 else:
2964 chainlengths.append(chainlengths[delta] + 1)
2958 chainlengths.append(chainlengths[delta] + 1)
2965 addsize(size, deltasize)
2959 addsize(size, deltasize)
2966 if delta == rev - 1:
2960 if delta == rev - 1:
2967 numprev += 1
2961 numprev += 1
2968 if delta == p1:
2962 if delta == p1:
2969 nump1prev += 1
2963 nump1prev += 1
2970 elif delta == p2:
2964 elif delta == p2:
2971 nump2prev += 1
2965 nump2prev += 1
2972 elif delta == p1:
2966 elif delta == p1:
2973 nump1 += 1
2967 nump1 += 1
2974 elif delta == p2:
2968 elif delta == p2:
2975 nump2 += 1
2969 nump2 += 1
2976 elif delta != nullrev:
2970 elif delta != nullrev:
2977 numother += 1
2971 numother += 1
2978
2972
2979 # Adjust size min value for empty cases
2973 # Adjust size min value for empty cases
2980 for size in (datasize, fullsize, deltasize):
2974 for size in (datasize, fullsize, deltasize):
2981 if size[0] is None:
2975 if size[0] is None:
2982 size[0] = 0
2976 size[0] = 0
2983
2977
2984 numdeltas = numrevs - numfull
2978 numdeltas = numrevs - numfull
2985 numoprev = numprev - nump1prev - nump2prev
2979 numoprev = numprev - nump1prev - nump2prev
2986 totalrawsize = datasize[2]
2980 totalrawsize = datasize[2]
2987 datasize[2] /= numrevs
2981 datasize[2] /= numrevs
2988 fulltotal = fullsize[2]
2982 fulltotal = fullsize[2]
2989 fullsize[2] /= numfull
2983 fullsize[2] /= numfull
2990 deltatotal = deltasize[2]
2984 deltatotal = deltasize[2]
2991 if numrevs - numfull > 0:
2985 if numrevs - numfull > 0:
2992 deltasize[2] /= numrevs - numfull
2986 deltasize[2] /= numrevs - numfull
2993 totalsize = fulltotal + deltatotal
2987 totalsize = fulltotal + deltatotal
2994 avgchainlen = sum(chainlengths) / numrevs
2988 avgchainlen = sum(chainlengths) / numrevs
2995 maxchainlen = max(chainlengths)
2989 maxchainlen = max(chainlengths)
2996 compratio = totalrawsize / totalsize
2990 compratio = totalrawsize / totalsize
2997
2991
2998 basedfmtstr = '%%%dd\n'
2992 basedfmtstr = '%%%dd\n'
2999 basepcfmtstr = '%%%dd %s(%%5.2f%%%%)\n'
2993 basepcfmtstr = '%%%dd %s(%%5.2f%%%%)\n'
3000
2994
3001 def dfmtstr(max):
2995 def dfmtstr(max):
3002 return basedfmtstr % len(str(max))
2996 return basedfmtstr % len(str(max))
3003 def pcfmtstr(max, padding=0):
2997 def pcfmtstr(max, padding=0):
3004 return basepcfmtstr % (len(str(max)), ' ' * padding)
2998 return basepcfmtstr % (len(str(max)), ' ' * padding)
3005
2999
3006 def pcfmt(value, total):
3000 def pcfmt(value, total):
3007 return (value, 100 * float(value) / total)
3001 return (value, 100 * float(value) / total)
3008
3002
3009 ui.write(('format : %d\n') % format)
3003 ui.write(('format : %d\n') % format)
3010 ui.write(('flags : %s\n') % ', '.join(flags))
3004 ui.write(('flags : %s\n') % ', '.join(flags))
3011
3005
3012 ui.write('\n')
3006 ui.write('\n')
3013 fmt = pcfmtstr(totalsize)
3007 fmt = pcfmtstr(totalsize)
3014 fmt2 = dfmtstr(totalsize)
3008 fmt2 = dfmtstr(totalsize)
3015 ui.write(('revisions : ') + fmt2 % numrevs)
3009 ui.write(('revisions : ') + fmt2 % numrevs)
3016 ui.write((' merges : ') + fmt % pcfmt(nummerges, numrevs))
3010 ui.write((' merges : ') + fmt % pcfmt(nummerges, numrevs))
3017 ui.write((' normal : ') + fmt % pcfmt(numrevs - nummerges, numrevs))
3011 ui.write((' normal : ') + fmt % pcfmt(numrevs - nummerges, numrevs))
3018 ui.write(('revisions : ') + fmt2 % numrevs)
3012 ui.write(('revisions : ') + fmt2 % numrevs)
3019 ui.write((' full : ') + fmt % pcfmt(numfull, numrevs))
3013 ui.write((' full : ') + fmt % pcfmt(numfull, numrevs))
3020 ui.write((' deltas : ') + fmt % pcfmt(numdeltas, numrevs))
3014 ui.write((' deltas : ') + fmt % pcfmt(numdeltas, numrevs))
3021 ui.write(('revision size : ') + fmt2 % totalsize)
3015 ui.write(('revision size : ') + fmt2 % totalsize)
3022 ui.write((' full : ') + fmt % pcfmt(fulltotal, totalsize))
3016 ui.write((' full : ') + fmt % pcfmt(fulltotal, totalsize))
3023 ui.write((' deltas : ') + fmt % pcfmt(deltatotal, totalsize))
3017 ui.write((' deltas : ') + fmt % pcfmt(deltatotal, totalsize))
3024
3018
3025 ui.write('\n')
3019 ui.write('\n')
3026 fmt = dfmtstr(max(avgchainlen, compratio))
3020 fmt = dfmtstr(max(avgchainlen, compratio))
3027 ui.write(('avg chain length : ') + fmt % avgchainlen)
3021 ui.write(('avg chain length : ') + fmt % avgchainlen)
3028 ui.write(('max chain length : ') + fmt % maxchainlen)
3022 ui.write(('max chain length : ') + fmt % maxchainlen)
3029 ui.write(('compression ratio : ') + fmt % compratio)
3023 ui.write(('compression ratio : ') + fmt % compratio)
3030
3024
3031 if format > 0:
3025 if format > 0:
3032 ui.write('\n')
3026 ui.write('\n')
3033 ui.write(('uncompressed data size (min/max/avg) : %d / %d / %d\n')
3027 ui.write(('uncompressed data size (min/max/avg) : %d / %d / %d\n')
3034 % tuple(datasize))
3028 % tuple(datasize))
3035 ui.write(('full revision size (min/max/avg) : %d / %d / %d\n')
3029 ui.write(('full revision size (min/max/avg) : %d / %d / %d\n')
3036 % tuple(fullsize))
3030 % tuple(fullsize))
3037 ui.write(('delta size (min/max/avg) : %d / %d / %d\n')
3031 ui.write(('delta size (min/max/avg) : %d / %d / %d\n')
3038 % tuple(deltasize))
3032 % tuple(deltasize))
3039
3033
3040 if numdeltas > 0:
3034 if numdeltas > 0:
3041 ui.write('\n')
3035 ui.write('\n')
3042 fmt = pcfmtstr(numdeltas)
3036 fmt = pcfmtstr(numdeltas)
3043 fmt2 = pcfmtstr(numdeltas, 4)
3037 fmt2 = pcfmtstr(numdeltas, 4)
3044 ui.write(('deltas against prev : ') + fmt % pcfmt(numprev, numdeltas))
3038 ui.write(('deltas against prev : ') + fmt % pcfmt(numprev, numdeltas))
3045 if numprev > 0:
3039 if numprev > 0:
3046 ui.write((' where prev = p1 : ') + fmt2 % pcfmt(nump1prev,
3040 ui.write((' where prev = p1 : ') + fmt2 % pcfmt(nump1prev,
3047 numprev))
3041 numprev))
3048 ui.write((' where prev = p2 : ') + fmt2 % pcfmt(nump2prev,
3042 ui.write((' where prev = p2 : ') + fmt2 % pcfmt(nump2prev,
3049 numprev))
3043 numprev))
3050 ui.write((' other : ') + fmt2 % pcfmt(numoprev,
3044 ui.write((' other : ') + fmt2 % pcfmt(numoprev,
3051 numprev))
3045 numprev))
3052 if gdelta:
3046 if gdelta:
3053 ui.write(('deltas against p1 : ')
3047 ui.write(('deltas against p1 : ')
3054 + fmt % pcfmt(nump1, numdeltas))
3048 + fmt % pcfmt(nump1, numdeltas))
3055 ui.write(('deltas against p2 : ')
3049 ui.write(('deltas against p2 : ')
3056 + fmt % pcfmt(nump2, numdeltas))
3050 + fmt % pcfmt(nump2, numdeltas))
3057 ui.write(('deltas against other : ') + fmt % pcfmt(numother,
3051 ui.write(('deltas against other : ') + fmt % pcfmt(numother,
3058 numdeltas))
3052 numdeltas))
3059
3053
3060 @command('debugrevspec',
3054 @command('debugrevspec',
3061 [('', 'optimize', None, _('print parsed tree after optimizing'))],
3055 [('', 'optimize', None, _('print parsed tree after optimizing'))],
3062 ('REVSPEC'))
3056 ('REVSPEC'))
3063 def debugrevspec(ui, repo, expr, **opts):
3057 def debugrevspec(ui, repo, expr, **opts):
3064 """parse and apply a revision specification
3058 """parse and apply a revision specification
3065
3059
3066 Use --verbose to print the parsed tree before and after aliases
3060 Use --verbose to print the parsed tree before and after aliases
3067 expansion.
3061 expansion.
3068 """
3062 """
3069 if ui.verbose:
3063 if ui.verbose:
3070 tree = revset.parse(expr, lookup=repo.__contains__)
3064 tree = revset.parse(expr, lookup=repo.__contains__)
3071 ui.note(revset.prettyformat(tree), "\n")
3065 ui.note(revset.prettyformat(tree), "\n")
3072 newtree = revset.findaliases(ui, tree)
3066 newtree = revset.findaliases(ui, tree)
3073 if newtree != tree:
3067 if newtree != tree:
3074 ui.note(revset.prettyformat(newtree), "\n")
3068 ui.note(revset.prettyformat(newtree), "\n")
3075 tree = newtree
3069 tree = newtree
3076 newtree = revset.foldconcat(tree)
3070 newtree = revset.foldconcat(tree)
3077 if newtree != tree:
3071 if newtree != tree:
3078 ui.note(revset.prettyformat(newtree), "\n")
3072 ui.note(revset.prettyformat(newtree), "\n")
3079 if opts["optimize"]:
3073 if opts["optimize"]:
3080 weight, optimizedtree = revset.optimize(newtree, True)
3074 weight, optimizedtree = revset.optimize(newtree, True)
3081 ui.note("* optimized:\n", revset.prettyformat(optimizedtree), "\n")
3075 ui.note("* optimized:\n", revset.prettyformat(optimizedtree), "\n")
3082 func = revset.match(ui, expr, repo)
3076 func = revset.match(ui, expr, repo)
3083 revs = func(repo)
3077 revs = func(repo)
3084 if ui.verbose:
3078 if ui.verbose:
3085 ui.note("* set:\n", revset.prettyformatset(revs), "\n")
3079 ui.note("* set:\n", revset.prettyformatset(revs), "\n")
3086 for c in revs:
3080 for c in revs:
3087 ui.write("%s\n" % c)
3081 ui.write("%s\n" % c)
3088
3082
3089 @command('debugsetparents', [], _('REV1 [REV2]'))
3083 @command('debugsetparents', [], _('REV1 [REV2]'))
3090 def debugsetparents(ui, repo, rev1, rev2=None):
3084 def debugsetparents(ui, repo, rev1, rev2=None):
3091 """manually set the parents of the current working directory
3085 """manually set the parents of the current working directory
3092
3086
3093 This is useful for writing repository conversion tools, but should
3087 This is useful for writing repository conversion tools, but should
3094 be used with care. For example, neither the working directory nor the
3088 be used with care. For example, neither the working directory nor the
3095 dirstate is updated, so file status may be incorrect after running this
3089 dirstate is updated, so file status may be incorrect after running this
3096 command.
3090 command.
3097
3091
3098 Returns 0 on success.
3092 Returns 0 on success.
3099 """
3093 """
3100
3094
3101 r1 = scmutil.revsingle(repo, rev1).node()
3095 r1 = scmutil.revsingle(repo, rev1).node()
3102 r2 = scmutil.revsingle(repo, rev2, 'null').node()
3096 r2 = scmutil.revsingle(repo, rev2, 'null').node()
3103
3097
3104 wlock = repo.wlock()
3098 wlock = repo.wlock()
3105 try:
3099 try:
3106 repo.dirstate.beginparentchange()
3100 repo.dirstate.beginparentchange()
3107 repo.setparents(r1, r2)
3101 repo.setparents(r1, r2)
3108 repo.dirstate.endparentchange()
3102 repo.dirstate.endparentchange()
3109 finally:
3103 finally:
3110 wlock.release()
3104 wlock.release()
3111
3105
3112 @command('debugdirstate|debugstate',
3106 @command('debugdirstate|debugstate',
3113 [('', 'nodates', None, _('do not display the saved mtime')),
3107 [('', 'nodates', None, _('do not display the saved mtime')),
3114 ('', 'datesort', None, _('sort by saved mtime'))],
3108 ('', 'datesort', None, _('sort by saved mtime'))],
3115 _('[OPTION]...'))
3109 _('[OPTION]...'))
3116 def debugstate(ui, repo, nodates=None, datesort=None):
3110 def debugstate(ui, repo, nodates=None, datesort=None):
3117 """show the contents of the current dirstate"""
3111 """show the contents of the current dirstate"""
3118 timestr = ""
3112 timestr = ""
3119 if datesort:
3113 if datesort:
3120 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
3114 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
3121 else:
3115 else:
3122 keyfunc = None # sort by filename
3116 keyfunc = None # sort by filename
3123 for file_, ent in sorted(repo.dirstate._map.iteritems(), key=keyfunc):
3117 for file_, ent in sorted(repo.dirstate._map.iteritems(), key=keyfunc):
3124 if ent[3] == -1:
3118 if ent[3] == -1:
3125 timestr = 'unset '
3119 timestr = 'unset '
3126 elif nodates:
3120 elif nodates:
3127 timestr = 'set '
3121 timestr = 'set '
3128 else:
3122 else:
3129 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
3123 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
3130 time.localtime(ent[3]))
3124 time.localtime(ent[3]))
3131 if ent[1] & 0o20000:
3125 if ent[1] & 0o20000:
3132 mode = 'lnk'
3126 mode = 'lnk'
3133 else:
3127 else:
3134 mode = '%3o' % (ent[1] & 0o777 & ~util.umask)
3128 mode = '%3o' % (ent[1] & 0o777 & ~util.umask)
3135 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
3129 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
3136 for f in repo.dirstate.copies():
3130 for f in repo.dirstate.copies():
3137 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
3131 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
3138
3132
3139 @command('debugsub',
3133 @command('debugsub',
3140 [('r', 'rev', '',
3134 [('r', 'rev', '',
3141 _('revision to check'), _('REV'))],
3135 _('revision to check'), _('REV'))],
3142 _('[-r REV] [REV]'))
3136 _('[-r REV] [REV]'))
3143 def debugsub(ui, repo, rev=None):
3137 def debugsub(ui, repo, rev=None):
3144 ctx = scmutil.revsingle(repo, rev, None)
3138 ctx = scmutil.revsingle(repo, rev, None)
3145 for k, v in sorted(ctx.substate.items()):
3139 for k, v in sorted(ctx.substate.items()):
3146 ui.write(('path %s\n') % k)
3140 ui.write(('path %s\n') % k)
3147 ui.write((' source %s\n') % v[0])
3141 ui.write((' source %s\n') % v[0])
3148 ui.write((' revision %s\n') % v[1])
3142 ui.write((' revision %s\n') % v[1])
3149
3143
3150 @command('debugsuccessorssets',
3144 @command('debugsuccessorssets',
3151 [],
3145 [],
3152 _('[REV]'))
3146 _('[REV]'))
3153 def debugsuccessorssets(ui, repo, *revs):
3147 def debugsuccessorssets(ui, repo, *revs):
3154 """show set of successors for revision
3148 """show set of successors for revision
3155
3149
3156 A successors set of changeset A is a consistent group of revisions that
3150 A successors set of changeset A is a consistent group of revisions that
3157 succeed A. It contains non-obsolete changesets only.
3151 succeed A. It contains non-obsolete changesets only.
3158
3152
3159 In most cases a changeset A has a single successors set containing a single
3153 In most cases a changeset A has a single successors set containing a single
3160 successor (changeset A replaced by A').
3154 successor (changeset A replaced by A').
3161
3155
3162 A changeset that is made obsolete with no successors are called "pruned".
3156 A changeset that is made obsolete with no successors are called "pruned".
3163 Such changesets have no successors sets at all.
3157 Such changesets have no successors sets at all.
3164
3158
3165 A changeset that has been "split" will have a successors set containing
3159 A changeset that has been "split" will have a successors set containing
3166 more than one successor.
3160 more than one successor.
3167
3161
3168 A changeset that has been rewritten in multiple different ways is called
3162 A changeset that has been rewritten in multiple different ways is called
3169 "divergent". Such changesets have multiple successor sets (each of which
3163 "divergent". Such changesets have multiple successor sets (each of which
3170 may also be split, i.e. have multiple successors).
3164 may also be split, i.e. have multiple successors).
3171
3165
3172 Results are displayed as follows::
3166 Results are displayed as follows::
3173
3167
3174 <rev1>
3168 <rev1>
3175 <successors-1A>
3169 <successors-1A>
3176 <rev2>
3170 <rev2>
3177 <successors-2A>
3171 <successors-2A>
3178 <successors-2B1> <successors-2B2> <successors-2B3>
3172 <successors-2B1> <successors-2B2> <successors-2B3>
3179
3173
3180 Here rev2 has two possible (i.e. divergent) successors sets. The first
3174 Here rev2 has two possible (i.e. divergent) successors sets. The first
3181 holds one element, whereas the second holds three (i.e. the changeset has
3175 holds one element, whereas the second holds three (i.e. the changeset has
3182 been split).
3176 been split).
3183 """
3177 """
3184 # passed to successorssets caching computation from one call to another
3178 # passed to successorssets caching computation from one call to another
3185 cache = {}
3179 cache = {}
3186 ctx2str = str
3180 ctx2str = str
3187 node2str = short
3181 node2str = short
3188 if ui.debug():
3182 if ui.debug():
3189 def ctx2str(ctx):
3183 def ctx2str(ctx):
3190 return ctx.hex()
3184 return ctx.hex()
3191 node2str = hex
3185 node2str = hex
3192 for rev in scmutil.revrange(repo, revs):
3186 for rev in scmutil.revrange(repo, revs):
3193 ctx = repo[rev]
3187 ctx = repo[rev]
3194 ui.write('%s\n'% ctx2str(ctx))
3188 ui.write('%s\n'% ctx2str(ctx))
3195 for succsset in obsolete.successorssets(repo, ctx.node(), cache):
3189 for succsset in obsolete.successorssets(repo, ctx.node(), cache):
3196 if succsset:
3190 if succsset:
3197 ui.write(' ')
3191 ui.write(' ')
3198 ui.write(node2str(succsset[0]))
3192 ui.write(node2str(succsset[0]))
3199 for node in succsset[1:]:
3193 for node in succsset[1:]:
3200 ui.write(' ')
3194 ui.write(' ')
3201 ui.write(node2str(node))
3195 ui.write(node2str(node))
3202 ui.write('\n')
3196 ui.write('\n')
3203
3197
3204 @command('debugwalk', walkopts, _('[OPTION]... [FILE]...'), inferrepo=True)
3198 @command('debugwalk', walkopts, _('[OPTION]... [FILE]...'), inferrepo=True)
3205 def debugwalk(ui, repo, *pats, **opts):
3199 def debugwalk(ui, repo, *pats, **opts):
3206 """show how files match on given patterns"""
3200 """show how files match on given patterns"""
3207 m = scmutil.match(repo[None], pats, opts)
3201 m = scmutil.match(repo[None], pats, opts)
3208 items = list(repo.walk(m))
3202 items = list(repo.walk(m))
3209 if not items:
3203 if not items:
3210 return
3204 return
3211 f = lambda fn: fn
3205 f = lambda fn: fn
3212 if ui.configbool('ui', 'slash') and os.sep != '/':
3206 if ui.configbool('ui', 'slash') and os.sep != '/':
3213 f = lambda fn: util.normpath(fn)
3207 f = lambda fn: util.normpath(fn)
3214 fmt = 'f %%-%ds %%-%ds %%s' % (
3208 fmt = 'f %%-%ds %%-%ds %%s' % (
3215 max([len(abs) for abs in items]),
3209 max([len(abs) for abs in items]),
3216 max([len(m.rel(abs)) for abs in items]))
3210 max([len(m.rel(abs)) for abs in items]))
3217 for abs in items:
3211 for abs in items:
3218 line = fmt % (abs, f(m.rel(abs)), m.exact(abs) and 'exact' or '')
3212 line = fmt % (abs, f(m.rel(abs)), m.exact(abs) and 'exact' or '')
3219 ui.write("%s\n" % line.rstrip())
3213 ui.write("%s\n" % line.rstrip())
3220
3214
3221 @command('debugwireargs',
3215 @command('debugwireargs',
3222 [('', 'three', '', 'three'),
3216 [('', 'three', '', 'three'),
3223 ('', 'four', '', 'four'),
3217 ('', 'four', '', 'four'),
3224 ('', 'five', '', 'five'),
3218 ('', 'five', '', 'five'),
3225 ] + remoteopts,
3219 ] + remoteopts,
3226 _('REPO [OPTIONS]... [ONE [TWO]]'),
3220 _('REPO [OPTIONS]... [ONE [TWO]]'),
3227 norepo=True)
3221 norepo=True)
3228 def debugwireargs(ui, repopath, *vals, **opts):
3222 def debugwireargs(ui, repopath, *vals, **opts):
3229 repo = hg.peer(ui, opts, repopath)
3223 repo = hg.peer(ui, opts, repopath)
3230 for opt in remoteopts:
3224 for opt in remoteopts:
3231 del opts[opt[1]]
3225 del opts[opt[1]]
3232 args = {}
3226 args = {}
3233 for k, v in opts.iteritems():
3227 for k, v in opts.iteritems():
3234 if v:
3228 if v:
3235 args[k] = v
3229 args[k] = v
3236 # run twice to check that we don't mess up the stream for the next command
3230 # run twice to check that we don't mess up the stream for the next command
3237 res1 = repo.debugwireargs(*vals, **args)
3231 res1 = repo.debugwireargs(*vals, **args)
3238 res2 = repo.debugwireargs(*vals, **args)
3232 res2 = repo.debugwireargs(*vals, **args)
3239 ui.write("%s\n" % res1)
3233 ui.write("%s\n" % res1)
3240 if res1 != res2:
3234 if res1 != res2:
3241 ui.warn("%s\n" % res2)
3235 ui.warn("%s\n" % res2)
3242
3236
3243 @command('^diff',
3237 @command('^diff',
3244 [('r', 'rev', [], _('revision'), _('REV')),
3238 [('r', 'rev', [], _('revision'), _('REV')),
3245 ('c', 'change', '', _('change made by revision'), _('REV'))
3239 ('c', 'change', '', _('change made by revision'), _('REV'))
3246 ] + diffopts + diffopts2 + walkopts + subrepoopts,
3240 ] + diffopts + diffopts2 + walkopts + subrepoopts,
3247 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'),
3241 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'),
3248 inferrepo=True)
3242 inferrepo=True)
3249 def diff(ui, repo, *pats, **opts):
3243 def diff(ui, repo, *pats, **opts):
3250 """diff repository (or selected files)
3244 """diff repository (or selected files)
3251
3245
3252 Show differences between revisions for the specified files.
3246 Show differences between revisions for the specified files.
3253
3247
3254 Differences between files are shown using the unified diff format.
3248 Differences between files are shown using the unified diff format.
3255
3249
3256 .. note::
3250 .. note::
3257
3251
3258 diff may generate unexpected results for merges, as it will
3252 diff may generate unexpected results for merges, as it will
3259 default to comparing against the working directory's first
3253 default to comparing against the working directory's first
3260 parent changeset if no revisions are specified.
3254 parent changeset if no revisions are specified.
3261
3255
3262 When two revision arguments are given, then changes are shown
3256 When two revision arguments are given, then changes are shown
3263 between those revisions. If only one revision is specified then
3257 between those revisions. If only one revision is specified then
3264 that revision is compared to the working directory, and, when no
3258 that revision is compared to the working directory, and, when no
3265 revisions are specified, the working directory files are compared
3259 revisions are specified, the working directory files are compared
3266 to its parent.
3260 to its parent.
3267
3261
3268 Alternatively you can specify -c/--change with a revision to see
3262 Alternatively you can specify -c/--change with a revision to see
3269 the changes in that changeset relative to its first parent.
3263 the changes in that changeset relative to its first parent.
3270
3264
3271 Without the -a/--text option, diff will avoid generating diffs of
3265 Without the -a/--text option, diff will avoid generating diffs of
3272 files it detects as binary. With -a, diff will generate a diff
3266 files it detects as binary. With -a, diff will generate a diff
3273 anyway, probably with undesirable results.
3267 anyway, probably with undesirable results.
3274
3268
3275 Use the -g/--git option to generate diffs in the git extended diff
3269 Use the -g/--git option to generate diffs in the git extended diff
3276 format. For more information, read :hg:`help diffs`.
3270 format. For more information, read :hg:`help diffs`.
3277
3271
3278 .. container:: verbose
3272 .. container:: verbose
3279
3273
3280 Examples:
3274 Examples:
3281
3275
3282 - compare a file in the current working directory to its parent::
3276 - compare a file in the current working directory to its parent::
3283
3277
3284 hg diff foo.c
3278 hg diff foo.c
3285
3279
3286 - compare two historical versions of a directory, with rename info::
3280 - compare two historical versions of a directory, with rename info::
3287
3281
3288 hg diff --git -r 1.0:1.2 lib/
3282 hg diff --git -r 1.0:1.2 lib/
3289
3283
3290 - get change stats relative to the last change on some date::
3284 - get change stats relative to the last change on some date::
3291
3285
3292 hg diff --stat -r "date('may 2')"
3286 hg diff --stat -r "date('may 2')"
3293
3287
3294 - diff all newly-added files that contain a keyword::
3288 - diff all newly-added files that contain a keyword::
3295
3289
3296 hg diff "set:added() and grep(GNU)"
3290 hg diff "set:added() and grep(GNU)"
3297
3291
3298 - compare a revision and its parents::
3292 - compare a revision and its parents::
3299
3293
3300 hg diff -c 9353 # compare against first parent
3294 hg diff -c 9353 # compare against first parent
3301 hg diff -r 9353^:9353 # same using revset syntax
3295 hg diff -r 9353^:9353 # same using revset syntax
3302 hg diff -r 9353^2:9353 # compare against the second parent
3296 hg diff -r 9353^2:9353 # compare against the second parent
3303
3297
3304 Returns 0 on success.
3298 Returns 0 on success.
3305 """
3299 """
3306
3300
3307 revs = opts.get('rev')
3301 revs = opts.get('rev')
3308 change = opts.get('change')
3302 change = opts.get('change')
3309 stat = opts.get('stat')
3303 stat = opts.get('stat')
3310 reverse = opts.get('reverse')
3304 reverse = opts.get('reverse')
3311
3305
3312 if revs and change:
3306 if revs and change:
3313 msg = _('cannot specify --rev and --change at the same time')
3307 msg = _('cannot specify --rev and --change at the same time')
3314 raise util.Abort(msg)
3308 raise util.Abort(msg)
3315 elif change:
3309 elif change:
3316 node2 = scmutil.revsingle(repo, change, None).node()
3310 node2 = scmutil.revsingle(repo, change, None).node()
3317 node1 = repo[node2].p1().node()
3311 node1 = repo[node2].p1().node()
3318 else:
3312 else:
3319 node1, node2 = scmutil.revpair(repo, revs)
3313 node1, node2 = scmutil.revpair(repo, revs)
3320
3314
3321 if reverse:
3315 if reverse:
3322 node1, node2 = node2, node1
3316 node1, node2 = node2, node1
3323
3317
3324 diffopts = patch.diffallopts(ui, opts)
3318 diffopts = patch.diffallopts(ui, opts)
3325 m = scmutil.match(repo[node2], pats, opts)
3319 m = scmutil.match(repo[node2], pats, opts)
3326 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
3320 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
3327 listsubrepos=opts.get('subrepos'),
3321 listsubrepos=opts.get('subrepos'),
3328 root=opts.get('root'))
3322 root=opts.get('root'))
3329
3323
3330 @command('^export',
3324 @command('^export',
3331 [('o', 'output', '',
3325 [('o', 'output', '',
3332 _('print output to file with formatted name'), _('FORMAT')),
3326 _('print output to file with formatted name'), _('FORMAT')),
3333 ('', 'switch-parent', None, _('diff against the second parent')),
3327 ('', 'switch-parent', None, _('diff against the second parent')),
3334 ('r', 'rev', [], _('revisions to export'), _('REV')),
3328 ('r', 'rev', [], _('revisions to export'), _('REV')),
3335 ] + diffopts,
3329 ] + diffopts,
3336 _('[OPTION]... [-o OUTFILESPEC] [-r] [REV]...'))
3330 _('[OPTION]... [-o OUTFILESPEC] [-r] [REV]...'))
3337 def export(ui, repo, *changesets, **opts):
3331 def export(ui, repo, *changesets, **opts):
3338 """dump the header and diffs for one or more changesets
3332 """dump the header and diffs for one or more changesets
3339
3333
3340 Print the changeset header and diffs for one or more revisions.
3334 Print the changeset header and diffs for one or more revisions.
3341 If no revision is given, the parent of the working directory is used.
3335 If no revision is given, the parent of the working directory is used.
3342
3336
3343 The information shown in the changeset header is: author, date,
3337 The information shown in the changeset header is: author, date,
3344 branch name (if non-default), changeset hash, parent(s) and commit
3338 branch name (if non-default), changeset hash, parent(s) and commit
3345 comment.
3339 comment.
3346
3340
3347 .. note::
3341 .. note::
3348
3342
3349 export may generate unexpected diff output for merge
3343 export may generate unexpected diff output for merge
3350 changesets, as it will compare the merge changeset against its
3344 changesets, as it will compare the merge changeset against its
3351 first parent only.
3345 first parent only.
3352
3346
3353 Output may be to a file, in which case the name of the file is
3347 Output may be to a file, in which case the name of the file is
3354 given using a format string. The formatting rules are as follows:
3348 given using a format string. The formatting rules are as follows:
3355
3349
3356 :``%%``: literal "%" character
3350 :``%%``: literal "%" character
3357 :``%H``: changeset hash (40 hexadecimal digits)
3351 :``%H``: changeset hash (40 hexadecimal digits)
3358 :``%N``: number of patches being generated
3352 :``%N``: number of patches being generated
3359 :``%R``: changeset revision number
3353 :``%R``: changeset revision number
3360 :``%b``: basename of the exporting repository
3354 :``%b``: basename of the exporting repository
3361 :``%h``: short-form changeset hash (12 hexadecimal digits)
3355 :``%h``: short-form changeset hash (12 hexadecimal digits)
3362 :``%m``: first line of the commit message (only alphanumeric characters)
3356 :``%m``: first line of the commit message (only alphanumeric characters)
3363 :``%n``: zero-padded sequence number, starting at 1
3357 :``%n``: zero-padded sequence number, starting at 1
3364 :``%r``: zero-padded changeset revision number
3358 :``%r``: zero-padded changeset revision number
3365
3359
3366 Without the -a/--text option, export will avoid generating diffs
3360 Without the -a/--text option, export will avoid generating diffs
3367 of files it detects as binary. With -a, export will generate a
3361 of files it detects as binary. With -a, export will generate a
3368 diff anyway, probably with undesirable results.
3362 diff anyway, probably with undesirable results.
3369
3363
3370 Use the -g/--git option to generate diffs in the git extended diff
3364 Use the -g/--git option to generate diffs in the git extended diff
3371 format. See :hg:`help diffs` for more information.
3365 format. See :hg:`help diffs` for more information.
3372
3366
3373 With the --switch-parent option, the diff will be against the
3367 With the --switch-parent option, the diff will be against the
3374 second parent. It can be useful to review a merge.
3368 second parent. It can be useful to review a merge.
3375
3369
3376 .. container:: verbose
3370 .. container:: verbose
3377
3371
3378 Examples:
3372 Examples:
3379
3373
3380 - use export and import to transplant a bugfix to the current
3374 - use export and import to transplant a bugfix to the current
3381 branch::
3375 branch::
3382
3376
3383 hg export -r 9353 | hg import -
3377 hg export -r 9353 | hg import -
3384
3378
3385 - export all the changesets between two revisions to a file with
3379 - export all the changesets between two revisions to a file with
3386 rename information::
3380 rename information::
3387
3381
3388 hg export --git -r 123:150 > changes.txt
3382 hg export --git -r 123:150 > changes.txt
3389
3383
3390 - split outgoing changes into a series of patches with
3384 - split outgoing changes into a series of patches with
3391 descriptive names::
3385 descriptive names::
3392
3386
3393 hg export -r "outgoing()" -o "%n-%m.patch"
3387 hg export -r "outgoing()" -o "%n-%m.patch"
3394
3388
3395 Returns 0 on success.
3389 Returns 0 on success.
3396 """
3390 """
3397 changesets += tuple(opts.get('rev', []))
3391 changesets += tuple(opts.get('rev', []))
3398 if not changesets:
3392 if not changesets:
3399 changesets = ['.']
3393 changesets = ['.']
3400 revs = scmutil.revrange(repo, changesets)
3394 revs = scmutil.revrange(repo, changesets)
3401 if not revs:
3395 if not revs:
3402 raise util.Abort(_("export requires at least one changeset"))
3396 raise util.Abort(_("export requires at least one changeset"))
3403 if len(revs) > 1:
3397 if len(revs) > 1:
3404 ui.note(_('exporting patches:\n'))
3398 ui.note(_('exporting patches:\n'))
3405 else:
3399 else:
3406 ui.note(_('exporting patch:\n'))
3400 ui.note(_('exporting patch:\n'))
3407 cmdutil.export(repo, revs, template=opts.get('output'),
3401 cmdutil.export(repo, revs, template=opts.get('output'),
3408 switch_parent=opts.get('switch_parent'),
3402 switch_parent=opts.get('switch_parent'),
3409 opts=patch.diffallopts(ui, opts))
3403 opts=patch.diffallopts(ui, opts))
3410
3404
3411 @command('files',
3405 @command('files',
3412 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3406 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3413 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3407 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3414 ] + walkopts + formatteropts + subrepoopts,
3408 ] + walkopts + formatteropts + subrepoopts,
3415 _('[OPTION]... [PATTERN]...'))
3409 _('[OPTION]... [PATTERN]...'))
3416 def files(ui, repo, *pats, **opts):
3410 def files(ui, repo, *pats, **opts):
3417 """list tracked files
3411 """list tracked files
3418
3412
3419 Print files under Mercurial control in the working directory or
3413 Print files under Mercurial control in the working directory or
3420 specified revision whose names match the given patterns (excluding
3414 specified revision whose names match the given patterns (excluding
3421 removed files).
3415 removed files).
3422
3416
3423 If no patterns are given to match, this command prints the names
3417 If no patterns are given to match, this command prints the names
3424 of all files under Mercurial control in the working directory.
3418 of all files under Mercurial control in the working directory.
3425
3419
3426 .. container:: verbose
3420 .. container:: verbose
3427
3421
3428 Examples:
3422 Examples:
3429
3423
3430 - list all files under the current directory::
3424 - list all files under the current directory::
3431
3425
3432 hg files .
3426 hg files .
3433
3427
3434 - shows sizes and flags for current revision::
3428 - shows sizes and flags for current revision::
3435
3429
3436 hg files -vr .
3430 hg files -vr .
3437
3431
3438 - list all files named README::
3432 - list all files named README::
3439
3433
3440 hg files -I "**/README"
3434 hg files -I "**/README"
3441
3435
3442 - list all binary files::
3436 - list all binary files::
3443
3437
3444 hg files "set:binary()"
3438 hg files "set:binary()"
3445
3439
3446 - find files containing a regular expression::
3440 - find files containing a regular expression::
3447
3441
3448 hg files "set:grep('bob')"
3442 hg files "set:grep('bob')"
3449
3443
3450 - search tracked file contents with xargs and grep::
3444 - search tracked file contents with xargs and grep::
3451
3445
3452 hg files -0 | xargs -0 grep foo
3446 hg files -0 | xargs -0 grep foo
3453
3447
3454 See :hg:`help patterns` and :hg:`help filesets` for more information
3448 See :hg:`help patterns` and :hg:`help filesets` for more information
3455 on specifying file patterns.
3449 on specifying file patterns.
3456
3450
3457 Returns 0 if a match is found, 1 otherwise.
3451 Returns 0 if a match is found, 1 otherwise.
3458
3452
3459 """
3453 """
3460 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
3454 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
3461
3455
3462 end = '\n'
3456 end = '\n'
3463 if opts.get('print0'):
3457 if opts.get('print0'):
3464 end = '\0'
3458 end = '\0'
3465 fm = ui.formatter('files', opts)
3459 fm = ui.formatter('files', opts)
3466 fmt = '%s' + end
3460 fmt = '%s' + end
3467
3461
3468 m = scmutil.match(ctx, pats, opts)
3462 m = scmutil.match(ctx, pats, opts)
3469 ret = cmdutil.files(ui, ctx, m, fm, fmt, opts.get('subrepos'))
3463 ret = cmdutil.files(ui, ctx, m, fm, fmt, opts.get('subrepos'))
3470
3464
3471 fm.end()
3465 fm.end()
3472
3466
3473 return ret
3467 return ret
3474
3468
3475 @command('^forget', walkopts, _('[OPTION]... FILE...'), inferrepo=True)
3469 @command('^forget', walkopts, _('[OPTION]... FILE...'), inferrepo=True)
3476 def forget(ui, repo, *pats, **opts):
3470 def forget(ui, repo, *pats, **opts):
3477 """forget the specified files on the next commit
3471 """forget the specified files on the next commit
3478
3472
3479 Mark the specified files so they will no longer be tracked
3473 Mark the specified files so they will no longer be tracked
3480 after the next commit.
3474 after the next commit.
3481
3475
3482 This only removes files from the current branch, not from the
3476 This only removes files from the current branch, not from the
3483 entire project history, and it does not delete them from the
3477 entire project history, and it does not delete them from the
3484 working directory.
3478 working directory.
3485
3479
3486 To delete the file from the working directory, see :hg:`remove`.
3480 To delete the file from the working directory, see :hg:`remove`.
3487
3481
3488 To undo a forget before the next commit, see :hg:`add`.
3482 To undo a forget before the next commit, see :hg:`add`.
3489
3483
3490 .. container:: verbose
3484 .. container:: verbose
3491
3485
3492 Examples:
3486 Examples:
3493
3487
3494 - forget newly-added binary files::
3488 - forget newly-added binary files::
3495
3489
3496 hg forget "set:added() and binary()"
3490 hg forget "set:added() and binary()"
3497
3491
3498 - forget files that would be excluded by .hgignore::
3492 - forget files that would be excluded by .hgignore::
3499
3493
3500 hg forget "set:hgignore()"
3494 hg forget "set:hgignore()"
3501
3495
3502 Returns 0 on success.
3496 Returns 0 on success.
3503 """
3497 """
3504
3498
3505 if not pats:
3499 if not pats:
3506 raise util.Abort(_('no files specified'))
3500 raise util.Abort(_('no files specified'))
3507
3501
3508 m = scmutil.match(repo[None], pats, opts)
3502 m = scmutil.match(repo[None], pats, opts)
3509 rejected = cmdutil.forget(ui, repo, m, prefix="", explicitonly=False)[0]
3503 rejected = cmdutil.forget(ui, repo, m, prefix="", explicitonly=False)[0]
3510 return rejected and 1 or 0
3504 return rejected and 1 or 0
3511
3505
3512 @command(
3506 @command(
3513 'graft',
3507 'graft',
3514 [('r', 'rev', [], _('revisions to graft'), _('REV')),
3508 [('r', 'rev', [], _('revisions to graft'), _('REV')),
3515 ('c', 'continue', False, _('resume interrupted graft')),
3509 ('c', 'continue', False, _('resume interrupted graft')),
3516 ('e', 'edit', False, _('invoke editor on commit messages')),
3510 ('e', 'edit', False, _('invoke editor on commit messages')),
3517 ('', 'log', None, _('append graft info to log message')),
3511 ('', 'log', None, _('append graft info to log message')),
3518 ('f', 'force', False, _('force graft')),
3512 ('f', 'force', False, _('force graft')),
3519 ('D', 'currentdate', False,
3513 ('D', 'currentdate', False,
3520 _('record the current date as commit date')),
3514 _('record the current date as commit date')),
3521 ('U', 'currentuser', False,
3515 ('U', 'currentuser', False,
3522 _('record the current user as committer'), _('DATE'))]
3516 _('record the current user as committer'), _('DATE'))]
3523 + commitopts2 + mergetoolopts + dryrunopts,
3517 + commitopts2 + mergetoolopts + dryrunopts,
3524 _('[OPTION]... [-r] REV...'))
3518 _('[OPTION]... [-r] REV...'))
3525 def graft(ui, repo, *revs, **opts):
3519 def graft(ui, repo, *revs, **opts):
3526 '''copy changes from other branches onto the current branch
3520 '''copy changes from other branches onto the current branch
3527
3521
3528 This command uses Mercurial's merge logic to copy individual
3522 This command uses Mercurial's merge logic to copy individual
3529 changes from other branches without merging branches in the
3523 changes from other branches without merging branches in the
3530 history graph. This is sometimes known as 'backporting' or
3524 history graph. This is sometimes known as 'backporting' or
3531 'cherry-picking'. By default, graft will copy user, date, and
3525 'cherry-picking'. By default, graft will copy user, date, and
3532 description from the source changesets.
3526 description from the source changesets.
3533
3527
3534 Changesets that are ancestors of the current revision, that have
3528 Changesets that are ancestors of the current revision, that have
3535 already been grafted, or that are merges will be skipped.
3529 already been grafted, or that are merges will be skipped.
3536
3530
3537 If --log is specified, log messages will have a comment appended
3531 If --log is specified, log messages will have a comment appended
3538 of the form::
3532 of the form::
3539
3533
3540 (grafted from CHANGESETHASH)
3534 (grafted from CHANGESETHASH)
3541
3535
3542 If --force is specified, revisions will be grafted even if they
3536 If --force is specified, revisions will be grafted even if they
3543 are already ancestors of or have been grafted to the destination.
3537 are already ancestors of or have been grafted to the destination.
3544 This is useful when the revisions have since been backed out.
3538 This is useful when the revisions have since been backed out.
3545
3539
3546 If a graft merge results in conflicts, the graft process is
3540 If a graft merge results in conflicts, the graft process is
3547 interrupted so that the current merge can be manually resolved.
3541 interrupted so that the current merge can be manually resolved.
3548 Once all conflicts are addressed, the graft process can be
3542 Once all conflicts are addressed, the graft process can be
3549 continued with the -c/--continue option.
3543 continued with the -c/--continue option.
3550
3544
3551 .. note::
3545 .. note::
3552
3546
3553 The -c/--continue option does not reapply earlier options, except
3547 The -c/--continue option does not reapply earlier options, except
3554 for --force.
3548 for --force.
3555
3549
3556 .. container:: verbose
3550 .. container:: verbose
3557
3551
3558 Examples:
3552 Examples:
3559
3553
3560 - copy a single change to the stable branch and edit its description::
3554 - copy a single change to the stable branch and edit its description::
3561
3555
3562 hg update stable
3556 hg update stable
3563 hg graft --edit 9393
3557 hg graft --edit 9393
3564
3558
3565 - graft a range of changesets with one exception, updating dates::
3559 - graft a range of changesets with one exception, updating dates::
3566
3560
3567 hg graft -D "2085::2093 and not 2091"
3561 hg graft -D "2085::2093 and not 2091"
3568
3562
3569 - continue a graft after resolving conflicts::
3563 - continue a graft after resolving conflicts::
3570
3564
3571 hg graft -c
3565 hg graft -c
3572
3566
3573 - show the source of a grafted changeset::
3567 - show the source of a grafted changeset::
3574
3568
3575 hg log --debug -r .
3569 hg log --debug -r .
3576
3570
3577 See :hg:`help revisions` and :hg:`help revsets` for more about
3571 See :hg:`help revisions` and :hg:`help revsets` for more about
3578 specifying revisions.
3572 specifying revisions.
3579
3573
3580 Returns 0 on successful completion.
3574 Returns 0 on successful completion.
3581 '''
3575 '''
3582
3576
3583 revs = list(revs)
3577 revs = list(revs)
3584 revs.extend(opts['rev'])
3578 revs.extend(opts['rev'])
3585
3579
3586 if not opts.get('user') and opts.get('currentuser'):
3580 if not opts.get('user') and opts.get('currentuser'):
3587 opts['user'] = ui.username()
3581 opts['user'] = ui.username()
3588 if not opts.get('date') and opts.get('currentdate'):
3582 if not opts.get('date') and opts.get('currentdate'):
3589 opts['date'] = "%d %d" % util.makedate()
3583 opts['date'] = "%d %d" % util.makedate()
3590
3584
3591 editor = cmdutil.getcommiteditor(editform='graft', **opts)
3585 editor = cmdutil.getcommiteditor(editform='graft', **opts)
3592
3586
3593 cont = False
3587 cont = False
3594 if opts['continue']:
3588 if opts['continue']:
3595 cont = True
3589 cont = True
3596 if revs:
3590 if revs:
3597 raise util.Abort(_("can't specify --continue and revisions"))
3591 raise util.Abort(_("can't specify --continue and revisions"))
3598 # read in unfinished revisions
3592 # read in unfinished revisions
3599 try:
3593 try:
3600 nodes = repo.vfs.read('graftstate').splitlines()
3594 nodes = repo.vfs.read('graftstate').splitlines()
3601 revs = [repo[node].rev() for node in nodes]
3595 revs = [repo[node].rev() for node in nodes]
3602 except IOError as inst:
3596 except IOError as inst:
3603 if inst.errno != errno.ENOENT:
3597 if inst.errno != errno.ENOENT:
3604 raise
3598 raise
3605 raise util.Abort(_("no graft state found, can't continue"))
3599 raise util.Abort(_("no graft state found, can't continue"))
3606 else:
3600 else:
3607 cmdutil.checkunfinished(repo)
3601 cmdutil.checkunfinished(repo)
3608 cmdutil.bailifchanged(repo)
3602 cmdutil.bailifchanged(repo)
3609 if not revs:
3603 if not revs:
3610 raise util.Abort(_('no revisions specified'))
3604 raise util.Abort(_('no revisions specified'))
3611 revs = scmutil.revrange(repo, revs)
3605 revs = scmutil.revrange(repo, revs)
3612
3606
3613 skipped = set()
3607 skipped = set()
3614 # check for merges
3608 # check for merges
3615 for rev in repo.revs('%ld and merge()', revs):
3609 for rev in repo.revs('%ld and merge()', revs):
3616 ui.warn(_('skipping ungraftable merge revision %s\n') % rev)
3610 ui.warn(_('skipping ungraftable merge revision %s\n') % rev)
3617 skipped.add(rev)
3611 skipped.add(rev)
3618 revs = [r for r in revs if r not in skipped]
3612 revs = [r for r in revs if r not in skipped]
3619 if not revs:
3613 if not revs:
3620 return -1
3614 return -1
3621
3615
3622 # Don't check in the --continue case, in effect retaining --force across
3616 # Don't check in the --continue case, in effect retaining --force across
3623 # --continues. That's because without --force, any revisions we decided to
3617 # --continues. That's because without --force, any revisions we decided to
3624 # skip would have been filtered out here, so they wouldn't have made their
3618 # skip would have been filtered out here, so they wouldn't have made their
3625 # way to the graftstate. With --force, any revisions we would have otherwise
3619 # way to the graftstate. With --force, any revisions we would have otherwise
3626 # skipped would not have been filtered out, and if they hadn't been applied
3620 # skipped would not have been filtered out, and if they hadn't been applied
3627 # already, they'd have been in the graftstate.
3621 # already, they'd have been in the graftstate.
3628 if not (cont or opts.get('force')):
3622 if not (cont or opts.get('force')):
3629 # check for ancestors of dest branch
3623 # check for ancestors of dest branch
3630 crev = repo['.'].rev()
3624 crev = repo['.'].rev()
3631 ancestors = repo.changelog.ancestors([crev], inclusive=True)
3625 ancestors = repo.changelog.ancestors([crev], inclusive=True)
3632 # Cannot use x.remove(y) on smart set, this has to be a list.
3626 # Cannot use x.remove(y) on smart set, this has to be a list.
3633 # XXX make this lazy in the future
3627 # XXX make this lazy in the future
3634 revs = list(revs)
3628 revs = list(revs)
3635 # don't mutate while iterating, create a copy
3629 # don't mutate while iterating, create a copy
3636 for rev in list(revs):
3630 for rev in list(revs):
3637 if rev in ancestors:
3631 if rev in ancestors:
3638 ui.warn(_('skipping ancestor revision %d:%s\n') %
3632 ui.warn(_('skipping ancestor revision %d:%s\n') %
3639 (rev, repo[rev]))
3633 (rev, repo[rev]))
3640 # XXX remove on list is slow
3634 # XXX remove on list is slow
3641 revs.remove(rev)
3635 revs.remove(rev)
3642 if not revs:
3636 if not revs:
3643 return -1
3637 return -1
3644
3638
3645 # analyze revs for earlier grafts
3639 # analyze revs for earlier grafts
3646 ids = {}
3640 ids = {}
3647 for ctx in repo.set("%ld", revs):
3641 for ctx in repo.set("%ld", revs):
3648 ids[ctx.hex()] = ctx.rev()
3642 ids[ctx.hex()] = ctx.rev()
3649 n = ctx.extra().get('source')
3643 n = ctx.extra().get('source')
3650 if n:
3644 if n:
3651 ids[n] = ctx.rev()
3645 ids[n] = ctx.rev()
3652
3646
3653 # check ancestors for earlier grafts
3647 # check ancestors for earlier grafts
3654 ui.debug('scanning for duplicate grafts\n')
3648 ui.debug('scanning for duplicate grafts\n')
3655
3649
3656 for rev in repo.changelog.findmissingrevs(revs, [crev]):
3650 for rev in repo.changelog.findmissingrevs(revs, [crev]):
3657 ctx = repo[rev]
3651 ctx = repo[rev]
3658 n = ctx.extra().get('source')
3652 n = ctx.extra().get('source')
3659 if n in ids:
3653 if n in ids:
3660 try:
3654 try:
3661 r = repo[n].rev()
3655 r = repo[n].rev()
3662 except error.RepoLookupError:
3656 except error.RepoLookupError:
3663 r = None
3657 r = None
3664 if r in revs:
3658 if r in revs:
3665 ui.warn(_('skipping revision %d:%s '
3659 ui.warn(_('skipping revision %d:%s '
3666 '(already grafted to %d:%s)\n')
3660 '(already grafted to %d:%s)\n')
3667 % (r, repo[r], rev, ctx))
3661 % (r, repo[r], rev, ctx))
3668 revs.remove(r)
3662 revs.remove(r)
3669 elif ids[n] in revs:
3663 elif ids[n] in revs:
3670 if r is None:
3664 if r is None:
3671 ui.warn(_('skipping already grafted revision %d:%s '
3665 ui.warn(_('skipping already grafted revision %d:%s '
3672 '(%d:%s also has unknown origin %s)\n')
3666 '(%d:%s also has unknown origin %s)\n')
3673 % (ids[n], repo[ids[n]], rev, ctx, n[:12]))
3667 % (ids[n], repo[ids[n]], rev, ctx, n[:12]))
3674 else:
3668 else:
3675 ui.warn(_('skipping already grafted revision %d:%s '
3669 ui.warn(_('skipping already grafted revision %d:%s '
3676 '(%d:%s also has origin %d:%s)\n')
3670 '(%d:%s also has origin %d:%s)\n')
3677 % (ids[n], repo[ids[n]], rev, ctx, r, n[:12]))
3671 % (ids[n], repo[ids[n]], rev, ctx, r, n[:12]))
3678 revs.remove(ids[n])
3672 revs.remove(ids[n])
3679 elif ctx.hex() in ids:
3673 elif ctx.hex() in ids:
3680 r = ids[ctx.hex()]
3674 r = ids[ctx.hex()]
3681 ui.warn(_('skipping already grafted revision %d:%s '
3675 ui.warn(_('skipping already grafted revision %d:%s '
3682 '(was grafted from %d:%s)\n') %
3676 '(was grafted from %d:%s)\n') %
3683 (r, repo[r], rev, ctx))
3677 (r, repo[r], rev, ctx))
3684 revs.remove(r)
3678 revs.remove(r)
3685 if not revs:
3679 if not revs:
3686 return -1
3680 return -1
3687
3681
3688 wlock = repo.wlock()
3682 wlock = repo.wlock()
3689 try:
3683 try:
3690 for pos, ctx in enumerate(repo.set("%ld", revs)):
3684 for pos, ctx in enumerate(repo.set("%ld", revs)):
3691 desc = '%d:%s "%s"' % (ctx.rev(), ctx,
3685 desc = '%d:%s "%s"' % (ctx.rev(), ctx,
3692 ctx.description().split('\n', 1)[0])
3686 ctx.description().split('\n', 1)[0])
3693 names = repo.nodetags(ctx.node()) + repo.nodebookmarks(ctx.node())
3687 names = repo.nodetags(ctx.node()) + repo.nodebookmarks(ctx.node())
3694 if names:
3688 if names:
3695 desc += ' (%s)' % ' '.join(names)
3689 desc += ' (%s)' % ' '.join(names)
3696 ui.status(_('grafting %s\n') % desc)
3690 ui.status(_('grafting %s\n') % desc)
3697 if opts.get('dry_run'):
3691 if opts.get('dry_run'):
3698 continue
3692 continue
3699
3693
3700 source = ctx.extra().get('source')
3694 source = ctx.extra().get('source')
3701 extra = {}
3695 extra = {}
3702 if source:
3696 if source:
3703 extra['source'] = source
3697 extra['source'] = source
3704 extra['intermediate-source'] = ctx.hex()
3698 extra['intermediate-source'] = ctx.hex()
3705 else:
3699 else:
3706 extra['source'] = ctx.hex()
3700 extra['source'] = ctx.hex()
3707 user = ctx.user()
3701 user = ctx.user()
3708 if opts.get('user'):
3702 if opts.get('user'):
3709 user = opts['user']
3703 user = opts['user']
3710 date = ctx.date()
3704 date = ctx.date()
3711 if opts.get('date'):
3705 if opts.get('date'):
3712 date = opts['date']
3706 date = opts['date']
3713 message = ctx.description()
3707 message = ctx.description()
3714 if opts.get('log'):
3708 if opts.get('log'):
3715 message += '\n(grafted from %s)' % ctx.hex()
3709 message += '\n(grafted from %s)' % ctx.hex()
3716
3710
3717 # we don't merge the first commit when continuing
3711 # we don't merge the first commit when continuing
3718 if not cont:
3712 if not cont:
3719 # perform the graft merge with p1(rev) as 'ancestor'
3713 # perform the graft merge with p1(rev) as 'ancestor'
3720 try:
3714 try:
3721 # ui.forcemerge is an internal variable, do not document
3715 # ui.forcemerge is an internal variable, do not document
3722 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
3716 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
3723 'graft')
3717 'graft')
3724 stats = mergemod.graft(repo, ctx, ctx.p1(),
3718 stats = mergemod.graft(repo, ctx, ctx.p1(),
3725 ['local', 'graft'])
3719 ['local', 'graft'])
3726 finally:
3720 finally:
3727 repo.ui.setconfig('ui', 'forcemerge', '', 'graft')
3721 repo.ui.setconfig('ui', 'forcemerge', '', 'graft')
3728 # report any conflicts
3722 # report any conflicts
3729 if stats and stats[3] > 0:
3723 if stats and stats[3] > 0:
3730 # write out state for --continue
3724 # write out state for --continue
3731 nodelines = [repo[rev].hex() + "\n" for rev in revs[pos:]]
3725 nodelines = [repo[rev].hex() + "\n" for rev in revs[pos:]]
3732 repo.vfs.write('graftstate', ''.join(nodelines))
3726 repo.vfs.write('graftstate', ''.join(nodelines))
3733 raise util.Abort(
3727 raise util.Abort(
3734 _("unresolved conflicts, can't continue"),
3728 _("unresolved conflicts, can't continue"),
3735 hint=_('use hg resolve and hg graft --continue'))
3729 hint=_('use hg resolve and hg graft --continue'))
3736 else:
3730 else:
3737 cont = False
3731 cont = False
3738
3732
3739 # commit
3733 # commit
3740 node = repo.commit(text=message, user=user,
3734 node = repo.commit(text=message, user=user,
3741 date=date, extra=extra, editor=editor)
3735 date=date, extra=extra, editor=editor)
3742 if node is None:
3736 if node is None:
3743 ui.warn(
3737 ui.warn(
3744 _('note: graft of %d:%s created no changes to commit\n') %
3738 _('note: graft of %d:%s created no changes to commit\n') %
3745 (ctx.rev(), ctx))
3739 (ctx.rev(), ctx))
3746 finally:
3740 finally:
3747 wlock.release()
3741 wlock.release()
3748
3742
3749 # remove state when we complete successfully
3743 # remove state when we complete successfully
3750 if not opts.get('dry_run'):
3744 if not opts.get('dry_run'):
3751 util.unlinkpath(repo.join('graftstate'), ignoremissing=True)
3745 util.unlinkpath(repo.join('graftstate'), ignoremissing=True)
3752
3746
3753 return 0
3747 return 0
3754
3748
3755 @command('grep',
3749 @command('grep',
3756 [('0', 'print0', None, _('end fields with NUL')),
3750 [('0', 'print0', None, _('end fields with NUL')),
3757 ('', 'all', None, _('print all revisions that match')),
3751 ('', 'all', None, _('print all revisions that match')),
3758 ('a', 'text', None, _('treat all files as text')),
3752 ('a', 'text', None, _('treat all files as text')),
3759 ('f', 'follow', None,
3753 ('f', 'follow', None,
3760 _('follow changeset history,'
3754 _('follow changeset history,'
3761 ' or file history across copies and renames')),
3755 ' or file history across copies and renames')),
3762 ('i', 'ignore-case', None, _('ignore case when matching')),
3756 ('i', 'ignore-case', None, _('ignore case when matching')),
3763 ('l', 'files-with-matches', None,
3757 ('l', 'files-with-matches', None,
3764 _('print only filenames and revisions that match')),
3758 _('print only filenames and revisions that match')),
3765 ('n', 'line-number', None, _('print matching line numbers')),
3759 ('n', 'line-number', None, _('print matching line numbers')),
3766 ('r', 'rev', [],
3760 ('r', 'rev', [],
3767 _('only search files changed within revision range'), _('REV')),
3761 _('only search files changed within revision range'), _('REV')),
3768 ('u', 'user', None, _('list the author (long with -v)')),
3762 ('u', 'user', None, _('list the author (long with -v)')),
3769 ('d', 'date', None, _('list the date (short with -q)')),
3763 ('d', 'date', None, _('list the date (short with -q)')),
3770 ] + walkopts,
3764 ] + walkopts,
3771 _('[OPTION]... PATTERN [FILE]...'),
3765 _('[OPTION]... PATTERN [FILE]...'),
3772 inferrepo=True)
3766 inferrepo=True)
3773 def grep(ui, repo, pattern, *pats, **opts):
3767 def grep(ui, repo, pattern, *pats, **opts):
3774 """search for a pattern in specified files and revisions
3768 """search for a pattern in specified files and revisions
3775
3769
3776 Search revisions of files for a regular expression.
3770 Search revisions of files for a regular expression.
3777
3771
3778 This command behaves differently than Unix grep. It only accepts
3772 This command behaves differently than Unix grep. It only accepts
3779 Python/Perl regexps. It searches repository history, not the
3773 Python/Perl regexps. It searches repository history, not the
3780 working directory. It always prints the revision number in which a
3774 working directory. It always prints the revision number in which a
3781 match appears.
3775 match appears.
3782
3776
3783 By default, grep only prints output for the first revision of a
3777 By default, grep only prints output for the first revision of a
3784 file in which it finds a match. To get it to print every revision
3778 file in which it finds a match. To get it to print every revision
3785 that contains a change in match status ("-" for a match that
3779 that contains a change in match status ("-" for a match that
3786 becomes a non-match, or "+" for a non-match that becomes a match),
3780 becomes a non-match, or "+" for a non-match that becomes a match),
3787 use the --all flag.
3781 use the --all flag.
3788
3782
3789 Returns 0 if a match is found, 1 otherwise.
3783 Returns 0 if a match is found, 1 otherwise.
3790 """
3784 """
3791 reflags = re.M
3785 reflags = re.M
3792 if opts.get('ignore_case'):
3786 if opts.get('ignore_case'):
3793 reflags |= re.I
3787 reflags |= re.I
3794 try:
3788 try:
3795 regexp = util.re.compile(pattern, reflags)
3789 regexp = util.re.compile(pattern, reflags)
3796 except re.error as inst:
3790 except re.error as inst:
3797 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
3791 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
3798 return 1
3792 return 1
3799 sep, eol = ':', '\n'
3793 sep, eol = ':', '\n'
3800 if opts.get('print0'):
3794 if opts.get('print0'):
3801 sep = eol = '\0'
3795 sep = eol = '\0'
3802
3796
3803 getfile = util.lrucachefunc(repo.file)
3797 getfile = util.lrucachefunc(repo.file)
3804
3798
3805 def matchlines(body):
3799 def matchlines(body):
3806 begin = 0
3800 begin = 0
3807 linenum = 0
3801 linenum = 0
3808 while begin < len(body):
3802 while begin < len(body):
3809 match = regexp.search(body, begin)
3803 match = regexp.search(body, begin)
3810 if not match:
3804 if not match:
3811 break
3805 break
3812 mstart, mend = match.span()
3806 mstart, mend = match.span()
3813 linenum += body.count('\n', begin, mstart) + 1
3807 linenum += body.count('\n', begin, mstart) + 1
3814 lstart = body.rfind('\n', begin, mstart) + 1 or begin
3808 lstart = body.rfind('\n', begin, mstart) + 1 or begin
3815 begin = body.find('\n', mend) + 1 or len(body) + 1
3809 begin = body.find('\n', mend) + 1 or len(body) + 1
3816 lend = begin - 1
3810 lend = begin - 1
3817 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
3811 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
3818
3812
3819 class linestate(object):
3813 class linestate(object):
3820 def __init__(self, line, linenum, colstart, colend):
3814 def __init__(self, line, linenum, colstart, colend):
3821 self.line = line
3815 self.line = line
3822 self.linenum = linenum
3816 self.linenum = linenum
3823 self.colstart = colstart
3817 self.colstart = colstart
3824 self.colend = colend
3818 self.colend = colend
3825
3819
3826 def __hash__(self):
3820 def __hash__(self):
3827 return hash((self.linenum, self.line))
3821 return hash((self.linenum, self.line))
3828
3822
3829 def __eq__(self, other):
3823 def __eq__(self, other):
3830 return self.line == other.line
3824 return self.line == other.line
3831
3825
3832 def __iter__(self):
3826 def __iter__(self):
3833 yield (self.line[:self.colstart], '')
3827 yield (self.line[:self.colstart], '')
3834 yield (self.line[self.colstart:self.colend], 'grep.match')
3828 yield (self.line[self.colstart:self.colend], 'grep.match')
3835 rest = self.line[self.colend:]
3829 rest = self.line[self.colend:]
3836 while rest != '':
3830 while rest != '':
3837 match = regexp.search(rest)
3831 match = regexp.search(rest)
3838 if not match:
3832 if not match:
3839 yield (rest, '')
3833 yield (rest, '')
3840 break
3834 break
3841 mstart, mend = match.span()
3835 mstart, mend = match.span()
3842 yield (rest[:mstart], '')
3836 yield (rest[:mstart], '')
3843 yield (rest[mstart:mend], 'grep.match')
3837 yield (rest[mstart:mend], 'grep.match')
3844 rest = rest[mend:]
3838 rest = rest[mend:]
3845
3839
3846 matches = {}
3840 matches = {}
3847 copies = {}
3841 copies = {}
3848 def grepbody(fn, rev, body):
3842 def grepbody(fn, rev, body):
3849 matches[rev].setdefault(fn, [])
3843 matches[rev].setdefault(fn, [])
3850 m = matches[rev][fn]
3844 m = matches[rev][fn]
3851 for lnum, cstart, cend, line in matchlines(body):
3845 for lnum, cstart, cend, line in matchlines(body):
3852 s = linestate(line, lnum, cstart, cend)
3846 s = linestate(line, lnum, cstart, cend)
3853 m.append(s)
3847 m.append(s)
3854
3848
3855 def difflinestates(a, b):
3849 def difflinestates(a, b):
3856 sm = difflib.SequenceMatcher(None, a, b)
3850 sm = difflib.SequenceMatcher(None, a, b)
3857 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
3851 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
3858 if tag == 'insert':
3852 if tag == 'insert':
3859 for i in xrange(blo, bhi):
3853 for i in xrange(blo, bhi):
3860 yield ('+', b[i])
3854 yield ('+', b[i])
3861 elif tag == 'delete':
3855 elif tag == 'delete':
3862 for i in xrange(alo, ahi):
3856 for i in xrange(alo, ahi):
3863 yield ('-', a[i])
3857 yield ('-', a[i])
3864 elif tag == 'replace':
3858 elif tag == 'replace':
3865 for i in xrange(alo, ahi):
3859 for i in xrange(alo, ahi):
3866 yield ('-', a[i])
3860 yield ('-', a[i])
3867 for i in xrange(blo, bhi):
3861 for i in xrange(blo, bhi):
3868 yield ('+', b[i])
3862 yield ('+', b[i])
3869
3863
3870 def display(fn, ctx, pstates, states):
3864 def display(fn, ctx, pstates, states):
3871 rev = ctx.rev()
3865 rev = ctx.rev()
3872 if ui.quiet:
3866 if ui.quiet:
3873 datefunc = util.shortdate
3867 datefunc = util.shortdate
3874 else:
3868 else:
3875 datefunc = util.datestr
3869 datefunc = util.datestr
3876 found = False
3870 found = False
3877 @util.cachefunc
3871 @util.cachefunc
3878 def binary():
3872 def binary():
3879 flog = getfile(fn)
3873 flog = getfile(fn)
3880 return util.binary(flog.read(ctx.filenode(fn)))
3874 return util.binary(flog.read(ctx.filenode(fn)))
3881
3875
3882 if opts.get('all'):
3876 if opts.get('all'):
3883 iter = difflinestates(pstates, states)
3877 iter = difflinestates(pstates, states)
3884 else:
3878 else:
3885 iter = [('', l) for l in states]
3879 iter = [('', l) for l in states]
3886 for change, l in iter:
3880 for change, l in iter:
3887 cols = [(fn, 'grep.filename'), (str(rev), 'grep.rev')]
3881 cols = [(fn, 'grep.filename'), (str(rev), 'grep.rev')]
3888
3882
3889 if opts.get('line_number'):
3883 if opts.get('line_number'):
3890 cols.append((str(l.linenum), 'grep.linenumber'))
3884 cols.append((str(l.linenum), 'grep.linenumber'))
3891 if opts.get('all'):
3885 if opts.get('all'):
3892 cols.append((change, 'grep.change'))
3886 cols.append((change, 'grep.change'))
3893 if opts.get('user'):
3887 if opts.get('user'):
3894 cols.append((ui.shortuser(ctx.user()), 'grep.user'))
3888 cols.append((ui.shortuser(ctx.user()), 'grep.user'))
3895 if opts.get('date'):
3889 if opts.get('date'):
3896 cols.append((datefunc(ctx.date()), 'grep.date'))
3890 cols.append((datefunc(ctx.date()), 'grep.date'))
3897 for col, label in cols[:-1]:
3891 for col, label in cols[:-1]:
3898 ui.write(col, label=label)
3892 ui.write(col, label=label)
3899 ui.write(sep, label='grep.sep')
3893 ui.write(sep, label='grep.sep')
3900 ui.write(cols[-1][0], label=cols[-1][1])
3894 ui.write(cols[-1][0], label=cols[-1][1])
3901 if not opts.get('files_with_matches'):
3895 if not opts.get('files_with_matches'):
3902 ui.write(sep, label='grep.sep')
3896 ui.write(sep, label='grep.sep')
3903 if not opts.get('text') and binary():
3897 if not opts.get('text') and binary():
3904 ui.write(" Binary file matches")
3898 ui.write(" Binary file matches")
3905 else:
3899 else:
3906 for s, label in l:
3900 for s, label in l:
3907 ui.write(s, label=label)
3901 ui.write(s, label=label)
3908 ui.write(eol)
3902 ui.write(eol)
3909 found = True
3903 found = True
3910 if opts.get('files_with_matches'):
3904 if opts.get('files_with_matches'):
3911 break
3905 break
3912 return found
3906 return found
3913
3907
3914 skip = {}
3908 skip = {}
3915 revfiles = {}
3909 revfiles = {}
3916 matchfn = scmutil.match(repo[None], pats, opts)
3910 matchfn = scmutil.match(repo[None], pats, opts)
3917 found = False
3911 found = False
3918 follow = opts.get('follow')
3912 follow = opts.get('follow')
3919
3913
3920 def prep(ctx, fns):
3914 def prep(ctx, fns):
3921 rev = ctx.rev()
3915 rev = ctx.rev()
3922 pctx = ctx.p1()
3916 pctx = ctx.p1()
3923 parent = pctx.rev()
3917 parent = pctx.rev()
3924 matches.setdefault(rev, {})
3918 matches.setdefault(rev, {})
3925 matches.setdefault(parent, {})
3919 matches.setdefault(parent, {})
3926 files = revfiles.setdefault(rev, [])
3920 files = revfiles.setdefault(rev, [])
3927 for fn in fns:
3921 for fn in fns:
3928 flog = getfile(fn)
3922 flog = getfile(fn)
3929 try:
3923 try:
3930 fnode = ctx.filenode(fn)
3924 fnode = ctx.filenode(fn)
3931 except error.LookupError:
3925 except error.LookupError:
3932 continue
3926 continue
3933
3927
3934 copied = flog.renamed(fnode)
3928 copied = flog.renamed(fnode)
3935 copy = follow and copied and copied[0]
3929 copy = follow and copied and copied[0]
3936 if copy:
3930 if copy:
3937 copies.setdefault(rev, {})[fn] = copy
3931 copies.setdefault(rev, {})[fn] = copy
3938 if fn in skip:
3932 if fn in skip:
3939 if copy:
3933 if copy:
3940 skip[copy] = True
3934 skip[copy] = True
3941 continue
3935 continue
3942 files.append(fn)
3936 files.append(fn)
3943
3937
3944 if fn not in matches[rev]:
3938 if fn not in matches[rev]:
3945 grepbody(fn, rev, flog.read(fnode))
3939 grepbody(fn, rev, flog.read(fnode))
3946
3940
3947 pfn = copy or fn
3941 pfn = copy or fn
3948 if pfn not in matches[parent]:
3942 if pfn not in matches[parent]:
3949 try:
3943 try:
3950 fnode = pctx.filenode(pfn)
3944 fnode = pctx.filenode(pfn)
3951 grepbody(pfn, parent, flog.read(fnode))
3945 grepbody(pfn, parent, flog.read(fnode))
3952 except error.LookupError:
3946 except error.LookupError:
3953 pass
3947 pass
3954
3948
3955 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
3949 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
3956 rev = ctx.rev()
3950 rev = ctx.rev()
3957 parent = ctx.p1().rev()
3951 parent = ctx.p1().rev()
3958 for fn in sorted(revfiles.get(rev, [])):
3952 for fn in sorted(revfiles.get(rev, [])):
3959 states = matches[rev][fn]
3953 states = matches[rev][fn]
3960 copy = copies.get(rev, {}).get(fn)
3954 copy = copies.get(rev, {}).get(fn)
3961 if fn in skip:
3955 if fn in skip:
3962 if copy:
3956 if copy:
3963 skip[copy] = True
3957 skip[copy] = True
3964 continue
3958 continue
3965 pstates = matches.get(parent, {}).get(copy or fn, [])
3959 pstates = matches.get(parent, {}).get(copy or fn, [])
3966 if pstates or states:
3960 if pstates or states:
3967 r = display(fn, ctx, pstates, states)
3961 r = display(fn, ctx, pstates, states)
3968 found = found or r
3962 found = found or r
3969 if r and not opts.get('all'):
3963 if r and not opts.get('all'):
3970 skip[fn] = True
3964 skip[fn] = True
3971 if copy:
3965 if copy:
3972 skip[copy] = True
3966 skip[copy] = True
3973 del matches[rev]
3967 del matches[rev]
3974 del revfiles[rev]
3968 del revfiles[rev]
3975
3969
3976 return not found
3970 return not found
3977
3971
3978 @command('heads',
3972 @command('heads',
3979 [('r', 'rev', '',
3973 [('r', 'rev', '',
3980 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
3974 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
3981 ('t', 'topo', False, _('show topological heads only')),
3975 ('t', 'topo', False, _('show topological heads only')),
3982 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
3976 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
3983 ('c', 'closed', False, _('show normal and closed branch heads')),
3977 ('c', 'closed', False, _('show normal and closed branch heads')),
3984 ] + templateopts,
3978 ] + templateopts,
3985 _('[-ct] [-r STARTREV] [REV]...'))
3979 _('[-ct] [-r STARTREV] [REV]...'))
3986 def heads(ui, repo, *branchrevs, **opts):
3980 def heads(ui, repo, *branchrevs, **opts):
3987 """show branch heads
3981 """show branch heads
3988
3982
3989 With no arguments, show all open branch heads in the repository.
3983 With no arguments, show all open branch heads in the repository.
3990 Branch heads are changesets that have no descendants on the
3984 Branch heads are changesets that have no descendants on the
3991 same branch. They are where development generally takes place and
3985 same branch. They are where development generally takes place and
3992 are the usual targets for update and merge operations.
3986 are the usual targets for update and merge operations.
3993
3987
3994 If one or more REVs are given, only open branch heads on the
3988 If one or more REVs are given, only open branch heads on the
3995 branches associated with the specified changesets are shown. This
3989 branches associated with the specified changesets are shown. This
3996 means that you can use :hg:`heads .` to see the heads on the
3990 means that you can use :hg:`heads .` to see the heads on the
3997 currently checked-out branch.
3991 currently checked-out branch.
3998
3992
3999 If -c/--closed is specified, also show branch heads marked closed
3993 If -c/--closed is specified, also show branch heads marked closed
4000 (see :hg:`commit --close-branch`).
3994 (see :hg:`commit --close-branch`).
4001
3995
4002 If STARTREV is specified, only those heads that are descendants of
3996 If STARTREV is specified, only those heads that are descendants of
4003 STARTREV will be displayed.
3997 STARTREV will be displayed.
4004
3998
4005 If -t/--topo is specified, named branch mechanics will be ignored and only
3999 If -t/--topo is specified, named branch mechanics will be ignored and only
4006 topological heads (changesets with no children) will be shown.
4000 topological heads (changesets with no children) will be shown.
4007
4001
4008 Returns 0 if matching heads are found, 1 if not.
4002 Returns 0 if matching heads are found, 1 if not.
4009 """
4003 """
4010
4004
4011 start = None
4005 start = None
4012 if 'rev' in opts:
4006 if 'rev' in opts:
4013 start = scmutil.revsingle(repo, opts['rev'], None).node()
4007 start = scmutil.revsingle(repo, opts['rev'], None).node()
4014
4008
4015 if opts.get('topo'):
4009 if opts.get('topo'):
4016 heads = [repo[h] for h in repo.heads(start)]
4010 heads = [repo[h] for h in repo.heads(start)]
4017 else:
4011 else:
4018 heads = []
4012 heads = []
4019 for branch in repo.branchmap():
4013 for branch in repo.branchmap():
4020 heads += repo.branchheads(branch, start, opts.get('closed'))
4014 heads += repo.branchheads(branch, start, opts.get('closed'))
4021 heads = [repo[h] for h in heads]
4015 heads = [repo[h] for h in heads]
4022
4016
4023 if branchrevs:
4017 if branchrevs:
4024 branches = set(repo[br].branch() for br in branchrevs)
4018 branches = set(repo[br].branch() for br in branchrevs)
4025 heads = [h for h in heads if h.branch() in branches]
4019 heads = [h for h in heads if h.branch() in branches]
4026
4020
4027 if opts.get('active') and branchrevs:
4021 if opts.get('active') and branchrevs:
4028 dagheads = repo.heads(start)
4022 dagheads = repo.heads(start)
4029 heads = [h for h in heads if h.node() in dagheads]
4023 heads = [h for h in heads if h.node() in dagheads]
4030
4024
4031 if branchrevs:
4025 if branchrevs:
4032 haveheads = set(h.branch() for h in heads)
4026 haveheads = set(h.branch() for h in heads)
4033 if branches - haveheads:
4027 if branches - haveheads:
4034 headless = ', '.join(b for b in branches - haveheads)
4028 headless = ', '.join(b for b in branches - haveheads)
4035 msg = _('no open branch heads found on branches %s')
4029 msg = _('no open branch heads found on branches %s')
4036 if opts.get('rev'):
4030 if opts.get('rev'):
4037 msg += _(' (started at %s)') % opts['rev']
4031 msg += _(' (started at %s)') % opts['rev']
4038 ui.warn((msg + '\n') % headless)
4032 ui.warn((msg + '\n') % headless)
4039
4033
4040 if not heads:
4034 if not heads:
4041 return 1
4035 return 1
4042
4036
4043 heads = sorted(heads, key=lambda x: -x.rev())
4037 heads = sorted(heads, key=lambda x: -x.rev())
4044 displayer = cmdutil.show_changeset(ui, repo, opts)
4038 displayer = cmdutil.show_changeset(ui, repo, opts)
4045 for ctx in heads:
4039 for ctx in heads:
4046 displayer.show(ctx)
4040 displayer.show(ctx)
4047 displayer.close()
4041 displayer.close()
4048
4042
4049 @command('help',
4043 @command('help',
4050 [('e', 'extension', None, _('show only help for extensions')),
4044 [('e', 'extension', None, _('show only help for extensions')),
4051 ('c', 'command', None, _('show only help for commands')),
4045 ('c', 'command', None, _('show only help for commands')),
4052 ('k', 'keyword', None, _('show topics matching keyword')),
4046 ('k', 'keyword', None, _('show topics matching keyword')),
4053 ],
4047 ],
4054 _('[-eck] [TOPIC]'),
4048 _('[-eck] [TOPIC]'),
4055 norepo=True)
4049 norepo=True)
4056 def help_(ui, name=None, **opts):
4050 def help_(ui, name=None, **opts):
4057 """show help for a given topic or a help overview
4051 """show help for a given topic or a help overview
4058
4052
4059 With no arguments, print a list of commands with short help messages.
4053 With no arguments, print a list of commands with short help messages.
4060
4054
4061 Given a topic, extension, or command name, print help for that
4055 Given a topic, extension, or command name, print help for that
4062 topic.
4056 topic.
4063
4057
4064 Returns 0 if successful.
4058 Returns 0 if successful.
4065 """
4059 """
4066
4060
4067 textwidth = min(ui.termwidth(), 80) - 2
4061 textwidth = min(ui.termwidth(), 80) - 2
4068
4062
4069 keep = []
4063 keep = []
4070 if ui.verbose:
4064 if ui.verbose:
4071 keep.append('verbose')
4065 keep.append('verbose')
4072 if sys.platform.startswith('win'):
4066 if sys.platform.startswith('win'):
4073 keep.append('windows')
4067 keep.append('windows')
4074 elif sys.platform == 'OpenVMS':
4068 elif sys.platform == 'OpenVMS':
4075 keep.append('vms')
4069 keep.append('vms')
4076 elif sys.platform == 'plan9':
4070 elif sys.platform == 'plan9':
4077 keep.append('plan9')
4071 keep.append('plan9')
4078 else:
4072 else:
4079 keep.append('unix')
4073 keep.append('unix')
4080 keep.append(sys.platform.lower())
4074 keep.append(sys.platform.lower())
4081
4075
4082 section = None
4076 section = None
4083 if name and '.' in name:
4077 if name and '.' in name:
4084 name, section = name.split('.', 1)
4078 name, section = name.split('.', 1)
4085 section = section.lower()
4079 section = section.lower()
4086
4080
4087 text = help.help_(ui, name, **opts)
4081 text = help.help_(ui, name, **opts)
4088
4082
4089 formatted, pruned = minirst.format(text, textwidth, keep=keep,
4083 formatted, pruned = minirst.format(text, textwidth, keep=keep,
4090 section=section)
4084 section=section)
4091
4085
4092 # We could have been given a weird ".foo" section without a name
4086 # We could have been given a weird ".foo" section without a name
4093 # to look for, or we could have simply failed to found "foo.bar"
4087 # to look for, or we could have simply failed to found "foo.bar"
4094 # because bar isn't a section of foo
4088 # because bar isn't a section of foo
4095 if section and not (formatted and name):
4089 if section and not (formatted and name):
4096 raise util.Abort(_("help section not found"))
4090 raise util.Abort(_("help section not found"))
4097
4091
4098 if 'verbose' in pruned:
4092 if 'verbose' in pruned:
4099 keep.append('omitted')
4093 keep.append('omitted')
4100 else:
4094 else:
4101 keep.append('notomitted')
4095 keep.append('notomitted')
4102 formatted, pruned = minirst.format(text, textwidth, keep=keep,
4096 formatted, pruned = minirst.format(text, textwidth, keep=keep,
4103 section=section)
4097 section=section)
4104 ui.write(formatted)
4098 ui.write(formatted)
4105
4099
4106
4100
4107 @command('identify|id',
4101 @command('identify|id',
4108 [('r', 'rev', '',
4102 [('r', 'rev', '',
4109 _('identify the specified revision'), _('REV')),
4103 _('identify the specified revision'), _('REV')),
4110 ('n', 'num', None, _('show local revision number')),
4104 ('n', 'num', None, _('show local revision number')),
4111 ('i', 'id', None, _('show global revision id')),
4105 ('i', 'id', None, _('show global revision id')),
4112 ('b', 'branch', None, _('show branch')),
4106 ('b', 'branch', None, _('show branch')),
4113 ('t', 'tags', None, _('show tags')),
4107 ('t', 'tags', None, _('show tags')),
4114 ('B', 'bookmarks', None, _('show bookmarks')),
4108 ('B', 'bookmarks', None, _('show bookmarks')),
4115 ] + remoteopts,
4109 ] + remoteopts,
4116 _('[-nibtB] [-r REV] [SOURCE]'),
4110 _('[-nibtB] [-r REV] [SOURCE]'),
4117 optionalrepo=True)
4111 optionalrepo=True)
4118 def identify(ui, repo, source=None, rev=None,
4112 def identify(ui, repo, source=None, rev=None,
4119 num=None, id=None, branch=None, tags=None, bookmarks=None, **opts):
4113 num=None, id=None, branch=None, tags=None, bookmarks=None, **opts):
4120 """identify the working directory or specified revision
4114 """identify the working directory or specified revision
4121
4115
4122 Print a summary identifying the repository state at REV using one or
4116 Print a summary identifying the repository state at REV using one or
4123 two parent hash identifiers, followed by a "+" if the working
4117 two parent hash identifiers, followed by a "+" if the working
4124 directory has uncommitted changes, the branch name (if not default),
4118 directory has uncommitted changes, the branch name (if not default),
4125 a list of tags, and a list of bookmarks.
4119 a list of tags, and a list of bookmarks.
4126
4120
4127 When REV is not given, print a summary of the current state of the
4121 When REV is not given, print a summary of the current state of the
4128 repository.
4122 repository.
4129
4123
4130 Specifying a path to a repository root or Mercurial bundle will
4124 Specifying a path to a repository root or Mercurial bundle will
4131 cause lookup to operate on that repository/bundle.
4125 cause lookup to operate on that repository/bundle.
4132
4126
4133 .. container:: verbose
4127 .. container:: verbose
4134
4128
4135 Examples:
4129 Examples:
4136
4130
4137 - generate a build identifier for the working directory::
4131 - generate a build identifier for the working directory::
4138
4132
4139 hg id --id > build-id.dat
4133 hg id --id > build-id.dat
4140
4134
4141 - find the revision corresponding to a tag::
4135 - find the revision corresponding to a tag::
4142
4136
4143 hg id -n -r 1.3
4137 hg id -n -r 1.3
4144
4138
4145 - check the most recent revision of a remote repository::
4139 - check the most recent revision of a remote repository::
4146
4140
4147 hg id -r tip http://selenic.com/hg/
4141 hg id -r tip http://selenic.com/hg/
4148
4142
4149 Returns 0 if successful.
4143 Returns 0 if successful.
4150 """
4144 """
4151
4145
4152 if not repo and not source:
4146 if not repo and not source:
4153 raise util.Abort(_("there is no Mercurial repository here "
4147 raise util.Abort(_("there is no Mercurial repository here "
4154 "(.hg not found)"))
4148 "(.hg not found)"))
4155
4149
4156 if ui.debugflag:
4150 if ui.debugflag:
4157 hexfunc = hex
4151 hexfunc = hex
4158 else:
4152 else:
4159 hexfunc = short
4153 hexfunc = short
4160 default = not (num or id or branch or tags or bookmarks)
4154 default = not (num or id or branch or tags or bookmarks)
4161 output = []
4155 output = []
4162 revs = []
4156 revs = []
4163
4157
4164 if source:
4158 if source:
4165 source, branches = hg.parseurl(ui.expandpath(source))
4159 source, branches = hg.parseurl(ui.expandpath(source))
4166 peer = hg.peer(repo or ui, opts, source) # only pass ui when no repo
4160 peer = hg.peer(repo or ui, opts, source) # only pass ui when no repo
4167 repo = peer.local()
4161 repo = peer.local()
4168 revs, checkout = hg.addbranchrevs(repo, peer, branches, None)
4162 revs, checkout = hg.addbranchrevs(repo, peer, branches, None)
4169
4163
4170 if not repo:
4164 if not repo:
4171 if num or branch or tags:
4165 if num or branch or tags:
4172 raise util.Abort(
4166 raise util.Abort(
4173 _("can't query remote revision number, branch, or tags"))
4167 _("can't query remote revision number, branch, or tags"))
4174 if not rev and revs:
4168 if not rev and revs:
4175 rev = revs[0]
4169 rev = revs[0]
4176 if not rev:
4170 if not rev:
4177 rev = "tip"
4171 rev = "tip"
4178
4172
4179 remoterev = peer.lookup(rev)
4173 remoterev = peer.lookup(rev)
4180 if default or id:
4174 if default or id:
4181 output = [hexfunc(remoterev)]
4175 output = [hexfunc(remoterev)]
4182
4176
4183 def getbms():
4177 def getbms():
4184 bms = []
4178 bms = []
4185
4179
4186 if 'bookmarks' in peer.listkeys('namespaces'):
4180 if 'bookmarks' in peer.listkeys('namespaces'):
4187 hexremoterev = hex(remoterev)
4181 hexremoterev = hex(remoterev)
4188 bms = [bm for bm, bmr in peer.listkeys('bookmarks').iteritems()
4182 bms = [bm for bm, bmr in peer.listkeys('bookmarks').iteritems()
4189 if bmr == hexremoterev]
4183 if bmr == hexremoterev]
4190
4184
4191 return sorted(bms)
4185 return sorted(bms)
4192
4186
4193 if bookmarks:
4187 if bookmarks:
4194 output.extend(getbms())
4188 output.extend(getbms())
4195 elif default and not ui.quiet:
4189 elif default and not ui.quiet:
4196 # multiple bookmarks for a single parent separated by '/'
4190 # multiple bookmarks for a single parent separated by '/'
4197 bm = '/'.join(getbms())
4191 bm = '/'.join(getbms())
4198 if bm:
4192 if bm:
4199 output.append(bm)
4193 output.append(bm)
4200 else:
4194 else:
4201 ctx = scmutil.revsingle(repo, rev, None)
4195 ctx = scmutil.revsingle(repo, rev, None)
4202
4196
4203 if ctx.rev() is None:
4197 if ctx.rev() is None:
4204 ctx = repo[None]
4198 ctx = repo[None]
4205 parents = ctx.parents()
4199 parents = ctx.parents()
4206 taglist = []
4200 taglist = []
4207 for p in parents:
4201 for p in parents:
4208 taglist.extend(p.tags())
4202 taglist.extend(p.tags())
4209
4203
4210 changed = ""
4204 changed = ""
4211 if default or id or num:
4205 if default or id or num:
4212 if (any(repo.status())
4206 if (any(repo.status())
4213 or any(ctx.sub(s).dirty() for s in ctx.substate)):
4207 or any(ctx.sub(s).dirty() for s in ctx.substate)):
4214 changed = '+'
4208 changed = '+'
4215 if default or id:
4209 if default or id:
4216 output = ["%s%s" %
4210 output = ["%s%s" %
4217 ('+'.join([hexfunc(p.node()) for p in parents]), changed)]
4211 ('+'.join([hexfunc(p.node()) for p in parents]), changed)]
4218 if num:
4212 if num:
4219 output.append("%s%s" %
4213 output.append("%s%s" %
4220 ('+'.join([str(p.rev()) for p in parents]), changed))
4214 ('+'.join([str(p.rev()) for p in parents]), changed))
4221 else:
4215 else:
4222 if default or id:
4216 if default or id:
4223 output = [hexfunc(ctx.node())]
4217 output = [hexfunc(ctx.node())]
4224 if num:
4218 if num:
4225 output.append(str(ctx.rev()))
4219 output.append(str(ctx.rev()))
4226 taglist = ctx.tags()
4220 taglist = ctx.tags()
4227
4221
4228 if default and not ui.quiet:
4222 if default and not ui.quiet:
4229 b = ctx.branch()
4223 b = ctx.branch()
4230 if b != 'default':
4224 if b != 'default':
4231 output.append("(%s)" % b)
4225 output.append("(%s)" % b)
4232
4226
4233 # multiple tags for a single parent separated by '/'
4227 # multiple tags for a single parent separated by '/'
4234 t = '/'.join(taglist)
4228 t = '/'.join(taglist)
4235 if t:
4229 if t:
4236 output.append(t)
4230 output.append(t)
4237
4231
4238 # multiple bookmarks for a single parent separated by '/'
4232 # multiple bookmarks for a single parent separated by '/'
4239 bm = '/'.join(ctx.bookmarks())
4233 bm = '/'.join(ctx.bookmarks())
4240 if bm:
4234 if bm:
4241 output.append(bm)
4235 output.append(bm)
4242 else:
4236 else:
4243 if branch:
4237 if branch:
4244 output.append(ctx.branch())
4238 output.append(ctx.branch())
4245
4239
4246 if tags:
4240 if tags:
4247 output.extend(taglist)
4241 output.extend(taglist)
4248
4242
4249 if bookmarks:
4243 if bookmarks:
4250 output.extend(ctx.bookmarks())
4244 output.extend(ctx.bookmarks())
4251
4245
4252 ui.write("%s\n" % ' '.join(output))
4246 ui.write("%s\n" % ' '.join(output))
4253
4247
4254 @command('import|patch',
4248 @command('import|patch',
4255 [('p', 'strip', 1,
4249 [('p', 'strip', 1,
4256 _('directory strip option for patch. This has the same '
4250 _('directory strip option for patch. This has the same '
4257 'meaning as the corresponding patch option'), _('NUM')),
4251 'meaning as the corresponding patch option'), _('NUM')),
4258 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
4252 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
4259 ('e', 'edit', False, _('invoke editor on commit messages')),
4253 ('e', 'edit', False, _('invoke editor on commit messages')),
4260 ('f', 'force', None,
4254 ('f', 'force', None,
4261 _('skip check for outstanding uncommitted changes (DEPRECATED)')),
4255 _('skip check for outstanding uncommitted changes (DEPRECATED)')),
4262 ('', 'no-commit', None,
4256 ('', 'no-commit', None,
4263 _("don't commit, just update the working directory")),
4257 _("don't commit, just update the working directory")),
4264 ('', 'bypass', None,
4258 ('', 'bypass', None,
4265 _("apply patch without touching the working directory")),
4259 _("apply patch without touching the working directory")),
4266 ('', 'partial', None,
4260 ('', 'partial', None,
4267 _('commit even if some hunks fail')),
4261 _('commit even if some hunks fail')),
4268 ('', 'exact', None,
4262 ('', 'exact', None,
4269 _('apply patch to the nodes from which it was generated')),
4263 _('apply patch to the nodes from which it was generated')),
4270 ('', 'prefix', '',
4264 ('', 'prefix', '',
4271 _('apply patch to subdirectory'), _('DIR')),
4265 _('apply patch to subdirectory'), _('DIR')),
4272 ('', 'import-branch', None,
4266 ('', 'import-branch', None,
4273 _('use any branch information in patch (implied by --exact)'))] +
4267 _('use any branch information in patch (implied by --exact)'))] +
4274 commitopts + commitopts2 + similarityopts,
4268 commitopts + commitopts2 + similarityopts,
4275 _('[OPTION]... PATCH...'))
4269 _('[OPTION]... PATCH...'))
4276 def import_(ui, repo, patch1=None, *patches, **opts):
4270 def import_(ui, repo, patch1=None, *patches, **opts):
4277 """import an ordered set of patches
4271 """import an ordered set of patches
4278
4272
4279 Import a list of patches and commit them individually (unless
4273 Import a list of patches and commit them individually (unless
4280 --no-commit is specified).
4274 --no-commit is specified).
4281
4275
4282 Because import first applies changes to the working directory,
4276 Because import first applies changes to the working directory,
4283 import will abort if there are outstanding changes.
4277 import will abort if there are outstanding changes.
4284
4278
4285 You can import a patch straight from a mail message. Even patches
4279 You can import a patch straight from a mail message. Even patches
4286 as attachments work (to use the body part, it must have type
4280 as attachments work (to use the body part, it must have type
4287 text/plain or text/x-patch). From and Subject headers of email
4281 text/plain or text/x-patch). From and Subject headers of email
4288 message are used as default committer and commit message. All
4282 message are used as default committer and commit message. All
4289 text/plain body parts before first diff are added to commit
4283 text/plain body parts before first diff are added to commit
4290 message.
4284 message.
4291
4285
4292 If the imported patch was generated by :hg:`export`, user and
4286 If the imported patch was generated by :hg:`export`, user and
4293 description from patch override values from message headers and
4287 description from patch override values from message headers and
4294 body. Values given on command line with -m/--message and -u/--user
4288 body. Values given on command line with -m/--message and -u/--user
4295 override these.
4289 override these.
4296
4290
4297 If --exact is specified, import will set the working directory to
4291 If --exact is specified, import will set the working directory to
4298 the parent of each patch before applying it, and will abort if the
4292 the parent of each patch before applying it, and will abort if the
4299 resulting changeset has a different ID than the one recorded in
4293 resulting changeset has a different ID than the one recorded in
4300 the patch. This may happen due to character set problems or other
4294 the patch. This may happen due to character set problems or other
4301 deficiencies in the text patch format.
4295 deficiencies in the text patch format.
4302
4296
4303 Use --bypass to apply and commit patches directly to the
4297 Use --bypass to apply and commit patches directly to the
4304 repository, not touching the working directory. Without --exact,
4298 repository, not touching the working directory. Without --exact,
4305 patches will be applied on top of the working directory parent
4299 patches will be applied on top of the working directory parent
4306 revision.
4300 revision.
4307
4301
4308 With -s/--similarity, hg will attempt to discover renames and
4302 With -s/--similarity, hg will attempt to discover renames and
4309 copies in the patch in the same way as :hg:`addremove`.
4303 copies in the patch in the same way as :hg:`addremove`.
4310
4304
4311 Use --partial to ensure a changeset will be created from the patch
4305 Use --partial to ensure a changeset will be created from the patch
4312 even if some hunks fail to apply. Hunks that fail to apply will be
4306 even if some hunks fail to apply. Hunks that fail to apply will be
4313 written to a <target-file>.rej file. Conflicts can then be resolved
4307 written to a <target-file>.rej file. Conflicts can then be resolved
4314 by hand before :hg:`commit --amend` is run to update the created
4308 by hand before :hg:`commit --amend` is run to update the created
4315 changeset. This flag exists to let people import patches that
4309 changeset. This flag exists to let people import patches that
4316 partially apply without losing the associated metadata (author,
4310 partially apply without losing the associated metadata (author,
4317 date, description, ...). Note that when none of the hunk applies
4311 date, description, ...). Note that when none of the hunk applies
4318 cleanly, :hg:`import --partial` will create an empty changeset,
4312 cleanly, :hg:`import --partial` will create an empty changeset,
4319 importing only the patch metadata.
4313 importing only the patch metadata.
4320
4314
4321 It is possible to use external patch programs to perform the patch
4315 It is possible to use external patch programs to perform the patch
4322 by setting the ``ui.patch`` configuration option. For the default
4316 by setting the ``ui.patch`` configuration option. For the default
4323 internal tool, the fuzz can also be configured via ``patch.fuzz``.
4317 internal tool, the fuzz can also be configured via ``patch.fuzz``.
4324 See :hg:`help config` for more information about configuration
4318 See :hg:`help config` for more information about configuration
4325 files and how to use these options.
4319 files and how to use these options.
4326
4320
4327 To read a patch from standard input, use "-" as the patch name. If
4321 To read a patch from standard input, use "-" as the patch name. If
4328 a URL is specified, the patch will be downloaded from it.
4322 a URL is specified, the patch will be downloaded from it.
4329 See :hg:`help dates` for a list of formats valid for -d/--date.
4323 See :hg:`help dates` for a list of formats valid for -d/--date.
4330
4324
4331 .. container:: verbose
4325 .. container:: verbose
4332
4326
4333 Examples:
4327 Examples:
4334
4328
4335 - import a traditional patch from a website and detect renames::
4329 - import a traditional patch from a website and detect renames::
4336
4330
4337 hg import -s 80 http://example.com/bugfix.patch
4331 hg import -s 80 http://example.com/bugfix.patch
4338
4332
4339 - import a changeset from an hgweb server::
4333 - import a changeset from an hgweb server::
4340
4334
4341 hg import http://www.selenic.com/hg/rev/5ca8c111e9aa
4335 hg import http://www.selenic.com/hg/rev/5ca8c111e9aa
4342
4336
4343 - import all the patches in an Unix-style mbox::
4337 - import all the patches in an Unix-style mbox::
4344
4338
4345 hg import incoming-patches.mbox
4339 hg import incoming-patches.mbox
4346
4340
4347 - attempt to exactly restore an exported changeset (not always
4341 - attempt to exactly restore an exported changeset (not always
4348 possible)::
4342 possible)::
4349
4343
4350 hg import --exact proposed-fix.patch
4344 hg import --exact proposed-fix.patch
4351
4345
4352 - use an external tool to apply a patch which is too fuzzy for
4346 - use an external tool to apply a patch which is too fuzzy for
4353 the default internal tool.
4347 the default internal tool.
4354
4348
4355 hg import --config ui.patch="patch --merge" fuzzy.patch
4349 hg import --config ui.patch="patch --merge" fuzzy.patch
4356
4350
4357 - change the default fuzzing from 2 to a less strict 7
4351 - change the default fuzzing from 2 to a less strict 7
4358
4352
4359 hg import --config ui.fuzz=7 fuzz.patch
4353 hg import --config ui.fuzz=7 fuzz.patch
4360
4354
4361 Returns 0 on success, 1 on partial success (see --partial).
4355 Returns 0 on success, 1 on partial success (see --partial).
4362 """
4356 """
4363
4357
4364 if not patch1:
4358 if not patch1:
4365 raise util.Abort(_('need at least one patch to import'))
4359 raise util.Abort(_('need at least one patch to import'))
4366
4360
4367 patches = (patch1,) + patches
4361 patches = (patch1,) + patches
4368
4362
4369 date = opts.get('date')
4363 date = opts.get('date')
4370 if date:
4364 if date:
4371 opts['date'] = util.parsedate(date)
4365 opts['date'] = util.parsedate(date)
4372
4366
4373 update = not opts.get('bypass')
4367 update = not opts.get('bypass')
4374 if not update and opts.get('no_commit'):
4368 if not update and opts.get('no_commit'):
4375 raise util.Abort(_('cannot use --no-commit with --bypass'))
4369 raise util.Abort(_('cannot use --no-commit with --bypass'))
4376 try:
4370 try:
4377 sim = float(opts.get('similarity') or 0)
4371 sim = float(opts.get('similarity') or 0)
4378 except ValueError:
4372 except ValueError:
4379 raise util.Abort(_('similarity must be a number'))
4373 raise util.Abort(_('similarity must be a number'))
4380 if sim < 0 or sim > 100:
4374 if sim < 0 or sim > 100:
4381 raise util.Abort(_('similarity must be between 0 and 100'))
4375 raise util.Abort(_('similarity must be between 0 and 100'))
4382 if sim and not update:
4376 if sim and not update:
4383 raise util.Abort(_('cannot use --similarity with --bypass'))
4377 raise util.Abort(_('cannot use --similarity with --bypass'))
4384 if opts.get('exact') and opts.get('edit'):
4378 if opts.get('exact') and opts.get('edit'):
4385 raise util.Abort(_('cannot use --exact with --edit'))
4379 raise util.Abort(_('cannot use --exact with --edit'))
4386 if opts.get('exact') and opts.get('prefix'):
4380 if opts.get('exact') and opts.get('prefix'):
4387 raise util.Abort(_('cannot use --exact with --prefix'))
4381 raise util.Abort(_('cannot use --exact with --prefix'))
4388
4382
4389 if update:
4383 if update:
4390 cmdutil.checkunfinished(repo)
4384 cmdutil.checkunfinished(repo)
4391 if (opts.get('exact') or not opts.get('force')) and update:
4385 if (opts.get('exact') or not opts.get('force')) and update:
4392 cmdutil.bailifchanged(repo)
4386 cmdutil.bailifchanged(repo)
4393
4387
4394 base = opts["base"]
4388 base = opts["base"]
4395 wlock = dsguard = lock = tr = None
4389 wlock = dsguard = lock = tr = None
4396 msgs = []
4390 msgs = []
4397 ret = 0
4391 ret = 0
4398
4392
4399
4393
4400 try:
4394 try:
4401 try:
4395 try:
4402 wlock = repo.wlock()
4396 wlock = repo.wlock()
4403 dsguard = cmdutil.dirstateguard(repo, 'import')
4397 dsguard = cmdutil.dirstateguard(repo, 'import')
4404 if not opts.get('no_commit'):
4398 if not opts.get('no_commit'):
4405 lock = repo.lock()
4399 lock = repo.lock()
4406 tr = repo.transaction('import')
4400 tr = repo.transaction('import')
4407 parents = repo.parents()
4401 parents = repo.parents()
4408 for patchurl in patches:
4402 for patchurl in patches:
4409 if patchurl == '-':
4403 if patchurl == '-':
4410 ui.status(_('applying patch from stdin\n'))
4404 ui.status(_('applying patch from stdin\n'))
4411 patchfile = ui.fin
4405 patchfile = ui.fin
4412 patchurl = 'stdin' # for error message
4406 patchurl = 'stdin' # for error message
4413 else:
4407 else:
4414 patchurl = os.path.join(base, patchurl)
4408 patchurl = os.path.join(base, patchurl)
4415 ui.status(_('applying %s\n') % patchurl)
4409 ui.status(_('applying %s\n') % patchurl)
4416 patchfile = hg.openpath(ui, patchurl)
4410 patchfile = hg.openpath(ui, patchurl)
4417
4411
4418 haspatch = False
4412 haspatch = False
4419 for hunk in patch.split(patchfile):
4413 for hunk in patch.split(patchfile):
4420 (msg, node, rej) = cmdutil.tryimportone(ui, repo, hunk,
4414 (msg, node, rej) = cmdutil.tryimportone(ui, repo, hunk,
4421 parents, opts,
4415 parents, opts,
4422 msgs, hg.clean)
4416 msgs, hg.clean)
4423 if msg:
4417 if msg:
4424 haspatch = True
4418 haspatch = True
4425 ui.note(msg + '\n')
4419 ui.note(msg + '\n')
4426 if update or opts.get('exact'):
4420 if update or opts.get('exact'):
4427 parents = repo.parents()
4421 parents = repo.parents()
4428 else:
4422 else:
4429 parents = [repo[node]]
4423 parents = [repo[node]]
4430 if rej:
4424 if rej:
4431 ui.write_err(_("patch applied partially\n"))
4425 ui.write_err(_("patch applied partially\n"))
4432 ui.write_err(_("(fix the .rej files and run "
4426 ui.write_err(_("(fix the .rej files and run "
4433 "`hg commit --amend`)\n"))
4427 "`hg commit --amend`)\n"))
4434 ret = 1
4428 ret = 1
4435 break
4429 break
4436
4430
4437 if not haspatch:
4431 if not haspatch:
4438 raise util.Abort(_('%s: no diffs found') % patchurl)
4432 raise util.Abort(_('%s: no diffs found') % patchurl)
4439
4433
4440 if tr:
4434 if tr:
4441 tr.close()
4435 tr.close()
4442 if msgs:
4436 if msgs:
4443 repo.savecommitmessage('\n* * *\n'.join(msgs))
4437 repo.savecommitmessage('\n* * *\n'.join(msgs))
4444 dsguard.close()
4438 dsguard.close()
4445 return ret
4439 return ret
4446 finally:
4440 finally:
4447 # TODO: get rid of this meaningless try/finally enclosing.
4441 # TODO: get rid of this meaningless try/finally enclosing.
4448 # this is kept only to reduce changes in a patch.
4442 # this is kept only to reduce changes in a patch.
4449 pass
4443 pass
4450 finally:
4444 finally:
4451 if tr:
4445 if tr:
4452 tr.release()
4446 tr.release()
4453 release(lock, dsguard, wlock)
4447 release(lock, dsguard, wlock)
4454
4448
4455 @command('incoming|in',
4449 @command('incoming|in',
4456 [('f', 'force', None,
4450 [('f', 'force', None,
4457 _('run even if remote repository is unrelated')),
4451 _('run even if remote repository is unrelated')),
4458 ('n', 'newest-first', None, _('show newest record first')),
4452 ('n', 'newest-first', None, _('show newest record first')),
4459 ('', 'bundle', '',
4453 ('', 'bundle', '',
4460 _('file to store the bundles into'), _('FILE')),
4454 _('file to store the bundles into'), _('FILE')),
4461 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
4455 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
4462 ('B', 'bookmarks', False, _("compare bookmarks")),
4456 ('B', 'bookmarks', False, _("compare bookmarks")),
4463 ('b', 'branch', [],
4457 ('b', 'branch', [],
4464 _('a specific branch you would like to pull'), _('BRANCH')),
4458 _('a specific branch you would like to pull'), _('BRANCH')),
4465 ] + logopts + remoteopts + subrepoopts,
4459 ] + logopts + remoteopts + subrepoopts,
4466 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
4460 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
4467 def incoming(ui, repo, source="default", **opts):
4461 def incoming(ui, repo, source="default", **opts):
4468 """show new changesets found in source
4462 """show new changesets found in source
4469
4463
4470 Show new changesets found in the specified path/URL or the default
4464 Show new changesets found in the specified path/URL or the default
4471 pull location. These are the changesets that would have been pulled
4465 pull location. These are the changesets that would have been pulled
4472 if a pull at the time you issued this command.
4466 if a pull at the time you issued this command.
4473
4467
4474 See pull for valid source format details.
4468 See pull for valid source format details.
4475
4469
4476 .. container:: verbose
4470 .. container:: verbose
4477
4471
4478 With -B/--bookmarks, the result of bookmark comparison between
4472 With -B/--bookmarks, the result of bookmark comparison between
4479 local and remote repositories is displayed. With -v/--verbose,
4473 local and remote repositories is displayed. With -v/--verbose,
4480 status is also displayed for each bookmark like below::
4474 status is also displayed for each bookmark like below::
4481
4475
4482 BM1 01234567890a added
4476 BM1 01234567890a added
4483 BM2 1234567890ab advanced
4477 BM2 1234567890ab advanced
4484 BM3 234567890abc diverged
4478 BM3 234567890abc diverged
4485 BM4 34567890abcd changed
4479 BM4 34567890abcd changed
4486
4480
4487 The action taken locally when pulling depends on the
4481 The action taken locally when pulling depends on the
4488 status of each bookmark:
4482 status of each bookmark:
4489
4483
4490 :``added``: pull will create it
4484 :``added``: pull will create it
4491 :``advanced``: pull will update it
4485 :``advanced``: pull will update it
4492 :``diverged``: pull will create a divergent bookmark
4486 :``diverged``: pull will create a divergent bookmark
4493 :``changed``: result depends on remote changesets
4487 :``changed``: result depends on remote changesets
4494
4488
4495 From the point of view of pulling behavior, bookmark
4489 From the point of view of pulling behavior, bookmark
4496 existing only in the remote repository are treated as ``added``,
4490 existing only in the remote repository are treated as ``added``,
4497 even if it is in fact locally deleted.
4491 even if it is in fact locally deleted.
4498
4492
4499 .. container:: verbose
4493 .. container:: verbose
4500
4494
4501 For remote repository, using --bundle avoids downloading the
4495 For remote repository, using --bundle avoids downloading the
4502 changesets twice if the incoming is followed by a pull.
4496 changesets twice if the incoming is followed by a pull.
4503
4497
4504 Examples:
4498 Examples:
4505
4499
4506 - show incoming changes with patches and full description::
4500 - show incoming changes with patches and full description::
4507
4501
4508 hg incoming -vp
4502 hg incoming -vp
4509
4503
4510 - show incoming changes excluding merges, store a bundle::
4504 - show incoming changes excluding merges, store a bundle::
4511
4505
4512 hg in -vpM --bundle incoming.hg
4506 hg in -vpM --bundle incoming.hg
4513 hg pull incoming.hg
4507 hg pull incoming.hg
4514
4508
4515 - briefly list changes inside a bundle::
4509 - briefly list changes inside a bundle::
4516
4510
4517 hg in changes.hg -T "{desc|firstline}\\n"
4511 hg in changes.hg -T "{desc|firstline}\\n"
4518
4512
4519 Returns 0 if there are incoming changes, 1 otherwise.
4513 Returns 0 if there are incoming changes, 1 otherwise.
4520 """
4514 """
4521 if opts.get('graph'):
4515 if opts.get('graph'):
4522 cmdutil.checkunsupportedgraphflags([], opts)
4516 cmdutil.checkunsupportedgraphflags([], opts)
4523 def display(other, chlist, displayer):
4517 def display(other, chlist, displayer):
4524 revdag = cmdutil.graphrevs(other, chlist, opts)
4518 revdag = cmdutil.graphrevs(other, chlist, opts)
4525 showparents = [ctx.node() for ctx in repo[None].parents()]
4519 showparents = [ctx.node() for ctx in repo[None].parents()]
4526 cmdutil.displaygraph(ui, revdag, displayer, showparents,
4520 cmdutil.displaygraph(ui, revdag, displayer, showparents,
4527 graphmod.asciiedges)
4521 graphmod.asciiedges)
4528
4522
4529 hg._incoming(display, lambda: 1, ui, repo, source, opts, buffered=True)
4523 hg._incoming(display, lambda: 1, ui, repo, source, opts, buffered=True)
4530 return 0
4524 return 0
4531
4525
4532 if opts.get('bundle') and opts.get('subrepos'):
4526 if opts.get('bundle') and opts.get('subrepos'):
4533 raise util.Abort(_('cannot combine --bundle and --subrepos'))
4527 raise util.Abort(_('cannot combine --bundle and --subrepos'))
4534
4528
4535 if opts.get('bookmarks'):
4529 if opts.get('bookmarks'):
4536 source, branches = hg.parseurl(ui.expandpath(source),
4530 source, branches = hg.parseurl(ui.expandpath(source),
4537 opts.get('branch'))
4531 opts.get('branch'))
4538 other = hg.peer(repo, opts, source)
4532 other = hg.peer(repo, opts, source)
4539 if 'bookmarks' not in other.listkeys('namespaces'):
4533 if 'bookmarks' not in other.listkeys('namespaces'):
4540 ui.warn(_("remote doesn't support bookmarks\n"))
4534 ui.warn(_("remote doesn't support bookmarks\n"))
4541 return 0
4535 return 0
4542 ui.status(_('comparing with %s\n') % util.hidepassword(source))
4536 ui.status(_('comparing with %s\n') % util.hidepassword(source))
4543 return bookmarks.incoming(ui, repo, other)
4537 return bookmarks.incoming(ui, repo, other)
4544
4538
4545 repo._subtoppath = ui.expandpath(source)
4539 repo._subtoppath = ui.expandpath(source)
4546 try:
4540 try:
4547 return hg.incoming(ui, repo, source, opts)
4541 return hg.incoming(ui, repo, source, opts)
4548 finally:
4542 finally:
4549 del repo._subtoppath
4543 del repo._subtoppath
4550
4544
4551
4545
4552 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'),
4546 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'),
4553 norepo=True)
4547 norepo=True)
4554 def init(ui, dest=".", **opts):
4548 def init(ui, dest=".", **opts):
4555 """create a new repository in the given directory
4549 """create a new repository in the given directory
4556
4550
4557 Initialize a new repository in the given directory. If the given
4551 Initialize a new repository in the given directory. If the given
4558 directory does not exist, it will be created.
4552 directory does not exist, it will be created.
4559
4553
4560 If no directory is given, the current directory is used.
4554 If no directory is given, the current directory is used.
4561
4555
4562 It is possible to specify an ``ssh://`` URL as the destination.
4556 It is possible to specify an ``ssh://`` URL as the destination.
4563 See :hg:`help urls` for more information.
4557 See :hg:`help urls` for more information.
4564
4558
4565 Returns 0 on success.
4559 Returns 0 on success.
4566 """
4560 """
4567 hg.peer(ui, opts, ui.expandpath(dest), create=True)
4561 hg.peer(ui, opts, ui.expandpath(dest), create=True)
4568
4562
4569 @command('locate',
4563 @command('locate',
4570 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
4564 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
4571 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
4565 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
4572 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
4566 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
4573 ] + walkopts,
4567 ] + walkopts,
4574 _('[OPTION]... [PATTERN]...'))
4568 _('[OPTION]... [PATTERN]...'))
4575 def locate(ui, repo, *pats, **opts):
4569 def locate(ui, repo, *pats, **opts):
4576 """locate files matching specific patterns (DEPRECATED)
4570 """locate files matching specific patterns (DEPRECATED)
4577
4571
4578 Print files under Mercurial control in the working directory whose
4572 Print files under Mercurial control in the working directory whose
4579 names match the given patterns.
4573 names match the given patterns.
4580
4574
4581 By default, this command searches all directories in the working
4575 By default, this command searches all directories in the working
4582 directory. To search just the current directory and its
4576 directory. To search just the current directory and its
4583 subdirectories, use "--include .".
4577 subdirectories, use "--include .".
4584
4578
4585 If no patterns are given to match, this command prints the names
4579 If no patterns are given to match, this command prints the names
4586 of all files under Mercurial control in the working directory.
4580 of all files under Mercurial control in the working directory.
4587
4581
4588 If you want to feed the output of this command into the "xargs"
4582 If you want to feed the output of this command into the "xargs"
4589 command, use the -0 option to both this command and "xargs". This
4583 command, use the -0 option to both this command and "xargs". This
4590 will avoid the problem of "xargs" treating single filenames that
4584 will avoid the problem of "xargs" treating single filenames that
4591 contain whitespace as multiple filenames.
4585 contain whitespace as multiple filenames.
4592
4586
4593 See :hg:`help files` for a more versatile command.
4587 See :hg:`help files` for a more versatile command.
4594
4588
4595 Returns 0 if a match is found, 1 otherwise.
4589 Returns 0 if a match is found, 1 otherwise.
4596 """
4590 """
4597 if opts.get('print0'):
4591 if opts.get('print0'):
4598 end = '\0'
4592 end = '\0'
4599 else:
4593 else:
4600 end = '\n'
4594 end = '\n'
4601 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
4595 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
4602
4596
4603 ret = 1
4597 ret = 1
4604 ctx = repo[rev]
4598 ctx = repo[rev]
4605 m = scmutil.match(ctx, pats, opts, default='relglob',
4599 m = scmutil.match(ctx, pats, opts, default='relglob',
4606 badfn=lambda x, y: False)
4600 badfn=lambda x, y: False)
4607
4601
4608 for abs in ctx.matches(m):
4602 for abs in ctx.matches(m):
4609 if opts.get('fullpath'):
4603 if opts.get('fullpath'):
4610 ui.write(repo.wjoin(abs), end)
4604 ui.write(repo.wjoin(abs), end)
4611 else:
4605 else:
4612 ui.write(((pats and m.rel(abs)) or abs), end)
4606 ui.write(((pats and m.rel(abs)) or abs), end)
4613 ret = 0
4607 ret = 0
4614
4608
4615 return ret
4609 return ret
4616
4610
4617 @command('^log|history',
4611 @command('^log|history',
4618 [('f', 'follow', None,
4612 [('f', 'follow', None,
4619 _('follow changeset history, or file history across copies and renames')),
4613 _('follow changeset history, or file history across copies and renames')),
4620 ('', 'follow-first', None,
4614 ('', 'follow-first', None,
4621 _('only follow the first parent of merge changesets (DEPRECATED)')),
4615 _('only follow the first parent of merge changesets (DEPRECATED)')),
4622 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
4616 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
4623 ('C', 'copies', None, _('show copied files')),
4617 ('C', 'copies', None, _('show copied files')),
4624 ('k', 'keyword', [],
4618 ('k', 'keyword', [],
4625 _('do case-insensitive search for a given text'), _('TEXT')),
4619 _('do case-insensitive search for a given text'), _('TEXT')),
4626 ('r', 'rev', [], _('show the specified revision or revset'), _('REV')),
4620 ('r', 'rev', [], _('show the specified revision or revset'), _('REV')),
4627 ('', 'removed', None, _('include revisions where files were removed')),
4621 ('', 'removed', None, _('include revisions where files were removed')),
4628 ('m', 'only-merges', None, _('show only merges (DEPRECATED)')),
4622 ('m', 'only-merges', None, _('show only merges (DEPRECATED)')),
4629 ('u', 'user', [], _('revisions committed by user'), _('USER')),
4623 ('u', 'user', [], _('revisions committed by user'), _('USER')),
4630 ('', 'only-branch', [],
4624 ('', 'only-branch', [],
4631 _('show only changesets within the given named branch (DEPRECATED)'),
4625 _('show only changesets within the given named branch (DEPRECATED)'),
4632 _('BRANCH')),
4626 _('BRANCH')),
4633 ('b', 'branch', [],
4627 ('b', 'branch', [],
4634 _('show changesets within the given named branch'), _('BRANCH')),
4628 _('show changesets within the given named branch'), _('BRANCH')),
4635 ('P', 'prune', [],
4629 ('P', 'prune', [],
4636 _('do not display revision or any of its ancestors'), _('REV')),
4630 _('do not display revision or any of its ancestors'), _('REV')),
4637 ] + logopts + walkopts,
4631 ] + logopts + walkopts,
4638 _('[OPTION]... [FILE]'),
4632 _('[OPTION]... [FILE]'),
4639 inferrepo=True)
4633 inferrepo=True)
4640 def log(ui, repo, *pats, **opts):
4634 def log(ui, repo, *pats, **opts):
4641 """show revision history of entire repository or files
4635 """show revision history of entire repository or files
4642
4636
4643 Print the revision history of the specified files or the entire
4637 Print the revision history of the specified files or the entire
4644 project.
4638 project.
4645
4639
4646 If no revision range is specified, the default is ``tip:0`` unless
4640 If no revision range is specified, the default is ``tip:0`` unless
4647 --follow is set, in which case the working directory parent is
4641 --follow is set, in which case the working directory parent is
4648 used as the starting revision.
4642 used as the starting revision.
4649
4643
4650 File history is shown without following rename or copy history of
4644 File history is shown without following rename or copy history of
4651 files. Use -f/--follow with a filename to follow history across
4645 files. Use -f/--follow with a filename to follow history across
4652 renames and copies. --follow without a filename will only show
4646 renames and copies. --follow without a filename will only show
4653 ancestors or descendants of the starting revision.
4647 ancestors or descendants of the starting revision.
4654
4648
4655 By default this command prints revision number and changeset id,
4649 By default this command prints revision number and changeset id,
4656 tags, non-trivial parents, user, date and time, and a summary for
4650 tags, non-trivial parents, user, date and time, and a summary for
4657 each commit. When the -v/--verbose switch is used, the list of
4651 each commit. When the -v/--verbose switch is used, the list of
4658 changed files and full commit message are shown.
4652 changed files and full commit message are shown.
4659
4653
4660 With --graph the revisions are shown as an ASCII art DAG with the most
4654 With --graph the revisions are shown as an ASCII art DAG with the most
4661 recent changeset at the top.
4655 recent changeset at the top.
4662 'o' is a changeset, '@' is a working directory parent, 'x' is obsolete,
4656 'o' is a changeset, '@' is a working directory parent, 'x' is obsolete,
4663 and '+' represents a fork where the changeset from the lines below is a
4657 and '+' represents a fork where the changeset from the lines below is a
4664 parent of the 'o' merge on the same line.
4658 parent of the 'o' merge on the same line.
4665
4659
4666 .. note::
4660 .. note::
4667
4661
4668 log -p/--patch may generate unexpected diff output for merge
4662 log -p/--patch may generate unexpected diff output for merge
4669 changesets, as it will only compare the merge changeset against
4663 changesets, as it will only compare the merge changeset against
4670 its first parent. Also, only files different from BOTH parents
4664 its first parent. Also, only files different from BOTH parents
4671 will appear in files:.
4665 will appear in files:.
4672
4666
4673 .. note::
4667 .. note::
4674
4668
4675 for performance reasons, log FILE may omit duplicate changes
4669 for performance reasons, log FILE may omit duplicate changes
4676 made on branches and will not show removals or mode changes. To
4670 made on branches and will not show removals or mode changes. To
4677 see all such changes, use the --removed switch.
4671 see all such changes, use the --removed switch.
4678
4672
4679 .. container:: verbose
4673 .. container:: verbose
4680
4674
4681 Some examples:
4675 Some examples:
4682
4676
4683 - changesets with full descriptions and file lists::
4677 - changesets with full descriptions and file lists::
4684
4678
4685 hg log -v
4679 hg log -v
4686
4680
4687 - changesets ancestral to the working directory::
4681 - changesets ancestral to the working directory::
4688
4682
4689 hg log -f
4683 hg log -f
4690
4684
4691 - last 10 commits on the current branch::
4685 - last 10 commits on the current branch::
4692
4686
4693 hg log -l 10 -b .
4687 hg log -l 10 -b .
4694
4688
4695 - changesets showing all modifications of a file, including removals::
4689 - changesets showing all modifications of a file, including removals::
4696
4690
4697 hg log --removed file.c
4691 hg log --removed file.c
4698
4692
4699 - all changesets that touch a directory, with diffs, excluding merges::
4693 - all changesets that touch a directory, with diffs, excluding merges::
4700
4694
4701 hg log -Mp lib/
4695 hg log -Mp lib/
4702
4696
4703 - all revision numbers that match a keyword::
4697 - all revision numbers that match a keyword::
4704
4698
4705 hg log -k bug --template "{rev}\\n"
4699 hg log -k bug --template "{rev}\\n"
4706
4700
4707 - list available log templates::
4701 - list available log templates::
4708
4702
4709 hg log -T list
4703 hg log -T list
4710
4704
4711 - check if a given changeset is included in a tagged release::
4705 - check if a given changeset is included in a tagged release::
4712
4706
4713 hg log -r "a21ccf and ancestor(1.9)"
4707 hg log -r "a21ccf and ancestor(1.9)"
4714
4708
4715 - find all changesets by some user in a date range::
4709 - find all changesets by some user in a date range::
4716
4710
4717 hg log -k alice -d "may 2008 to jul 2008"
4711 hg log -k alice -d "may 2008 to jul 2008"
4718
4712
4719 - summary of all changesets after the last tag::
4713 - summary of all changesets after the last tag::
4720
4714
4721 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
4715 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
4722
4716
4723 See :hg:`help dates` for a list of formats valid for -d/--date.
4717 See :hg:`help dates` for a list of formats valid for -d/--date.
4724
4718
4725 See :hg:`help revisions` and :hg:`help revsets` for more about
4719 See :hg:`help revisions` and :hg:`help revsets` for more about
4726 specifying revisions.
4720 specifying revisions.
4727
4721
4728 See :hg:`help templates` for more about pre-packaged styles and
4722 See :hg:`help templates` for more about pre-packaged styles and
4729 specifying custom templates.
4723 specifying custom templates.
4730
4724
4731 Returns 0 on success.
4725 Returns 0 on success.
4732
4726
4733 """
4727 """
4734 if opts.get('follow') and opts.get('rev'):
4728 if opts.get('follow') and opts.get('rev'):
4735 opts['rev'] = [revset.formatspec('reverse(::%lr)', opts.get('rev'))]
4729 opts['rev'] = [revset.formatspec('reverse(::%lr)', opts.get('rev'))]
4736 del opts['follow']
4730 del opts['follow']
4737
4731
4738 if opts.get('graph'):
4732 if opts.get('graph'):
4739 return cmdutil.graphlog(ui, repo, *pats, **opts)
4733 return cmdutil.graphlog(ui, repo, *pats, **opts)
4740
4734
4741 revs, expr, filematcher = cmdutil.getlogrevs(repo, pats, opts)
4735 revs, expr, filematcher = cmdutil.getlogrevs(repo, pats, opts)
4742 limit = cmdutil.loglimit(opts)
4736 limit = cmdutil.loglimit(opts)
4743 count = 0
4737 count = 0
4744
4738
4745 getrenamed = None
4739 getrenamed = None
4746 if opts.get('copies'):
4740 if opts.get('copies'):
4747 endrev = None
4741 endrev = None
4748 if opts.get('rev'):
4742 if opts.get('rev'):
4749 endrev = scmutil.revrange(repo, opts.get('rev')).max() + 1
4743 endrev = scmutil.revrange(repo, opts.get('rev')).max() + 1
4750 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
4744 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
4751
4745
4752 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
4746 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
4753 for rev in revs:
4747 for rev in revs:
4754 if count == limit:
4748 if count == limit:
4755 break
4749 break
4756 ctx = repo[rev]
4750 ctx = repo[rev]
4757 copies = None
4751 copies = None
4758 if getrenamed is not None and rev:
4752 if getrenamed is not None and rev:
4759 copies = []
4753 copies = []
4760 for fn in ctx.files():
4754 for fn in ctx.files():
4761 rename = getrenamed(fn, rev)
4755 rename = getrenamed(fn, rev)
4762 if rename:
4756 if rename:
4763 copies.append((fn, rename[0]))
4757 copies.append((fn, rename[0]))
4764 if filematcher:
4758 if filematcher:
4765 revmatchfn = filematcher(ctx.rev())
4759 revmatchfn = filematcher(ctx.rev())
4766 else:
4760 else:
4767 revmatchfn = None
4761 revmatchfn = None
4768 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
4762 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
4769 if displayer.flush(ctx):
4763 if displayer.flush(ctx):
4770 count += 1
4764 count += 1
4771
4765
4772 displayer.close()
4766 displayer.close()
4773
4767
4774 @command('manifest',
4768 @command('manifest',
4775 [('r', 'rev', '', _('revision to display'), _('REV')),
4769 [('r', 'rev', '', _('revision to display'), _('REV')),
4776 ('', 'all', False, _("list files from all revisions"))]
4770 ('', 'all', False, _("list files from all revisions"))]
4777 + formatteropts,
4771 + formatteropts,
4778 _('[-r REV]'))
4772 _('[-r REV]'))
4779 def manifest(ui, repo, node=None, rev=None, **opts):
4773 def manifest(ui, repo, node=None, rev=None, **opts):
4780 """output the current or given revision of the project manifest
4774 """output the current or given revision of the project manifest
4781
4775
4782 Print a list of version controlled files for the given revision.
4776 Print a list of version controlled files for the given revision.
4783 If no revision is given, the first parent of the working directory
4777 If no revision is given, the first parent of the working directory
4784 is used, or the null revision if no revision is checked out.
4778 is used, or the null revision if no revision is checked out.
4785
4779
4786 With -v, print file permissions, symlink and executable bits.
4780 With -v, print file permissions, symlink and executable bits.
4787 With --debug, print file revision hashes.
4781 With --debug, print file revision hashes.
4788
4782
4789 If option --all is specified, the list of all files from all revisions
4783 If option --all is specified, the list of all files from all revisions
4790 is printed. This includes deleted and renamed files.
4784 is printed. This includes deleted and renamed files.
4791
4785
4792 Returns 0 on success.
4786 Returns 0 on success.
4793 """
4787 """
4794
4788
4795 fm = ui.formatter('manifest', opts)
4789 fm = ui.formatter('manifest', opts)
4796
4790
4797 if opts.get('all'):
4791 if opts.get('all'):
4798 if rev or node:
4792 if rev or node:
4799 raise util.Abort(_("can't specify a revision with --all"))
4793 raise util.Abort(_("can't specify a revision with --all"))
4800
4794
4801 res = []
4795 res = []
4802 prefix = "data/"
4796 prefix = "data/"
4803 suffix = ".i"
4797 suffix = ".i"
4804 plen = len(prefix)
4798 plen = len(prefix)
4805 slen = len(suffix)
4799 slen = len(suffix)
4806 lock = repo.lock()
4800 lock = repo.lock()
4807 try:
4801 try:
4808 for fn, b, size in repo.store.datafiles():
4802 for fn, b, size in repo.store.datafiles():
4809 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
4803 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
4810 res.append(fn[plen:-slen])
4804 res.append(fn[plen:-slen])
4811 finally:
4805 finally:
4812 lock.release()
4806 lock.release()
4813 for f in res:
4807 for f in res:
4814 fm.startitem()
4808 fm.startitem()
4815 fm.write("path", '%s\n', f)
4809 fm.write("path", '%s\n', f)
4816 fm.end()
4810 fm.end()
4817 return
4811 return
4818
4812
4819 if rev and node:
4813 if rev and node:
4820 raise util.Abort(_("please specify just one revision"))
4814 raise util.Abort(_("please specify just one revision"))
4821
4815
4822 if not node:
4816 if not node:
4823 node = rev
4817 node = rev
4824
4818
4825 char = {'l': '@', 'x': '*', '': ''}
4819 char = {'l': '@', 'x': '*', '': ''}
4826 mode = {'l': '644', 'x': '755', '': '644'}
4820 mode = {'l': '644', 'x': '755', '': '644'}
4827 ctx = scmutil.revsingle(repo, node)
4821 ctx = scmutil.revsingle(repo, node)
4828 mf = ctx.manifest()
4822 mf = ctx.manifest()
4829 for f in ctx:
4823 for f in ctx:
4830 fm.startitem()
4824 fm.startitem()
4831 fl = ctx[f].flags()
4825 fl = ctx[f].flags()
4832 fm.condwrite(ui.debugflag, 'hash', '%s ', hex(mf[f]))
4826 fm.condwrite(ui.debugflag, 'hash', '%s ', hex(mf[f]))
4833 fm.condwrite(ui.verbose, 'mode type', '%s %1s ', mode[fl], char[fl])
4827 fm.condwrite(ui.verbose, 'mode type', '%s %1s ', mode[fl], char[fl])
4834 fm.write('path', '%s\n', f)
4828 fm.write('path', '%s\n', f)
4835 fm.end()
4829 fm.end()
4836
4830
4837 @command('^merge',
4831 @command('^merge',
4838 [('f', 'force', None,
4832 [('f', 'force', None,
4839 _('force a merge including outstanding changes (DEPRECATED)')),
4833 _('force a merge including outstanding changes (DEPRECATED)')),
4840 ('r', 'rev', '', _('revision to merge'), _('REV')),
4834 ('r', 'rev', '', _('revision to merge'), _('REV')),
4841 ('P', 'preview', None,
4835 ('P', 'preview', None,
4842 _('review revisions to merge (no merge is performed)'))
4836 _('review revisions to merge (no merge is performed)'))
4843 ] + mergetoolopts,
4837 ] + mergetoolopts,
4844 _('[-P] [-f] [[-r] REV]'))
4838 _('[-P] [-f] [[-r] REV]'))
4845 def merge(ui, repo, node=None, **opts):
4839 def merge(ui, repo, node=None, **opts):
4846 """merge another revision into working directory
4840 """merge another revision into working directory
4847
4841
4848 The current working directory is updated with all changes made in
4842 The current working directory is updated with all changes made in
4849 the requested revision since the last common predecessor revision.
4843 the requested revision since the last common predecessor revision.
4850
4844
4851 Files that changed between either parent are marked as changed for
4845 Files that changed between either parent are marked as changed for
4852 the next commit and a commit must be performed before any further
4846 the next commit and a commit must be performed before any further
4853 updates to the repository are allowed. The next commit will have
4847 updates to the repository are allowed. The next commit will have
4854 two parents.
4848 two parents.
4855
4849
4856 ``--tool`` can be used to specify the merge tool used for file
4850 ``--tool`` can be used to specify the merge tool used for file
4857 merges. It overrides the HGMERGE environment variable and your
4851 merges. It overrides the HGMERGE environment variable and your
4858 configuration files. See :hg:`help merge-tools` for options.
4852 configuration files. See :hg:`help merge-tools` for options.
4859
4853
4860 If no revision is specified, the working directory's parent is a
4854 If no revision is specified, the working directory's parent is a
4861 head revision, and the current branch contains exactly one other
4855 head revision, and the current branch contains exactly one other
4862 head, the other head is merged with by default. Otherwise, an
4856 head, the other head is merged with by default. Otherwise, an
4863 explicit revision with which to merge with must be provided.
4857 explicit revision with which to merge with must be provided.
4864
4858
4865 :hg:`resolve` must be used to resolve unresolved files.
4859 :hg:`resolve` must be used to resolve unresolved files.
4866
4860
4867 To undo an uncommitted merge, use :hg:`update --clean .` which
4861 To undo an uncommitted merge, use :hg:`update --clean .` which
4868 will check out a clean copy of the original merge parent, losing
4862 will check out a clean copy of the original merge parent, losing
4869 all changes.
4863 all changes.
4870
4864
4871 Returns 0 on success, 1 if there are unresolved files.
4865 Returns 0 on success, 1 if there are unresolved files.
4872 """
4866 """
4873
4867
4874 if opts.get('rev') and node:
4868 if opts.get('rev') and node:
4875 raise util.Abort(_("please specify just one revision"))
4869 raise util.Abort(_("please specify just one revision"))
4876 if not node:
4870 if not node:
4877 node = opts.get('rev')
4871 node = opts.get('rev')
4878
4872
4879 if node:
4873 if node:
4880 node = scmutil.revsingle(repo, node).node()
4874 node = scmutil.revsingle(repo, node).node()
4881
4875
4882 if not node:
4876 if not node:
4883 node = scmutil.revsingle(repo, '_mergedefaultdest()').node()
4877 node = scmutil.revsingle(repo, '_mergedefaultdest()').node()
4884
4878
4885 if opts.get('preview'):
4879 if opts.get('preview'):
4886 # find nodes that are ancestors of p2 but not of p1
4880 # find nodes that are ancestors of p2 but not of p1
4887 p1 = repo.lookup('.')
4881 p1 = repo.lookup('.')
4888 p2 = repo.lookup(node)
4882 p2 = repo.lookup(node)
4889 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
4883 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
4890
4884
4891 displayer = cmdutil.show_changeset(ui, repo, opts)
4885 displayer = cmdutil.show_changeset(ui, repo, opts)
4892 for node in nodes:
4886 for node in nodes:
4893 displayer.show(repo[node])
4887 displayer.show(repo[node])
4894 displayer.close()
4888 displayer.close()
4895 return 0
4889 return 0
4896
4890
4897 try:
4891 try:
4898 # ui.forcemerge is an internal variable, do not document
4892 # ui.forcemerge is an internal variable, do not document
4899 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''), 'merge')
4893 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''), 'merge')
4900 return hg.merge(repo, node, force=opts.get('force'))
4894 return hg.merge(repo, node, force=opts.get('force'))
4901 finally:
4895 finally:
4902 ui.setconfig('ui', 'forcemerge', '', 'merge')
4896 ui.setconfig('ui', 'forcemerge', '', 'merge')
4903
4897
4904 @command('outgoing|out',
4898 @command('outgoing|out',
4905 [('f', 'force', None, _('run even when the destination is unrelated')),
4899 [('f', 'force', None, _('run even when the destination is unrelated')),
4906 ('r', 'rev', [],
4900 ('r', 'rev', [],
4907 _('a changeset intended to be included in the destination'), _('REV')),
4901 _('a changeset intended to be included in the destination'), _('REV')),
4908 ('n', 'newest-first', None, _('show newest record first')),
4902 ('n', 'newest-first', None, _('show newest record first')),
4909 ('B', 'bookmarks', False, _('compare bookmarks')),
4903 ('B', 'bookmarks', False, _('compare bookmarks')),
4910 ('b', 'branch', [], _('a specific branch you would like to push'),
4904 ('b', 'branch', [], _('a specific branch you would like to push'),
4911 _('BRANCH')),
4905 _('BRANCH')),
4912 ] + logopts + remoteopts + subrepoopts,
4906 ] + logopts + remoteopts + subrepoopts,
4913 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
4907 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
4914 def outgoing(ui, repo, dest=None, **opts):
4908 def outgoing(ui, repo, dest=None, **opts):
4915 """show changesets not found in the destination
4909 """show changesets not found in the destination
4916
4910
4917 Show changesets not found in the specified destination repository
4911 Show changesets not found in the specified destination repository
4918 or the default push location. These are the changesets that would
4912 or the default push location. These are the changesets that would
4919 be pushed if a push was requested.
4913 be pushed if a push was requested.
4920
4914
4921 See pull for details of valid destination formats.
4915 See pull for details of valid destination formats.
4922
4916
4923 .. container:: verbose
4917 .. container:: verbose
4924
4918
4925 With -B/--bookmarks, the result of bookmark comparison between
4919 With -B/--bookmarks, the result of bookmark comparison between
4926 local and remote repositories is displayed. With -v/--verbose,
4920 local and remote repositories is displayed. With -v/--verbose,
4927 status is also displayed for each bookmark like below::
4921 status is also displayed for each bookmark like below::
4928
4922
4929 BM1 01234567890a added
4923 BM1 01234567890a added
4930 BM2 deleted
4924 BM2 deleted
4931 BM3 234567890abc advanced
4925 BM3 234567890abc advanced
4932 BM4 34567890abcd diverged
4926 BM4 34567890abcd diverged
4933 BM5 4567890abcde changed
4927 BM5 4567890abcde changed
4934
4928
4935 The action taken when pushing depends on the
4929 The action taken when pushing depends on the
4936 status of each bookmark:
4930 status of each bookmark:
4937
4931
4938 :``added``: push with ``-B`` will create it
4932 :``added``: push with ``-B`` will create it
4939 :``deleted``: push with ``-B`` will delete it
4933 :``deleted``: push with ``-B`` will delete it
4940 :``advanced``: push will update it
4934 :``advanced``: push will update it
4941 :``diverged``: push with ``-B`` will update it
4935 :``diverged``: push with ``-B`` will update it
4942 :``changed``: push with ``-B`` will update it
4936 :``changed``: push with ``-B`` will update it
4943
4937
4944 From the point of view of pushing behavior, bookmarks
4938 From the point of view of pushing behavior, bookmarks
4945 existing only in the remote repository are treated as
4939 existing only in the remote repository are treated as
4946 ``deleted``, even if it is in fact added remotely.
4940 ``deleted``, even if it is in fact added remotely.
4947
4941
4948 Returns 0 if there are outgoing changes, 1 otherwise.
4942 Returns 0 if there are outgoing changes, 1 otherwise.
4949 """
4943 """
4950 if opts.get('graph'):
4944 if opts.get('graph'):
4951 cmdutil.checkunsupportedgraphflags([], opts)
4945 cmdutil.checkunsupportedgraphflags([], opts)
4952 o, other = hg._outgoing(ui, repo, dest, opts)
4946 o, other = hg._outgoing(ui, repo, dest, opts)
4953 if not o:
4947 if not o:
4954 cmdutil.outgoinghooks(ui, repo, other, opts, o)
4948 cmdutil.outgoinghooks(ui, repo, other, opts, o)
4955 return
4949 return
4956
4950
4957 revdag = cmdutil.graphrevs(repo, o, opts)
4951 revdag = cmdutil.graphrevs(repo, o, opts)
4958 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
4952 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
4959 showparents = [ctx.node() for ctx in repo[None].parents()]
4953 showparents = [ctx.node() for ctx in repo[None].parents()]
4960 cmdutil.displaygraph(ui, revdag, displayer, showparents,
4954 cmdutil.displaygraph(ui, revdag, displayer, showparents,
4961 graphmod.asciiedges)
4955 graphmod.asciiedges)
4962 cmdutil.outgoinghooks(ui, repo, other, opts, o)
4956 cmdutil.outgoinghooks(ui, repo, other, opts, o)
4963 return 0
4957 return 0
4964
4958
4965 if opts.get('bookmarks'):
4959 if opts.get('bookmarks'):
4966 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4960 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4967 dest, branches = hg.parseurl(dest, opts.get('branch'))
4961 dest, branches = hg.parseurl(dest, opts.get('branch'))
4968 other = hg.peer(repo, opts, dest)
4962 other = hg.peer(repo, opts, dest)
4969 if 'bookmarks' not in other.listkeys('namespaces'):
4963 if 'bookmarks' not in other.listkeys('namespaces'):
4970 ui.warn(_("remote doesn't support bookmarks\n"))
4964 ui.warn(_("remote doesn't support bookmarks\n"))
4971 return 0
4965 return 0
4972 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
4966 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
4973 return bookmarks.outgoing(ui, repo, other)
4967 return bookmarks.outgoing(ui, repo, other)
4974
4968
4975 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
4969 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
4976 try:
4970 try:
4977 return hg.outgoing(ui, repo, dest, opts)
4971 return hg.outgoing(ui, repo, dest, opts)
4978 finally:
4972 finally:
4979 del repo._subtoppath
4973 del repo._subtoppath
4980
4974
4981 @command('parents',
4975 @command('parents',
4982 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
4976 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
4983 ] + templateopts,
4977 ] + templateopts,
4984 _('[-r REV] [FILE]'),
4978 _('[-r REV] [FILE]'),
4985 inferrepo=True)
4979 inferrepo=True)
4986 def parents(ui, repo, file_=None, **opts):
4980 def parents(ui, repo, file_=None, **opts):
4987 """show the parents of the working directory or revision (DEPRECATED)
4981 """show the parents of the working directory or revision (DEPRECATED)
4988
4982
4989 Print the working directory's parent revisions. If a revision is
4983 Print the working directory's parent revisions. If a revision is
4990 given via -r/--rev, the parent of that revision will be printed.
4984 given via -r/--rev, the parent of that revision will be printed.
4991 If a file argument is given, the revision in which the file was
4985 If a file argument is given, the revision in which the file was
4992 last changed (before the working directory revision or the
4986 last changed (before the working directory revision or the
4993 argument to --rev if given) is printed.
4987 argument to --rev if given) is printed.
4994
4988
4995 See :hg:`summary` and :hg:`help revsets` for related information.
4989 See :hg:`summary` and :hg:`help revsets` for related information.
4996
4990
4997 Returns 0 on success.
4991 Returns 0 on success.
4998 """
4992 """
4999
4993
5000 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
4994 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
5001
4995
5002 if file_:
4996 if file_:
5003 m = scmutil.match(ctx, (file_,), opts)
4997 m = scmutil.match(ctx, (file_,), opts)
5004 if m.anypats() or len(m.files()) != 1:
4998 if m.anypats() or len(m.files()) != 1:
5005 raise util.Abort(_('can only specify an explicit filename'))
4999 raise util.Abort(_('can only specify an explicit filename'))
5006 file_ = m.files()[0]
5000 file_ = m.files()[0]
5007 filenodes = []
5001 filenodes = []
5008 for cp in ctx.parents():
5002 for cp in ctx.parents():
5009 if not cp:
5003 if not cp:
5010 continue
5004 continue
5011 try:
5005 try:
5012 filenodes.append(cp.filenode(file_))
5006 filenodes.append(cp.filenode(file_))
5013 except error.LookupError:
5007 except error.LookupError:
5014 pass
5008 pass
5015 if not filenodes:
5009 if not filenodes:
5016 raise util.Abort(_("'%s' not found in manifest!") % file_)
5010 raise util.Abort(_("'%s' not found in manifest!") % file_)
5017 p = []
5011 p = []
5018 for fn in filenodes:
5012 for fn in filenodes:
5019 fctx = repo.filectx(file_, fileid=fn)
5013 fctx = repo.filectx(file_, fileid=fn)
5020 p.append(fctx.node())
5014 p.append(fctx.node())
5021 else:
5015 else:
5022 p = [cp.node() for cp in ctx.parents()]
5016 p = [cp.node() for cp in ctx.parents()]
5023
5017
5024 displayer = cmdutil.show_changeset(ui, repo, opts)
5018 displayer = cmdutil.show_changeset(ui, repo, opts)
5025 for n in p:
5019 for n in p:
5026 if n != nullid:
5020 if n != nullid:
5027 displayer.show(repo[n])
5021 displayer.show(repo[n])
5028 displayer.close()
5022 displayer.close()
5029
5023
5030 @command('paths', [], _('[NAME]'), optionalrepo=True)
5024 @command('paths', [], _('[NAME]'), optionalrepo=True)
5031 def paths(ui, repo, search=None):
5025 def paths(ui, repo, search=None):
5032 """show aliases for remote repositories
5026 """show aliases for remote repositories
5033
5027
5034 Show definition of symbolic path name NAME. If no name is given,
5028 Show definition of symbolic path name NAME. If no name is given,
5035 show definition of all available names.
5029 show definition of all available names.
5036
5030
5037 Option -q/--quiet suppresses all output when searching for NAME
5031 Option -q/--quiet suppresses all output when searching for NAME
5038 and shows only the path names when listing all definitions.
5032 and shows only the path names when listing all definitions.
5039
5033
5040 Path names are defined in the [paths] section of your
5034 Path names are defined in the [paths] section of your
5041 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
5035 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
5042 repository, ``.hg/hgrc`` is used, too.
5036 repository, ``.hg/hgrc`` is used, too.
5043
5037
5044 The path names ``default`` and ``default-push`` have a special
5038 The path names ``default`` and ``default-push`` have a special
5045 meaning. When performing a push or pull operation, they are used
5039 meaning. When performing a push or pull operation, they are used
5046 as fallbacks if no location is specified on the command-line.
5040 as fallbacks if no location is specified on the command-line.
5047 When ``default-push`` is set, it will be used for push and
5041 When ``default-push`` is set, it will be used for push and
5048 ``default`` will be used for pull; otherwise ``default`` is used
5042 ``default`` will be used for pull; otherwise ``default`` is used
5049 as the fallback for both. When cloning a repository, the clone
5043 as the fallback for both. When cloning a repository, the clone
5050 source is written as ``default`` in ``.hg/hgrc``. Note that
5044 source is written as ``default`` in ``.hg/hgrc``. Note that
5051 ``default`` and ``default-push`` apply to all inbound (e.g.
5045 ``default`` and ``default-push`` apply to all inbound (e.g.
5052 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
5046 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
5053 :hg:`bundle`) operations.
5047 :hg:`bundle`) operations.
5054
5048
5055 See :hg:`help urls` for more information.
5049 See :hg:`help urls` for more information.
5056
5050
5057 Returns 0 on success.
5051 Returns 0 on success.
5058 """
5052 """
5059 if search:
5053 if search:
5060 for name, path in sorted(ui.paths.iteritems()):
5054 for name, path in sorted(ui.paths.iteritems()):
5061 if name == search:
5055 if name == search:
5062 ui.status("%s\n" % util.hidepassword(path.loc))
5056 ui.status("%s\n" % util.hidepassword(path.loc))
5063 return
5057 return
5064 if not ui.quiet:
5058 if not ui.quiet:
5065 ui.warn(_("not found!\n"))
5059 ui.warn(_("not found!\n"))
5066 return 1
5060 return 1
5067 else:
5061 else:
5068 for name, path in sorted(ui.paths.iteritems()):
5062 for name, path in sorted(ui.paths.iteritems()):
5069 if ui.quiet:
5063 if ui.quiet:
5070 ui.write("%s\n" % name)
5064 ui.write("%s\n" % name)
5071 else:
5065 else:
5072 ui.write("%s = %s\n" % (name,
5066 ui.write("%s = %s\n" % (name,
5073 util.hidepassword(path.loc)))
5067 util.hidepassword(path.loc)))
5074
5068
5075 @command('phase',
5069 @command('phase',
5076 [('p', 'public', False, _('set changeset phase to public')),
5070 [('p', 'public', False, _('set changeset phase to public')),
5077 ('d', 'draft', False, _('set changeset phase to draft')),
5071 ('d', 'draft', False, _('set changeset phase to draft')),
5078 ('s', 'secret', False, _('set changeset phase to secret')),
5072 ('s', 'secret', False, _('set changeset phase to secret')),
5079 ('f', 'force', False, _('allow to move boundary backward')),
5073 ('f', 'force', False, _('allow to move boundary backward')),
5080 ('r', 'rev', [], _('target revision'), _('REV')),
5074 ('r', 'rev', [], _('target revision'), _('REV')),
5081 ],
5075 ],
5082 _('[-p|-d|-s] [-f] [-r] [REV...]'))
5076 _('[-p|-d|-s] [-f] [-r] [REV...]'))
5083 def phase(ui, repo, *revs, **opts):
5077 def phase(ui, repo, *revs, **opts):
5084 """set or show the current phase name
5078 """set or show the current phase name
5085
5079
5086 With no argument, show the phase name of the current revision(s).
5080 With no argument, show the phase name of the current revision(s).
5087
5081
5088 With one of -p/--public, -d/--draft or -s/--secret, change the
5082 With one of -p/--public, -d/--draft or -s/--secret, change the
5089 phase value of the specified revisions.
5083 phase value of the specified revisions.
5090
5084
5091 Unless -f/--force is specified, :hg:`phase` won't move changeset from a
5085 Unless -f/--force is specified, :hg:`phase` won't move changeset from a
5092 lower phase to an higher phase. Phases are ordered as follows::
5086 lower phase to an higher phase. Phases are ordered as follows::
5093
5087
5094 public < draft < secret
5088 public < draft < secret
5095
5089
5096 Returns 0 on success, 1 if some phases could not be changed.
5090 Returns 0 on success, 1 if some phases could not be changed.
5097
5091
5098 (For more information about the phases concept, see :hg:`help phases`.)
5092 (For more information about the phases concept, see :hg:`help phases`.)
5099 """
5093 """
5100 # search for a unique phase argument
5094 # search for a unique phase argument
5101 targetphase = None
5095 targetphase = None
5102 for idx, name in enumerate(phases.phasenames):
5096 for idx, name in enumerate(phases.phasenames):
5103 if opts[name]:
5097 if opts[name]:
5104 if targetphase is not None:
5098 if targetphase is not None:
5105 raise util.Abort(_('only one phase can be specified'))
5099 raise util.Abort(_('only one phase can be specified'))
5106 targetphase = idx
5100 targetphase = idx
5107
5101
5108 # look for specified revision
5102 # look for specified revision
5109 revs = list(revs)
5103 revs = list(revs)
5110 revs.extend(opts['rev'])
5104 revs.extend(opts['rev'])
5111 if not revs:
5105 if not revs:
5112 # display both parents as the second parent phase can influence
5106 # display both parents as the second parent phase can influence
5113 # the phase of a merge commit
5107 # the phase of a merge commit
5114 revs = [c.rev() for c in repo[None].parents()]
5108 revs = [c.rev() for c in repo[None].parents()]
5115
5109
5116 revs = scmutil.revrange(repo, revs)
5110 revs = scmutil.revrange(repo, revs)
5117
5111
5118 lock = None
5112 lock = None
5119 ret = 0
5113 ret = 0
5120 if targetphase is None:
5114 if targetphase is None:
5121 # display
5115 # display
5122 for r in revs:
5116 for r in revs:
5123 ctx = repo[r]
5117 ctx = repo[r]
5124 ui.write('%i: %s\n' % (ctx.rev(), ctx.phasestr()))
5118 ui.write('%i: %s\n' % (ctx.rev(), ctx.phasestr()))
5125 else:
5119 else:
5126 tr = None
5120 tr = None
5127 lock = repo.lock()
5121 lock = repo.lock()
5128 try:
5122 try:
5129 tr = repo.transaction("phase")
5123 tr = repo.transaction("phase")
5130 # set phase
5124 # set phase
5131 if not revs:
5125 if not revs:
5132 raise util.Abort(_('empty revision set'))
5126 raise util.Abort(_('empty revision set'))
5133 nodes = [repo[r].node() for r in revs]
5127 nodes = [repo[r].node() for r in revs]
5134 # moving revision from public to draft may hide them
5128 # moving revision from public to draft may hide them
5135 # We have to check result on an unfiltered repository
5129 # We have to check result on an unfiltered repository
5136 unfi = repo.unfiltered()
5130 unfi = repo.unfiltered()
5137 getphase = unfi._phasecache.phase
5131 getphase = unfi._phasecache.phase
5138 olddata = [getphase(unfi, r) for r in unfi]
5132 olddata = [getphase(unfi, r) for r in unfi]
5139 phases.advanceboundary(repo, tr, targetphase, nodes)
5133 phases.advanceboundary(repo, tr, targetphase, nodes)
5140 if opts['force']:
5134 if opts['force']:
5141 phases.retractboundary(repo, tr, targetphase, nodes)
5135 phases.retractboundary(repo, tr, targetphase, nodes)
5142 tr.close()
5136 tr.close()
5143 finally:
5137 finally:
5144 if tr is not None:
5138 if tr is not None:
5145 tr.release()
5139 tr.release()
5146 lock.release()
5140 lock.release()
5147 getphase = unfi._phasecache.phase
5141 getphase = unfi._phasecache.phase
5148 newdata = [getphase(unfi, r) for r in unfi]
5142 newdata = [getphase(unfi, r) for r in unfi]
5149 changes = sum(newdata[r] != olddata[r] for r in unfi)
5143 changes = sum(newdata[r] != olddata[r] for r in unfi)
5150 cl = unfi.changelog
5144 cl = unfi.changelog
5151 rejected = [n for n in nodes
5145 rejected = [n for n in nodes
5152 if newdata[cl.rev(n)] < targetphase]
5146 if newdata[cl.rev(n)] < targetphase]
5153 if rejected:
5147 if rejected:
5154 ui.warn(_('cannot move %i changesets to a higher '
5148 ui.warn(_('cannot move %i changesets to a higher '
5155 'phase, use --force\n') % len(rejected))
5149 'phase, use --force\n') % len(rejected))
5156 ret = 1
5150 ret = 1
5157 if changes:
5151 if changes:
5158 msg = _('phase changed for %i changesets\n') % changes
5152 msg = _('phase changed for %i changesets\n') % changes
5159 if ret:
5153 if ret:
5160 ui.status(msg)
5154 ui.status(msg)
5161 else:
5155 else:
5162 ui.note(msg)
5156 ui.note(msg)
5163 else:
5157 else:
5164 ui.warn(_('no phases changed\n'))
5158 ui.warn(_('no phases changed\n'))
5165 return ret
5159 return ret
5166
5160
5167 def postincoming(ui, repo, modheads, optupdate, checkout):
5161 def postincoming(ui, repo, modheads, optupdate, checkout):
5168 if modheads == 0:
5162 if modheads == 0:
5169 return
5163 return
5170 if optupdate:
5164 if optupdate:
5171 checkout, movemarkfrom = bookmarks.calculateupdate(ui, repo, checkout)
5165 checkout, movemarkfrom = bookmarks.calculateupdate(ui, repo, checkout)
5172 try:
5166 try:
5173 ret = hg.update(repo, checkout)
5167 ret = hg.update(repo, checkout)
5174 except util.Abort as inst:
5168 except util.Abort as inst:
5175 ui.warn(_("not updating: %s\n") % str(inst))
5169 ui.warn(_("not updating: %s\n") % str(inst))
5176 if inst.hint:
5170 if inst.hint:
5177 ui.warn(_("(%s)\n") % inst.hint)
5171 ui.warn(_("(%s)\n") % inst.hint)
5178 return 0
5172 return 0
5179 if not ret and not checkout:
5173 if not ret and not checkout:
5180 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
5174 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
5181 ui.status(_("updating bookmark %s\n") % repo._activebookmark)
5175 ui.status(_("updating bookmark %s\n") % repo._activebookmark)
5182 return ret
5176 return ret
5183 if modheads > 1:
5177 if modheads > 1:
5184 currentbranchheads = len(repo.branchheads())
5178 currentbranchheads = len(repo.branchheads())
5185 if currentbranchheads == modheads:
5179 if currentbranchheads == modheads:
5186 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
5180 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
5187 elif currentbranchheads > 1:
5181 elif currentbranchheads > 1:
5188 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to "
5182 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to "
5189 "merge)\n"))
5183 "merge)\n"))
5190 else:
5184 else:
5191 ui.status(_("(run 'hg heads' to see heads)\n"))
5185 ui.status(_("(run 'hg heads' to see heads)\n"))
5192 else:
5186 else:
5193 ui.status(_("(run 'hg update' to get a working copy)\n"))
5187 ui.status(_("(run 'hg update' to get a working copy)\n"))
5194
5188
5195 @command('^pull',
5189 @command('^pull',
5196 [('u', 'update', None,
5190 [('u', 'update', None,
5197 _('update to new branch head if changesets were pulled')),
5191 _('update to new branch head if changesets were pulled')),
5198 ('f', 'force', None, _('run even when remote repository is unrelated')),
5192 ('f', 'force', None, _('run even when remote repository is unrelated')),
5199 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
5193 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
5200 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
5194 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
5201 ('b', 'branch', [], _('a specific branch you would like to pull'),
5195 ('b', 'branch', [], _('a specific branch you would like to pull'),
5202 _('BRANCH')),
5196 _('BRANCH')),
5203 ] + remoteopts,
5197 ] + remoteopts,
5204 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
5198 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
5205 def pull(ui, repo, source="default", **opts):
5199 def pull(ui, repo, source="default", **opts):
5206 """pull changes from the specified source
5200 """pull changes from the specified source
5207
5201
5208 Pull changes from a remote repository to a local one.
5202 Pull changes from a remote repository to a local one.
5209
5203
5210 This finds all changes from the repository at the specified path
5204 This finds all changes from the repository at the specified path
5211 or URL and adds them to a local repository (the current one unless
5205 or URL and adds them to a local repository (the current one unless
5212 -R is specified). By default, this does not update the copy of the
5206 -R is specified). By default, this does not update the copy of the
5213 project in the working directory.
5207 project in the working directory.
5214
5208
5215 Use :hg:`incoming` if you want to see what would have been added
5209 Use :hg:`incoming` if you want to see what would have been added
5216 by a pull at the time you issued this command. If you then decide
5210 by a pull at the time you issued this command. If you then decide
5217 to add those changes to the repository, you should use :hg:`pull
5211 to add those changes to the repository, you should use :hg:`pull
5218 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
5212 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
5219
5213
5220 If SOURCE is omitted, the 'default' path will be used.
5214 If SOURCE is omitted, the 'default' path will be used.
5221 See :hg:`help urls` for more information.
5215 See :hg:`help urls` for more information.
5222
5216
5223 Returns 0 on success, 1 if an update had unresolved files.
5217 Returns 0 on success, 1 if an update had unresolved files.
5224 """
5218 """
5225 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
5219 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
5226 ui.status(_('pulling from %s\n') % util.hidepassword(source))
5220 ui.status(_('pulling from %s\n') % util.hidepassword(source))
5227 other = hg.peer(repo, opts, source)
5221 other = hg.peer(repo, opts, source)
5228 try:
5222 try:
5229 revs, checkout = hg.addbranchrevs(repo, other, branches,
5223 revs, checkout = hg.addbranchrevs(repo, other, branches,
5230 opts.get('rev'))
5224 opts.get('rev'))
5231
5225
5232
5226
5233 pullopargs = {}
5227 pullopargs = {}
5234 if opts.get('bookmark'):
5228 if opts.get('bookmark'):
5235 if not revs:
5229 if not revs:
5236 revs = []
5230 revs = []
5237 # The list of bookmark used here is not the one used to actually
5231 # The list of bookmark used here is not the one used to actually
5238 # update the bookmark name. This can result in the revision pulled
5232 # update the bookmark name. This can result in the revision pulled
5239 # not ending up with the name of the bookmark because of a race
5233 # not ending up with the name of the bookmark because of a race
5240 # condition on the server. (See issue 4689 for details)
5234 # condition on the server. (See issue 4689 for details)
5241 remotebookmarks = other.listkeys('bookmarks')
5235 remotebookmarks = other.listkeys('bookmarks')
5242 pullopargs['remotebookmarks'] = remotebookmarks
5236 pullopargs['remotebookmarks'] = remotebookmarks
5243 for b in opts['bookmark']:
5237 for b in opts['bookmark']:
5244 if b not in remotebookmarks:
5238 if b not in remotebookmarks:
5245 raise util.Abort(_('remote bookmark %s not found!') % b)
5239 raise util.Abort(_('remote bookmark %s not found!') % b)
5246 revs.append(remotebookmarks[b])
5240 revs.append(remotebookmarks[b])
5247
5241
5248 if revs:
5242 if revs:
5249 try:
5243 try:
5250 # When 'rev' is a bookmark name, we cannot guarantee that it
5244 # When 'rev' is a bookmark name, we cannot guarantee that it
5251 # will be updated with that name because of a race condition
5245 # will be updated with that name because of a race condition
5252 # server side. (See issue 4689 for details)
5246 # server side. (See issue 4689 for details)
5253 oldrevs = revs
5247 oldrevs = revs
5254 revs = [] # actually, nodes
5248 revs = [] # actually, nodes
5255 for r in oldrevs:
5249 for r in oldrevs:
5256 node = other.lookup(r)
5250 node = other.lookup(r)
5257 revs.append(node)
5251 revs.append(node)
5258 if r == checkout:
5252 if r == checkout:
5259 checkout = node
5253 checkout = node
5260 except error.CapabilityError:
5254 except error.CapabilityError:
5261 err = _("other repository doesn't support revision lookup, "
5255 err = _("other repository doesn't support revision lookup, "
5262 "so a rev cannot be specified.")
5256 "so a rev cannot be specified.")
5263 raise util.Abort(err)
5257 raise util.Abort(err)
5264
5258
5265 modheads = exchange.pull(repo, other, heads=revs,
5259 modheads = exchange.pull(repo, other, heads=revs,
5266 force=opts.get('force'),
5260 force=opts.get('force'),
5267 bookmarks=opts.get('bookmark', ()),
5261 bookmarks=opts.get('bookmark', ()),
5268 opargs=pullopargs).cgresult
5262 opargs=pullopargs).cgresult
5269 if checkout:
5263 if checkout:
5270 checkout = str(repo.changelog.rev(checkout))
5264 checkout = str(repo.changelog.rev(checkout))
5271 repo._subtoppath = source
5265 repo._subtoppath = source
5272 try:
5266 try:
5273 ret = postincoming(ui, repo, modheads, opts.get('update'), checkout)
5267 ret = postincoming(ui, repo, modheads, opts.get('update'), checkout)
5274
5268
5275 finally:
5269 finally:
5276 del repo._subtoppath
5270 del repo._subtoppath
5277
5271
5278 finally:
5272 finally:
5279 other.close()
5273 other.close()
5280 return ret
5274 return ret
5281
5275
5282 @command('^push',
5276 @command('^push',
5283 [('f', 'force', None, _('force push')),
5277 [('f', 'force', None, _('force push')),
5284 ('r', 'rev', [],
5278 ('r', 'rev', [],
5285 _('a changeset intended to be included in the destination'),
5279 _('a changeset intended to be included in the destination'),
5286 _('REV')),
5280 _('REV')),
5287 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
5281 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
5288 ('b', 'branch', [],
5282 ('b', 'branch', [],
5289 _('a specific branch you would like to push'), _('BRANCH')),
5283 _('a specific branch you would like to push'), _('BRANCH')),
5290 ('', 'new-branch', False, _('allow pushing a new branch')),
5284 ('', 'new-branch', False, _('allow pushing a new branch')),
5291 ] + remoteopts,
5285 ] + remoteopts,
5292 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
5286 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
5293 def push(ui, repo, dest=None, **opts):
5287 def push(ui, repo, dest=None, **opts):
5294 """push changes to the specified destination
5288 """push changes to the specified destination
5295
5289
5296 Push changesets from the local repository to the specified
5290 Push changesets from the local repository to the specified
5297 destination.
5291 destination.
5298
5292
5299 This operation is symmetrical to pull: it is identical to a pull
5293 This operation is symmetrical to pull: it is identical to a pull
5300 in the destination repository from the current one.
5294 in the destination repository from the current one.
5301
5295
5302 By default, push will not allow creation of new heads at the
5296 By default, push will not allow creation of new heads at the
5303 destination, since multiple heads would make it unclear which head
5297 destination, since multiple heads would make it unclear which head
5304 to use. In this situation, it is recommended to pull and merge
5298 to use. In this situation, it is recommended to pull and merge
5305 before pushing.
5299 before pushing.
5306
5300
5307 Use --new-branch if you want to allow push to create a new named
5301 Use --new-branch if you want to allow push to create a new named
5308 branch that is not present at the destination. This allows you to
5302 branch that is not present at the destination. This allows you to
5309 only create a new branch without forcing other changes.
5303 only create a new branch without forcing other changes.
5310
5304
5311 .. note::
5305 .. note::
5312
5306
5313 Extra care should be taken with the -f/--force option,
5307 Extra care should be taken with the -f/--force option,
5314 which will push all new heads on all branches, an action which will
5308 which will push all new heads on all branches, an action which will
5315 almost always cause confusion for collaborators.
5309 almost always cause confusion for collaborators.
5316
5310
5317 If -r/--rev is used, the specified revision and all its ancestors
5311 If -r/--rev is used, the specified revision and all its ancestors
5318 will be pushed to the remote repository.
5312 will be pushed to the remote repository.
5319
5313
5320 If -B/--bookmark is used, the specified bookmarked revision, its
5314 If -B/--bookmark is used, the specified bookmarked revision, its
5321 ancestors, and the bookmark will be pushed to the remote
5315 ancestors, and the bookmark will be pushed to the remote
5322 repository.
5316 repository.
5323
5317
5324 Please see :hg:`help urls` for important details about ``ssh://``
5318 Please see :hg:`help urls` for important details about ``ssh://``
5325 URLs. If DESTINATION is omitted, a default path will be used.
5319 URLs. If DESTINATION is omitted, a default path will be used.
5326
5320
5327 Returns 0 if push was successful, 1 if nothing to push.
5321 Returns 0 if push was successful, 1 if nothing to push.
5328 """
5322 """
5329
5323
5330 if opts.get('bookmark'):
5324 if opts.get('bookmark'):
5331 ui.setconfig('bookmarks', 'pushing', opts['bookmark'], 'push')
5325 ui.setconfig('bookmarks', 'pushing', opts['bookmark'], 'push')
5332 for b in opts['bookmark']:
5326 for b in opts['bookmark']:
5333 # translate -B options to -r so changesets get pushed
5327 # translate -B options to -r so changesets get pushed
5334 if b in repo._bookmarks:
5328 if b in repo._bookmarks:
5335 opts.setdefault('rev', []).append(b)
5329 opts.setdefault('rev', []).append(b)
5336 else:
5330 else:
5337 # if we try to push a deleted bookmark, translate it to null
5331 # if we try to push a deleted bookmark, translate it to null
5338 # this lets simultaneous -r, -b options continue working
5332 # this lets simultaneous -r, -b options continue working
5339 opts.setdefault('rev', []).append("null")
5333 opts.setdefault('rev', []).append("null")
5340
5334
5341 path = ui.paths.getpath(dest, default='default')
5335 path = ui.paths.getpath(dest, default='default')
5342 if not path:
5336 if not path:
5343 raise util.Abort(_('default repository not configured!'),
5337 raise util.Abort(_('default repository not configured!'),
5344 hint=_('see the "path" section in "hg help config"'))
5338 hint=_('see the "path" section in "hg help config"'))
5345 dest, branches = path.pushloc, (path.branch, opts.get('branch') or [])
5339 dest, branches = path.pushloc, (path.branch, opts.get('branch') or [])
5346 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
5340 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
5347 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
5341 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
5348 other = hg.peer(repo, opts, dest)
5342 other = hg.peer(repo, opts, dest)
5349
5343
5350 if revs:
5344 if revs:
5351 revs = [repo.lookup(r) for r in scmutil.revrange(repo, revs)]
5345 revs = [repo.lookup(r) for r in scmutil.revrange(repo, revs)]
5352 if not revs:
5346 if not revs:
5353 raise util.Abort(_("specified revisions evaluate to an empty set"),
5347 raise util.Abort(_("specified revisions evaluate to an empty set"),
5354 hint=_("use different revision arguments"))
5348 hint=_("use different revision arguments"))
5355
5349
5356 repo._subtoppath = dest
5350 repo._subtoppath = dest
5357 try:
5351 try:
5358 # push subrepos depth-first for coherent ordering
5352 # push subrepos depth-first for coherent ordering
5359 c = repo['']
5353 c = repo['']
5360 subs = c.substate # only repos that are committed
5354 subs = c.substate # only repos that are committed
5361 for s in sorted(subs):
5355 for s in sorted(subs):
5362 result = c.sub(s).push(opts)
5356 result = c.sub(s).push(opts)
5363 if result == 0:
5357 if result == 0:
5364 return not result
5358 return not result
5365 finally:
5359 finally:
5366 del repo._subtoppath
5360 del repo._subtoppath
5367 pushop = exchange.push(repo, other, opts.get('force'), revs=revs,
5361 pushop = exchange.push(repo, other, opts.get('force'), revs=revs,
5368 newbranch=opts.get('new_branch'),
5362 newbranch=opts.get('new_branch'),
5369 bookmarks=opts.get('bookmark', ()))
5363 bookmarks=opts.get('bookmark', ()))
5370
5364
5371 result = not pushop.cgresult
5365 result = not pushop.cgresult
5372
5366
5373 if pushop.bkresult is not None:
5367 if pushop.bkresult is not None:
5374 if pushop.bkresult == 2:
5368 if pushop.bkresult == 2:
5375 result = 2
5369 result = 2
5376 elif not result and pushop.bkresult:
5370 elif not result and pushop.bkresult:
5377 result = 2
5371 result = 2
5378
5372
5379 return result
5373 return result
5380
5374
5381 @command('recover', [])
5375 @command('recover', [])
5382 def recover(ui, repo):
5376 def recover(ui, repo):
5383 """roll back an interrupted transaction
5377 """roll back an interrupted transaction
5384
5378
5385 Recover from an interrupted commit or pull.
5379 Recover from an interrupted commit or pull.
5386
5380
5387 This command tries to fix the repository status after an
5381 This command tries to fix the repository status after an
5388 interrupted operation. It should only be necessary when Mercurial
5382 interrupted operation. It should only be necessary when Mercurial
5389 suggests it.
5383 suggests it.
5390
5384
5391 Returns 0 if successful, 1 if nothing to recover or verify fails.
5385 Returns 0 if successful, 1 if nothing to recover or verify fails.
5392 """
5386 """
5393 if repo.recover():
5387 if repo.recover():
5394 return hg.verify(repo)
5388 return hg.verify(repo)
5395 return 1
5389 return 1
5396
5390
5397 @command('^remove|rm',
5391 @command('^remove|rm',
5398 [('A', 'after', None, _('record delete for missing files')),
5392 [('A', 'after', None, _('record delete for missing files')),
5399 ('f', 'force', None,
5393 ('f', 'force', None,
5400 _('remove (and delete) file even if added or modified')),
5394 _('remove (and delete) file even if added or modified')),
5401 ] + subrepoopts + walkopts,
5395 ] + subrepoopts + walkopts,
5402 _('[OPTION]... FILE...'),
5396 _('[OPTION]... FILE...'),
5403 inferrepo=True)
5397 inferrepo=True)
5404 def remove(ui, repo, *pats, **opts):
5398 def remove(ui, repo, *pats, **opts):
5405 """remove the specified files on the next commit
5399 """remove the specified files on the next commit
5406
5400
5407 Schedule the indicated files for removal from the current branch.
5401 Schedule the indicated files for removal from the current branch.
5408
5402
5409 This command schedules the files to be removed at the next commit.
5403 This command schedules the files to be removed at the next commit.
5410 To undo a remove before that, see :hg:`revert`. To undo added
5404 To undo a remove before that, see :hg:`revert`. To undo added
5411 files, see :hg:`forget`.
5405 files, see :hg:`forget`.
5412
5406
5413 .. container:: verbose
5407 .. container:: verbose
5414
5408
5415 -A/--after can be used to remove only files that have already
5409 -A/--after can be used to remove only files that have already
5416 been deleted, -f/--force can be used to force deletion, and -Af
5410 been deleted, -f/--force can be used to force deletion, and -Af
5417 can be used to remove files from the next revision without
5411 can be used to remove files from the next revision without
5418 deleting them from the working directory.
5412 deleting them from the working directory.
5419
5413
5420 The following table details the behavior of remove for different
5414 The following table details the behavior of remove for different
5421 file states (columns) and option combinations (rows). The file
5415 file states (columns) and option combinations (rows). The file
5422 states are Added [A], Clean [C], Modified [M] and Missing [!]
5416 states are Added [A], Clean [C], Modified [M] and Missing [!]
5423 (as reported by :hg:`status`). The actions are Warn, Remove
5417 (as reported by :hg:`status`). The actions are Warn, Remove
5424 (from branch) and Delete (from disk):
5418 (from branch) and Delete (from disk):
5425
5419
5426 ========= == == == ==
5420 ========= == == == ==
5427 opt/state A C M !
5421 opt/state A C M !
5428 ========= == == == ==
5422 ========= == == == ==
5429 none W RD W R
5423 none W RD W R
5430 -f R RD RD R
5424 -f R RD RD R
5431 -A W W W R
5425 -A W W W R
5432 -Af R R R R
5426 -Af R R R R
5433 ========= == == == ==
5427 ========= == == == ==
5434
5428
5435 Note that remove never deletes files in Added [A] state from the
5429 Note that remove never deletes files in Added [A] state from the
5436 working directory, not even if option --force is specified.
5430 working directory, not even if option --force is specified.
5437
5431
5438 Returns 0 on success, 1 if any warnings encountered.
5432 Returns 0 on success, 1 if any warnings encountered.
5439 """
5433 """
5440
5434
5441 after, force = opts.get('after'), opts.get('force')
5435 after, force = opts.get('after'), opts.get('force')
5442 if not pats and not after:
5436 if not pats and not after:
5443 raise util.Abort(_('no files specified'))
5437 raise util.Abort(_('no files specified'))
5444
5438
5445 m = scmutil.match(repo[None], pats, opts)
5439 m = scmutil.match(repo[None], pats, opts)
5446 subrepos = opts.get('subrepos')
5440 subrepos = opts.get('subrepos')
5447 return cmdutil.remove(ui, repo, m, "", after, force, subrepos)
5441 return cmdutil.remove(ui, repo, m, "", after, force, subrepos)
5448
5442
5449 @command('rename|move|mv',
5443 @command('rename|move|mv',
5450 [('A', 'after', None, _('record a rename that has already occurred')),
5444 [('A', 'after', None, _('record a rename that has already occurred')),
5451 ('f', 'force', None, _('forcibly copy over an existing managed file')),
5445 ('f', 'force', None, _('forcibly copy over an existing managed file')),
5452 ] + walkopts + dryrunopts,
5446 ] + walkopts + dryrunopts,
5453 _('[OPTION]... SOURCE... DEST'))
5447 _('[OPTION]... SOURCE... DEST'))
5454 def rename(ui, repo, *pats, **opts):
5448 def rename(ui, repo, *pats, **opts):
5455 """rename files; equivalent of copy + remove
5449 """rename files; equivalent of copy + remove
5456
5450
5457 Mark dest as copies of sources; mark sources for deletion. If dest
5451 Mark dest as copies of sources; mark sources for deletion. If dest
5458 is a directory, copies are put in that directory. If dest is a
5452 is a directory, copies are put in that directory. If dest is a
5459 file, there can only be one source.
5453 file, there can only be one source.
5460
5454
5461 By default, this command copies the contents of files as they
5455 By default, this command copies the contents of files as they
5462 exist in the working directory. If invoked with -A/--after, the
5456 exist in the working directory. If invoked with -A/--after, the
5463 operation is recorded, but no copying is performed.
5457 operation is recorded, but no copying is performed.
5464
5458
5465 This command takes effect at the next commit. To undo a rename
5459 This command takes effect at the next commit. To undo a rename
5466 before that, see :hg:`revert`.
5460 before that, see :hg:`revert`.
5467
5461
5468 Returns 0 on success, 1 if errors are encountered.
5462 Returns 0 on success, 1 if errors are encountered.
5469 """
5463 """
5470 wlock = repo.wlock(False)
5464 wlock = repo.wlock(False)
5471 try:
5465 try:
5472 return cmdutil.copy(ui, repo, pats, opts, rename=True)
5466 return cmdutil.copy(ui, repo, pats, opts, rename=True)
5473 finally:
5467 finally:
5474 wlock.release()
5468 wlock.release()
5475
5469
5476 @command('resolve',
5470 @command('resolve',
5477 [('a', 'all', None, _('select all unresolved files')),
5471 [('a', 'all', None, _('select all unresolved files')),
5478 ('l', 'list', None, _('list state of files needing merge')),
5472 ('l', 'list', None, _('list state of files needing merge')),
5479 ('m', 'mark', None, _('mark files as resolved')),
5473 ('m', 'mark', None, _('mark files as resolved')),
5480 ('u', 'unmark', None, _('mark files as unresolved')),
5474 ('u', 'unmark', None, _('mark files as unresolved')),
5481 ('n', 'no-status', None, _('hide status prefix'))]
5475 ('n', 'no-status', None, _('hide status prefix'))]
5482 + mergetoolopts + walkopts + formatteropts,
5476 + mergetoolopts + walkopts + formatteropts,
5483 _('[OPTION]... [FILE]...'),
5477 _('[OPTION]... [FILE]...'),
5484 inferrepo=True)
5478 inferrepo=True)
5485 def resolve(ui, repo, *pats, **opts):
5479 def resolve(ui, repo, *pats, **opts):
5486 """redo merges or set/view the merge status of files
5480 """redo merges or set/view the merge status of files
5487
5481
5488 Merges with unresolved conflicts are often the result of
5482 Merges with unresolved conflicts are often the result of
5489 non-interactive merging using the ``internal:merge`` configuration
5483 non-interactive merging using the ``internal:merge`` configuration
5490 setting, or a command-line merge tool like ``diff3``. The resolve
5484 setting, or a command-line merge tool like ``diff3``. The resolve
5491 command is used to manage the files involved in a merge, after
5485 command is used to manage the files involved in a merge, after
5492 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
5486 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
5493 working directory must have two parents). See :hg:`help
5487 working directory must have two parents). See :hg:`help
5494 merge-tools` for information on configuring merge tools.
5488 merge-tools` for information on configuring merge tools.
5495
5489
5496 The resolve command can be used in the following ways:
5490 The resolve command can be used in the following ways:
5497
5491
5498 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
5492 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
5499 files, discarding any previous merge attempts. Re-merging is not
5493 files, discarding any previous merge attempts. Re-merging is not
5500 performed for files already marked as resolved. Use ``--all/-a``
5494 performed for files already marked as resolved. Use ``--all/-a``
5501 to select all unresolved files. ``--tool`` can be used to specify
5495 to select all unresolved files. ``--tool`` can be used to specify
5502 the merge tool used for the given files. It overrides the HGMERGE
5496 the merge tool used for the given files. It overrides the HGMERGE
5503 environment variable and your configuration files. Previous file
5497 environment variable and your configuration files. Previous file
5504 contents are saved with a ``.orig`` suffix.
5498 contents are saved with a ``.orig`` suffix.
5505
5499
5506 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
5500 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
5507 (e.g. after having manually fixed-up the files). The default is
5501 (e.g. after having manually fixed-up the files). The default is
5508 to mark all unresolved files.
5502 to mark all unresolved files.
5509
5503
5510 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
5504 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
5511 default is to mark all resolved files.
5505 default is to mark all resolved files.
5512
5506
5513 - :hg:`resolve -l`: list files which had or still have conflicts.
5507 - :hg:`resolve -l`: list files which had or still have conflicts.
5514 In the printed list, ``U`` = unresolved and ``R`` = resolved.
5508 In the printed list, ``U`` = unresolved and ``R`` = resolved.
5515
5509
5516 Note that Mercurial will not let you commit files with unresolved
5510 Note that Mercurial will not let you commit files with unresolved
5517 merge conflicts. You must use :hg:`resolve -m ...` before you can
5511 merge conflicts. You must use :hg:`resolve -m ...` before you can
5518 commit after a conflicting merge.
5512 commit after a conflicting merge.
5519
5513
5520 Returns 0 on success, 1 if any files fail a resolve attempt.
5514 Returns 0 on success, 1 if any files fail a resolve attempt.
5521 """
5515 """
5522
5516
5523 all, mark, unmark, show, nostatus = \
5517 all, mark, unmark, show, nostatus = \
5524 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
5518 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
5525
5519
5526 if (show and (mark or unmark)) or (mark and unmark):
5520 if (show and (mark or unmark)) or (mark and unmark):
5527 raise util.Abort(_("too many options specified"))
5521 raise util.Abort(_("too many options specified"))
5528 if pats and all:
5522 if pats and all:
5529 raise util.Abort(_("can't specify --all and patterns"))
5523 raise util.Abort(_("can't specify --all and patterns"))
5530 if not (all or pats or show or mark or unmark):
5524 if not (all or pats or show or mark or unmark):
5531 raise util.Abort(_('no files or directories specified'),
5525 raise util.Abort(_('no files or directories specified'),
5532 hint=('use --all to re-merge all unresolved files'))
5526 hint=('use --all to re-merge all unresolved files'))
5533
5527
5534 if show:
5528 if show:
5535 fm = ui.formatter('resolve', opts)
5529 fm = ui.formatter('resolve', opts)
5536 ms = mergemod.mergestate(repo)
5530 ms = mergemod.mergestate(repo)
5537 m = scmutil.match(repo[None], pats, opts)
5531 m = scmutil.match(repo[None], pats, opts)
5538 for f in ms:
5532 for f in ms:
5539 if not m(f):
5533 if not m(f):
5540 continue
5534 continue
5541 l = 'resolve.' + {'u': 'unresolved', 'r': 'resolved'}[ms[f]]
5535 l = 'resolve.' + {'u': 'unresolved', 'r': 'resolved'}[ms[f]]
5542 fm.startitem()
5536 fm.startitem()
5543 fm.condwrite(not nostatus, 'status', '%s ', ms[f].upper(), label=l)
5537 fm.condwrite(not nostatus, 'status', '%s ', ms[f].upper(), label=l)
5544 fm.write('path', '%s\n', f, label=l)
5538 fm.write('path', '%s\n', f, label=l)
5545 fm.end()
5539 fm.end()
5546 return 0
5540 return 0
5547
5541
5548 wlock = repo.wlock()
5542 wlock = repo.wlock()
5549 try:
5543 try:
5550 ms = mergemod.mergestate(repo)
5544 ms = mergemod.mergestate(repo)
5551
5545
5552 if not (ms.active() or repo.dirstate.p2() != nullid):
5546 if not (ms.active() or repo.dirstate.p2() != nullid):
5553 raise util.Abort(
5547 raise util.Abort(
5554 _('resolve command not applicable when not merging'))
5548 _('resolve command not applicable when not merging'))
5555
5549
5556 m = scmutil.match(repo[None], pats, opts)
5550 m = scmutil.match(repo[None], pats, opts)
5557 ret = 0
5551 ret = 0
5558 didwork = False
5552 didwork = False
5559
5553
5560 for f in ms:
5554 for f in ms:
5561 if not m(f):
5555 if not m(f):
5562 continue
5556 continue
5563
5557
5564 didwork = True
5558 didwork = True
5565
5559
5566 if mark:
5560 if mark:
5567 ms.mark(f, "r")
5561 ms.mark(f, "r")
5568 elif unmark:
5562 elif unmark:
5569 ms.mark(f, "u")
5563 ms.mark(f, "u")
5570 else:
5564 else:
5571 wctx = repo[None]
5565 wctx = repo[None]
5572
5566
5573 # backup pre-resolve (merge uses .orig for its own purposes)
5567 # backup pre-resolve (merge uses .orig for its own purposes)
5574 a = repo.wjoin(f)
5568 a = repo.wjoin(f)
5575 util.copyfile(a, a + ".resolve")
5569 util.copyfile(a, a + ".resolve")
5576
5570
5577 try:
5571 try:
5578 # resolve file
5572 # resolve file
5579 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
5573 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
5580 'resolve')
5574 'resolve')
5581 if ms.resolve(f, wctx):
5575 if ms.resolve(f, wctx):
5582 ret = 1
5576 ret = 1
5583 finally:
5577 finally:
5584 ui.setconfig('ui', 'forcemerge', '', 'resolve')
5578 ui.setconfig('ui', 'forcemerge', '', 'resolve')
5585 ms.commit()
5579 ms.commit()
5586
5580
5587 # replace filemerge's .orig file with our resolve file
5581 # replace filemerge's .orig file with our resolve file
5588 util.rename(a + ".resolve", a + ".orig")
5582 util.rename(a + ".resolve", a + ".orig")
5589
5583
5590 ms.commit()
5584 ms.commit()
5591
5585
5592 if not didwork and pats:
5586 if not didwork and pats:
5593 ui.warn(_("arguments do not match paths that need resolving\n"))
5587 ui.warn(_("arguments do not match paths that need resolving\n"))
5594
5588
5595 finally:
5589 finally:
5596 wlock.release()
5590 wlock.release()
5597
5591
5598 # Nudge users into finishing an unfinished operation
5592 # Nudge users into finishing an unfinished operation
5599 if not list(ms.unresolved()):
5593 if not list(ms.unresolved()):
5600 ui.status(_('(no more unresolved files)\n'))
5594 ui.status(_('(no more unresolved files)\n'))
5601
5595
5602 return ret
5596 return ret
5603
5597
5604 @command('revert',
5598 @command('revert',
5605 [('a', 'all', None, _('revert all changes when no arguments given')),
5599 [('a', 'all', None, _('revert all changes when no arguments given')),
5606 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5600 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5607 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
5601 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
5608 ('C', 'no-backup', None, _('do not save backup copies of files')),
5602 ('C', 'no-backup', None, _('do not save backup copies of files')),
5609 ('i', 'interactive', None,
5603 ('i', 'interactive', None,
5610 _('interactively select the changes (EXPERIMENTAL)')),
5604 _('interactively select the changes (EXPERIMENTAL)')),
5611 ] + walkopts + dryrunopts,
5605 ] + walkopts + dryrunopts,
5612 _('[OPTION]... [-r REV] [NAME]...'))
5606 _('[OPTION]... [-r REV] [NAME]...'))
5613 def revert(ui, repo, *pats, **opts):
5607 def revert(ui, repo, *pats, **opts):
5614 """restore files to their checkout state
5608 """restore files to their checkout state
5615
5609
5616 .. note::
5610 .. note::
5617
5611
5618 To check out earlier revisions, you should use :hg:`update REV`.
5612 To check out earlier revisions, you should use :hg:`update REV`.
5619 To cancel an uncommitted merge (and lose your changes),
5613 To cancel an uncommitted merge (and lose your changes),
5620 use :hg:`update --clean .`.
5614 use :hg:`update --clean .`.
5621
5615
5622 With no revision specified, revert the specified files or directories
5616 With no revision specified, revert the specified files or directories
5623 to the contents they had in the parent of the working directory.
5617 to the contents they had in the parent of the working directory.
5624 This restores the contents of files to an unmodified
5618 This restores the contents of files to an unmodified
5625 state and unschedules adds, removes, copies, and renames. If the
5619 state and unschedules adds, removes, copies, and renames. If the
5626 working directory has two parents, you must explicitly specify a
5620 working directory has two parents, you must explicitly specify a
5627 revision.
5621 revision.
5628
5622
5629 Using the -r/--rev or -d/--date options, revert the given files or
5623 Using the -r/--rev or -d/--date options, revert the given files or
5630 directories to their states as of a specific revision. Because
5624 directories to their states as of a specific revision. Because
5631 revert does not change the working directory parents, this will
5625 revert does not change the working directory parents, this will
5632 cause these files to appear modified. This can be helpful to "back
5626 cause these files to appear modified. This can be helpful to "back
5633 out" some or all of an earlier change. See :hg:`backout` for a
5627 out" some or all of an earlier change. See :hg:`backout` for a
5634 related method.
5628 related method.
5635
5629
5636 Modified files are saved with a .orig suffix before reverting.
5630 Modified files are saved with a .orig suffix before reverting.
5637 To disable these backups, use --no-backup.
5631 To disable these backups, use --no-backup.
5638
5632
5639 See :hg:`help dates` for a list of formats valid for -d/--date.
5633 See :hg:`help dates` for a list of formats valid for -d/--date.
5640
5634
5641 See :hg:`help backout` for a way to reverse the effect of an
5635 See :hg:`help backout` for a way to reverse the effect of an
5642 earlier changeset.
5636 earlier changeset.
5643
5637
5644 Returns 0 on success.
5638 Returns 0 on success.
5645 """
5639 """
5646
5640
5647 if opts.get("date"):
5641 if opts.get("date"):
5648 if opts.get("rev"):
5642 if opts.get("rev"):
5649 raise util.Abort(_("you can't specify a revision and a date"))
5643 raise util.Abort(_("you can't specify a revision and a date"))
5650 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
5644 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
5651
5645
5652 parent, p2 = repo.dirstate.parents()
5646 parent, p2 = repo.dirstate.parents()
5653 if not opts.get('rev') and p2 != nullid:
5647 if not opts.get('rev') and p2 != nullid:
5654 # revert after merge is a trap for new users (issue2915)
5648 # revert after merge is a trap for new users (issue2915)
5655 raise util.Abort(_('uncommitted merge with no revision specified'),
5649 raise util.Abort(_('uncommitted merge with no revision specified'),
5656 hint=_('use "hg update" or see "hg help revert"'))
5650 hint=_('use "hg update" or see "hg help revert"'))
5657
5651
5658 ctx = scmutil.revsingle(repo, opts.get('rev'))
5652 ctx = scmutil.revsingle(repo, opts.get('rev'))
5659
5653
5660 if (not (pats or opts.get('include') or opts.get('exclude') or
5654 if (not (pats or opts.get('include') or opts.get('exclude') or
5661 opts.get('all') or opts.get('interactive'))):
5655 opts.get('all') or opts.get('interactive'))):
5662 msg = _("no files or directories specified")
5656 msg = _("no files or directories specified")
5663 if p2 != nullid:
5657 if p2 != nullid:
5664 hint = _("uncommitted merge, use --all to discard all changes,"
5658 hint = _("uncommitted merge, use --all to discard all changes,"
5665 " or 'hg update -C .' to abort the merge")
5659 " or 'hg update -C .' to abort the merge")
5666 raise util.Abort(msg, hint=hint)
5660 raise util.Abort(msg, hint=hint)
5667 dirty = any(repo.status())
5661 dirty = any(repo.status())
5668 node = ctx.node()
5662 node = ctx.node()
5669 if node != parent:
5663 if node != parent:
5670 if dirty:
5664 if dirty:
5671 hint = _("uncommitted changes, use --all to discard all"
5665 hint = _("uncommitted changes, use --all to discard all"
5672 " changes, or 'hg update %s' to update") % ctx.rev()
5666 " changes, or 'hg update %s' to update") % ctx.rev()
5673 else:
5667 else:
5674 hint = _("use --all to revert all files,"
5668 hint = _("use --all to revert all files,"
5675 " or 'hg update %s' to update") % ctx.rev()
5669 " or 'hg update %s' to update") % ctx.rev()
5676 elif dirty:
5670 elif dirty:
5677 hint = _("uncommitted changes, use --all to discard all changes")
5671 hint = _("uncommitted changes, use --all to discard all changes")
5678 else:
5672 else:
5679 hint = _("use --all to revert all files")
5673 hint = _("use --all to revert all files")
5680 raise util.Abort(msg, hint=hint)
5674 raise util.Abort(msg, hint=hint)
5681
5675
5682 return cmdutil.revert(ui, repo, ctx, (parent, p2), *pats, **opts)
5676 return cmdutil.revert(ui, repo, ctx, (parent, p2), *pats, **opts)
5683
5677
5684 @command('rollback', dryrunopts +
5678 @command('rollback', dryrunopts +
5685 [('f', 'force', False, _('ignore safety measures'))])
5679 [('f', 'force', False, _('ignore safety measures'))])
5686 def rollback(ui, repo, **opts):
5680 def rollback(ui, repo, **opts):
5687 """roll back the last transaction (DANGEROUS) (DEPRECATED)
5681 """roll back the last transaction (DANGEROUS) (DEPRECATED)
5688
5682
5689 Please use :hg:`commit --amend` instead of rollback to correct
5683 Please use :hg:`commit --amend` instead of rollback to correct
5690 mistakes in the last commit.
5684 mistakes in the last commit.
5691
5685
5692 This command should be used with care. There is only one level of
5686 This command should be used with care. There is only one level of
5693 rollback, and there is no way to undo a rollback. It will also
5687 rollback, and there is no way to undo a rollback. It will also
5694 restore the dirstate at the time of the last transaction, losing
5688 restore the dirstate at the time of the last transaction, losing
5695 any dirstate changes since that time. This command does not alter
5689 any dirstate changes since that time. This command does not alter
5696 the working directory.
5690 the working directory.
5697
5691
5698 Transactions are used to encapsulate the effects of all commands
5692 Transactions are used to encapsulate the effects of all commands
5699 that create new changesets or propagate existing changesets into a
5693 that create new changesets or propagate existing changesets into a
5700 repository.
5694 repository.
5701
5695
5702 .. container:: verbose
5696 .. container:: verbose
5703
5697
5704 For example, the following commands are transactional, and their
5698 For example, the following commands are transactional, and their
5705 effects can be rolled back:
5699 effects can be rolled back:
5706
5700
5707 - commit
5701 - commit
5708 - import
5702 - import
5709 - pull
5703 - pull
5710 - push (with this repository as the destination)
5704 - push (with this repository as the destination)
5711 - unbundle
5705 - unbundle
5712
5706
5713 To avoid permanent data loss, rollback will refuse to rollback a
5707 To avoid permanent data loss, rollback will refuse to rollback a
5714 commit transaction if it isn't checked out. Use --force to
5708 commit transaction if it isn't checked out. Use --force to
5715 override this protection.
5709 override this protection.
5716
5710
5717 This command is not intended for use on public repositories. Once
5711 This command is not intended for use on public repositories. Once
5718 changes are visible for pull by other users, rolling a transaction
5712 changes are visible for pull by other users, rolling a transaction
5719 back locally is ineffective (someone else may already have pulled
5713 back locally is ineffective (someone else may already have pulled
5720 the changes). Furthermore, a race is possible with readers of the
5714 the changes). Furthermore, a race is possible with readers of the
5721 repository; for example an in-progress pull from the repository
5715 repository; for example an in-progress pull from the repository
5722 may fail if a rollback is performed.
5716 may fail if a rollback is performed.
5723
5717
5724 Returns 0 on success, 1 if no rollback data is available.
5718 Returns 0 on success, 1 if no rollback data is available.
5725 """
5719 """
5726 return repo.rollback(dryrun=opts.get('dry_run'),
5720 return repo.rollback(dryrun=opts.get('dry_run'),
5727 force=opts.get('force'))
5721 force=opts.get('force'))
5728
5722
5729 @command('root', [])
5723 @command('root', [])
5730 def root(ui, repo):
5724 def root(ui, repo):
5731 """print the root (top) of the current working directory
5725 """print the root (top) of the current working directory
5732
5726
5733 Print the root directory of the current repository.
5727 Print the root directory of the current repository.
5734
5728
5735 Returns 0 on success.
5729 Returns 0 on success.
5736 """
5730 """
5737 ui.write(repo.root + "\n")
5731 ui.write(repo.root + "\n")
5738
5732
5739 @command('^serve',
5733 @command('^serve',
5740 [('A', 'accesslog', '', _('name of access log file to write to'),
5734 [('A', 'accesslog', '', _('name of access log file to write to'),
5741 _('FILE')),
5735 _('FILE')),
5742 ('d', 'daemon', None, _('run server in background')),
5736 ('d', 'daemon', None, _('run server in background')),
5743 ('', 'daemon-pipefds', '', _('used internally by daemon mode'), _('FILE')),
5737 ('', 'daemon-pipefds', '', _('used internally by daemon mode'), _('FILE')),
5744 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
5738 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
5745 # use string type, then we can check if something was passed
5739 # use string type, then we can check if something was passed
5746 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
5740 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
5747 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
5741 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
5748 _('ADDR')),
5742 _('ADDR')),
5749 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
5743 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
5750 _('PREFIX')),
5744 _('PREFIX')),
5751 ('n', 'name', '',
5745 ('n', 'name', '',
5752 _('name to show in web pages (default: working directory)'), _('NAME')),
5746 _('name to show in web pages (default: working directory)'), _('NAME')),
5753 ('', 'web-conf', '',
5747 ('', 'web-conf', '',
5754 _('name of the hgweb config file (see "hg help hgweb")'), _('FILE')),
5748 _('name of the hgweb config file (see "hg help hgweb")'), _('FILE')),
5755 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
5749 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
5756 _('FILE')),
5750 _('FILE')),
5757 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
5751 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
5758 ('', 'stdio', None, _('for remote clients')),
5752 ('', 'stdio', None, _('for remote clients')),
5759 ('', 'cmdserver', '', _('for remote clients'), _('MODE')),
5753 ('', 'cmdserver', '', _('for remote clients'), _('MODE')),
5760 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
5754 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
5761 ('', 'style', '', _('template style to use'), _('STYLE')),
5755 ('', 'style', '', _('template style to use'), _('STYLE')),
5762 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
5756 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
5763 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))],
5757 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))],
5764 _('[OPTION]...'),
5758 _('[OPTION]...'),
5765 optionalrepo=True)
5759 optionalrepo=True)
5766 def serve(ui, repo, **opts):
5760 def serve(ui, repo, **opts):
5767 """start stand-alone webserver
5761 """start stand-alone webserver
5768
5762
5769 Start a local HTTP repository browser and pull server. You can use
5763 Start a local HTTP repository browser and pull server. You can use
5770 this for ad-hoc sharing and browsing of repositories. It is
5764 this for ad-hoc sharing and browsing of repositories. It is
5771 recommended to use a real web server to serve a repository for
5765 recommended to use a real web server to serve a repository for
5772 longer periods of time.
5766 longer periods of time.
5773
5767
5774 Please note that the server does not implement access control.
5768 Please note that the server does not implement access control.
5775 This means that, by default, anybody can read from the server and
5769 This means that, by default, anybody can read from the server and
5776 nobody can write to it by default. Set the ``web.allow_push``
5770 nobody can write to it by default. Set the ``web.allow_push``
5777 option to ``*`` to allow everybody to push to the server. You
5771 option to ``*`` to allow everybody to push to the server. You
5778 should use a real web server if you need to authenticate users.
5772 should use a real web server if you need to authenticate users.
5779
5773
5780 By default, the server logs accesses to stdout and errors to
5774 By default, the server logs accesses to stdout and errors to
5781 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
5775 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
5782 files.
5776 files.
5783
5777
5784 To have the server choose a free port number to listen on, specify
5778 To have the server choose a free port number to listen on, specify
5785 a port number of 0; in this case, the server will print the port
5779 a port number of 0; in this case, the server will print the port
5786 number it uses.
5780 number it uses.
5787
5781
5788 Returns 0 on success.
5782 Returns 0 on success.
5789 """
5783 """
5790
5784
5791 if opts["stdio"] and opts["cmdserver"]:
5785 if opts["stdio"] and opts["cmdserver"]:
5792 raise util.Abort(_("cannot use --stdio with --cmdserver"))
5786 raise util.Abort(_("cannot use --stdio with --cmdserver"))
5793
5787
5794 if opts["stdio"]:
5788 if opts["stdio"]:
5795 if repo is None:
5789 if repo is None:
5796 raise error.RepoError(_("there is no Mercurial repository here"
5790 raise error.RepoError(_("there is no Mercurial repository here"
5797 " (.hg not found)"))
5791 " (.hg not found)"))
5798 s = sshserver.sshserver(ui, repo)
5792 s = sshserver.sshserver(ui, repo)
5799 s.serve_forever()
5793 s.serve_forever()
5800
5794
5801 if opts["cmdserver"]:
5795 if opts["cmdserver"]:
5802 import commandserver
5796 import commandserver
5803 service = commandserver.createservice(ui, repo, opts)
5797 service = commandserver.createservice(ui, repo, opts)
5804 return cmdutil.service(opts, initfn=service.init, runfn=service.run)
5798 return cmdutil.service(opts, initfn=service.init, runfn=service.run)
5805
5799
5806 # this way we can check if something was given in the command-line
5800 # this way we can check if something was given in the command-line
5807 if opts.get('port'):
5801 if opts.get('port'):
5808 opts['port'] = util.getport(opts.get('port'))
5802 opts['port'] = util.getport(opts.get('port'))
5809
5803
5810 if repo:
5804 if repo:
5811 baseui = repo.baseui
5805 baseui = repo.baseui
5812 else:
5806 else:
5813 baseui = ui
5807 baseui = ui
5814 optlist = ("name templates style address port prefix ipv6"
5808 optlist = ("name templates style address port prefix ipv6"
5815 " accesslog errorlog certificate encoding")
5809 " accesslog errorlog certificate encoding")
5816 for o in optlist.split():
5810 for o in optlist.split():
5817 val = opts.get(o, '')
5811 val = opts.get(o, '')
5818 if val in (None, ''): # should check against default options instead
5812 if val in (None, ''): # should check against default options instead
5819 continue
5813 continue
5820 baseui.setconfig("web", o, val, 'serve')
5814 baseui.setconfig("web", o, val, 'serve')
5821 if repo and repo.ui != baseui:
5815 if repo and repo.ui != baseui:
5822 repo.ui.setconfig("web", o, val, 'serve')
5816 repo.ui.setconfig("web", o, val, 'serve')
5823
5817
5824 o = opts.get('web_conf') or opts.get('webdir_conf')
5818 o = opts.get('web_conf') or opts.get('webdir_conf')
5825 if not o:
5819 if not o:
5826 if not repo:
5820 if not repo:
5827 raise error.RepoError(_("there is no Mercurial repository"
5821 raise error.RepoError(_("there is no Mercurial repository"
5828 " here (.hg not found)"))
5822 " here (.hg not found)"))
5829 o = repo
5823 o = repo
5830
5824
5831 app = hgweb.hgweb(o, baseui=baseui)
5825 app = hgweb.hgweb(o, baseui=baseui)
5832 service = httpservice(ui, app, opts)
5826 service = httpservice(ui, app, opts)
5833 cmdutil.service(opts, initfn=service.init, runfn=service.run)
5827 cmdutil.service(opts, initfn=service.init, runfn=service.run)
5834
5828
5835 class httpservice(object):
5829 class httpservice(object):
5836 def __init__(self, ui, app, opts):
5830 def __init__(self, ui, app, opts):
5837 self.ui = ui
5831 self.ui = ui
5838 self.app = app
5832 self.app = app
5839 self.opts = opts
5833 self.opts = opts
5840
5834
5841 def init(self):
5835 def init(self):
5842 util.setsignalhandler()
5836 util.setsignalhandler()
5843 self.httpd = hgweb_server.create_server(self.ui, self.app)
5837 self.httpd = hgweb_server.create_server(self.ui, self.app)
5844
5838
5845 if self.opts['port'] and not self.ui.verbose:
5839 if self.opts['port'] and not self.ui.verbose:
5846 return
5840 return
5847
5841
5848 if self.httpd.prefix:
5842 if self.httpd.prefix:
5849 prefix = self.httpd.prefix.strip('/') + '/'
5843 prefix = self.httpd.prefix.strip('/') + '/'
5850 else:
5844 else:
5851 prefix = ''
5845 prefix = ''
5852
5846
5853 port = ':%d' % self.httpd.port
5847 port = ':%d' % self.httpd.port
5854 if port == ':80':
5848 if port == ':80':
5855 port = ''
5849 port = ''
5856
5850
5857 bindaddr = self.httpd.addr
5851 bindaddr = self.httpd.addr
5858 if bindaddr == '0.0.0.0':
5852 if bindaddr == '0.0.0.0':
5859 bindaddr = '*'
5853 bindaddr = '*'
5860 elif ':' in bindaddr: # IPv6
5854 elif ':' in bindaddr: # IPv6
5861 bindaddr = '[%s]' % bindaddr
5855 bindaddr = '[%s]' % bindaddr
5862
5856
5863 fqaddr = self.httpd.fqaddr
5857 fqaddr = self.httpd.fqaddr
5864 if ':' in fqaddr:
5858 if ':' in fqaddr:
5865 fqaddr = '[%s]' % fqaddr
5859 fqaddr = '[%s]' % fqaddr
5866 if self.opts['port']:
5860 if self.opts['port']:
5867 write = self.ui.status
5861 write = self.ui.status
5868 else:
5862 else:
5869 write = self.ui.write
5863 write = self.ui.write
5870 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
5864 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
5871 (fqaddr, port, prefix, bindaddr, self.httpd.port))
5865 (fqaddr, port, prefix, bindaddr, self.httpd.port))
5872 self.ui.flush() # avoid buffering of status message
5866 self.ui.flush() # avoid buffering of status message
5873
5867
5874 def run(self):
5868 def run(self):
5875 self.httpd.serve_forever()
5869 self.httpd.serve_forever()
5876
5870
5877
5871
5878 @command('^status|st',
5872 @command('^status|st',
5879 [('A', 'all', None, _('show status of all files')),
5873 [('A', 'all', None, _('show status of all files')),
5880 ('m', 'modified', None, _('show only modified files')),
5874 ('m', 'modified', None, _('show only modified files')),
5881 ('a', 'added', None, _('show only added files')),
5875 ('a', 'added', None, _('show only added files')),
5882 ('r', 'removed', None, _('show only removed files')),
5876 ('r', 'removed', None, _('show only removed files')),
5883 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
5877 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
5884 ('c', 'clean', None, _('show only files without changes')),
5878 ('c', 'clean', None, _('show only files without changes')),
5885 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
5879 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
5886 ('i', 'ignored', None, _('show only ignored files')),
5880 ('i', 'ignored', None, _('show only ignored files')),
5887 ('n', 'no-status', None, _('hide status prefix')),
5881 ('n', 'no-status', None, _('hide status prefix')),
5888 ('C', 'copies', None, _('show source of copied files')),
5882 ('C', 'copies', None, _('show source of copied files')),
5889 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
5883 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
5890 ('', 'rev', [], _('show difference from revision'), _('REV')),
5884 ('', 'rev', [], _('show difference from revision'), _('REV')),
5891 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
5885 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
5892 ] + walkopts + subrepoopts + formatteropts,
5886 ] + walkopts + subrepoopts + formatteropts,
5893 _('[OPTION]... [FILE]...'),
5887 _('[OPTION]... [FILE]...'),
5894 inferrepo=True)
5888 inferrepo=True)
5895 def status(ui, repo, *pats, **opts):
5889 def status(ui, repo, *pats, **opts):
5896 """show changed files in the working directory
5890 """show changed files in the working directory
5897
5891
5898 Show status of files in the repository. If names are given, only
5892 Show status of files in the repository. If names are given, only
5899 files that match are shown. Files that are clean or ignored or
5893 files that match are shown. Files that are clean or ignored or
5900 the source of a copy/move operation, are not listed unless
5894 the source of a copy/move operation, are not listed unless
5901 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
5895 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
5902 Unless options described with "show only ..." are given, the
5896 Unless options described with "show only ..." are given, the
5903 options -mardu are used.
5897 options -mardu are used.
5904
5898
5905 Option -q/--quiet hides untracked (unknown and ignored) files
5899 Option -q/--quiet hides untracked (unknown and ignored) files
5906 unless explicitly requested with -u/--unknown or -i/--ignored.
5900 unless explicitly requested with -u/--unknown or -i/--ignored.
5907
5901
5908 .. note::
5902 .. note::
5909
5903
5910 status may appear to disagree with diff if permissions have
5904 status may appear to disagree with diff if permissions have
5911 changed or a merge has occurred. The standard diff format does
5905 changed or a merge has occurred. The standard diff format does
5912 not report permission changes and diff only reports changes
5906 not report permission changes and diff only reports changes
5913 relative to one merge parent.
5907 relative to one merge parent.
5914
5908
5915 If one revision is given, it is used as the base revision.
5909 If one revision is given, it is used as the base revision.
5916 If two revisions are given, the differences between them are
5910 If two revisions are given, the differences between them are
5917 shown. The --change option can also be used as a shortcut to list
5911 shown. The --change option can also be used as a shortcut to list
5918 the changed files of a revision from its first parent.
5912 the changed files of a revision from its first parent.
5919
5913
5920 The codes used to show the status of files are::
5914 The codes used to show the status of files are::
5921
5915
5922 M = modified
5916 M = modified
5923 A = added
5917 A = added
5924 R = removed
5918 R = removed
5925 C = clean
5919 C = clean
5926 ! = missing (deleted by non-hg command, but still tracked)
5920 ! = missing (deleted by non-hg command, but still tracked)
5927 ? = not tracked
5921 ? = not tracked
5928 I = ignored
5922 I = ignored
5929 = origin of the previous file (with --copies)
5923 = origin of the previous file (with --copies)
5930
5924
5931 .. container:: verbose
5925 .. container:: verbose
5932
5926
5933 Examples:
5927 Examples:
5934
5928
5935 - show changes in the working directory relative to a
5929 - show changes in the working directory relative to a
5936 changeset::
5930 changeset::
5937
5931
5938 hg status --rev 9353
5932 hg status --rev 9353
5939
5933
5940 - show changes in the working directory relative to the
5934 - show changes in the working directory relative to the
5941 current directory (see :hg:`help patterns` for more information)::
5935 current directory (see :hg:`help patterns` for more information)::
5942
5936
5943 hg status re:
5937 hg status re:
5944
5938
5945 - show all changes including copies in an existing changeset::
5939 - show all changes including copies in an existing changeset::
5946
5940
5947 hg status --copies --change 9353
5941 hg status --copies --change 9353
5948
5942
5949 - get a NUL separated list of added files, suitable for xargs::
5943 - get a NUL separated list of added files, suitable for xargs::
5950
5944
5951 hg status -an0
5945 hg status -an0
5952
5946
5953 Returns 0 on success.
5947 Returns 0 on success.
5954 """
5948 """
5955
5949
5956 revs = opts.get('rev')
5950 revs = opts.get('rev')
5957 change = opts.get('change')
5951 change = opts.get('change')
5958
5952
5959 if revs and change:
5953 if revs and change:
5960 msg = _('cannot specify --rev and --change at the same time')
5954 msg = _('cannot specify --rev and --change at the same time')
5961 raise util.Abort(msg)
5955 raise util.Abort(msg)
5962 elif change:
5956 elif change:
5963 node2 = scmutil.revsingle(repo, change, None).node()
5957 node2 = scmutil.revsingle(repo, change, None).node()
5964 node1 = repo[node2].p1().node()
5958 node1 = repo[node2].p1().node()
5965 else:
5959 else:
5966 node1, node2 = scmutil.revpair(repo, revs)
5960 node1, node2 = scmutil.revpair(repo, revs)
5967
5961
5968 if pats:
5962 if pats:
5969 cwd = repo.getcwd()
5963 cwd = repo.getcwd()
5970 else:
5964 else:
5971 cwd = ''
5965 cwd = ''
5972
5966
5973 if opts.get('print0'):
5967 if opts.get('print0'):
5974 end = '\0'
5968 end = '\0'
5975 else:
5969 else:
5976 end = '\n'
5970 end = '\n'
5977 copy = {}
5971 copy = {}
5978 states = 'modified added removed deleted unknown ignored clean'.split()
5972 states = 'modified added removed deleted unknown ignored clean'.split()
5979 show = [k for k in states if opts.get(k)]
5973 show = [k for k in states if opts.get(k)]
5980 if opts.get('all'):
5974 if opts.get('all'):
5981 show += ui.quiet and (states[:4] + ['clean']) or states
5975 show += ui.quiet and (states[:4] + ['clean']) or states
5982 if not show:
5976 if not show:
5983 if ui.quiet:
5977 if ui.quiet:
5984 show = states[:4]
5978 show = states[:4]
5985 else:
5979 else:
5986 show = states[:5]
5980 show = states[:5]
5987
5981
5988 m = scmutil.match(repo[node2], pats, opts)
5982 m = scmutil.match(repo[node2], pats, opts)
5989 stat = repo.status(node1, node2, m,
5983 stat = repo.status(node1, node2, m,
5990 'ignored' in show, 'clean' in show, 'unknown' in show,
5984 'ignored' in show, 'clean' in show, 'unknown' in show,
5991 opts.get('subrepos'))
5985 opts.get('subrepos'))
5992 changestates = zip(states, 'MAR!?IC', stat)
5986 changestates = zip(states, 'MAR!?IC', stat)
5993
5987
5994 if (opts.get('all') or opts.get('copies')
5988 if (opts.get('all') or opts.get('copies')
5995 or ui.configbool('ui', 'statuscopies')) and not opts.get('no_status'):
5989 or ui.configbool('ui', 'statuscopies')) and not opts.get('no_status'):
5996 copy = copies.pathcopies(repo[node1], repo[node2], m)
5990 copy = copies.pathcopies(repo[node1], repo[node2], m)
5997
5991
5998 fm = ui.formatter('status', opts)
5992 fm = ui.formatter('status', opts)
5999 fmt = '%s' + end
5993 fmt = '%s' + end
6000 showchar = not opts.get('no_status')
5994 showchar = not opts.get('no_status')
6001
5995
6002 for state, char, files in changestates:
5996 for state, char, files in changestates:
6003 if state in show:
5997 if state in show:
6004 label = 'status.' + state
5998 label = 'status.' + state
6005 for f in files:
5999 for f in files:
6006 fm.startitem()
6000 fm.startitem()
6007 fm.condwrite(showchar, 'status', '%s ', char, label=label)
6001 fm.condwrite(showchar, 'status', '%s ', char, label=label)
6008 fm.write('path', fmt, repo.pathto(f, cwd), label=label)
6002 fm.write('path', fmt, repo.pathto(f, cwd), label=label)
6009 if f in copy:
6003 if f in copy:
6010 fm.write("copy", ' %s' + end, repo.pathto(copy[f], cwd),
6004 fm.write("copy", ' %s' + end, repo.pathto(copy[f], cwd),
6011 label='status.copied')
6005 label='status.copied')
6012 fm.end()
6006 fm.end()
6013
6007
6014 @command('^summary|sum',
6008 @command('^summary|sum',
6015 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
6009 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
6016 def summary(ui, repo, **opts):
6010 def summary(ui, repo, **opts):
6017 """summarize working directory state
6011 """summarize working directory state
6018
6012
6019 This generates a brief summary of the working directory state,
6013 This generates a brief summary of the working directory state,
6020 including parents, branch, commit status, phase and available updates.
6014 including parents, branch, commit status, phase and available updates.
6021
6015
6022 With the --remote option, this will check the default paths for
6016 With the --remote option, this will check the default paths for
6023 incoming and outgoing changes. This can be time-consuming.
6017 incoming and outgoing changes. This can be time-consuming.
6024
6018
6025 Returns 0 on success.
6019 Returns 0 on success.
6026 """
6020 """
6027
6021
6028 ctx = repo[None]
6022 ctx = repo[None]
6029 parents = ctx.parents()
6023 parents = ctx.parents()
6030 pnode = parents[0].node()
6024 pnode = parents[0].node()
6031 marks = []
6025 marks = []
6032
6026
6033 for p in parents:
6027 for p in parents:
6034 # label with log.changeset (instead of log.parent) since this
6028 # label with log.changeset (instead of log.parent) since this
6035 # shows a working directory parent *changeset*:
6029 # shows a working directory parent *changeset*:
6036 # i18n: column positioning for "hg summary"
6030 # i18n: column positioning for "hg summary"
6037 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
6031 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
6038 label='log.changeset changeset.%s' % p.phasestr())
6032 label='log.changeset changeset.%s' % p.phasestr())
6039 ui.write(' '.join(p.tags()), label='log.tag')
6033 ui.write(' '.join(p.tags()), label='log.tag')
6040 if p.bookmarks():
6034 if p.bookmarks():
6041 marks.extend(p.bookmarks())
6035 marks.extend(p.bookmarks())
6042 if p.rev() == -1:
6036 if p.rev() == -1:
6043 if not len(repo):
6037 if not len(repo):
6044 ui.write(_(' (empty repository)'))
6038 ui.write(_(' (empty repository)'))
6045 else:
6039 else:
6046 ui.write(_(' (no revision checked out)'))
6040 ui.write(_(' (no revision checked out)'))
6047 ui.write('\n')
6041 ui.write('\n')
6048 if p.description():
6042 if p.description():
6049 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
6043 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
6050 label='log.summary')
6044 label='log.summary')
6051
6045
6052 branch = ctx.branch()
6046 branch = ctx.branch()
6053 bheads = repo.branchheads(branch)
6047 bheads = repo.branchheads(branch)
6054 # i18n: column positioning for "hg summary"
6048 # i18n: column positioning for "hg summary"
6055 m = _('branch: %s\n') % branch
6049 m = _('branch: %s\n') % branch
6056 if branch != 'default':
6050 if branch != 'default':
6057 ui.write(m, label='log.branch')
6051 ui.write(m, label='log.branch')
6058 else:
6052 else:
6059 ui.status(m, label='log.branch')
6053 ui.status(m, label='log.branch')
6060
6054
6061 if marks:
6055 if marks:
6062 active = repo._activebookmark
6056 active = repo._activebookmark
6063 # i18n: column positioning for "hg summary"
6057 # i18n: column positioning for "hg summary"
6064 ui.write(_('bookmarks:'), label='log.bookmark')
6058 ui.write(_('bookmarks:'), label='log.bookmark')
6065 if active is not None:
6059 if active is not None:
6066 if active in marks:
6060 if active in marks:
6067 ui.write(' *' + active, label=activebookmarklabel)
6061 ui.write(' *' + active, label=activebookmarklabel)
6068 marks.remove(active)
6062 marks.remove(active)
6069 else:
6063 else:
6070 ui.write(' [%s]' % active, label=activebookmarklabel)
6064 ui.write(' [%s]' % active, label=activebookmarklabel)
6071 for m in marks:
6065 for m in marks:
6072 ui.write(' ' + m, label='log.bookmark')
6066 ui.write(' ' + m, label='log.bookmark')
6073 ui.write('\n', label='log.bookmark')
6067 ui.write('\n', label='log.bookmark')
6074
6068
6075 status = repo.status(unknown=True)
6069 status = repo.status(unknown=True)
6076
6070
6077 c = repo.dirstate.copies()
6071 c = repo.dirstate.copies()
6078 copied, renamed = [], []
6072 copied, renamed = [], []
6079 for d, s in c.iteritems():
6073 for d, s in c.iteritems():
6080 if s in status.removed:
6074 if s in status.removed:
6081 status.removed.remove(s)
6075 status.removed.remove(s)
6082 renamed.append(d)
6076 renamed.append(d)
6083 else:
6077 else:
6084 copied.append(d)
6078 copied.append(d)
6085 if d in status.added:
6079 if d in status.added:
6086 status.added.remove(d)
6080 status.added.remove(d)
6087
6081
6088 ms = mergemod.mergestate(repo)
6082 ms = mergemod.mergestate(repo)
6089 unresolved = [f for f in ms if ms[f] == 'u']
6083 unresolved = [f for f in ms if ms[f] == 'u']
6090
6084
6091 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
6085 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
6092
6086
6093 labels = [(ui.label(_('%d modified'), 'status.modified'), status.modified),
6087 labels = [(ui.label(_('%d modified'), 'status.modified'), status.modified),
6094 (ui.label(_('%d added'), 'status.added'), status.added),
6088 (ui.label(_('%d added'), 'status.added'), status.added),
6095 (ui.label(_('%d removed'), 'status.removed'), status.removed),
6089 (ui.label(_('%d removed'), 'status.removed'), status.removed),
6096 (ui.label(_('%d renamed'), 'status.copied'), renamed),
6090 (ui.label(_('%d renamed'), 'status.copied'), renamed),
6097 (ui.label(_('%d copied'), 'status.copied'), copied),
6091 (ui.label(_('%d copied'), 'status.copied'), copied),
6098 (ui.label(_('%d deleted'), 'status.deleted'), status.deleted),
6092 (ui.label(_('%d deleted'), 'status.deleted'), status.deleted),
6099 (ui.label(_('%d unknown'), 'status.unknown'), status.unknown),
6093 (ui.label(_('%d unknown'), 'status.unknown'), status.unknown),
6100 (ui.label(_('%d unresolved'), 'resolve.unresolved'), unresolved),
6094 (ui.label(_('%d unresolved'), 'resolve.unresolved'), unresolved),
6101 (ui.label(_('%d subrepos'), 'status.modified'), subs)]
6095 (ui.label(_('%d subrepos'), 'status.modified'), subs)]
6102 t = []
6096 t = []
6103 for l, s in labels:
6097 for l, s in labels:
6104 if s:
6098 if s:
6105 t.append(l % len(s))
6099 t.append(l % len(s))
6106
6100
6107 t = ', '.join(t)
6101 t = ', '.join(t)
6108 cleanworkdir = False
6102 cleanworkdir = False
6109
6103
6110 if repo.vfs.exists('updatestate'):
6104 if repo.vfs.exists('updatestate'):
6111 t += _(' (interrupted update)')
6105 t += _(' (interrupted update)')
6112 elif len(parents) > 1:
6106 elif len(parents) > 1:
6113 t += _(' (merge)')
6107 t += _(' (merge)')
6114 elif branch != parents[0].branch():
6108 elif branch != parents[0].branch():
6115 t += _(' (new branch)')
6109 t += _(' (new branch)')
6116 elif (parents[0].closesbranch() and
6110 elif (parents[0].closesbranch() and
6117 pnode in repo.branchheads(branch, closed=True)):
6111 pnode in repo.branchheads(branch, closed=True)):
6118 t += _(' (head closed)')
6112 t += _(' (head closed)')
6119 elif not (status.modified or status.added or status.removed or renamed or
6113 elif not (status.modified or status.added or status.removed or renamed or
6120 copied or subs):
6114 copied or subs):
6121 t += _(' (clean)')
6115 t += _(' (clean)')
6122 cleanworkdir = True
6116 cleanworkdir = True
6123 elif pnode not in bheads:
6117 elif pnode not in bheads:
6124 t += _(' (new branch head)')
6118 t += _(' (new branch head)')
6125
6119
6126 if parents:
6120 if parents:
6127 pendingphase = max(p.phase() for p in parents)
6121 pendingphase = max(p.phase() for p in parents)
6128 else:
6122 else:
6129 pendingphase = phases.public
6123 pendingphase = phases.public
6130
6124
6131 if pendingphase > phases.newcommitphase(ui):
6125 if pendingphase > phases.newcommitphase(ui):
6132 t += ' (%s)' % phases.phasenames[pendingphase]
6126 t += ' (%s)' % phases.phasenames[pendingphase]
6133
6127
6134 if cleanworkdir:
6128 if cleanworkdir:
6135 # i18n: column positioning for "hg summary"
6129 # i18n: column positioning for "hg summary"
6136 ui.status(_('commit: %s\n') % t.strip())
6130 ui.status(_('commit: %s\n') % t.strip())
6137 else:
6131 else:
6138 # i18n: column positioning for "hg summary"
6132 # i18n: column positioning for "hg summary"
6139 ui.write(_('commit: %s\n') % t.strip())
6133 ui.write(_('commit: %s\n') % t.strip())
6140
6134
6141 # all ancestors of branch heads - all ancestors of parent = new csets
6135 # all ancestors of branch heads - all ancestors of parent = new csets
6142 new = len(repo.changelog.findmissing([pctx.node() for pctx in parents],
6136 new = len(repo.changelog.findmissing([pctx.node() for pctx in parents],
6143 bheads))
6137 bheads))
6144
6138
6145 if new == 0:
6139 if new == 0:
6146 # i18n: column positioning for "hg summary"
6140 # i18n: column positioning for "hg summary"
6147 ui.status(_('update: (current)\n'))
6141 ui.status(_('update: (current)\n'))
6148 elif pnode not in bheads:
6142 elif pnode not in bheads:
6149 # i18n: column positioning for "hg summary"
6143 # i18n: column positioning for "hg summary"
6150 ui.write(_('update: %d new changesets (update)\n') % new)
6144 ui.write(_('update: %d new changesets (update)\n') % new)
6151 else:
6145 else:
6152 # i18n: column positioning for "hg summary"
6146 # i18n: column positioning for "hg summary"
6153 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
6147 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
6154 (new, len(bheads)))
6148 (new, len(bheads)))
6155
6149
6156 t = []
6150 t = []
6157 draft = len(repo.revs('draft()'))
6151 draft = len(repo.revs('draft()'))
6158 if draft:
6152 if draft:
6159 t.append(_('%d draft') % draft)
6153 t.append(_('%d draft') % draft)
6160 secret = len(repo.revs('secret()'))
6154 secret = len(repo.revs('secret()'))
6161 if secret:
6155 if secret:
6162 t.append(_('%d secret') % secret)
6156 t.append(_('%d secret') % secret)
6163
6157
6164 if draft or secret:
6158 if draft or secret:
6165 ui.status(_('phases: %s\n') % ', '.join(t))
6159 ui.status(_('phases: %s\n') % ', '.join(t))
6166
6160
6167 cmdutil.summaryhooks(ui, repo)
6161 cmdutil.summaryhooks(ui, repo)
6168
6162
6169 if opts.get('remote'):
6163 if opts.get('remote'):
6170 needsincoming, needsoutgoing = True, True
6164 needsincoming, needsoutgoing = True, True
6171 else:
6165 else:
6172 needsincoming, needsoutgoing = False, False
6166 needsincoming, needsoutgoing = False, False
6173 for i, o in cmdutil.summaryremotehooks(ui, repo, opts, None):
6167 for i, o in cmdutil.summaryremotehooks(ui, repo, opts, None):
6174 if i:
6168 if i:
6175 needsincoming = True
6169 needsincoming = True
6176 if o:
6170 if o:
6177 needsoutgoing = True
6171 needsoutgoing = True
6178 if not needsincoming and not needsoutgoing:
6172 if not needsincoming and not needsoutgoing:
6179 return
6173 return
6180
6174
6181 def getincoming():
6175 def getincoming():
6182 source, branches = hg.parseurl(ui.expandpath('default'))
6176 source, branches = hg.parseurl(ui.expandpath('default'))
6183 sbranch = branches[0]
6177 sbranch = branches[0]
6184 try:
6178 try:
6185 other = hg.peer(repo, {}, source)
6179 other = hg.peer(repo, {}, source)
6186 except error.RepoError:
6180 except error.RepoError:
6187 if opts.get('remote'):
6181 if opts.get('remote'):
6188 raise
6182 raise
6189 return source, sbranch, None, None, None
6183 return source, sbranch, None, None, None
6190 revs, checkout = hg.addbranchrevs(repo, other, branches, None)
6184 revs, checkout = hg.addbranchrevs(repo, other, branches, None)
6191 if revs:
6185 if revs:
6192 revs = [other.lookup(rev) for rev in revs]
6186 revs = [other.lookup(rev) for rev in revs]
6193 ui.debug('comparing with %s\n' % util.hidepassword(source))
6187 ui.debug('comparing with %s\n' % util.hidepassword(source))
6194 repo.ui.pushbuffer()
6188 repo.ui.pushbuffer()
6195 commoninc = discovery.findcommonincoming(repo, other, heads=revs)
6189 commoninc = discovery.findcommonincoming(repo, other, heads=revs)
6196 repo.ui.popbuffer()
6190 repo.ui.popbuffer()
6197 return source, sbranch, other, commoninc, commoninc[1]
6191 return source, sbranch, other, commoninc, commoninc[1]
6198
6192
6199 if needsincoming:
6193 if needsincoming:
6200 source, sbranch, sother, commoninc, incoming = getincoming()
6194 source, sbranch, sother, commoninc, incoming = getincoming()
6201 else:
6195 else:
6202 source = sbranch = sother = commoninc = incoming = None
6196 source = sbranch = sother = commoninc = incoming = None
6203
6197
6204 def getoutgoing():
6198 def getoutgoing():
6205 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
6199 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
6206 dbranch = branches[0]
6200 dbranch = branches[0]
6207 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
6201 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
6208 if source != dest:
6202 if source != dest:
6209 try:
6203 try:
6210 dother = hg.peer(repo, {}, dest)
6204 dother = hg.peer(repo, {}, dest)
6211 except error.RepoError:
6205 except error.RepoError:
6212 if opts.get('remote'):
6206 if opts.get('remote'):
6213 raise
6207 raise
6214 return dest, dbranch, None, None
6208 return dest, dbranch, None, None
6215 ui.debug('comparing with %s\n' % util.hidepassword(dest))
6209 ui.debug('comparing with %s\n' % util.hidepassword(dest))
6216 elif sother is None:
6210 elif sother is None:
6217 # there is no explicit destination peer, but source one is invalid
6211 # there is no explicit destination peer, but source one is invalid
6218 return dest, dbranch, None, None
6212 return dest, dbranch, None, None
6219 else:
6213 else:
6220 dother = sother
6214 dother = sother
6221 if (source != dest or (sbranch is not None and sbranch != dbranch)):
6215 if (source != dest or (sbranch is not None and sbranch != dbranch)):
6222 common = None
6216 common = None
6223 else:
6217 else:
6224 common = commoninc
6218 common = commoninc
6225 if revs:
6219 if revs:
6226 revs = [repo.lookup(rev) for rev in revs]
6220 revs = [repo.lookup(rev) for rev in revs]
6227 repo.ui.pushbuffer()
6221 repo.ui.pushbuffer()
6228 outgoing = discovery.findcommonoutgoing(repo, dother, onlyheads=revs,
6222 outgoing = discovery.findcommonoutgoing(repo, dother, onlyheads=revs,
6229 commoninc=common)
6223 commoninc=common)
6230 repo.ui.popbuffer()
6224 repo.ui.popbuffer()
6231 return dest, dbranch, dother, outgoing
6225 return dest, dbranch, dother, outgoing
6232
6226
6233 if needsoutgoing:
6227 if needsoutgoing:
6234 dest, dbranch, dother, outgoing = getoutgoing()
6228 dest, dbranch, dother, outgoing = getoutgoing()
6235 else:
6229 else:
6236 dest = dbranch = dother = outgoing = None
6230 dest = dbranch = dother = outgoing = None
6237
6231
6238 if opts.get('remote'):
6232 if opts.get('remote'):
6239 t = []
6233 t = []
6240 if incoming:
6234 if incoming:
6241 t.append(_('1 or more incoming'))
6235 t.append(_('1 or more incoming'))
6242 o = outgoing.missing
6236 o = outgoing.missing
6243 if o:
6237 if o:
6244 t.append(_('%d outgoing') % len(o))
6238 t.append(_('%d outgoing') % len(o))
6245 other = dother or sother
6239 other = dother or sother
6246 if 'bookmarks' in other.listkeys('namespaces'):
6240 if 'bookmarks' in other.listkeys('namespaces'):
6247 counts = bookmarks.summary(repo, other)
6241 counts = bookmarks.summary(repo, other)
6248 if counts[0] > 0:
6242 if counts[0] > 0:
6249 t.append(_('%d incoming bookmarks') % counts[0])
6243 t.append(_('%d incoming bookmarks') % counts[0])
6250 if counts[1] > 0:
6244 if counts[1] > 0:
6251 t.append(_('%d outgoing bookmarks') % counts[1])
6245 t.append(_('%d outgoing bookmarks') % counts[1])
6252
6246
6253 if t:
6247 if t:
6254 # i18n: column positioning for "hg summary"
6248 # i18n: column positioning for "hg summary"
6255 ui.write(_('remote: %s\n') % (', '.join(t)))
6249 ui.write(_('remote: %s\n') % (', '.join(t)))
6256 else:
6250 else:
6257 # i18n: column positioning for "hg summary"
6251 # i18n: column positioning for "hg summary"
6258 ui.status(_('remote: (synced)\n'))
6252 ui.status(_('remote: (synced)\n'))
6259
6253
6260 cmdutil.summaryremotehooks(ui, repo, opts,
6254 cmdutil.summaryremotehooks(ui, repo, opts,
6261 ((source, sbranch, sother, commoninc),
6255 ((source, sbranch, sother, commoninc),
6262 (dest, dbranch, dother, outgoing)))
6256 (dest, dbranch, dother, outgoing)))
6263
6257
6264 @command('tag',
6258 @command('tag',
6265 [('f', 'force', None, _('force tag')),
6259 [('f', 'force', None, _('force tag')),
6266 ('l', 'local', None, _('make the tag local')),
6260 ('l', 'local', None, _('make the tag local')),
6267 ('r', 'rev', '', _('revision to tag'), _('REV')),
6261 ('r', 'rev', '', _('revision to tag'), _('REV')),
6268 ('', 'remove', None, _('remove a tag')),
6262 ('', 'remove', None, _('remove a tag')),
6269 # -l/--local is already there, commitopts cannot be used
6263 # -l/--local is already there, commitopts cannot be used
6270 ('e', 'edit', None, _('invoke editor on commit messages')),
6264 ('e', 'edit', None, _('invoke editor on commit messages')),
6271 ('m', 'message', '', _('use text as commit message'), _('TEXT')),
6265 ('m', 'message', '', _('use text as commit message'), _('TEXT')),
6272 ] + commitopts2,
6266 ] + commitopts2,
6273 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
6267 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
6274 def tag(ui, repo, name1, *names, **opts):
6268 def tag(ui, repo, name1, *names, **opts):
6275 """add one or more tags for the current or given revision
6269 """add one or more tags for the current or given revision
6276
6270
6277 Name a particular revision using <name>.
6271 Name a particular revision using <name>.
6278
6272
6279 Tags are used to name particular revisions of the repository and are
6273 Tags are used to name particular revisions of the repository and are
6280 very useful to compare different revisions, to go back to significant
6274 very useful to compare different revisions, to go back to significant
6281 earlier versions or to mark branch points as releases, etc. Changing
6275 earlier versions or to mark branch points as releases, etc. Changing
6282 an existing tag is normally disallowed; use -f/--force to override.
6276 an existing tag is normally disallowed; use -f/--force to override.
6283
6277
6284 If no revision is given, the parent of the working directory is
6278 If no revision is given, the parent of the working directory is
6285 used.
6279 used.
6286
6280
6287 To facilitate version control, distribution, and merging of tags,
6281 To facilitate version control, distribution, and merging of tags,
6288 they are stored as a file named ".hgtags" which is managed similarly
6282 they are stored as a file named ".hgtags" which is managed similarly
6289 to other project files and can be hand-edited if necessary. This
6283 to other project files and can be hand-edited if necessary. This
6290 also means that tagging creates a new commit. The file
6284 also means that tagging creates a new commit. The file
6291 ".hg/localtags" is used for local tags (not shared among
6285 ".hg/localtags" is used for local tags (not shared among
6292 repositories).
6286 repositories).
6293
6287
6294 Tag commits are usually made at the head of a branch. If the parent
6288 Tag commits are usually made at the head of a branch. If the parent
6295 of the working directory is not a branch head, :hg:`tag` aborts; use
6289 of the working directory is not a branch head, :hg:`tag` aborts; use
6296 -f/--force to force the tag commit to be based on a non-head
6290 -f/--force to force the tag commit to be based on a non-head
6297 changeset.
6291 changeset.
6298
6292
6299 See :hg:`help dates` for a list of formats valid for -d/--date.
6293 See :hg:`help dates` for a list of formats valid for -d/--date.
6300
6294
6301 Since tag names have priority over branch names during revision
6295 Since tag names have priority over branch names during revision
6302 lookup, using an existing branch name as a tag name is discouraged.
6296 lookup, using an existing branch name as a tag name is discouraged.
6303
6297
6304 Returns 0 on success.
6298 Returns 0 on success.
6305 """
6299 """
6306 wlock = lock = None
6300 wlock = lock = None
6307 try:
6301 try:
6308 wlock = repo.wlock()
6302 wlock = repo.wlock()
6309 lock = repo.lock()
6303 lock = repo.lock()
6310 rev_ = "."
6304 rev_ = "."
6311 names = [t.strip() for t in (name1,) + names]
6305 names = [t.strip() for t in (name1,) + names]
6312 if len(names) != len(set(names)):
6306 if len(names) != len(set(names)):
6313 raise util.Abort(_('tag names must be unique'))
6307 raise util.Abort(_('tag names must be unique'))
6314 for n in names:
6308 for n in names:
6315 scmutil.checknewlabel(repo, n, 'tag')
6309 scmutil.checknewlabel(repo, n, 'tag')
6316 if not n:
6310 if not n:
6317 raise util.Abort(_('tag names cannot consist entirely of '
6311 raise util.Abort(_('tag names cannot consist entirely of '
6318 'whitespace'))
6312 'whitespace'))
6319 if opts.get('rev') and opts.get('remove'):
6313 if opts.get('rev') and opts.get('remove'):
6320 raise util.Abort(_("--rev and --remove are incompatible"))
6314 raise util.Abort(_("--rev and --remove are incompatible"))
6321 if opts.get('rev'):
6315 if opts.get('rev'):
6322 rev_ = opts['rev']
6316 rev_ = opts['rev']
6323 message = opts.get('message')
6317 message = opts.get('message')
6324 if opts.get('remove'):
6318 if opts.get('remove'):
6325 if opts.get('local'):
6319 if opts.get('local'):
6326 expectedtype = 'local'
6320 expectedtype = 'local'
6327 else:
6321 else:
6328 expectedtype = 'global'
6322 expectedtype = 'global'
6329
6323
6330 for n in names:
6324 for n in names:
6331 if not repo.tagtype(n):
6325 if not repo.tagtype(n):
6332 raise util.Abort(_("tag '%s' does not exist") % n)
6326 raise util.Abort(_("tag '%s' does not exist") % n)
6333 if repo.tagtype(n) != expectedtype:
6327 if repo.tagtype(n) != expectedtype:
6334 if expectedtype == 'global':
6328 if expectedtype == 'global':
6335 raise util.Abort(_("tag '%s' is not a global tag") % n)
6329 raise util.Abort(_("tag '%s' is not a global tag") % n)
6336 else:
6330 else:
6337 raise util.Abort(_("tag '%s' is not a local tag") % n)
6331 raise util.Abort(_("tag '%s' is not a local tag") % n)
6338 rev_ = 'null'
6332 rev_ = 'null'
6339 if not message:
6333 if not message:
6340 # we don't translate commit messages
6334 # we don't translate commit messages
6341 message = 'Removed tag %s' % ', '.join(names)
6335 message = 'Removed tag %s' % ', '.join(names)
6342 elif not opts.get('force'):
6336 elif not opts.get('force'):
6343 for n in names:
6337 for n in names:
6344 if n in repo.tags():
6338 if n in repo.tags():
6345 raise util.Abort(_("tag '%s' already exists "
6339 raise util.Abort(_("tag '%s' already exists "
6346 "(use -f to force)") % n)
6340 "(use -f to force)") % n)
6347 if not opts.get('local'):
6341 if not opts.get('local'):
6348 p1, p2 = repo.dirstate.parents()
6342 p1, p2 = repo.dirstate.parents()
6349 if p2 != nullid:
6343 if p2 != nullid:
6350 raise util.Abort(_('uncommitted merge'))
6344 raise util.Abort(_('uncommitted merge'))
6351 bheads = repo.branchheads()
6345 bheads = repo.branchheads()
6352 if not opts.get('force') and bheads and p1 not in bheads:
6346 if not opts.get('force') and bheads and p1 not in bheads:
6353 raise util.Abort(_('not at a branch head (use -f to force)'))
6347 raise util.Abort(_('not at a branch head (use -f to force)'))
6354 r = scmutil.revsingle(repo, rev_).node()
6348 r = scmutil.revsingle(repo, rev_).node()
6355
6349
6356 if not message:
6350 if not message:
6357 # we don't translate commit messages
6351 # we don't translate commit messages
6358 message = ('Added tag %s for changeset %s' %
6352 message = ('Added tag %s for changeset %s' %
6359 (', '.join(names), short(r)))
6353 (', '.join(names), short(r)))
6360
6354
6361 date = opts.get('date')
6355 date = opts.get('date')
6362 if date:
6356 if date:
6363 date = util.parsedate(date)
6357 date = util.parsedate(date)
6364
6358
6365 if opts.get('remove'):
6359 if opts.get('remove'):
6366 editform = 'tag.remove'
6360 editform = 'tag.remove'
6367 else:
6361 else:
6368 editform = 'tag.add'
6362 editform = 'tag.add'
6369 editor = cmdutil.getcommiteditor(editform=editform, **opts)
6363 editor = cmdutil.getcommiteditor(editform=editform, **opts)
6370
6364
6371 # don't allow tagging the null rev
6365 # don't allow tagging the null rev
6372 if (not opts.get('remove') and
6366 if (not opts.get('remove') and
6373 scmutil.revsingle(repo, rev_).rev() == nullrev):
6367 scmutil.revsingle(repo, rev_).rev() == nullrev):
6374 raise util.Abort(_("cannot tag null revision"))
6368 raise util.Abort(_("cannot tag null revision"))
6375
6369
6376 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date,
6370 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date,
6377 editor=editor)
6371 editor=editor)
6378 finally:
6372 finally:
6379 release(lock, wlock)
6373 release(lock, wlock)
6380
6374
6381 @command('tags', formatteropts, '')
6375 @command('tags', formatteropts, '')
6382 def tags(ui, repo, **opts):
6376 def tags(ui, repo, **opts):
6383 """list repository tags
6377 """list repository tags
6384
6378
6385 This lists both regular and local tags. When the -v/--verbose
6379 This lists both regular and local tags. When the -v/--verbose
6386 switch is used, a third column "local" is printed for local tags.
6380 switch is used, a third column "local" is printed for local tags.
6387
6381
6388 Returns 0 on success.
6382 Returns 0 on success.
6389 """
6383 """
6390
6384
6391 fm = ui.formatter('tags', opts)
6385 fm = ui.formatter('tags', opts)
6392 hexfunc = fm.hexfunc
6386 hexfunc = fm.hexfunc
6393 tagtype = ""
6387 tagtype = ""
6394
6388
6395 for t, n in reversed(repo.tagslist()):
6389 for t, n in reversed(repo.tagslist()):
6396 hn = hexfunc(n)
6390 hn = hexfunc(n)
6397 label = 'tags.normal'
6391 label = 'tags.normal'
6398 tagtype = ''
6392 tagtype = ''
6399 if repo.tagtype(t) == 'local':
6393 if repo.tagtype(t) == 'local':
6400 label = 'tags.local'
6394 label = 'tags.local'
6401 tagtype = 'local'
6395 tagtype = 'local'
6402
6396
6403 fm.startitem()
6397 fm.startitem()
6404 fm.write('tag', '%s', t, label=label)
6398 fm.write('tag', '%s', t, label=label)
6405 fmt = " " * (30 - encoding.colwidth(t)) + ' %5d:%s'
6399 fmt = " " * (30 - encoding.colwidth(t)) + ' %5d:%s'
6406 fm.condwrite(not ui.quiet, 'rev node', fmt,
6400 fm.condwrite(not ui.quiet, 'rev node', fmt,
6407 repo.changelog.rev(n), hn, label=label)
6401 repo.changelog.rev(n), hn, label=label)
6408 fm.condwrite(ui.verbose and tagtype, 'type', ' %s',
6402 fm.condwrite(ui.verbose and tagtype, 'type', ' %s',
6409 tagtype, label=label)
6403 tagtype, label=label)
6410 fm.plain('\n')
6404 fm.plain('\n')
6411 fm.end()
6405 fm.end()
6412
6406
6413 @command('tip',
6407 @command('tip',
6414 [('p', 'patch', None, _('show patch')),
6408 [('p', 'patch', None, _('show patch')),
6415 ('g', 'git', None, _('use git extended diff format')),
6409 ('g', 'git', None, _('use git extended diff format')),
6416 ] + templateopts,
6410 ] + templateopts,
6417 _('[-p] [-g]'))
6411 _('[-p] [-g]'))
6418 def tip(ui, repo, **opts):
6412 def tip(ui, repo, **opts):
6419 """show the tip revision (DEPRECATED)
6413 """show the tip revision (DEPRECATED)
6420
6414
6421 The tip revision (usually just called the tip) is the changeset
6415 The tip revision (usually just called the tip) is the changeset
6422 most recently added to the repository (and therefore the most
6416 most recently added to the repository (and therefore the most
6423 recently changed head).
6417 recently changed head).
6424
6418
6425 If you have just made a commit, that commit will be the tip. If
6419 If you have just made a commit, that commit will be the tip. If
6426 you have just pulled changes from another repository, the tip of
6420 you have just pulled changes from another repository, the tip of
6427 that repository becomes the current tip. The "tip" tag is special
6421 that repository becomes the current tip. The "tip" tag is special
6428 and cannot be renamed or assigned to a different changeset.
6422 and cannot be renamed or assigned to a different changeset.
6429
6423
6430 This command is deprecated, please use :hg:`heads` instead.
6424 This command is deprecated, please use :hg:`heads` instead.
6431
6425
6432 Returns 0 on success.
6426 Returns 0 on success.
6433 """
6427 """
6434 displayer = cmdutil.show_changeset(ui, repo, opts)
6428 displayer = cmdutil.show_changeset(ui, repo, opts)
6435 displayer.show(repo['tip'])
6429 displayer.show(repo['tip'])
6436 displayer.close()
6430 displayer.close()
6437
6431
6438 @command('unbundle',
6432 @command('unbundle',
6439 [('u', 'update', None,
6433 [('u', 'update', None,
6440 _('update to new branch head if changesets were unbundled'))],
6434 _('update to new branch head if changesets were unbundled'))],
6441 _('[-u] FILE...'))
6435 _('[-u] FILE...'))
6442 def unbundle(ui, repo, fname1, *fnames, **opts):
6436 def unbundle(ui, repo, fname1, *fnames, **opts):
6443 """apply one or more changegroup files
6437 """apply one or more changegroup files
6444
6438
6445 Apply one or more compressed changegroup files generated by the
6439 Apply one or more compressed changegroup files generated by the
6446 bundle command.
6440 bundle command.
6447
6441
6448 Returns 0 on success, 1 if an update has unresolved files.
6442 Returns 0 on success, 1 if an update has unresolved files.
6449 """
6443 """
6450 fnames = (fname1,) + fnames
6444 fnames = (fname1,) + fnames
6451
6445
6452 lock = repo.lock()
6446 lock = repo.lock()
6453 try:
6447 try:
6454 for fname in fnames:
6448 for fname in fnames:
6455 f = hg.openpath(ui, fname)
6449 f = hg.openpath(ui, fname)
6456 gen = exchange.readbundle(ui, f, fname)
6450 gen = exchange.readbundle(ui, f, fname)
6457 if isinstance(gen, bundle2.unbundle20):
6451 if isinstance(gen, bundle2.unbundle20):
6458 tr = repo.transaction('unbundle')
6452 tr = repo.transaction('unbundle')
6459 try:
6453 try:
6460 op = bundle2.processbundle(repo, gen, lambda: tr)
6454 op = bundle2.processbundle(repo, gen, lambda: tr)
6461 tr.close()
6455 tr.close()
6462 except error.BundleUnknownFeatureError as exc:
6456 except error.BundleUnknownFeatureError as exc:
6463 raise util.Abort(_('%s: unknown bundle feature, %s')
6457 raise util.Abort(_('%s: unknown bundle feature, %s')
6464 % (fname, exc),
6458 % (fname, exc),
6465 hint=_("see https://mercurial-scm.org/"
6459 hint=_("see https://mercurial-scm.org/"
6466 "wiki/BundleFeature for more "
6460 "wiki/BundleFeature for more "
6467 "information"))
6461 "information"))
6468 finally:
6462 finally:
6469 if tr:
6463 if tr:
6470 tr.release()
6464 tr.release()
6471 changes = [r.get('result', 0)
6465 changes = [r.get('result', 0)
6472 for r in op.records['changegroup']]
6466 for r in op.records['changegroup']]
6473 modheads = changegroup.combineresults(changes)
6467 modheads = changegroup.combineresults(changes)
6474 else:
6468 else:
6475 modheads = changegroup.addchangegroup(repo, gen, 'unbundle',
6469 modheads = changegroup.addchangegroup(repo, gen, 'unbundle',
6476 'bundle:' + fname)
6470 'bundle:' + fname)
6477 finally:
6471 finally:
6478 lock.release()
6472 lock.release()
6479
6473
6480 return postincoming(ui, repo, modheads, opts.get('update'), None)
6474 return postincoming(ui, repo, modheads, opts.get('update'), None)
6481
6475
6482 @command('^update|up|checkout|co',
6476 @command('^update|up|checkout|co',
6483 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
6477 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
6484 ('c', 'check', None,
6478 ('c', 'check', None,
6485 _('update across branches if no uncommitted changes')),
6479 _('update across branches if no uncommitted changes')),
6486 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
6480 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
6487 ('r', 'rev', '', _('revision'), _('REV'))
6481 ('r', 'rev', '', _('revision'), _('REV'))
6488 ] + mergetoolopts,
6482 ] + mergetoolopts,
6489 _('[-c] [-C] [-d DATE] [[-r] REV]'))
6483 _('[-c] [-C] [-d DATE] [[-r] REV]'))
6490 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False,
6484 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False,
6491 tool=None):
6485 tool=None):
6492 """update working directory (or switch revisions)
6486 """update working directory (or switch revisions)
6493
6487
6494 Update the repository's working directory to the specified
6488 Update the repository's working directory to the specified
6495 changeset. If no changeset is specified, update to the tip of the
6489 changeset. If no changeset is specified, update to the tip of the
6496 current named branch and move the active bookmark (see :hg:`help
6490 current named branch and move the active bookmark (see :hg:`help
6497 bookmarks`).
6491 bookmarks`).
6498
6492
6499 Update sets the working directory's parent revision to the specified
6493 Update sets the working directory's parent revision to the specified
6500 changeset (see :hg:`help parents`).
6494 changeset (see :hg:`help parents`).
6501
6495
6502 If the changeset is not a descendant or ancestor of the working
6496 If the changeset is not a descendant or ancestor of the working
6503 directory's parent, the update is aborted. With the -c/--check
6497 directory's parent, the update is aborted. With the -c/--check
6504 option, the working directory is checked for uncommitted changes; if
6498 option, the working directory is checked for uncommitted changes; if
6505 none are found, the working directory is updated to the specified
6499 none are found, the working directory is updated to the specified
6506 changeset.
6500 changeset.
6507
6501
6508 .. container:: verbose
6502 .. container:: verbose
6509
6503
6510 The following rules apply when the working directory contains
6504 The following rules apply when the working directory contains
6511 uncommitted changes:
6505 uncommitted changes:
6512
6506
6513 1. If neither -c/--check nor -C/--clean is specified, and if
6507 1. If neither -c/--check nor -C/--clean is specified, and if
6514 the requested changeset is an ancestor or descendant of
6508 the requested changeset is an ancestor or descendant of
6515 the working directory's parent, the uncommitted changes
6509 the working directory's parent, the uncommitted changes
6516 are merged into the requested changeset and the merged
6510 are merged into the requested changeset and the merged
6517 result is left uncommitted. If the requested changeset is
6511 result is left uncommitted. If the requested changeset is
6518 not an ancestor or descendant (that is, it is on another
6512 not an ancestor or descendant (that is, it is on another
6519 branch), the update is aborted and the uncommitted changes
6513 branch), the update is aborted and the uncommitted changes
6520 are preserved.
6514 are preserved.
6521
6515
6522 2. With the -c/--check option, the update is aborted and the
6516 2. With the -c/--check option, the update is aborted and the
6523 uncommitted changes are preserved.
6517 uncommitted changes are preserved.
6524
6518
6525 3. With the -C/--clean option, uncommitted changes are discarded and
6519 3. With the -C/--clean option, uncommitted changes are discarded and
6526 the working directory is updated to the requested changeset.
6520 the working directory is updated to the requested changeset.
6527
6521
6528 To cancel an uncommitted merge (and lose your changes), use
6522 To cancel an uncommitted merge (and lose your changes), use
6529 :hg:`update --clean .`.
6523 :hg:`update --clean .`.
6530
6524
6531 Use null as the changeset to remove the working directory (like
6525 Use null as the changeset to remove the working directory (like
6532 :hg:`clone -U`).
6526 :hg:`clone -U`).
6533
6527
6534 If you want to revert just one file to an older revision, use
6528 If you want to revert just one file to an older revision, use
6535 :hg:`revert [-r REV] NAME`.
6529 :hg:`revert [-r REV] NAME`.
6536
6530
6537 See :hg:`help dates` for a list of formats valid for -d/--date.
6531 See :hg:`help dates` for a list of formats valid for -d/--date.
6538
6532
6539 Returns 0 on success, 1 if there are unresolved files.
6533 Returns 0 on success, 1 if there are unresolved files.
6540 """
6534 """
6541 if rev and node:
6535 if rev and node:
6542 raise util.Abort(_("please specify just one revision"))
6536 raise util.Abort(_("please specify just one revision"))
6543
6537
6544 if rev is None or rev == '':
6538 if rev is None or rev == '':
6545 rev = node
6539 rev = node
6546
6540
6547 wlock = repo.wlock()
6541 wlock = repo.wlock()
6548 try:
6542 try:
6549 cmdutil.clearunfinished(repo)
6543 cmdutil.clearunfinished(repo)
6550
6544
6551 if date:
6545 if date:
6552 if rev is not None:
6546 if rev is not None:
6553 raise util.Abort(_("you can't specify a revision and a date"))
6547 raise util.Abort(_("you can't specify a revision and a date"))
6554 rev = cmdutil.finddate(ui, repo, date)
6548 rev = cmdutil.finddate(ui, repo, date)
6555
6549
6556 # with no argument, we also move the active bookmark, if any
6550 # with no argument, we also move the active bookmark, if any
6557 rev, movemarkfrom = bookmarks.calculateupdate(ui, repo, rev)
6551 rev, movemarkfrom = bookmarks.calculateupdate(ui, repo, rev)
6558
6552
6559 # if we defined a bookmark, we have to remember the original name
6553 # if we defined a bookmark, we have to remember the original name
6560 brev = rev
6554 brev = rev
6561 rev = scmutil.revsingle(repo, rev, rev).rev()
6555 rev = scmutil.revsingle(repo, rev, rev).rev()
6562
6556
6563 if check and clean:
6557 if check and clean:
6564 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
6558 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
6565
6559
6566 if check:
6560 if check:
6567 cmdutil.bailifchanged(repo, merge=False)
6561 cmdutil.bailifchanged(repo, merge=False)
6568 if rev is None:
6562 if rev is None:
6569 rev = repo[repo[None].branch()].rev()
6563 rev = repo[repo[None].branch()].rev()
6570
6564
6571 repo.ui.setconfig('ui', 'forcemerge', tool, 'update')
6565 repo.ui.setconfig('ui', 'forcemerge', tool, 'update')
6572
6566
6573 if clean:
6567 if clean:
6574 ret = hg.clean(repo, rev)
6568 ret = hg.clean(repo, rev)
6575 else:
6569 else:
6576 ret = hg.update(repo, rev)
6570 ret = hg.update(repo, rev)
6577
6571
6578 if not ret and movemarkfrom:
6572 if not ret and movemarkfrom:
6579 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
6573 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
6580 ui.status(_("updating bookmark %s\n") % repo._activebookmark)
6574 ui.status(_("updating bookmark %s\n") % repo._activebookmark)
6581 else:
6575 else:
6582 # this can happen with a non-linear update
6576 # this can happen with a non-linear update
6583 ui.status(_("(leaving bookmark %s)\n") %
6577 ui.status(_("(leaving bookmark %s)\n") %
6584 repo._activebookmark)
6578 repo._activebookmark)
6585 bookmarks.deactivate(repo)
6579 bookmarks.deactivate(repo)
6586 elif brev in repo._bookmarks:
6580 elif brev in repo._bookmarks:
6587 bookmarks.activate(repo, brev)
6581 bookmarks.activate(repo, brev)
6588 ui.status(_("(activating bookmark %s)\n") % brev)
6582 ui.status(_("(activating bookmark %s)\n") % brev)
6589 elif brev:
6583 elif brev:
6590 if repo._activebookmark:
6584 if repo._activebookmark:
6591 ui.status(_("(leaving bookmark %s)\n") %
6585 ui.status(_("(leaving bookmark %s)\n") %
6592 repo._activebookmark)
6586 repo._activebookmark)
6593 bookmarks.deactivate(repo)
6587 bookmarks.deactivate(repo)
6594 finally:
6588 finally:
6595 wlock.release()
6589 wlock.release()
6596
6590
6597 return ret
6591 return ret
6598
6592
6599 @command('verify', [])
6593 @command('verify', [])
6600 def verify(ui, repo):
6594 def verify(ui, repo):
6601 """verify the integrity of the repository
6595 """verify the integrity of the repository
6602
6596
6603 Verify the integrity of the current repository.
6597 Verify the integrity of the current repository.
6604
6598
6605 This will perform an extensive check of the repository's
6599 This will perform an extensive check of the repository's
6606 integrity, validating the hashes and checksums of each entry in
6600 integrity, validating the hashes and checksums of each entry in
6607 the changelog, manifest, and tracked files, as well as the
6601 the changelog, manifest, and tracked files, as well as the
6608 integrity of their crosslinks and indices.
6602 integrity of their crosslinks and indices.
6609
6603
6610 Please see https://mercurial-scm.org/wiki/RepositoryCorruption
6604 Please see https://mercurial-scm.org/wiki/RepositoryCorruption
6611 for more information about recovery from corruption of the
6605 for more information about recovery from corruption of the
6612 repository.
6606 repository.
6613
6607
6614 Returns 0 on success, 1 if errors are encountered.
6608 Returns 0 on success, 1 if errors are encountered.
6615 """
6609 """
6616 return hg.verify(repo)
6610 return hg.verify(repo)
6617
6611
6618 @command('version', [], norepo=True)
6612 @command('version', [], norepo=True)
6619 def version_(ui):
6613 def version_(ui):
6620 """output version and copyright information"""
6614 """output version and copyright information"""
6621 ui.write(_("Mercurial Distributed SCM (version %s)\n")
6615 ui.write(_("Mercurial Distributed SCM (version %s)\n")
6622 % util.version())
6616 % util.version())
6623 ui.status(_(
6617 ui.status(_(
6624 "(see https://mercurial-scm.org for more information)\n"
6618 "(see https://mercurial-scm.org for more information)\n"
6625 "\nCopyright (C) 2005-2015 Matt Mackall and others\n"
6619 "\nCopyright (C) 2005-2015 Matt Mackall and others\n"
6626 "This is free software; see the source for copying conditions. "
6620 "This is free software; see the source for copying conditions. "
6627 "There is NO\nwarranty; "
6621 "There is NO\nwarranty; "
6628 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
6622 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
6629 ))
6623 ))
6630
6624
6631 ui.note(_("\nEnabled extensions:\n\n"))
6625 ui.note(_("\nEnabled extensions:\n\n"))
6632 if ui.verbose:
6626 if ui.verbose:
6633 # format names and versions into columns
6627 # format names and versions into columns
6634 names = []
6628 names = []
6635 vers = []
6629 vers = []
6636 for name, module in extensions.extensions():
6630 for name, module in extensions.extensions():
6637 names.append(name)
6631 names.append(name)
6638 vers.append(extensions.moduleversion(module))
6632 vers.append(extensions.moduleversion(module))
6639 if names:
6633 if names:
6640 maxnamelen = max(len(n) for n in names)
6634 maxnamelen = max(len(n) for n in names)
6641 for i, name in enumerate(names):
6635 for i, name in enumerate(names):
6642 ui.write(" %-*s %s\n" % (maxnamelen, name, vers[i]))
6636 ui.write(" %-*s %s\n" % (maxnamelen, name, vers[i]))
General Comments 0
You need to be logged in to leave comments. Login now