##// END OF EJS Templates
revert: properly back up added files with local modification...
Pierre-Yves David -
r22611:2ff28e07 default
parent child Browse files
Show More
@@ -1,2889 +1,2893 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, nullid, nullrev, short
8 from node import hex, nullid, nullrev, short
9 from i18n import _
9 from i18n import _
10 import os, sys, errno, re, tempfile
10 import os, sys, errno, re, tempfile
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 context, repair, graphmod, revset, phases, obsolete, pathutil
13 import context, repair, graphmod, revset, phases, obsolete, pathutil
14 import changelog
14 import changelog
15 import bookmarks
15 import bookmarks
16 import encoding
16 import encoding
17 import lock as lockmod
17 import lock as lockmod
18
18
19 def parsealiases(cmd):
19 def parsealiases(cmd):
20 return cmd.lstrip("^").split("|")
20 return cmd.lstrip("^").split("|")
21
21
22 def findpossible(cmd, table, strict=False):
22 def findpossible(cmd, table, strict=False):
23 """
23 """
24 Return cmd -> (aliases, command table entry)
24 Return cmd -> (aliases, command table entry)
25 for each matching command.
25 for each matching command.
26 Return debug commands (or their aliases) only if no normal command matches.
26 Return debug commands (or their aliases) only if no normal command matches.
27 """
27 """
28 choice = {}
28 choice = {}
29 debugchoice = {}
29 debugchoice = {}
30
30
31 if cmd in table:
31 if cmd in table:
32 # short-circuit exact matches, "log" alias beats "^log|history"
32 # short-circuit exact matches, "log" alias beats "^log|history"
33 keys = [cmd]
33 keys = [cmd]
34 else:
34 else:
35 keys = table.keys()
35 keys = table.keys()
36
36
37 for e in keys:
37 for e in keys:
38 aliases = parsealiases(e)
38 aliases = parsealiases(e)
39 found = None
39 found = None
40 if cmd in aliases:
40 if cmd in aliases:
41 found = cmd
41 found = cmd
42 elif not strict:
42 elif not strict:
43 for a in aliases:
43 for a in aliases:
44 if a.startswith(cmd):
44 if a.startswith(cmd):
45 found = a
45 found = a
46 break
46 break
47 if found is not None:
47 if found is not None:
48 if aliases[0].startswith("debug") or found.startswith("debug"):
48 if aliases[0].startswith("debug") or found.startswith("debug"):
49 debugchoice[found] = (aliases, table[e])
49 debugchoice[found] = (aliases, table[e])
50 else:
50 else:
51 choice[found] = (aliases, table[e])
51 choice[found] = (aliases, table[e])
52
52
53 if not choice and debugchoice:
53 if not choice and debugchoice:
54 choice = debugchoice
54 choice = debugchoice
55
55
56 return choice
56 return choice
57
57
58 def findcmd(cmd, table, strict=True):
58 def findcmd(cmd, table, strict=True):
59 """Return (aliases, command table entry) for command string."""
59 """Return (aliases, command table entry) for command string."""
60 choice = findpossible(cmd, table, strict)
60 choice = findpossible(cmd, table, strict)
61
61
62 if cmd in choice:
62 if cmd in choice:
63 return choice[cmd]
63 return choice[cmd]
64
64
65 if len(choice) > 1:
65 if len(choice) > 1:
66 clist = choice.keys()
66 clist = choice.keys()
67 clist.sort()
67 clist.sort()
68 raise error.AmbiguousCommand(cmd, clist)
68 raise error.AmbiguousCommand(cmd, clist)
69
69
70 if choice:
70 if choice:
71 return choice.values()[0]
71 return choice.values()[0]
72
72
73 raise error.UnknownCommand(cmd)
73 raise error.UnknownCommand(cmd)
74
74
75 def findrepo(p):
75 def findrepo(p):
76 while not os.path.isdir(os.path.join(p, ".hg")):
76 while not os.path.isdir(os.path.join(p, ".hg")):
77 oldp, p = p, os.path.dirname(p)
77 oldp, p = p, os.path.dirname(p)
78 if p == oldp:
78 if p == oldp:
79 return None
79 return None
80
80
81 return p
81 return p
82
82
83 def bailifchanged(repo):
83 def bailifchanged(repo):
84 if repo.dirstate.p2() != nullid:
84 if repo.dirstate.p2() != nullid:
85 raise util.Abort(_('outstanding uncommitted merge'))
85 raise util.Abort(_('outstanding uncommitted merge'))
86 modified, added, removed, deleted = repo.status()[:4]
86 modified, added, removed, deleted = repo.status()[:4]
87 if modified or added or removed or deleted:
87 if modified or added or removed or deleted:
88 raise util.Abort(_('uncommitted changes'))
88 raise util.Abort(_('uncommitted changes'))
89 ctx = repo[None]
89 ctx = repo[None]
90 for s in sorted(ctx.substate):
90 for s in sorted(ctx.substate):
91 if ctx.sub(s).dirty():
91 if ctx.sub(s).dirty():
92 raise util.Abort(_("uncommitted changes in subrepo %s") % s)
92 raise util.Abort(_("uncommitted changes in subrepo %s") % s)
93
93
94 def logmessage(ui, opts):
94 def logmessage(ui, opts):
95 """ get the log message according to -m and -l option """
95 """ get the log message according to -m and -l option """
96 message = opts.get('message')
96 message = opts.get('message')
97 logfile = opts.get('logfile')
97 logfile = opts.get('logfile')
98
98
99 if message and logfile:
99 if message and logfile:
100 raise util.Abort(_('options --message and --logfile are mutually '
100 raise util.Abort(_('options --message and --logfile are mutually '
101 'exclusive'))
101 'exclusive'))
102 if not message and logfile:
102 if not message and logfile:
103 try:
103 try:
104 if logfile == '-':
104 if logfile == '-':
105 message = ui.fin.read()
105 message = ui.fin.read()
106 else:
106 else:
107 message = '\n'.join(util.readfile(logfile).splitlines())
107 message = '\n'.join(util.readfile(logfile).splitlines())
108 except IOError, inst:
108 except IOError, inst:
109 raise util.Abort(_("can't read commit message '%s': %s") %
109 raise util.Abort(_("can't read commit message '%s': %s") %
110 (logfile, inst.strerror))
110 (logfile, inst.strerror))
111 return message
111 return message
112
112
113 def mergeeditform(ctxorbool, baseform):
113 def mergeeditform(ctxorbool, baseform):
114 """build appropriate editform from ctxorbool and baseform
114 """build appropriate editform from ctxorbool and baseform
115
115
116 'cxtorbool' is one of a ctx to be committed, or a bool whether
116 'cxtorbool' is one of a ctx to be committed, or a bool whether
117 merging is committed.
117 merging is committed.
118
118
119 This returns editform 'baseform' with '.merge' if merging is
119 This returns editform 'baseform' with '.merge' if merging is
120 committed, or one with '.normal' suffix otherwise.
120 committed, or one with '.normal' suffix otherwise.
121 """
121 """
122 if isinstance(ctxorbool, bool):
122 if isinstance(ctxorbool, bool):
123 if ctxorbool:
123 if ctxorbool:
124 return baseform + ".merge"
124 return baseform + ".merge"
125 elif 1 < len(ctxorbool.parents()):
125 elif 1 < len(ctxorbool.parents()):
126 return baseform + ".merge"
126 return baseform + ".merge"
127
127
128 return baseform + ".normal"
128 return baseform + ".normal"
129
129
130 def getcommiteditor(edit=False, finishdesc=None, extramsg=None,
130 def getcommiteditor(edit=False, finishdesc=None, extramsg=None,
131 editform='', **opts):
131 editform='', **opts):
132 """get appropriate commit message editor according to '--edit' option
132 """get appropriate commit message editor according to '--edit' option
133
133
134 'finishdesc' is a function to be called with edited commit message
134 'finishdesc' is a function to be called with edited commit message
135 (= 'description' of the new changeset) just after editing, but
135 (= 'description' of the new changeset) just after editing, but
136 before checking empty-ness. It should return actual text to be
136 before checking empty-ness. It should return actual text to be
137 stored into history. This allows to change description before
137 stored into history. This allows to change description before
138 storing.
138 storing.
139
139
140 'extramsg' is a extra message to be shown in the editor instead of
140 'extramsg' is a extra message to be shown in the editor instead of
141 'Leave message empty to abort commit' line. 'HG: ' prefix and EOL
141 'Leave message empty to abort commit' line. 'HG: ' prefix and EOL
142 is automatically added.
142 is automatically added.
143
143
144 'editform' is a dot-separated list of names, to distinguish
144 'editform' is a dot-separated list of names, to distinguish
145 the purpose of commit text editing.
145 the purpose of commit text editing.
146
146
147 'getcommiteditor' returns 'commitforceeditor' regardless of
147 'getcommiteditor' returns 'commitforceeditor' regardless of
148 'edit', if one of 'finishdesc' or 'extramsg' is specified, because
148 'edit', if one of 'finishdesc' or 'extramsg' is specified, because
149 they are specific for usage in MQ.
149 they are specific for usage in MQ.
150 """
150 """
151 if edit or finishdesc or extramsg:
151 if edit or finishdesc or extramsg:
152 return lambda r, c, s: commitforceeditor(r, c, s,
152 return lambda r, c, s: commitforceeditor(r, c, s,
153 finishdesc=finishdesc,
153 finishdesc=finishdesc,
154 extramsg=extramsg,
154 extramsg=extramsg,
155 editform=editform)
155 editform=editform)
156 elif editform:
156 elif editform:
157 return lambda r, c, s: commiteditor(r, c, s, editform=editform)
157 return lambda r, c, s: commiteditor(r, c, s, editform=editform)
158 else:
158 else:
159 return commiteditor
159 return commiteditor
160
160
161 def loglimit(opts):
161 def loglimit(opts):
162 """get the log limit according to option -l/--limit"""
162 """get the log limit according to option -l/--limit"""
163 limit = opts.get('limit')
163 limit = opts.get('limit')
164 if limit:
164 if limit:
165 try:
165 try:
166 limit = int(limit)
166 limit = int(limit)
167 except ValueError:
167 except ValueError:
168 raise util.Abort(_('limit must be a positive integer'))
168 raise util.Abort(_('limit must be a positive integer'))
169 if limit <= 0:
169 if limit <= 0:
170 raise util.Abort(_('limit must be positive'))
170 raise util.Abort(_('limit must be positive'))
171 else:
171 else:
172 limit = None
172 limit = None
173 return limit
173 return limit
174
174
175 def makefilename(repo, pat, node, desc=None,
175 def makefilename(repo, pat, node, desc=None,
176 total=None, seqno=None, revwidth=None, pathname=None):
176 total=None, seqno=None, revwidth=None, pathname=None):
177 node_expander = {
177 node_expander = {
178 'H': lambda: hex(node),
178 'H': lambda: hex(node),
179 'R': lambda: str(repo.changelog.rev(node)),
179 'R': lambda: str(repo.changelog.rev(node)),
180 'h': lambda: short(node),
180 'h': lambda: short(node),
181 'm': lambda: re.sub('[^\w]', '_', str(desc))
181 'm': lambda: re.sub('[^\w]', '_', str(desc))
182 }
182 }
183 expander = {
183 expander = {
184 '%': lambda: '%',
184 '%': lambda: '%',
185 'b': lambda: os.path.basename(repo.root),
185 'b': lambda: os.path.basename(repo.root),
186 }
186 }
187
187
188 try:
188 try:
189 if node:
189 if node:
190 expander.update(node_expander)
190 expander.update(node_expander)
191 if node:
191 if node:
192 expander['r'] = (lambda:
192 expander['r'] = (lambda:
193 str(repo.changelog.rev(node)).zfill(revwidth or 0))
193 str(repo.changelog.rev(node)).zfill(revwidth or 0))
194 if total is not None:
194 if total is not None:
195 expander['N'] = lambda: str(total)
195 expander['N'] = lambda: str(total)
196 if seqno is not None:
196 if seqno is not None:
197 expander['n'] = lambda: str(seqno)
197 expander['n'] = lambda: str(seqno)
198 if total is not None and seqno is not None:
198 if total is not None and seqno is not None:
199 expander['n'] = lambda: str(seqno).zfill(len(str(total)))
199 expander['n'] = lambda: str(seqno).zfill(len(str(total)))
200 if pathname is not None:
200 if pathname is not None:
201 expander['s'] = lambda: os.path.basename(pathname)
201 expander['s'] = lambda: os.path.basename(pathname)
202 expander['d'] = lambda: os.path.dirname(pathname) or '.'
202 expander['d'] = lambda: os.path.dirname(pathname) or '.'
203 expander['p'] = lambda: pathname
203 expander['p'] = lambda: pathname
204
204
205 newname = []
205 newname = []
206 patlen = len(pat)
206 patlen = len(pat)
207 i = 0
207 i = 0
208 while i < patlen:
208 while i < patlen:
209 c = pat[i]
209 c = pat[i]
210 if c == '%':
210 if c == '%':
211 i += 1
211 i += 1
212 c = pat[i]
212 c = pat[i]
213 c = expander[c]()
213 c = expander[c]()
214 newname.append(c)
214 newname.append(c)
215 i += 1
215 i += 1
216 return ''.join(newname)
216 return ''.join(newname)
217 except KeyError, inst:
217 except KeyError, inst:
218 raise util.Abort(_("invalid format spec '%%%s' in output filename") %
218 raise util.Abort(_("invalid format spec '%%%s' in output filename") %
219 inst.args[0])
219 inst.args[0])
220
220
221 def makefileobj(repo, pat, node=None, desc=None, total=None,
221 def makefileobj(repo, pat, node=None, desc=None, total=None,
222 seqno=None, revwidth=None, mode='wb', modemap=None,
222 seqno=None, revwidth=None, mode='wb', modemap=None,
223 pathname=None):
223 pathname=None):
224
224
225 writable = mode not in ('r', 'rb')
225 writable = mode not in ('r', 'rb')
226
226
227 if not pat or pat == '-':
227 if not pat or pat == '-':
228 fp = writable and repo.ui.fout or repo.ui.fin
228 fp = writable and repo.ui.fout or repo.ui.fin
229 if util.safehasattr(fp, 'fileno'):
229 if util.safehasattr(fp, 'fileno'):
230 return os.fdopen(os.dup(fp.fileno()), mode)
230 return os.fdopen(os.dup(fp.fileno()), mode)
231 else:
231 else:
232 # if this fp can't be duped properly, return
232 # if this fp can't be duped properly, return
233 # a dummy object that can be closed
233 # a dummy object that can be closed
234 class wrappedfileobj(object):
234 class wrappedfileobj(object):
235 noop = lambda x: None
235 noop = lambda x: None
236 def __init__(self, f):
236 def __init__(self, f):
237 self.f = f
237 self.f = f
238 def __getattr__(self, attr):
238 def __getattr__(self, attr):
239 if attr == 'close':
239 if attr == 'close':
240 return self.noop
240 return self.noop
241 else:
241 else:
242 return getattr(self.f, attr)
242 return getattr(self.f, attr)
243
243
244 return wrappedfileobj(fp)
244 return wrappedfileobj(fp)
245 if util.safehasattr(pat, 'write') and writable:
245 if util.safehasattr(pat, 'write') and writable:
246 return pat
246 return pat
247 if util.safehasattr(pat, 'read') and 'r' in mode:
247 if util.safehasattr(pat, 'read') and 'r' in mode:
248 return pat
248 return pat
249 fn = makefilename(repo, pat, node, desc, total, seqno, revwidth, pathname)
249 fn = makefilename(repo, pat, node, desc, total, seqno, revwidth, pathname)
250 if modemap is not None:
250 if modemap is not None:
251 mode = modemap.get(fn, mode)
251 mode = modemap.get(fn, mode)
252 if mode == 'wb':
252 if mode == 'wb':
253 modemap[fn] = 'ab'
253 modemap[fn] = 'ab'
254 return open(fn, mode)
254 return open(fn, mode)
255
255
256 def openrevlog(repo, cmd, file_, opts):
256 def openrevlog(repo, cmd, file_, opts):
257 """opens the changelog, manifest, a filelog or a given revlog"""
257 """opens the changelog, manifest, a filelog or a given revlog"""
258 cl = opts['changelog']
258 cl = opts['changelog']
259 mf = opts['manifest']
259 mf = opts['manifest']
260 msg = None
260 msg = None
261 if cl and mf:
261 if cl and mf:
262 msg = _('cannot specify --changelog and --manifest at the same time')
262 msg = _('cannot specify --changelog and --manifest at the same time')
263 elif cl or mf:
263 elif cl or mf:
264 if file_:
264 if file_:
265 msg = _('cannot specify filename with --changelog or --manifest')
265 msg = _('cannot specify filename with --changelog or --manifest')
266 elif not repo:
266 elif not repo:
267 msg = _('cannot specify --changelog or --manifest '
267 msg = _('cannot specify --changelog or --manifest '
268 'without a repository')
268 'without a repository')
269 if msg:
269 if msg:
270 raise util.Abort(msg)
270 raise util.Abort(msg)
271
271
272 r = None
272 r = None
273 if repo:
273 if repo:
274 if cl:
274 if cl:
275 r = repo.unfiltered().changelog
275 r = repo.unfiltered().changelog
276 elif mf:
276 elif mf:
277 r = repo.manifest
277 r = repo.manifest
278 elif file_:
278 elif file_:
279 filelog = repo.file(file_)
279 filelog = repo.file(file_)
280 if len(filelog):
280 if len(filelog):
281 r = filelog
281 r = filelog
282 if not r:
282 if not r:
283 if not file_:
283 if not file_:
284 raise error.CommandError(cmd, _('invalid arguments'))
284 raise error.CommandError(cmd, _('invalid arguments'))
285 if not os.path.isfile(file_):
285 if not os.path.isfile(file_):
286 raise util.Abort(_("revlog '%s' not found") % file_)
286 raise util.Abort(_("revlog '%s' not found") % file_)
287 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False),
287 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False),
288 file_[:-2] + ".i")
288 file_[:-2] + ".i")
289 return r
289 return r
290
290
291 def copy(ui, repo, pats, opts, rename=False):
291 def copy(ui, repo, pats, opts, rename=False):
292 # called with the repo lock held
292 # called with the repo lock held
293 #
293 #
294 # hgsep => pathname that uses "/" to separate directories
294 # hgsep => pathname that uses "/" to separate directories
295 # ossep => pathname that uses os.sep to separate directories
295 # ossep => pathname that uses os.sep to separate directories
296 cwd = repo.getcwd()
296 cwd = repo.getcwd()
297 targets = {}
297 targets = {}
298 after = opts.get("after")
298 after = opts.get("after")
299 dryrun = opts.get("dry_run")
299 dryrun = opts.get("dry_run")
300 wctx = repo[None]
300 wctx = repo[None]
301
301
302 def walkpat(pat):
302 def walkpat(pat):
303 srcs = []
303 srcs = []
304 badstates = after and '?' or '?r'
304 badstates = after and '?' or '?r'
305 m = scmutil.match(repo[None], [pat], opts, globbed=True)
305 m = scmutil.match(repo[None], [pat], opts, globbed=True)
306 for abs in repo.walk(m):
306 for abs in repo.walk(m):
307 state = repo.dirstate[abs]
307 state = repo.dirstate[abs]
308 rel = m.rel(abs)
308 rel = m.rel(abs)
309 exact = m.exact(abs)
309 exact = m.exact(abs)
310 if state in badstates:
310 if state in badstates:
311 if exact and state == '?':
311 if exact and state == '?':
312 ui.warn(_('%s: not copying - file is not managed\n') % rel)
312 ui.warn(_('%s: not copying - file is not managed\n') % rel)
313 if exact and state == 'r':
313 if exact and state == 'r':
314 ui.warn(_('%s: not copying - file has been marked for'
314 ui.warn(_('%s: not copying - file has been marked for'
315 ' remove\n') % rel)
315 ' remove\n') % rel)
316 continue
316 continue
317 # abs: hgsep
317 # abs: hgsep
318 # rel: ossep
318 # rel: ossep
319 srcs.append((abs, rel, exact))
319 srcs.append((abs, rel, exact))
320 return srcs
320 return srcs
321
321
322 # abssrc: hgsep
322 # abssrc: hgsep
323 # relsrc: ossep
323 # relsrc: ossep
324 # otarget: ossep
324 # otarget: ossep
325 def copyfile(abssrc, relsrc, otarget, exact):
325 def copyfile(abssrc, relsrc, otarget, exact):
326 abstarget = pathutil.canonpath(repo.root, cwd, otarget)
326 abstarget = pathutil.canonpath(repo.root, cwd, otarget)
327 if '/' in abstarget:
327 if '/' in abstarget:
328 # We cannot normalize abstarget itself, this would prevent
328 # We cannot normalize abstarget itself, this would prevent
329 # case only renames, like a => A.
329 # case only renames, like a => A.
330 abspath, absname = abstarget.rsplit('/', 1)
330 abspath, absname = abstarget.rsplit('/', 1)
331 abstarget = repo.dirstate.normalize(abspath) + '/' + absname
331 abstarget = repo.dirstate.normalize(abspath) + '/' + absname
332 reltarget = repo.pathto(abstarget, cwd)
332 reltarget = repo.pathto(abstarget, cwd)
333 target = repo.wjoin(abstarget)
333 target = repo.wjoin(abstarget)
334 src = repo.wjoin(abssrc)
334 src = repo.wjoin(abssrc)
335 state = repo.dirstate[abstarget]
335 state = repo.dirstate[abstarget]
336
336
337 scmutil.checkportable(ui, abstarget)
337 scmutil.checkportable(ui, abstarget)
338
338
339 # check for collisions
339 # check for collisions
340 prevsrc = targets.get(abstarget)
340 prevsrc = targets.get(abstarget)
341 if prevsrc is not None:
341 if prevsrc is not None:
342 ui.warn(_('%s: not overwriting - %s collides with %s\n') %
342 ui.warn(_('%s: not overwriting - %s collides with %s\n') %
343 (reltarget, repo.pathto(abssrc, cwd),
343 (reltarget, repo.pathto(abssrc, cwd),
344 repo.pathto(prevsrc, cwd)))
344 repo.pathto(prevsrc, cwd)))
345 return
345 return
346
346
347 # check for overwrites
347 # check for overwrites
348 exists = os.path.lexists(target)
348 exists = os.path.lexists(target)
349 samefile = False
349 samefile = False
350 if exists and abssrc != abstarget:
350 if exists and abssrc != abstarget:
351 if (repo.dirstate.normalize(abssrc) ==
351 if (repo.dirstate.normalize(abssrc) ==
352 repo.dirstate.normalize(abstarget)):
352 repo.dirstate.normalize(abstarget)):
353 if not rename:
353 if not rename:
354 ui.warn(_("%s: can't copy - same file\n") % reltarget)
354 ui.warn(_("%s: can't copy - same file\n") % reltarget)
355 return
355 return
356 exists = False
356 exists = False
357 samefile = True
357 samefile = True
358
358
359 if not after and exists or after and state in 'mn':
359 if not after and exists or after and state in 'mn':
360 if not opts['force']:
360 if not opts['force']:
361 ui.warn(_('%s: not overwriting - file exists\n') %
361 ui.warn(_('%s: not overwriting - file exists\n') %
362 reltarget)
362 reltarget)
363 return
363 return
364
364
365 if after:
365 if after:
366 if not exists:
366 if not exists:
367 if rename:
367 if rename:
368 ui.warn(_('%s: not recording move - %s does not exist\n') %
368 ui.warn(_('%s: not recording move - %s does not exist\n') %
369 (relsrc, reltarget))
369 (relsrc, reltarget))
370 else:
370 else:
371 ui.warn(_('%s: not recording copy - %s does not exist\n') %
371 ui.warn(_('%s: not recording copy - %s does not exist\n') %
372 (relsrc, reltarget))
372 (relsrc, reltarget))
373 return
373 return
374 elif not dryrun:
374 elif not dryrun:
375 try:
375 try:
376 if exists:
376 if exists:
377 os.unlink(target)
377 os.unlink(target)
378 targetdir = os.path.dirname(target) or '.'
378 targetdir = os.path.dirname(target) or '.'
379 if not os.path.isdir(targetdir):
379 if not os.path.isdir(targetdir):
380 os.makedirs(targetdir)
380 os.makedirs(targetdir)
381 if samefile:
381 if samefile:
382 tmp = target + "~hgrename"
382 tmp = target + "~hgrename"
383 os.rename(src, tmp)
383 os.rename(src, tmp)
384 os.rename(tmp, target)
384 os.rename(tmp, target)
385 else:
385 else:
386 util.copyfile(src, target)
386 util.copyfile(src, target)
387 srcexists = True
387 srcexists = True
388 except IOError, inst:
388 except IOError, inst:
389 if inst.errno == errno.ENOENT:
389 if inst.errno == errno.ENOENT:
390 ui.warn(_('%s: deleted in working copy\n') % relsrc)
390 ui.warn(_('%s: deleted in working copy\n') % relsrc)
391 srcexists = False
391 srcexists = False
392 else:
392 else:
393 ui.warn(_('%s: cannot copy - %s\n') %
393 ui.warn(_('%s: cannot copy - %s\n') %
394 (relsrc, inst.strerror))
394 (relsrc, inst.strerror))
395 return True # report a failure
395 return True # report a failure
396
396
397 if ui.verbose or not exact:
397 if ui.verbose or not exact:
398 if rename:
398 if rename:
399 ui.status(_('moving %s to %s\n') % (relsrc, reltarget))
399 ui.status(_('moving %s to %s\n') % (relsrc, reltarget))
400 else:
400 else:
401 ui.status(_('copying %s to %s\n') % (relsrc, reltarget))
401 ui.status(_('copying %s to %s\n') % (relsrc, reltarget))
402
402
403 targets[abstarget] = abssrc
403 targets[abstarget] = abssrc
404
404
405 # fix up dirstate
405 # fix up dirstate
406 scmutil.dirstatecopy(ui, repo, wctx, abssrc, abstarget,
406 scmutil.dirstatecopy(ui, repo, wctx, abssrc, abstarget,
407 dryrun=dryrun, cwd=cwd)
407 dryrun=dryrun, cwd=cwd)
408 if rename and not dryrun:
408 if rename and not dryrun:
409 if not after and srcexists and not samefile:
409 if not after and srcexists and not samefile:
410 util.unlinkpath(repo.wjoin(abssrc))
410 util.unlinkpath(repo.wjoin(abssrc))
411 wctx.forget([abssrc])
411 wctx.forget([abssrc])
412
412
413 # pat: ossep
413 # pat: ossep
414 # dest ossep
414 # dest ossep
415 # srcs: list of (hgsep, hgsep, ossep, bool)
415 # srcs: list of (hgsep, hgsep, ossep, bool)
416 # return: function that takes hgsep and returns ossep
416 # return: function that takes hgsep and returns ossep
417 def targetpathfn(pat, dest, srcs):
417 def targetpathfn(pat, dest, srcs):
418 if os.path.isdir(pat):
418 if os.path.isdir(pat):
419 abspfx = pathutil.canonpath(repo.root, cwd, pat)
419 abspfx = pathutil.canonpath(repo.root, cwd, pat)
420 abspfx = util.localpath(abspfx)
420 abspfx = util.localpath(abspfx)
421 if destdirexists:
421 if destdirexists:
422 striplen = len(os.path.split(abspfx)[0])
422 striplen = len(os.path.split(abspfx)[0])
423 else:
423 else:
424 striplen = len(abspfx)
424 striplen = len(abspfx)
425 if striplen:
425 if striplen:
426 striplen += len(os.sep)
426 striplen += len(os.sep)
427 res = lambda p: os.path.join(dest, util.localpath(p)[striplen:])
427 res = lambda p: os.path.join(dest, util.localpath(p)[striplen:])
428 elif destdirexists:
428 elif destdirexists:
429 res = lambda p: os.path.join(dest,
429 res = lambda p: os.path.join(dest,
430 os.path.basename(util.localpath(p)))
430 os.path.basename(util.localpath(p)))
431 else:
431 else:
432 res = lambda p: dest
432 res = lambda p: dest
433 return res
433 return res
434
434
435 # pat: ossep
435 # pat: ossep
436 # dest ossep
436 # dest ossep
437 # srcs: list of (hgsep, hgsep, ossep, bool)
437 # srcs: list of (hgsep, hgsep, ossep, bool)
438 # return: function that takes hgsep and returns ossep
438 # return: function that takes hgsep and returns ossep
439 def targetpathafterfn(pat, dest, srcs):
439 def targetpathafterfn(pat, dest, srcs):
440 if matchmod.patkind(pat):
440 if matchmod.patkind(pat):
441 # a mercurial pattern
441 # a mercurial pattern
442 res = lambda p: os.path.join(dest,
442 res = lambda p: os.path.join(dest,
443 os.path.basename(util.localpath(p)))
443 os.path.basename(util.localpath(p)))
444 else:
444 else:
445 abspfx = pathutil.canonpath(repo.root, cwd, pat)
445 abspfx = pathutil.canonpath(repo.root, cwd, pat)
446 if len(abspfx) < len(srcs[0][0]):
446 if len(abspfx) < len(srcs[0][0]):
447 # A directory. Either the target path contains the last
447 # A directory. Either the target path contains the last
448 # component of the source path or it does not.
448 # component of the source path or it does not.
449 def evalpath(striplen):
449 def evalpath(striplen):
450 score = 0
450 score = 0
451 for s in srcs:
451 for s in srcs:
452 t = os.path.join(dest, util.localpath(s[0])[striplen:])
452 t = os.path.join(dest, util.localpath(s[0])[striplen:])
453 if os.path.lexists(t):
453 if os.path.lexists(t):
454 score += 1
454 score += 1
455 return score
455 return score
456
456
457 abspfx = util.localpath(abspfx)
457 abspfx = util.localpath(abspfx)
458 striplen = len(abspfx)
458 striplen = len(abspfx)
459 if striplen:
459 if striplen:
460 striplen += len(os.sep)
460 striplen += len(os.sep)
461 if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])):
461 if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])):
462 score = evalpath(striplen)
462 score = evalpath(striplen)
463 striplen1 = len(os.path.split(abspfx)[0])
463 striplen1 = len(os.path.split(abspfx)[0])
464 if striplen1:
464 if striplen1:
465 striplen1 += len(os.sep)
465 striplen1 += len(os.sep)
466 if evalpath(striplen1) > score:
466 if evalpath(striplen1) > score:
467 striplen = striplen1
467 striplen = striplen1
468 res = lambda p: os.path.join(dest,
468 res = lambda p: os.path.join(dest,
469 util.localpath(p)[striplen:])
469 util.localpath(p)[striplen:])
470 else:
470 else:
471 # a file
471 # a file
472 if destdirexists:
472 if destdirexists:
473 res = lambda p: os.path.join(dest,
473 res = lambda p: os.path.join(dest,
474 os.path.basename(util.localpath(p)))
474 os.path.basename(util.localpath(p)))
475 else:
475 else:
476 res = lambda p: dest
476 res = lambda p: dest
477 return res
477 return res
478
478
479
479
480 pats = scmutil.expandpats(pats)
480 pats = scmutil.expandpats(pats)
481 if not pats:
481 if not pats:
482 raise util.Abort(_('no source or destination specified'))
482 raise util.Abort(_('no source or destination specified'))
483 if len(pats) == 1:
483 if len(pats) == 1:
484 raise util.Abort(_('no destination specified'))
484 raise util.Abort(_('no destination specified'))
485 dest = pats.pop()
485 dest = pats.pop()
486 destdirexists = os.path.isdir(dest) and not os.path.islink(dest)
486 destdirexists = os.path.isdir(dest) and not os.path.islink(dest)
487 if not destdirexists:
487 if not destdirexists:
488 if len(pats) > 1 or matchmod.patkind(pats[0]):
488 if len(pats) > 1 or matchmod.patkind(pats[0]):
489 raise util.Abort(_('with multiple sources, destination must be an '
489 raise util.Abort(_('with multiple sources, destination must be an '
490 'existing directory'))
490 'existing directory'))
491 if util.endswithsep(dest):
491 if util.endswithsep(dest):
492 raise util.Abort(_('destination %s is not a directory') % dest)
492 raise util.Abort(_('destination %s is not a directory') % dest)
493
493
494 tfn = targetpathfn
494 tfn = targetpathfn
495 if after:
495 if after:
496 tfn = targetpathafterfn
496 tfn = targetpathafterfn
497 copylist = []
497 copylist = []
498 for pat in pats:
498 for pat in pats:
499 srcs = walkpat(pat)
499 srcs = walkpat(pat)
500 if not srcs:
500 if not srcs:
501 continue
501 continue
502 copylist.append((tfn(pat, dest, srcs), srcs))
502 copylist.append((tfn(pat, dest, srcs), srcs))
503 if not copylist:
503 if not copylist:
504 raise util.Abort(_('no files to copy'))
504 raise util.Abort(_('no files to copy'))
505
505
506 errors = 0
506 errors = 0
507 for targetpath, srcs in copylist:
507 for targetpath, srcs in copylist:
508 for abssrc, relsrc, exact in srcs:
508 for abssrc, relsrc, exact in srcs:
509 if copyfile(abssrc, relsrc, targetpath(abssrc), exact):
509 if copyfile(abssrc, relsrc, targetpath(abssrc), exact):
510 errors += 1
510 errors += 1
511
511
512 if errors:
512 if errors:
513 ui.warn(_('(consider using --after)\n'))
513 ui.warn(_('(consider using --after)\n'))
514
514
515 return errors != 0
515 return errors != 0
516
516
517 def service(opts, parentfn=None, initfn=None, runfn=None, logfile=None,
517 def service(opts, parentfn=None, initfn=None, runfn=None, logfile=None,
518 runargs=None, appendpid=False):
518 runargs=None, appendpid=False):
519 '''Run a command as a service.'''
519 '''Run a command as a service.'''
520
520
521 def writepid(pid):
521 def writepid(pid):
522 if opts['pid_file']:
522 if opts['pid_file']:
523 mode = appendpid and 'a' or 'w'
523 mode = appendpid and 'a' or 'w'
524 fp = open(opts['pid_file'], mode)
524 fp = open(opts['pid_file'], mode)
525 fp.write(str(pid) + '\n')
525 fp.write(str(pid) + '\n')
526 fp.close()
526 fp.close()
527
527
528 if opts['daemon'] and not opts['daemon_pipefds']:
528 if opts['daemon'] and not opts['daemon_pipefds']:
529 # Signal child process startup with file removal
529 # Signal child process startup with file removal
530 lockfd, lockpath = tempfile.mkstemp(prefix='hg-service-')
530 lockfd, lockpath = tempfile.mkstemp(prefix='hg-service-')
531 os.close(lockfd)
531 os.close(lockfd)
532 try:
532 try:
533 if not runargs:
533 if not runargs:
534 runargs = util.hgcmd() + sys.argv[1:]
534 runargs = util.hgcmd() + sys.argv[1:]
535 runargs.append('--daemon-pipefds=%s' % lockpath)
535 runargs.append('--daemon-pipefds=%s' % lockpath)
536 # Don't pass --cwd to the child process, because we've already
536 # Don't pass --cwd to the child process, because we've already
537 # changed directory.
537 # changed directory.
538 for i in xrange(1, len(runargs)):
538 for i in xrange(1, len(runargs)):
539 if runargs[i].startswith('--cwd='):
539 if runargs[i].startswith('--cwd='):
540 del runargs[i]
540 del runargs[i]
541 break
541 break
542 elif runargs[i].startswith('--cwd'):
542 elif runargs[i].startswith('--cwd'):
543 del runargs[i:i + 2]
543 del runargs[i:i + 2]
544 break
544 break
545 def condfn():
545 def condfn():
546 return not os.path.exists(lockpath)
546 return not os.path.exists(lockpath)
547 pid = util.rundetached(runargs, condfn)
547 pid = util.rundetached(runargs, condfn)
548 if pid < 0:
548 if pid < 0:
549 raise util.Abort(_('child process failed to start'))
549 raise util.Abort(_('child process failed to start'))
550 writepid(pid)
550 writepid(pid)
551 finally:
551 finally:
552 try:
552 try:
553 os.unlink(lockpath)
553 os.unlink(lockpath)
554 except OSError, e:
554 except OSError, e:
555 if e.errno != errno.ENOENT:
555 if e.errno != errno.ENOENT:
556 raise
556 raise
557 if parentfn:
557 if parentfn:
558 return parentfn(pid)
558 return parentfn(pid)
559 else:
559 else:
560 return
560 return
561
561
562 if initfn:
562 if initfn:
563 initfn()
563 initfn()
564
564
565 if not opts['daemon']:
565 if not opts['daemon']:
566 writepid(os.getpid())
566 writepid(os.getpid())
567
567
568 if opts['daemon_pipefds']:
568 if opts['daemon_pipefds']:
569 lockpath = opts['daemon_pipefds']
569 lockpath = opts['daemon_pipefds']
570 try:
570 try:
571 os.setsid()
571 os.setsid()
572 except AttributeError:
572 except AttributeError:
573 pass
573 pass
574 os.unlink(lockpath)
574 os.unlink(lockpath)
575 util.hidewindow()
575 util.hidewindow()
576 sys.stdout.flush()
576 sys.stdout.flush()
577 sys.stderr.flush()
577 sys.stderr.flush()
578
578
579 nullfd = os.open(os.devnull, os.O_RDWR)
579 nullfd = os.open(os.devnull, os.O_RDWR)
580 logfilefd = nullfd
580 logfilefd = nullfd
581 if logfile:
581 if logfile:
582 logfilefd = os.open(logfile, os.O_RDWR | os.O_CREAT | os.O_APPEND)
582 logfilefd = os.open(logfile, os.O_RDWR | os.O_CREAT | os.O_APPEND)
583 os.dup2(nullfd, 0)
583 os.dup2(nullfd, 0)
584 os.dup2(logfilefd, 1)
584 os.dup2(logfilefd, 1)
585 os.dup2(logfilefd, 2)
585 os.dup2(logfilefd, 2)
586 if nullfd not in (0, 1, 2):
586 if nullfd not in (0, 1, 2):
587 os.close(nullfd)
587 os.close(nullfd)
588 if logfile and logfilefd not in (0, 1, 2):
588 if logfile and logfilefd not in (0, 1, 2):
589 os.close(logfilefd)
589 os.close(logfilefd)
590
590
591 if runfn:
591 if runfn:
592 return runfn()
592 return runfn()
593
593
594 def tryimportone(ui, repo, hunk, parents, opts, msgs, updatefunc):
594 def tryimportone(ui, repo, hunk, parents, opts, msgs, updatefunc):
595 """Utility function used by commands.import to import a single patch
595 """Utility function used by commands.import to import a single patch
596
596
597 This function is explicitly defined here to help the evolve extension to
597 This function is explicitly defined here to help the evolve extension to
598 wrap this part of the import logic.
598 wrap this part of the import logic.
599
599
600 The API is currently a bit ugly because it a simple code translation from
600 The API is currently a bit ugly because it a simple code translation from
601 the import command. Feel free to make it better.
601 the import command. Feel free to make it better.
602
602
603 :hunk: a patch (as a binary string)
603 :hunk: a patch (as a binary string)
604 :parents: nodes that will be parent of the created commit
604 :parents: nodes that will be parent of the created commit
605 :opts: the full dict of option passed to the import command
605 :opts: the full dict of option passed to the import command
606 :msgs: list to save commit message to.
606 :msgs: list to save commit message to.
607 (used in case we need to save it when failing)
607 (used in case we need to save it when failing)
608 :updatefunc: a function that update a repo to a given node
608 :updatefunc: a function that update a repo to a given node
609 updatefunc(<repo>, <node>)
609 updatefunc(<repo>, <node>)
610 """
610 """
611 tmpname, message, user, date, branch, nodeid, p1, p2 = \
611 tmpname, message, user, date, branch, nodeid, p1, p2 = \
612 patch.extract(ui, hunk)
612 patch.extract(ui, hunk)
613
613
614 update = not opts.get('bypass')
614 update = not opts.get('bypass')
615 strip = opts["strip"]
615 strip = opts["strip"]
616 sim = float(opts.get('similarity') or 0)
616 sim = float(opts.get('similarity') or 0)
617 if not tmpname:
617 if not tmpname:
618 return (None, None, False)
618 return (None, None, False)
619 msg = _('applied to working directory')
619 msg = _('applied to working directory')
620
620
621 rejects = False
621 rejects = False
622
622
623 try:
623 try:
624 cmdline_message = logmessage(ui, opts)
624 cmdline_message = logmessage(ui, opts)
625 if cmdline_message:
625 if cmdline_message:
626 # pickup the cmdline msg
626 # pickup the cmdline msg
627 message = cmdline_message
627 message = cmdline_message
628 elif message:
628 elif message:
629 # pickup the patch msg
629 # pickup the patch msg
630 message = message.strip()
630 message = message.strip()
631 else:
631 else:
632 # launch the editor
632 # launch the editor
633 message = None
633 message = None
634 ui.debug('message:\n%s\n' % message)
634 ui.debug('message:\n%s\n' % message)
635
635
636 if len(parents) == 1:
636 if len(parents) == 1:
637 parents.append(repo[nullid])
637 parents.append(repo[nullid])
638 if opts.get('exact'):
638 if opts.get('exact'):
639 if not nodeid or not p1:
639 if not nodeid or not p1:
640 raise util.Abort(_('not a Mercurial patch'))
640 raise util.Abort(_('not a Mercurial patch'))
641 p1 = repo[p1]
641 p1 = repo[p1]
642 p2 = repo[p2 or nullid]
642 p2 = repo[p2 or nullid]
643 elif p2:
643 elif p2:
644 try:
644 try:
645 p1 = repo[p1]
645 p1 = repo[p1]
646 p2 = repo[p2]
646 p2 = repo[p2]
647 # Without any options, consider p2 only if the
647 # Without any options, consider p2 only if the
648 # patch is being applied on top of the recorded
648 # patch is being applied on top of the recorded
649 # first parent.
649 # first parent.
650 if p1 != parents[0]:
650 if p1 != parents[0]:
651 p1 = parents[0]
651 p1 = parents[0]
652 p2 = repo[nullid]
652 p2 = repo[nullid]
653 except error.RepoError:
653 except error.RepoError:
654 p1, p2 = parents
654 p1, p2 = parents
655 if p2.node() == nullid:
655 if p2.node() == nullid:
656 ui.warn(_("warning: import the patch as a normal revision\n"
656 ui.warn(_("warning: import the patch as a normal revision\n"
657 "(use --exact to import the patch as a merge)\n"))
657 "(use --exact to import the patch as a merge)\n"))
658 else:
658 else:
659 p1, p2 = parents
659 p1, p2 = parents
660
660
661 n = None
661 n = None
662 if update:
662 if update:
663 repo.dirstate.beginparentchange()
663 repo.dirstate.beginparentchange()
664 if p1 != parents[0]:
664 if p1 != parents[0]:
665 updatefunc(repo, p1.node())
665 updatefunc(repo, p1.node())
666 if p2 != parents[1]:
666 if p2 != parents[1]:
667 repo.setparents(p1.node(), p2.node())
667 repo.setparents(p1.node(), p2.node())
668
668
669 if opts.get('exact') or opts.get('import_branch'):
669 if opts.get('exact') or opts.get('import_branch'):
670 repo.dirstate.setbranch(branch or 'default')
670 repo.dirstate.setbranch(branch or 'default')
671
671
672 partial = opts.get('partial', False)
672 partial = opts.get('partial', False)
673 files = set()
673 files = set()
674 try:
674 try:
675 patch.patch(ui, repo, tmpname, strip=strip, files=files,
675 patch.patch(ui, repo, tmpname, strip=strip, files=files,
676 eolmode=None, similarity=sim / 100.0)
676 eolmode=None, similarity=sim / 100.0)
677 except patch.PatchError, e:
677 except patch.PatchError, e:
678 if not partial:
678 if not partial:
679 raise util.Abort(str(e))
679 raise util.Abort(str(e))
680 if partial:
680 if partial:
681 rejects = True
681 rejects = True
682
682
683 files = list(files)
683 files = list(files)
684 if opts.get('no_commit'):
684 if opts.get('no_commit'):
685 if message:
685 if message:
686 msgs.append(message)
686 msgs.append(message)
687 else:
687 else:
688 if opts.get('exact') or p2:
688 if opts.get('exact') or p2:
689 # If you got here, you either use --force and know what
689 # If you got here, you either use --force and know what
690 # you are doing or used --exact or a merge patch while
690 # you are doing or used --exact or a merge patch while
691 # being updated to its first parent.
691 # being updated to its first parent.
692 m = None
692 m = None
693 else:
693 else:
694 m = scmutil.matchfiles(repo, files or [])
694 m = scmutil.matchfiles(repo, files or [])
695 editform = mergeeditform(repo[None], 'import.normal')
695 editform = mergeeditform(repo[None], 'import.normal')
696 if opts.get('exact'):
696 if opts.get('exact'):
697 editor = None
697 editor = None
698 else:
698 else:
699 editor = getcommiteditor(editform=editform, **opts)
699 editor = getcommiteditor(editform=editform, **opts)
700 n = repo.commit(message, opts.get('user') or user,
700 n = repo.commit(message, opts.get('user') or user,
701 opts.get('date') or date, match=m,
701 opts.get('date') or date, match=m,
702 editor=editor, force=partial)
702 editor=editor, force=partial)
703 repo.dirstate.endparentchange()
703 repo.dirstate.endparentchange()
704 else:
704 else:
705 if opts.get('exact') or opts.get('import_branch'):
705 if opts.get('exact') or opts.get('import_branch'):
706 branch = branch or 'default'
706 branch = branch or 'default'
707 else:
707 else:
708 branch = p1.branch()
708 branch = p1.branch()
709 store = patch.filestore()
709 store = patch.filestore()
710 try:
710 try:
711 files = set()
711 files = set()
712 try:
712 try:
713 patch.patchrepo(ui, repo, p1, store, tmpname, strip,
713 patch.patchrepo(ui, repo, p1, store, tmpname, strip,
714 files, eolmode=None)
714 files, eolmode=None)
715 except patch.PatchError, e:
715 except patch.PatchError, e:
716 raise util.Abort(str(e))
716 raise util.Abort(str(e))
717 if opts.get('exact'):
717 if opts.get('exact'):
718 editor = None
718 editor = None
719 else:
719 else:
720 editor = getcommiteditor(editform='import.bypass')
720 editor = getcommiteditor(editform='import.bypass')
721 memctx = context.makememctx(repo, (p1.node(), p2.node()),
721 memctx = context.makememctx(repo, (p1.node(), p2.node()),
722 message,
722 message,
723 opts.get('user') or user,
723 opts.get('user') or user,
724 opts.get('date') or date,
724 opts.get('date') or date,
725 branch, files, store,
725 branch, files, store,
726 editor=editor)
726 editor=editor)
727 n = memctx.commit()
727 n = memctx.commit()
728 finally:
728 finally:
729 store.close()
729 store.close()
730 if opts.get('exact') and opts.get('no_commit'):
730 if opts.get('exact') and opts.get('no_commit'):
731 # --exact with --no-commit is still useful in that it does merge
731 # --exact with --no-commit is still useful in that it does merge
732 # and branch bits
732 # and branch bits
733 ui.warn(_("warning: can't check exact import with --no-commit\n"))
733 ui.warn(_("warning: can't check exact import with --no-commit\n"))
734 elif opts.get('exact') and hex(n) != nodeid:
734 elif opts.get('exact') and hex(n) != nodeid:
735 raise util.Abort(_('patch is damaged or loses information'))
735 raise util.Abort(_('patch is damaged or loses information'))
736 if n:
736 if n:
737 # i18n: refers to a short changeset id
737 # i18n: refers to a short changeset id
738 msg = _('created %s') % short(n)
738 msg = _('created %s') % short(n)
739 return (msg, n, rejects)
739 return (msg, n, rejects)
740 finally:
740 finally:
741 os.unlink(tmpname)
741 os.unlink(tmpname)
742
742
743 def export(repo, revs, template='hg-%h.patch', fp=None, switch_parent=False,
743 def export(repo, revs, template='hg-%h.patch', fp=None, switch_parent=False,
744 opts=None):
744 opts=None):
745 '''export changesets as hg patches.'''
745 '''export changesets as hg patches.'''
746
746
747 total = len(revs)
747 total = len(revs)
748 revwidth = max([len(str(rev)) for rev in revs])
748 revwidth = max([len(str(rev)) for rev in revs])
749 filemode = {}
749 filemode = {}
750
750
751 def single(rev, seqno, fp):
751 def single(rev, seqno, fp):
752 ctx = repo[rev]
752 ctx = repo[rev]
753 node = ctx.node()
753 node = ctx.node()
754 parents = [p.node() for p in ctx.parents() if p]
754 parents = [p.node() for p in ctx.parents() if p]
755 branch = ctx.branch()
755 branch = ctx.branch()
756 if switch_parent:
756 if switch_parent:
757 parents.reverse()
757 parents.reverse()
758 prev = (parents and parents[0]) or nullid
758 prev = (parents and parents[0]) or nullid
759
759
760 shouldclose = False
760 shouldclose = False
761 if not fp and len(template) > 0:
761 if not fp and len(template) > 0:
762 desc_lines = ctx.description().rstrip().split('\n')
762 desc_lines = ctx.description().rstrip().split('\n')
763 desc = desc_lines[0] #Commit always has a first line.
763 desc = desc_lines[0] #Commit always has a first line.
764 fp = makefileobj(repo, template, node, desc=desc, total=total,
764 fp = makefileobj(repo, template, node, desc=desc, total=total,
765 seqno=seqno, revwidth=revwidth, mode='wb',
765 seqno=seqno, revwidth=revwidth, mode='wb',
766 modemap=filemode)
766 modemap=filemode)
767 if fp != template:
767 if fp != template:
768 shouldclose = True
768 shouldclose = True
769 if fp and fp != sys.stdout and util.safehasattr(fp, 'name'):
769 if fp and fp != sys.stdout and util.safehasattr(fp, 'name'):
770 repo.ui.note("%s\n" % fp.name)
770 repo.ui.note("%s\n" % fp.name)
771
771
772 if not fp:
772 if not fp:
773 write = repo.ui.write
773 write = repo.ui.write
774 else:
774 else:
775 def write(s, **kw):
775 def write(s, **kw):
776 fp.write(s)
776 fp.write(s)
777
777
778
778
779 write("# HG changeset patch\n")
779 write("# HG changeset patch\n")
780 write("# User %s\n" % ctx.user())
780 write("# User %s\n" % ctx.user())
781 write("# Date %d %d\n" % ctx.date())
781 write("# Date %d %d\n" % ctx.date())
782 write("# %s\n" % util.datestr(ctx.date()))
782 write("# %s\n" % util.datestr(ctx.date()))
783 if branch and branch != 'default':
783 if branch and branch != 'default':
784 write("# Branch %s\n" % branch)
784 write("# Branch %s\n" % branch)
785 write("# Node ID %s\n" % hex(node))
785 write("# Node ID %s\n" % hex(node))
786 write("# Parent %s\n" % hex(prev))
786 write("# Parent %s\n" % hex(prev))
787 if len(parents) > 1:
787 if len(parents) > 1:
788 write("# Parent %s\n" % hex(parents[1]))
788 write("# Parent %s\n" % hex(parents[1]))
789 write(ctx.description().rstrip())
789 write(ctx.description().rstrip())
790 write("\n\n")
790 write("\n\n")
791
791
792 for chunk, label in patch.diffui(repo, prev, node, opts=opts):
792 for chunk, label in patch.diffui(repo, prev, node, opts=opts):
793 write(chunk, label=label)
793 write(chunk, label=label)
794
794
795 if shouldclose:
795 if shouldclose:
796 fp.close()
796 fp.close()
797
797
798 for seqno, rev in enumerate(revs):
798 for seqno, rev in enumerate(revs):
799 single(rev, seqno + 1, fp)
799 single(rev, seqno + 1, fp)
800
800
801 def diffordiffstat(ui, repo, diffopts, node1, node2, match,
801 def diffordiffstat(ui, repo, diffopts, node1, node2, match,
802 changes=None, stat=False, fp=None, prefix='',
802 changes=None, stat=False, fp=None, prefix='',
803 listsubrepos=False):
803 listsubrepos=False):
804 '''show diff or diffstat.'''
804 '''show diff or diffstat.'''
805 if fp is None:
805 if fp is None:
806 write = ui.write
806 write = ui.write
807 else:
807 else:
808 def write(s, **kw):
808 def write(s, **kw):
809 fp.write(s)
809 fp.write(s)
810
810
811 if stat:
811 if stat:
812 diffopts = diffopts.copy(context=0)
812 diffopts = diffopts.copy(context=0)
813 width = 80
813 width = 80
814 if not ui.plain():
814 if not ui.plain():
815 width = ui.termwidth()
815 width = ui.termwidth()
816 chunks = patch.diff(repo, node1, node2, match, changes, diffopts,
816 chunks = patch.diff(repo, node1, node2, match, changes, diffopts,
817 prefix=prefix)
817 prefix=prefix)
818 for chunk, label in patch.diffstatui(util.iterlines(chunks),
818 for chunk, label in patch.diffstatui(util.iterlines(chunks),
819 width=width,
819 width=width,
820 git=diffopts.git):
820 git=diffopts.git):
821 write(chunk, label=label)
821 write(chunk, label=label)
822 else:
822 else:
823 for chunk, label in patch.diffui(repo, node1, node2, match,
823 for chunk, label in patch.diffui(repo, node1, node2, match,
824 changes, diffopts, prefix=prefix):
824 changes, diffopts, prefix=prefix):
825 write(chunk, label=label)
825 write(chunk, label=label)
826
826
827 if listsubrepos:
827 if listsubrepos:
828 ctx1 = repo[node1]
828 ctx1 = repo[node1]
829 ctx2 = repo[node2]
829 ctx2 = repo[node2]
830 for subpath, sub in scmutil.itersubrepos(ctx1, ctx2):
830 for subpath, sub in scmutil.itersubrepos(ctx1, ctx2):
831 tempnode2 = node2
831 tempnode2 = node2
832 try:
832 try:
833 if node2 is not None:
833 if node2 is not None:
834 tempnode2 = ctx2.substate[subpath][1]
834 tempnode2 = ctx2.substate[subpath][1]
835 except KeyError:
835 except KeyError:
836 # A subrepo that existed in node1 was deleted between node1 and
836 # A subrepo that existed in node1 was deleted between node1 and
837 # node2 (inclusive). Thus, ctx2's substate won't contain that
837 # node2 (inclusive). Thus, ctx2's substate won't contain that
838 # subpath. The best we can do is to ignore it.
838 # subpath. The best we can do is to ignore it.
839 tempnode2 = None
839 tempnode2 = None
840 submatch = matchmod.narrowmatcher(subpath, match)
840 submatch = matchmod.narrowmatcher(subpath, match)
841 sub.diff(ui, diffopts, tempnode2, submatch, changes=changes,
841 sub.diff(ui, diffopts, tempnode2, submatch, changes=changes,
842 stat=stat, fp=fp, prefix=prefix)
842 stat=stat, fp=fp, prefix=prefix)
843
843
844 class changeset_printer(object):
844 class changeset_printer(object):
845 '''show changeset information when templating not requested.'''
845 '''show changeset information when templating not requested.'''
846
846
847 def __init__(self, ui, repo, matchfn, diffopts, buffered):
847 def __init__(self, ui, repo, matchfn, diffopts, buffered):
848 self.ui = ui
848 self.ui = ui
849 self.repo = repo
849 self.repo = repo
850 self.buffered = buffered
850 self.buffered = buffered
851 self.matchfn = matchfn
851 self.matchfn = matchfn
852 self.diffopts = diffopts
852 self.diffopts = diffopts
853 self.header = {}
853 self.header = {}
854 self.hunk = {}
854 self.hunk = {}
855 self.lastheader = None
855 self.lastheader = None
856 self.footer = None
856 self.footer = None
857
857
858 def flush(self, rev):
858 def flush(self, rev):
859 if rev in self.header:
859 if rev in self.header:
860 h = self.header[rev]
860 h = self.header[rev]
861 if h != self.lastheader:
861 if h != self.lastheader:
862 self.lastheader = h
862 self.lastheader = h
863 self.ui.write(h)
863 self.ui.write(h)
864 del self.header[rev]
864 del self.header[rev]
865 if rev in self.hunk:
865 if rev in self.hunk:
866 self.ui.write(self.hunk[rev])
866 self.ui.write(self.hunk[rev])
867 del self.hunk[rev]
867 del self.hunk[rev]
868 return 1
868 return 1
869 return 0
869 return 0
870
870
871 def close(self):
871 def close(self):
872 if self.footer:
872 if self.footer:
873 self.ui.write(self.footer)
873 self.ui.write(self.footer)
874
874
875 def show(self, ctx, copies=None, matchfn=None, **props):
875 def show(self, ctx, copies=None, matchfn=None, **props):
876 if self.buffered:
876 if self.buffered:
877 self.ui.pushbuffer()
877 self.ui.pushbuffer()
878 self._show(ctx, copies, matchfn, props)
878 self._show(ctx, copies, matchfn, props)
879 self.hunk[ctx.rev()] = self.ui.popbuffer(labeled=True)
879 self.hunk[ctx.rev()] = self.ui.popbuffer(labeled=True)
880 else:
880 else:
881 self._show(ctx, copies, matchfn, props)
881 self._show(ctx, copies, matchfn, props)
882
882
883 def _show(self, ctx, copies, matchfn, props):
883 def _show(self, ctx, copies, matchfn, props):
884 '''show a single changeset or file revision'''
884 '''show a single changeset or file revision'''
885 changenode = ctx.node()
885 changenode = ctx.node()
886 rev = ctx.rev()
886 rev = ctx.rev()
887
887
888 if self.ui.quiet:
888 if self.ui.quiet:
889 self.ui.write("%d:%s\n" % (rev, short(changenode)),
889 self.ui.write("%d:%s\n" % (rev, short(changenode)),
890 label='log.node')
890 label='log.node')
891 return
891 return
892
892
893 log = self.repo.changelog
893 log = self.repo.changelog
894 date = util.datestr(ctx.date())
894 date = util.datestr(ctx.date())
895
895
896 hexfunc = self.ui.debugflag and hex or short
896 hexfunc = self.ui.debugflag and hex or short
897
897
898 parents = [(p, hexfunc(log.node(p)))
898 parents = [(p, hexfunc(log.node(p)))
899 for p in self._meaningful_parentrevs(log, rev)]
899 for p in self._meaningful_parentrevs(log, rev)]
900
900
901 # i18n: column positioning for "hg log"
901 # i18n: column positioning for "hg log"
902 self.ui.write(_("changeset: %d:%s\n") % (rev, hexfunc(changenode)),
902 self.ui.write(_("changeset: %d:%s\n") % (rev, hexfunc(changenode)),
903 label='log.changeset changeset.%s' % ctx.phasestr())
903 label='log.changeset changeset.%s' % ctx.phasestr())
904
904
905 branch = ctx.branch()
905 branch = ctx.branch()
906 # don't show the default branch name
906 # don't show the default branch name
907 if branch != 'default':
907 if branch != 'default':
908 # i18n: column positioning for "hg log"
908 # i18n: column positioning for "hg log"
909 self.ui.write(_("branch: %s\n") % branch,
909 self.ui.write(_("branch: %s\n") % branch,
910 label='log.branch')
910 label='log.branch')
911 for bookmark in self.repo.nodebookmarks(changenode):
911 for bookmark in self.repo.nodebookmarks(changenode):
912 # i18n: column positioning for "hg log"
912 # i18n: column positioning for "hg log"
913 self.ui.write(_("bookmark: %s\n") % bookmark,
913 self.ui.write(_("bookmark: %s\n") % bookmark,
914 label='log.bookmark')
914 label='log.bookmark')
915 for tag in self.repo.nodetags(changenode):
915 for tag in self.repo.nodetags(changenode):
916 # i18n: column positioning for "hg log"
916 # i18n: column positioning for "hg log"
917 self.ui.write(_("tag: %s\n") % tag,
917 self.ui.write(_("tag: %s\n") % tag,
918 label='log.tag')
918 label='log.tag')
919 if self.ui.debugflag and ctx.phase():
919 if self.ui.debugflag and ctx.phase():
920 # i18n: column positioning for "hg log"
920 # i18n: column positioning for "hg log"
921 self.ui.write(_("phase: %s\n") % _(ctx.phasestr()),
921 self.ui.write(_("phase: %s\n") % _(ctx.phasestr()),
922 label='log.phase')
922 label='log.phase')
923 for parent in parents:
923 for parent in parents:
924 label = 'log.parent changeset.%s' % self.repo[parent[0]].phasestr()
924 label = 'log.parent changeset.%s' % self.repo[parent[0]].phasestr()
925 # i18n: column positioning for "hg log"
925 # i18n: column positioning for "hg log"
926 self.ui.write(_("parent: %d:%s\n") % parent,
926 self.ui.write(_("parent: %d:%s\n") % parent,
927 label=label)
927 label=label)
928
928
929 if self.ui.debugflag:
929 if self.ui.debugflag:
930 mnode = ctx.manifestnode()
930 mnode = ctx.manifestnode()
931 # i18n: column positioning for "hg log"
931 # i18n: column positioning for "hg log"
932 self.ui.write(_("manifest: %d:%s\n") %
932 self.ui.write(_("manifest: %d:%s\n") %
933 (self.repo.manifest.rev(mnode), hex(mnode)),
933 (self.repo.manifest.rev(mnode), hex(mnode)),
934 label='ui.debug log.manifest')
934 label='ui.debug log.manifest')
935 # i18n: column positioning for "hg log"
935 # i18n: column positioning for "hg log"
936 self.ui.write(_("user: %s\n") % ctx.user(),
936 self.ui.write(_("user: %s\n") % ctx.user(),
937 label='log.user')
937 label='log.user')
938 # i18n: column positioning for "hg log"
938 # i18n: column positioning for "hg log"
939 self.ui.write(_("date: %s\n") % date,
939 self.ui.write(_("date: %s\n") % date,
940 label='log.date')
940 label='log.date')
941
941
942 if self.ui.debugflag:
942 if self.ui.debugflag:
943 files = self.repo.status(log.parents(changenode)[0], changenode)[:3]
943 files = self.repo.status(log.parents(changenode)[0], changenode)[:3]
944 for key, value in zip([# i18n: column positioning for "hg log"
944 for key, value in zip([# i18n: column positioning for "hg log"
945 _("files:"),
945 _("files:"),
946 # i18n: column positioning for "hg log"
946 # i18n: column positioning for "hg log"
947 _("files+:"),
947 _("files+:"),
948 # i18n: column positioning for "hg log"
948 # i18n: column positioning for "hg log"
949 _("files-:")], files):
949 _("files-:")], files):
950 if value:
950 if value:
951 self.ui.write("%-12s %s\n" % (key, " ".join(value)),
951 self.ui.write("%-12s %s\n" % (key, " ".join(value)),
952 label='ui.debug log.files')
952 label='ui.debug log.files')
953 elif ctx.files() and self.ui.verbose:
953 elif ctx.files() and self.ui.verbose:
954 # i18n: column positioning for "hg log"
954 # i18n: column positioning for "hg log"
955 self.ui.write(_("files: %s\n") % " ".join(ctx.files()),
955 self.ui.write(_("files: %s\n") % " ".join(ctx.files()),
956 label='ui.note log.files')
956 label='ui.note log.files')
957 if copies and self.ui.verbose:
957 if copies and self.ui.verbose:
958 copies = ['%s (%s)' % c for c in copies]
958 copies = ['%s (%s)' % c for c in copies]
959 # i18n: column positioning for "hg log"
959 # i18n: column positioning for "hg log"
960 self.ui.write(_("copies: %s\n") % ' '.join(copies),
960 self.ui.write(_("copies: %s\n") % ' '.join(copies),
961 label='ui.note log.copies')
961 label='ui.note log.copies')
962
962
963 extra = ctx.extra()
963 extra = ctx.extra()
964 if extra and self.ui.debugflag:
964 if extra and self.ui.debugflag:
965 for key, value in sorted(extra.items()):
965 for key, value in sorted(extra.items()):
966 # i18n: column positioning for "hg log"
966 # i18n: column positioning for "hg log"
967 self.ui.write(_("extra: %s=%s\n")
967 self.ui.write(_("extra: %s=%s\n")
968 % (key, value.encode('string_escape')),
968 % (key, value.encode('string_escape')),
969 label='ui.debug log.extra')
969 label='ui.debug log.extra')
970
970
971 description = ctx.description().strip()
971 description = ctx.description().strip()
972 if description:
972 if description:
973 if self.ui.verbose:
973 if self.ui.verbose:
974 self.ui.write(_("description:\n"),
974 self.ui.write(_("description:\n"),
975 label='ui.note log.description')
975 label='ui.note log.description')
976 self.ui.write(description,
976 self.ui.write(description,
977 label='ui.note log.description')
977 label='ui.note log.description')
978 self.ui.write("\n\n")
978 self.ui.write("\n\n")
979 else:
979 else:
980 # i18n: column positioning for "hg log"
980 # i18n: column positioning for "hg log"
981 self.ui.write(_("summary: %s\n") %
981 self.ui.write(_("summary: %s\n") %
982 description.splitlines()[0],
982 description.splitlines()[0],
983 label='log.summary')
983 label='log.summary')
984 self.ui.write("\n")
984 self.ui.write("\n")
985
985
986 self.showpatch(changenode, matchfn)
986 self.showpatch(changenode, matchfn)
987
987
988 def showpatch(self, node, matchfn):
988 def showpatch(self, node, matchfn):
989 if not matchfn:
989 if not matchfn:
990 matchfn = self.matchfn
990 matchfn = self.matchfn
991 if matchfn:
991 if matchfn:
992 stat = self.diffopts.get('stat')
992 stat = self.diffopts.get('stat')
993 diff = self.diffopts.get('patch')
993 diff = self.diffopts.get('patch')
994 diffopts = patch.diffopts(self.ui, self.diffopts)
994 diffopts = patch.diffopts(self.ui, self.diffopts)
995 prev = self.repo.changelog.parents(node)[0]
995 prev = self.repo.changelog.parents(node)[0]
996 if stat:
996 if stat:
997 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
997 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
998 match=matchfn, stat=True)
998 match=matchfn, stat=True)
999 if diff:
999 if diff:
1000 if stat:
1000 if stat:
1001 self.ui.write("\n")
1001 self.ui.write("\n")
1002 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1002 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1003 match=matchfn, stat=False)
1003 match=matchfn, stat=False)
1004 self.ui.write("\n")
1004 self.ui.write("\n")
1005
1005
1006 def _meaningful_parentrevs(self, log, rev):
1006 def _meaningful_parentrevs(self, log, rev):
1007 """Return list of meaningful (or all if debug) parentrevs for rev.
1007 """Return list of meaningful (or all if debug) parentrevs for rev.
1008
1008
1009 For merges (two non-nullrev revisions) both parents are meaningful.
1009 For merges (two non-nullrev revisions) both parents are meaningful.
1010 Otherwise the first parent revision is considered meaningful if it
1010 Otherwise the first parent revision is considered meaningful if it
1011 is not the preceding revision.
1011 is not the preceding revision.
1012 """
1012 """
1013 parents = log.parentrevs(rev)
1013 parents = log.parentrevs(rev)
1014 if not self.ui.debugflag and parents[1] == nullrev:
1014 if not self.ui.debugflag and parents[1] == nullrev:
1015 if parents[0] >= rev - 1:
1015 if parents[0] >= rev - 1:
1016 parents = []
1016 parents = []
1017 else:
1017 else:
1018 parents = [parents[0]]
1018 parents = [parents[0]]
1019 return parents
1019 return parents
1020
1020
1021 class jsonchangeset(changeset_printer):
1021 class jsonchangeset(changeset_printer):
1022 '''format changeset information.'''
1022 '''format changeset information.'''
1023
1023
1024 def __init__(self, ui, repo, matchfn, diffopts, buffered):
1024 def __init__(self, ui, repo, matchfn, diffopts, buffered):
1025 changeset_printer.__init__(self, ui, repo, matchfn, diffopts, buffered)
1025 changeset_printer.__init__(self, ui, repo, matchfn, diffopts, buffered)
1026 self.cache = {}
1026 self.cache = {}
1027 self._first = True
1027 self._first = True
1028
1028
1029 def close(self):
1029 def close(self):
1030 if not self._first:
1030 if not self._first:
1031 self.ui.write("\n]\n")
1031 self.ui.write("\n]\n")
1032 else:
1032 else:
1033 self.ui.write("[]\n")
1033 self.ui.write("[]\n")
1034
1034
1035 def _show(self, ctx, copies, matchfn, props):
1035 def _show(self, ctx, copies, matchfn, props):
1036 '''show a single changeset or file revision'''
1036 '''show a single changeset or file revision'''
1037 hexnode = hex(ctx.node())
1037 hexnode = hex(ctx.node())
1038 rev = ctx.rev()
1038 rev = ctx.rev()
1039 j = encoding.jsonescape
1039 j = encoding.jsonescape
1040
1040
1041 if self._first:
1041 if self._first:
1042 self.ui.write("[\n {")
1042 self.ui.write("[\n {")
1043 self._first = False
1043 self._first = False
1044 else:
1044 else:
1045 self.ui.write(",\n {")
1045 self.ui.write(",\n {")
1046
1046
1047 if self.ui.quiet:
1047 if self.ui.quiet:
1048 self.ui.write('\n "rev": %d' % rev)
1048 self.ui.write('\n "rev": %d' % rev)
1049 self.ui.write(',\n "node": "%s"' % hexnode)
1049 self.ui.write(',\n "node": "%s"' % hexnode)
1050 self.ui.write('\n }')
1050 self.ui.write('\n }')
1051 return
1051 return
1052
1052
1053 self.ui.write('\n "rev": %d' % rev)
1053 self.ui.write('\n "rev": %d' % rev)
1054 self.ui.write(',\n "node": "%s"' % hexnode)
1054 self.ui.write(',\n "node": "%s"' % hexnode)
1055 self.ui.write(',\n "branch": "%s"' % j(ctx.branch()))
1055 self.ui.write(',\n "branch": "%s"' % j(ctx.branch()))
1056 self.ui.write(',\n "phase": "%s"' % ctx.phasestr())
1056 self.ui.write(',\n "phase": "%s"' % ctx.phasestr())
1057 self.ui.write(',\n "user": "%s"' % j(ctx.user()))
1057 self.ui.write(',\n "user": "%s"' % j(ctx.user()))
1058 self.ui.write(',\n "date": [%d, %d]' % ctx.date())
1058 self.ui.write(',\n "date": [%d, %d]' % ctx.date())
1059 self.ui.write(',\n "desc": "%s"' % j(ctx.description()))
1059 self.ui.write(',\n "desc": "%s"' % j(ctx.description()))
1060
1060
1061 self.ui.write(',\n "bookmarks": [%s]' %
1061 self.ui.write(',\n "bookmarks": [%s]' %
1062 ", ".join('"%s"' % j(b) for b in ctx.bookmarks()))
1062 ", ".join('"%s"' % j(b) for b in ctx.bookmarks()))
1063 self.ui.write(',\n "tags": [%s]' %
1063 self.ui.write(',\n "tags": [%s]' %
1064 ", ".join('"%s"' % j(t) for t in ctx.tags()))
1064 ", ".join('"%s"' % j(t) for t in ctx.tags()))
1065 self.ui.write(',\n "parents": [%s]' %
1065 self.ui.write(',\n "parents": [%s]' %
1066 ", ".join('"%s"' % c.hex() for c in ctx.parents()))
1066 ", ".join('"%s"' % c.hex() for c in ctx.parents()))
1067
1067
1068 if self.ui.debugflag:
1068 if self.ui.debugflag:
1069 self.ui.write(',\n "manifest": "%s"' % hex(ctx.manifestnode()))
1069 self.ui.write(',\n "manifest": "%s"' % hex(ctx.manifestnode()))
1070
1070
1071 self.ui.write(',\n "extra": {%s}' %
1071 self.ui.write(',\n "extra": {%s}' %
1072 ", ".join('"%s": "%s"' % (j(k), j(v))
1072 ", ".join('"%s": "%s"' % (j(k), j(v))
1073 for k, v in ctx.extra().items()))
1073 for k, v in ctx.extra().items()))
1074
1074
1075 files = ctx.status(ctx.p1())
1075 files = ctx.status(ctx.p1())
1076 self.ui.write(',\n "modified": [%s]' %
1076 self.ui.write(',\n "modified": [%s]' %
1077 ", ".join('"%s"' % j(f) for f in files[0]))
1077 ", ".join('"%s"' % j(f) for f in files[0]))
1078 self.ui.write(',\n "added": [%s]' %
1078 self.ui.write(',\n "added": [%s]' %
1079 ", ".join('"%s"' % j(f) for f in files[1]))
1079 ", ".join('"%s"' % j(f) for f in files[1]))
1080 self.ui.write(',\n "removed": [%s]' %
1080 self.ui.write(',\n "removed": [%s]' %
1081 ", ".join('"%s"' % j(f) for f in files[2]))
1081 ", ".join('"%s"' % j(f) for f in files[2]))
1082
1082
1083 elif self.ui.verbose:
1083 elif self.ui.verbose:
1084 self.ui.write(',\n "files": [%s]' %
1084 self.ui.write(',\n "files": [%s]' %
1085 ", ".join('"%s"' % j(f) for f in ctx.files()))
1085 ", ".join('"%s"' % j(f) for f in ctx.files()))
1086
1086
1087 if copies:
1087 if copies:
1088 self.ui.write(',\n "copies": {%s}' %
1088 self.ui.write(',\n "copies": {%s}' %
1089 ", ".join('"%s": %s' % (j(k), j(copies[k]))
1089 ", ".join('"%s": %s' % (j(k), j(copies[k]))
1090 for k in copies))
1090 for k in copies))
1091
1091
1092 matchfn = self.matchfn
1092 matchfn = self.matchfn
1093 if matchfn:
1093 if matchfn:
1094 stat = self.diffopts.get('stat')
1094 stat = self.diffopts.get('stat')
1095 diff = self.diffopts.get('patch')
1095 diff = self.diffopts.get('patch')
1096 diffopts = patch.diffopts(self.ui, self.diffopts)
1096 diffopts = patch.diffopts(self.ui, self.diffopts)
1097 node, prev = ctx.node(), ctx.p1().node()
1097 node, prev = ctx.node(), ctx.p1().node()
1098 if stat:
1098 if stat:
1099 self.ui.pushbuffer()
1099 self.ui.pushbuffer()
1100 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1100 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1101 match=matchfn, stat=True)
1101 match=matchfn, stat=True)
1102 self.ui.write(',\n "diffstat": "%s"' % j(self.ui.popbuffer()))
1102 self.ui.write(',\n "diffstat": "%s"' % j(self.ui.popbuffer()))
1103 if diff:
1103 if diff:
1104 self.ui.pushbuffer()
1104 self.ui.pushbuffer()
1105 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1105 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1106 match=matchfn, stat=False)
1106 match=matchfn, stat=False)
1107 self.ui.write(',\n "diff": "%s"' % j(self.ui.popbuffer()))
1107 self.ui.write(',\n "diff": "%s"' % j(self.ui.popbuffer()))
1108
1108
1109 self.ui.write("\n }")
1109 self.ui.write("\n }")
1110
1110
1111 class changeset_templater(changeset_printer):
1111 class changeset_templater(changeset_printer):
1112 '''format changeset information.'''
1112 '''format changeset information.'''
1113
1113
1114 def __init__(self, ui, repo, matchfn, diffopts, tmpl, mapfile, buffered):
1114 def __init__(self, ui, repo, matchfn, diffopts, tmpl, mapfile, buffered):
1115 changeset_printer.__init__(self, ui, repo, matchfn, diffopts, buffered)
1115 changeset_printer.__init__(self, ui, repo, matchfn, diffopts, buffered)
1116 formatnode = ui.debugflag and (lambda x: x) or (lambda x: x[:12])
1116 formatnode = ui.debugflag and (lambda x: x) or (lambda x: x[:12])
1117 defaulttempl = {
1117 defaulttempl = {
1118 'parent': '{rev}:{node|formatnode} ',
1118 'parent': '{rev}:{node|formatnode} ',
1119 'manifest': '{rev}:{node|formatnode}',
1119 'manifest': '{rev}:{node|formatnode}',
1120 'file_copy': '{name} ({source})',
1120 'file_copy': '{name} ({source})',
1121 'extra': '{key}={value|stringescape}'
1121 'extra': '{key}={value|stringescape}'
1122 }
1122 }
1123 # filecopy is preserved for compatibility reasons
1123 # filecopy is preserved for compatibility reasons
1124 defaulttempl['filecopy'] = defaulttempl['file_copy']
1124 defaulttempl['filecopy'] = defaulttempl['file_copy']
1125 self.t = templater.templater(mapfile, {'formatnode': formatnode},
1125 self.t = templater.templater(mapfile, {'formatnode': formatnode},
1126 cache=defaulttempl)
1126 cache=defaulttempl)
1127 if tmpl:
1127 if tmpl:
1128 self.t.cache['changeset'] = tmpl
1128 self.t.cache['changeset'] = tmpl
1129
1129
1130 self.cache = {}
1130 self.cache = {}
1131
1131
1132 def _meaningful_parentrevs(self, ctx):
1132 def _meaningful_parentrevs(self, ctx):
1133 """Return list of meaningful (or all if debug) parentrevs for rev.
1133 """Return list of meaningful (or all if debug) parentrevs for rev.
1134 """
1134 """
1135 parents = ctx.parents()
1135 parents = ctx.parents()
1136 if len(parents) > 1:
1136 if len(parents) > 1:
1137 return parents
1137 return parents
1138 if self.ui.debugflag:
1138 if self.ui.debugflag:
1139 return [parents[0], self.repo['null']]
1139 return [parents[0], self.repo['null']]
1140 if parents[0].rev() >= ctx.rev() - 1:
1140 if parents[0].rev() >= ctx.rev() - 1:
1141 return []
1141 return []
1142 return parents
1142 return parents
1143
1143
1144 def _show(self, ctx, copies, matchfn, props):
1144 def _show(self, ctx, copies, matchfn, props):
1145 '''show a single changeset or file revision'''
1145 '''show a single changeset or file revision'''
1146
1146
1147 showlist = templatekw.showlist
1147 showlist = templatekw.showlist
1148
1148
1149 # showparents() behaviour depends on ui trace level which
1149 # showparents() behaviour depends on ui trace level which
1150 # causes unexpected behaviours at templating level and makes
1150 # causes unexpected behaviours at templating level and makes
1151 # it harder to extract it in a standalone function. Its
1151 # it harder to extract it in a standalone function. Its
1152 # behaviour cannot be changed so leave it here for now.
1152 # behaviour cannot be changed so leave it here for now.
1153 def showparents(**args):
1153 def showparents(**args):
1154 ctx = args['ctx']
1154 ctx = args['ctx']
1155 parents = [[('rev', p.rev()), ('node', p.hex())]
1155 parents = [[('rev', p.rev()), ('node', p.hex())]
1156 for p in self._meaningful_parentrevs(ctx)]
1156 for p in self._meaningful_parentrevs(ctx)]
1157 return showlist('parent', parents, **args)
1157 return showlist('parent', parents, **args)
1158
1158
1159 props = props.copy()
1159 props = props.copy()
1160 props.update(templatekw.keywords)
1160 props.update(templatekw.keywords)
1161 props['parents'] = showparents
1161 props['parents'] = showparents
1162 props['templ'] = self.t
1162 props['templ'] = self.t
1163 props['ctx'] = ctx
1163 props['ctx'] = ctx
1164 props['repo'] = self.repo
1164 props['repo'] = self.repo
1165 props['revcache'] = {'copies': copies}
1165 props['revcache'] = {'copies': copies}
1166 props['cache'] = self.cache
1166 props['cache'] = self.cache
1167
1167
1168 # find correct templates for current mode
1168 # find correct templates for current mode
1169
1169
1170 tmplmodes = [
1170 tmplmodes = [
1171 (True, None),
1171 (True, None),
1172 (self.ui.verbose, 'verbose'),
1172 (self.ui.verbose, 'verbose'),
1173 (self.ui.quiet, 'quiet'),
1173 (self.ui.quiet, 'quiet'),
1174 (self.ui.debugflag, 'debug'),
1174 (self.ui.debugflag, 'debug'),
1175 ]
1175 ]
1176
1176
1177 types = {'header': '', 'footer':'', 'changeset': 'changeset'}
1177 types = {'header': '', 'footer':'', 'changeset': 'changeset'}
1178 for mode, postfix in tmplmodes:
1178 for mode, postfix in tmplmodes:
1179 for type in types:
1179 for type in types:
1180 cur = postfix and ('%s_%s' % (type, postfix)) or type
1180 cur = postfix and ('%s_%s' % (type, postfix)) or type
1181 if mode and cur in self.t:
1181 if mode and cur in self.t:
1182 types[type] = cur
1182 types[type] = cur
1183
1183
1184 try:
1184 try:
1185
1185
1186 # write header
1186 # write header
1187 if types['header']:
1187 if types['header']:
1188 h = templater.stringify(self.t(types['header'], **props))
1188 h = templater.stringify(self.t(types['header'], **props))
1189 if self.buffered:
1189 if self.buffered:
1190 self.header[ctx.rev()] = h
1190 self.header[ctx.rev()] = h
1191 else:
1191 else:
1192 if self.lastheader != h:
1192 if self.lastheader != h:
1193 self.lastheader = h
1193 self.lastheader = h
1194 self.ui.write(h)
1194 self.ui.write(h)
1195
1195
1196 # write changeset metadata, then patch if requested
1196 # write changeset metadata, then patch if requested
1197 key = types['changeset']
1197 key = types['changeset']
1198 self.ui.write(templater.stringify(self.t(key, **props)))
1198 self.ui.write(templater.stringify(self.t(key, **props)))
1199 self.showpatch(ctx.node(), matchfn)
1199 self.showpatch(ctx.node(), matchfn)
1200
1200
1201 if types['footer']:
1201 if types['footer']:
1202 if not self.footer:
1202 if not self.footer:
1203 self.footer = templater.stringify(self.t(types['footer'],
1203 self.footer = templater.stringify(self.t(types['footer'],
1204 **props))
1204 **props))
1205
1205
1206 except KeyError, inst:
1206 except KeyError, inst:
1207 msg = _("%s: no key named '%s'")
1207 msg = _("%s: no key named '%s'")
1208 raise util.Abort(msg % (self.t.mapfile, inst.args[0]))
1208 raise util.Abort(msg % (self.t.mapfile, inst.args[0]))
1209 except SyntaxError, inst:
1209 except SyntaxError, inst:
1210 raise util.Abort('%s: %s' % (self.t.mapfile, inst.args[0]))
1210 raise util.Abort('%s: %s' % (self.t.mapfile, inst.args[0]))
1211
1211
1212 def gettemplate(ui, tmpl, style):
1212 def gettemplate(ui, tmpl, style):
1213 """
1213 """
1214 Find the template matching the given template spec or style.
1214 Find the template matching the given template spec or style.
1215 """
1215 """
1216
1216
1217 # ui settings
1217 # ui settings
1218 if not tmpl and not style: # template are stronger than style
1218 if not tmpl and not style: # template are stronger than style
1219 tmpl = ui.config('ui', 'logtemplate')
1219 tmpl = ui.config('ui', 'logtemplate')
1220 if tmpl:
1220 if tmpl:
1221 try:
1221 try:
1222 tmpl = templater.parsestring(tmpl)
1222 tmpl = templater.parsestring(tmpl)
1223 except SyntaxError:
1223 except SyntaxError:
1224 tmpl = templater.parsestring(tmpl, quoted=False)
1224 tmpl = templater.parsestring(tmpl, quoted=False)
1225 return tmpl, None
1225 return tmpl, None
1226 else:
1226 else:
1227 style = util.expandpath(ui.config('ui', 'style', ''))
1227 style = util.expandpath(ui.config('ui', 'style', ''))
1228
1228
1229 if not tmpl and style:
1229 if not tmpl and style:
1230 mapfile = style
1230 mapfile = style
1231 if not os.path.split(mapfile)[0]:
1231 if not os.path.split(mapfile)[0]:
1232 mapname = (templater.templatepath('map-cmdline.' + mapfile)
1232 mapname = (templater.templatepath('map-cmdline.' + mapfile)
1233 or templater.templatepath(mapfile))
1233 or templater.templatepath(mapfile))
1234 if mapname:
1234 if mapname:
1235 mapfile = mapname
1235 mapfile = mapname
1236 return None, mapfile
1236 return None, mapfile
1237
1237
1238 if not tmpl:
1238 if not tmpl:
1239 return None, None
1239 return None, None
1240
1240
1241 # looks like a literal template?
1241 # looks like a literal template?
1242 if '{' in tmpl:
1242 if '{' in tmpl:
1243 return tmpl, None
1243 return tmpl, None
1244
1244
1245 # perhaps a stock style?
1245 # perhaps a stock style?
1246 if not os.path.split(tmpl)[0]:
1246 if not os.path.split(tmpl)[0]:
1247 mapname = (templater.templatepath('map-cmdline.' + tmpl)
1247 mapname = (templater.templatepath('map-cmdline.' + tmpl)
1248 or templater.templatepath(tmpl))
1248 or templater.templatepath(tmpl))
1249 if mapname and os.path.isfile(mapname):
1249 if mapname and os.path.isfile(mapname):
1250 return None, mapname
1250 return None, mapname
1251
1251
1252 # perhaps it's a reference to [templates]
1252 # perhaps it's a reference to [templates]
1253 t = ui.config('templates', tmpl)
1253 t = ui.config('templates', tmpl)
1254 if t:
1254 if t:
1255 try:
1255 try:
1256 tmpl = templater.parsestring(t)
1256 tmpl = templater.parsestring(t)
1257 except SyntaxError:
1257 except SyntaxError:
1258 tmpl = templater.parsestring(t, quoted=False)
1258 tmpl = templater.parsestring(t, quoted=False)
1259 return tmpl, None
1259 return tmpl, None
1260
1260
1261 if tmpl == 'list':
1261 if tmpl == 'list':
1262 ui.write(_("available styles: %s\n") % templater.stylelist())
1262 ui.write(_("available styles: %s\n") % templater.stylelist())
1263 raise util.Abort(_("specify a template"))
1263 raise util.Abort(_("specify a template"))
1264
1264
1265 # perhaps it's a path to a map or a template
1265 # perhaps it's a path to a map or a template
1266 if ('/' in tmpl or '\\' in tmpl) and os.path.isfile(tmpl):
1266 if ('/' in tmpl or '\\' in tmpl) and os.path.isfile(tmpl):
1267 # is it a mapfile for a style?
1267 # is it a mapfile for a style?
1268 if os.path.basename(tmpl).startswith("map-"):
1268 if os.path.basename(tmpl).startswith("map-"):
1269 return None, os.path.realpath(tmpl)
1269 return None, os.path.realpath(tmpl)
1270 tmpl = open(tmpl).read()
1270 tmpl = open(tmpl).read()
1271 return tmpl, None
1271 return tmpl, None
1272
1272
1273 # constant string?
1273 # constant string?
1274 return tmpl, None
1274 return tmpl, None
1275
1275
1276 def show_changeset(ui, repo, opts, buffered=False):
1276 def show_changeset(ui, repo, opts, buffered=False):
1277 """show one changeset using template or regular display.
1277 """show one changeset using template or regular display.
1278
1278
1279 Display format will be the first non-empty hit of:
1279 Display format will be the first non-empty hit of:
1280 1. option 'template'
1280 1. option 'template'
1281 2. option 'style'
1281 2. option 'style'
1282 3. [ui] setting 'logtemplate'
1282 3. [ui] setting 'logtemplate'
1283 4. [ui] setting 'style'
1283 4. [ui] setting 'style'
1284 If all of these values are either the unset or the empty string,
1284 If all of these values are either the unset or the empty string,
1285 regular display via changeset_printer() is done.
1285 regular display via changeset_printer() is done.
1286 """
1286 """
1287 # options
1287 # options
1288 matchfn = None
1288 matchfn = None
1289 if opts.get('patch') or opts.get('stat'):
1289 if opts.get('patch') or opts.get('stat'):
1290 matchfn = scmutil.matchall(repo)
1290 matchfn = scmutil.matchall(repo)
1291
1291
1292 if opts.get('template') == 'json':
1292 if opts.get('template') == 'json':
1293 return jsonchangeset(ui, repo, matchfn, opts, buffered)
1293 return jsonchangeset(ui, repo, matchfn, opts, buffered)
1294
1294
1295 tmpl, mapfile = gettemplate(ui, opts.get('template'), opts.get('style'))
1295 tmpl, mapfile = gettemplate(ui, opts.get('template'), opts.get('style'))
1296
1296
1297 if not tmpl and not mapfile:
1297 if not tmpl and not mapfile:
1298 return changeset_printer(ui, repo, matchfn, opts, buffered)
1298 return changeset_printer(ui, repo, matchfn, opts, buffered)
1299
1299
1300 try:
1300 try:
1301 t = changeset_templater(ui, repo, matchfn, opts, tmpl, mapfile,
1301 t = changeset_templater(ui, repo, matchfn, opts, tmpl, mapfile,
1302 buffered)
1302 buffered)
1303 except SyntaxError, inst:
1303 except SyntaxError, inst:
1304 raise util.Abort(inst.args[0])
1304 raise util.Abort(inst.args[0])
1305 return t
1305 return t
1306
1306
1307 def showmarker(ui, marker):
1307 def showmarker(ui, marker):
1308 """utility function to display obsolescence marker in a readable way
1308 """utility function to display obsolescence marker in a readable way
1309
1309
1310 To be used by debug function."""
1310 To be used by debug function."""
1311 ui.write(hex(marker.precnode()))
1311 ui.write(hex(marker.precnode()))
1312 for repl in marker.succnodes():
1312 for repl in marker.succnodes():
1313 ui.write(' ')
1313 ui.write(' ')
1314 ui.write(hex(repl))
1314 ui.write(hex(repl))
1315 ui.write(' %X ' % marker.flags())
1315 ui.write(' %X ' % marker.flags())
1316 parents = marker.parentnodes()
1316 parents = marker.parentnodes()
1317 if parents is not None:
1317 if parents is not None:
1318 ui.write('{%s} ' % ', '.join(hex(p) for p in parents))
1318 ui.write('{%s} ' % ', '.join(hex(p) for p in parents))
1319 ui.write('(%s) ' % util.datestr(marker.date()))
1319 ui.write('(%s) ' % util.datestr(marker.date()))
1320 ui.write('{%s}' % (', '.join('%r: %r' % t for t in
1320 ui.write('{%s}' % (', '.join('%r: %r' % t for t in
1321 sorted(marker.metadata().items())
1321 sorted(marker.metadata().items())
1322 if t[0] != 'date')))
1322 if t[0] != 'date')))
1323 ui.write('\n')
1323 ui.write('\n')
1324
1324
1325 def finddate(ui, repo, date):
1325 def finddate(ui, repo, date):
1326 """Find the tipmost changeset that matches the given date spec"""
1326 """Find the tipmost changeset that matches the given date spec"""
1327
1327
1328 df = util.matchdate(date)
1328 df = util.matchdate(date)
1329 m = scmutil.matchall(repo)
1329 m = scmutil.matchall(repo)
1330 results = {}
1330 results = {}
1331
1331
1332 def prep(ctx, fns):
1332 def prep(ctx, fns):
1333 d = ctx.date()
1333 d = ctx.date()
1334 if df(d[0]):
1334 if df(d[0]):
1335 results[ctx.rev()] = d
1335 results[ctx.rev()] = d
1336
1336
1337 for ctx in walkchangerevs(repo, m, {'rev': None}, prep):
1337 for ctx in walkchangerevs(repo, m, {'rev': None}, prep):
1338 rev = ctx.rev()
1338 rev = ctx.rev()
1339 if rev in results:
1339 if rev in results:
1340 ui.status(_("found revision %s from %s\n") %
1340 ui.status(_("found revision %s from %s\n") %
1341 (rev, util.datestr(results[rev])))
1341 (rev, util.datestr(results[rev])))
1342 return str(rev)
1342 return str(rev)
1343
1343
1344 raise util.Abort(_("revision matching date not found"))
1344 raise util.Abort(_("revision matching date not found"))
1345
1345
1346 def increasingwindows(windowsize=8, sizelimit=512):
1346 def increasingwindows(windowsize=8, sizelimit=512):
1347 while True:
1347 while True:
1348 yield windowsize
1348 yield windowsize
1349 if windowsize < sizelimit:
1349 if windowsize < sizelimit:
1350 windowsize *= 2
1350 windowsize *= 2
1351
1351
1352 class FileWalkError(Exception):
1352 class FileWalkError(Exception):
1353 pass
1353 pass
1354
1354
1355 def walkfilerevs(repo, match, follow, revs, fncache):
1355 def walkfilerevs(repo, match, follow, revs, fncache):
1356 '''Walks the file history for the matched files.
1356 '''Walks the file history for the matched files.
1357
1357
1358 Returns the changeset revs that are involved in the file history.
1358 Returns the changeset revs that are involved in the file history.
1359
1359
1360 Throws FileWalkError if the file history can't be walked using
1360 Throws FileWalkError if the file history can't be walked using
1361 filelogs alone.
1361 filelogs alone.
1362 '''
1362 '''
1363 wanted = set()
1363 wanted = set()
1364 copies = []
1364 copies = []
1365 minrev, maxrev = min(revs), max(revs)
1365 minrev, maxrev = min(revs), max(revs)
1366 def filerevgen(filelog, last):
1366 def filerevgen(filelog, last):
1367 """
1367 """
1368 Only files, no patterns. Check the history of each file.
1368 Only files, no patterns. Check the history of each file.
1369
1369
1370 Examines filelog entries within minrev, maxrev linkrev range
1370 Examines filelog entries within minrev, maxrev linkrev range
1371 Returns an iterator yielding (linkrev, parentlinkrevs, copied)
1371 Returns an iterator yielding (linkrev, parentlinkrevs, copied)
1372 tuples in backwards order
1372 tuples in backwards order
1373 """
1373 """
1374 cl_count = len(repo)
1374 cl_count = len(repo)
1375 revs = []
1375 revs = []
1376 for j in xrange(0, last + 1):
1376 for j in xrange(0, last + 1):
1377 linkrev = filelog.linkrev(j)
1377 linkrev = filelog.linkrev(j)
1378 if linkrev < minrev:
1378 if linkrev < minrev:
1379 continue
1379 continue
1380 # only yield rev for which we have the changelog, it can
1380 # only yield rev for which we have the changelog, it can
1381 # happen while doing "hg log" during a pull or commit
1381 # happen while doing "hg log" during a pull or commit
1382 if linkrev >= cl_count:
1382 if linkrev >= cl_count:
1383 break
1383 break
1384
1384
1385 parentlinkrevs = []
1385 parentlinkrevs = []
1386 for p in filelog.parentrevs(j):
1386 for p in filelog.parentrevs(j):
1387 if p != nullrev:
1387 if p != nullrev:
1388 parentlinkrevs.append(filelog.linkrev(p))
1388 parentlinkrevs.append(filelog.linkrev(p))
1389 n = filelog.node(j)
1389 n = filelog.node(j)
1390 revs.append((linkrev, parentlinkrevs,
1390 revs.append((linkrev, parentlinkrevs,
1391 follow and filelog.renamed(n)))
1391 follow and filelog.renamed(n)))
1392
1392
1393 return reversed(revs)
1393 return reversed(revs)
1394 def iterfiles():
1394 def iterfiles():
1395 pctx = repo['.']
1395 pctx = repo['.']
1396 for filename in match.files():
1396 for filename in match.files():
1397 if follow:
1397 if follow:
1398 if filename not in pctx:
1398 if filename not in pctx:
1399 raise util.Abort(_('cannot follow file not in parent '
1399 raise util.Abort(_('cannot follow file not in parent '
1400 'revision: "%s"') % filename)
1400 'revision: "%s"') % filename)
1401 yield filename, pctx[filename].filenode()
1401 yield filename, pctx[filename].filenode()
1402 else:
1402 else:
1403 yield filename, None
1403 yield filename, None
1404 for filename_node in copies:
1404 for filename_node in copies:
1405 yield filename_node
1405 yield filename_node
1406
1406
1407 for file_, node in iterfiles():
1407 for file_, node in iterfiles():
1408 filelog = repo.file(file_)
1408 filelog = repo.file(file_)
1409 if not len(filelog):
1409 if not len(filelog):
1410 if node is None:
1410 if node is None:
1411 # A zero count may be a directory or deleted file, so
1411 # A zero count may be a directory or deleted file, so
1412 # try to find matching entries on the slow path.
1412 # try to find matching entries on the slow path.
1413 if follow:
1413 if follow:
1414 raise util.Abort(
1414 raise util.Abort(
1415 _('cannot follow nonexistent file: "%s"') % file_)
1415 _('cannot follow nonexistent file: "%s"') % file_)
1416 raise FileWalkError("Cannot walk via filelog")
1416 raise FileWalkError("Cannot walk via filelog")
1417 else:
1417 else:
1418 continue
1418 continue
1419
1419
1420 if node is None:
1420 if node is None:
1421 last = len(filelog) - 1
1421 last = len(filelog) - 1
1422 else:
1422 else:
1423 last = filelog.rev(node)
1423 last = filelog.rev(node)
1424
1424
1425
1425
1426 # keep track of all ancestors of the file
1426 # keep track of all ancestors of the file
1427 ancestors = set([filelog.linkrev(last)])
1427 ancestors = set([filelog.linkrev(last)])
1428
1428
1429 # iterate from latest to oldest revision
1429 # iterate from latest to oldest revision
1430 for rev, flparentlinkrevs, copied in filerevgen(filelog, last):
1430 for rev, flparentlinkrevs, copied in filerevgen(filelog, last):
1431 if not follow:
1431 if not follow:
1432 if rev > maxrev:
1432 if rev > maxrev:
1433 continue
1433 continue
1434 else:
1434 else:
1435 # Note that last might not be the first interesting
1435 # Note that last might not be the first interesting
1436 # rev to us:
1436 # rev to us:
1437 # if the file has been changed after maxrev, we'll
1437 # if the file has been changed after maxrev, we'll
1438 # have linkrev(last) > maxrev, and we still need
1438 # have linkrev(last) > maxrev, and we still need
1439 # to explore the file graph
1439 # to explore the file graph
1440 if rev not in ancestors:
1440 if rev not in ancestors:
1441 continue
1441 continue
1442 # XXX insert 1327 fix here
1442 # XXX insert 1327 fix here
1443 if flparentlinkrevs:
1443 if flparentlinkrevs:
1444 ancestors.update(flparentlinkrevs)
1444 ancestors.update(flparentlinkrevs)
1445
1445
1446 fncache.setdefault(rev, []).append(file_)
1446 fncache.setdefault(rev, []).append(file_)
1447 wanted.add(rev)
1447 wanted.add(rev)
1448 if copied:
1448 if copied:
1449 copies.append(copied)
1449 copies.append(copied)
1450
1450
1451 return wanted
1451 return wanted
1452
1452
1453 def walkchangerevs(repo, match, opts, prepare):
1453 def walkchangerevs(repo, match, opts, prepare):
1454 '''Iterate over files and the revs in which they changed.
1454 '''Iterate over files and the revs in which they changed.
1455
1455
1456 Callers most commonly need to iterate backwards over the history
1456 Callers most commonly need to iterate backwards over the history
1457 in which they are interested. Doing so has awful (quadratic-looking)
1457 in which they are interested. Doing so has awful (quadratic-looking)
1458 performance, so we use iterators in a "windowed" way.
1458 performance, so we use iterators in a "windowed" way.
1459
1459
1460 We walk a window of revisions in the desired order. Within the
1460 We walk a window of revisions in the desired order. Within the
1461 window, we first walk forwards to gather data, then in the desired
1461 window, we first walk forwards to gather data, then in the desired
1462 order (usually backwards) to display it.
1462 order (usually backwards) to display it.
1463
1463
1464 This function returns an iterator yielding contexts. Before
1464 This function returns an iterator yielding contexts. Before
1465 yielding each context, the iterator will first call the prepare
1465 yielding each context, the iterator will first call the prepare
1466 function on each context in the window in forward order.'''
1466 function on each context in the window in forward order.'''
1467
1467
1468 follow = opts.get('follow') or opts.get('follow_first')
1468 follow = opts.get('follow') or opts.get('follow_first')
1469
1469
1470 if opts.get('rev'):
1470 if opts.get('rev'):
1471 revs = scmutil.revrange(repo, opts.get('rev'))
1471 revs = scmutil.revrange(repo, opts.get('rev'))
1472 elif follow:
1472 elif follow:
1473 revs = repo.revs('reverse(:.)')
1473 revs = repo.revs('reverse(:.)')
1474 else:
1474 else:
1475 revs = revset.spanset(repo)
1475 revs = revset.spanset(repo)
1476 revs.reverse()
1476 revs.reverse()
1477 if not revs:
1477 if not revs:
1478 return []
1478 return []
1479 wanted = set()
1479 wanted = set()
1480 slowpath = match.anypats() or (match.files() and opts.get('removed'))
1480 slowpath = match.anypats() or (match.files() and opts.get('removed'))
1481 fncache = {}
1481 fncache = {}
1482 change = repo.changectx
1482 change = repo.changectx
1483
1483
1484 # First step is to fill wanted, the set of revisions that we want to yield.
1484 # First step is to fill wanted, the set of revisions that we want to yield.
1485 # When it does not induce extra cost, we also fill fncache for revisions in
1485 # When it does not induce extra cost, we also fill fncache for revisions in
1486 # wanted: a cache of filenames that were changed (ctx.files()) and that
1486 # wanted: a cache of filenames that were changed (ctx.files()) and that
1487 # match the file filtering conditions.
1487 # match the file filtering conditions.
1488
1488
1489 if not slowpath and not match.files():
1489 if not slowpath and not match.files():
1490 # No files, no patterns. Display all revs.
1490 # No files, no patterns. Display all revs.
1491 wanted = revs
1491 wanted = revs
1492
1492
1493 if not slowpath and match.files():
1493 if not slowpath and match.files():
1494 # We only have to read through the filelog to find wanted revisions
1494 # We only have to read through the filelog to find wanted revisions
1495
1495
1496 try:
1496 try:
1497 wanted = walkfilerevs(repo, match, follow, revs, fncache)
1497 wanted = walkfilerevs(repo, match, follow, revs, fncache)
1498 except FileWalkError:
1498 except FileWalkError:
1499 slowpath = True
1499 slowpath = True
1500
1500
1501 # We decided to fall back to the slowpath because at least one
1501 # We decided to fall back to the slowpath because at least one
1502 # of the paths was not a file. Check to see if at least one of them
1502 # of the paths was not a file. Check to see if at least one of them
1503 # existed in history, otherwise simply return
1503 # existed in history, otherwise simply return
1504 for path in match.files():
1504 for path in match.files():
1505 if path == '.' or path in repo.store:
1505 if path == '.' or path in repo.store:
1506 break
1506 break
1507 else:
1507 else:
1508 return []
1508 return []
1509
1509
1510 if slowpath:
1510 if slowpath:
1511 # We have to read the changelog to match filenames against
1511 # We have to read the changelog to match filenames against
1512 # changed files
1512 # changed files
1513
1513
1514 if follow:
1514 if follow:
1515 raise util.Abort(_('can only follow copies/renames for explicit '
1515 raise util.Abort(_('can only follow copies/renames for explicit '
1516 'filenames'))
1516 'filenames'))
1517
1517
1518 # The slow path checks files modified in every changeset.
1518 # The slow path checks files modified in every changeset.
1519 # This is really slow on large repos, so compute the set lazily.
1519 # This is really slow on large repos, so compute the set lazily.
1520 class lazywantedset(object):
1520 class lazywantedset(object):
1521 def __init__(self):
1521 def __init__(self):
1522 self.set = set()
1522 self.set = set()
1523 self.revs = set(revs)
1523 self.revs = set(revs)
1524
1524
1525 # No need to worry about locality here because it will be accessed
1525 # No need to worry about locality here because it will be accessed
1526 # in the same order as the increasing window below.
1526 # in the same order as the increasing window below.
1527 def __contains__(self, value):
1527 def __contains__(self, value):
1528 if value in self.set:
1528 if value in self.set:
1529 return True
1529 return True
1530 elif not value in self.revs:
1530 elif not value in self.revs:
1531 return False
1531 return False
1532 else:
1532 else:
1533 self.revs.discard(value)
1533 self.revs.discard(value)
1534 ctx = change(value)
1534 ctx = change(value)
1535 matches = filter(match, ctx.files())
1535 matches = filter(match, ctx.files())
1536 if matches:
1536 if matches:
1537 fncache[value] = matches
1537 fncache[value] = matches
1538 self.set.add(value)
1538 self.set.add(value)
1539 return True
1539 return True
1540 return False
1540 return False
1541
1541
1542 def discard(self, value):
1542 def discard(self, value):
1543 self.revs.discard(value)
1543 self.revs.discard(value)
1544 self.set.discard(value)
1544 self.set.discard(value)
1545
1545
1546 wanted = lazywantedset()
1546 wanted = lazywantedset()
1547
1547
1548 class followfilter(object):
1548 class followfilter(object):
1549 def __init__(self, onlyfirst=False):
1549 def __init__(self, onlyfirst=False):
1550 self.startrev = nullrev
1550 self.startrev = nullrev
1551 self.roots = set()
1551 self.roots = set()
1552 self.onlyfirst = onlyfirst
1552 self.onlyfirst = onlyfirst
1553
1553
1554 def match(self, rev):
1554 def match(self, rev):
1555 def realparents(rev):
1555 def realparents(rev):
1556 if self.onlyfirst:
1556 if self.onlyfirst:
1557 return repo.changelog.parentrevs(rev)[0:1]
1557 return repo.changelog.parentrevs(rev)[0:1]
1558 else:
1558 else:
1559 return filter(lambda x: x != nullrev,
1559 return filter(lambda x: x != nullrev,
1560 repo.changelog.parentrevs(rev))
1560 repo.changelog.parentrevs(rev))
1561
1561
1562 if self.startrev == nullrev:
1562 if self.startrev == nullrev:
1563 self.startrev = rev
1563 self.startrev = rev
1564 return True
1564 return True
1565
1565
1566 if rev > self.startrev:
1566 if rev > self.startrev:
1567 # forward: all descendants
1567 # forward: all descendants
1568 if not self.roots:
1568 if not self.roots:
1569 self.roots.add(self.startrev)
1569 self.roots.add(self.startrev)
1570 for parent in realparents(rev):
1570 for parent in realparents(rev):
1571 if parent in self.roots:
1571 if parent in self.roots:
1572 self.roots.add(rev)
1572 self.roots.add(rev)
1573 return True
1573 return True
1574 else:
1574 else:
1575 # backwards: all parents
1575 # backwards: all parents
1576 if not self.roots:
1576 if not self.roots:
1577 self.roots.update(realparents(self.startrev))
1577 self.roots.update(realparents(self.startrev))
1578 if rev in self.roots:
1578 if rev in self.roots:
1579 self.roots.remove(rev)
1579 self.roots.remove(rev)
1580 self.roots.update(realparents(rev))
1580 self.roots.update(realparents(rev))
1581 return True
1581 return True
1582
1582
1583 return False
1583 return False
1584
1584
1585 # it might be worthwhile to do this in the iterator if the rev range
1585 # it might be worthwhile to do this in the iterator if the rev range
1586 # is descending and the prune args are all within that range
1586 # is descending and the prune args are all within that range
1587 for rev in opts.get('prune', ()):
1587 for rev in opts.get('prune', ()):
1588 rev = repo[rev].rev()
1588 rev = repo[rev].rev()
1589 ff = followfilter()
1589 ff = followfilter()
1590 stop = min(revs[0], revs[-1])
1590 stop = min(revs[0], revs[-1])
1591 for x in xrange(rev, stop - 1, -1):
1591 for x in xrange(rev, stop - 1, -1):
1592 if ff.match(x):
1592 if ff.match(x):
1593 wanted = wanted - [x]
1593 wanted = wanted - [x]
1594
1594
1595 # Now that wanted is correctly initialized, we can iterate over the
1595 # Now that wanted is correctly initialized, we can iterate over the
1596 # revision range, yielding only revisions in wanted.
1596 # revision range, yielding only revisions in wanted.
1597 def iterate():
1597 def iterate():
1598 if follow and not match.files():
1598 if follow and not match.files():
1599 ff = followfilter(onlyfirst=opts.get('follow_first'))
1599 ff = followfilter(onlyfirst=opts.get('follow_first'))
1600 def want(rev):
1600 def want(rev):
1601 return ff.match(rev) and rev in wanted
1601 return ff.match(rev) and rev in wanted
1602 else:
1602 else:
1603 def want(rev):
1603 def want(rev):
1604 return rev in wanted
1604 return rev in wanted
1605
1605
1606 it = iter(revs)
1606 it = iter(revs)
1607 stopiteration = False
1607 stopiteration = False
1608 for windowsize in increasingwindows():
1608 for windowsize in increasingwindows():
1609 nrevs = []
1609 nrevs = []
1610 for i in xrange(windowsize):
1610 for i in xrange(windowsize):
1611 try:
1611 try:
1612 rev = it.next()
1612 rev = it.next()
1613 if want(rev):
1613 if want(rev):
1614 nrevs.append(rev)
1614 nrevs.append(rev)
1615 except (StopIteration):
1615 except (StopIteration):
1616 stopiteration = True
1616 stopiteration = True
1617 break
1617 break
1618 for rev in sorted(nrevs):
1618 for rev in sorted(nrevs):
1619 fns = fncache.get(rev)
1619 fns = fncache.get(rev)
1620 ctx = change(rev)
1620 ctx = change(rev)
1621 if not fns:
1621 if not fns:
1622 def fns_generator():
1622 def fns_generator():
1623 for f in ctx.files():
1623 for f in ctx.files():
1624 if match(f):
1624 if match(f):
1625 yield f
1625 yield f
1626 fns = fns_generator()
1626 fns = fns_generator()
1627 prepare(ctx, fns)
1627 prepare(ctx, fns)
1628 for rev in nrevs:
1628 for rev in nrevs:
1629 yield change(rev)
1629 yield change(rev)
1630
1630
1631 if stopiteration:
1631 if stopiteration:
1632 break
1632 break
1633
1633
1634 return iterate()
1634 return iterate()
1635
1635
1636 def _makefollowlogfilematcher(repo, files, followfirst):
1636 def _makefollowlogfilematcher(repo, files, followfirst):
1637 # When displaying a revision with --patch --follow FILE, we have
1637 # When displaying a revision with --patch --follow FILE, we have
1638 # to know which file of the revision must be diffed. With
1638 # to know which file of the revision must be diffed. With
1639 # --follow, we want the names of the ancestors of FILE in the
1639 # --follow, we want the names of the ancestors of FILE in the
1640 # revision, stored in "fcache". "fcache" is populated by
1640 # revision, stored in "fcache". "fcache" is populated by
1641 # reproducing the graph traversal already done by --follow revset
1641 # reproducing the graph traversal already done by --follow revset
1642 # and relating linkrevs to file names (which is not "correct" but
1642 # and relating linkrevs to file names (which is not "correct" but
1643 # good enough).
1643 # good enough).
1644 fcache = {}
1644 fcache = {}
1645 fcacheready = [False]
1645 fcacheready = [False]
1646 pctx = repo['.']
1646 pctx = repo['.']
1647
1647
1648 def populate():
1648 def populate():
1649 for fn in files:
1649 for fn in files:
1650 for i in ((pctx[fn],), pctx[fn].ancestors(followfirst=followfirst)):
1650 for i in ((pctx[fn],), pctx[fn].ancestors(followfirst=followfirst)):
1651 for c in i:
1651 for c in i:
1652 fcache.setdefault(c.linkrev(), set()).add(c.path())
1652 fcache.setdefault(c.linkrev(), set()).add(c.path())
1653
1653
1654 def filematcher(rev):
1654 def filematcher(rev):
1655 if not fcacheready[0]:
1655 if not fcacheready[0]:
1656 # Lazy initialization
1656 # Lazy initialization
1657 fcacheready[0] = True
1657 fcacheready[0] = True
1658 populate()
1658 populate()
1659 return scmutil.matchfiles(repo, fcache.get(rev, []))
1659 return scmutil.matchfiles(repo, fcache.get(rev, []))
1660
1660
1661 return filematcher
1661 return filematcher
1662
1662
1663 def _makenofollowlogfilematcher(repo, pats, opts):
1663 def _makenofollowlogfilematcher(repo, pats, opts):
1664 '''hook for extensions to override the filematcher for non-follow cases'''
1664 '''hook for extensions to override the filematcher for non-follow cases'''
1665 return None
1665 return None
1666
1666
1667 def _makelogrevset(repo, pats, opts, revs):
1667 def _makelogrevset(repo, pats, opts, revs):
1668 """Return (expr, filematcher) where expr is a revset string built
1668 """Return (expr, filematcher) where expr is a revset string built
1669 from log options and file patterns or None. If --stat or --patch
1669 from log options and file patterns or None. If --stat or --patch
1670 are not passed filematcher is None. Otherwise it is a callable
1670 are not passed filematcher is None. Otherwise it is a callable
1671 taking a revision number and returning a match objects filtering
1671 taking a revision number and returning a match objects filtering
1672 the files to be detailed when displaying the revision.
1672 the files to be detailed when displaying the revision.
1673 """
1673 """
1674 opt2revset = {
1674 opt2revset = {
1675 'no_merges': ('not merge()', None),
1675 'no_merges': ('not merge()', None),
1676 'only_merges': ('merge()', None),
1676 'only_merges': ('merge()', None),
1677 '_ancestors': ('ancestors(%(val)s)', None),
1677 '_ancestors': ('ancestors(%(val)s)', None),
1678 '_fancestors': ('_firstancestors(%(val)s)', None),
1678 '_fancestors': ('_firstancestors(%(val)s)', None),
1679 '_descendants': ('descendants(%(val)s)', None),
1679 '_descendants': ('descendants(%(val)s)', None),
1680 '_fdescendants': ('_firstdescendants(%(val)s)', None),
1680 '_fdescendants': ('_firstdescendants(%(val)s)', None),
1681 '_matchfiles': ('_matchfiles(%(val)s)', None),
1681 '_matchfiles': ('_matchfiles(%(val)s)', None),
1682 'date': ('date(%(val)r)', None),
1682 'date': ('date(%(val)r)', None),
1683 'branch': ('branch(%(val)r)', ' or '),
1683 'branch': ('branch(%(val)r)', ' or '),
1684 '_patslog': ('filelog(%(val)r)', ' or '),
1684 '_patslog': ('filelog(%(val)r)', ' or '),
1685 '_patsfollow': ('follow(%(val)r)', ' or '),
1685 '_patsfollow': ('follow(%(val)r)', ' or '),
1686 '_patsfollowfirst': ('_followfirst(%(val)r)', ' or '),
1686 '_patsfollowfirst': ('_followfirst(%(val)r)', ' or '),
1687 'keyword': ('keyword(%(val)r)', ' or '),
1687 'keyword': ('keyword(%(val)r)', ' or '),
1688 'prune': ('not (%(val)r or ancestors(%(val)r))', ' and '),
1688 'prune': ('not (%(val)r or ancestors(%(val)r))', ' and '),
1689 'user': ('user(%(val)r)', ' or '),
1689 'user': ('user(%(val)r)', ' or '),
1690 }
1690 }
1691
1691
1692 opts = dict(opts)
1692 opts = dict(opts)
1693 # follow or not follow?
1693 # follow or not follow?
1694 follow = opts.get('follow') or opts.get('follow_first')
1694 follow = opts.get('follow') or opts.get('follow_first')
1695 followfirst = opts.get('follow_first') and 1 or 0
1695 followfirst = opts.get('follow_first') and 1 or 0
1696 # --follow with FILE behaviour depends on revs...
1696 # --follow with FILE behaviour depends on revs...
1697 it = iter(revs)
1697 it = iter(revs)
1698 startrev = it.next()
1698 startrev = it.next()
1699 try:
1699 try:
1700 followdescendants = startrev < it.next()
1700 followdescendants = startrev < it.next()
1701 except (StopIteration):
1701 except (StopIteration):
1702 followdescendants = False
1702 followdescendants = False
1703
1703
1704 # branch and only_branch are really aliases and must be handled at
1704 # branch and only_branch are really aliases and must be handled at
1705 # the same time
1705 # the same time
1706 opts['branch'] = opts.get('branch', []) + opts.get('only_branch', [])
1706 opts['branch'] = opts.get('branch', []) + opts.get('only_branch', [])
1707 opts['branch'] = [repo.lookupbranch(b) for b in opts['branch']]
1707 opts['branch'] = [repo.lookupbranch(b) for b in opts['branch']]
1708 # pats/include/exclude are passed to match.match() directly in
1708 # pats/include/exclude are passed to match.match() directly in
1709 # _matchfiles() revset but walkchangerevs() builds its matcher with
1709 # _matchfiles() revset but walkchangerevs() builds its matcher with
1710 # scmutil.match(). The difference is input pats are globbed on
1710 # scmutil.match(). The difference is input pats are globbed on
1711 # platforms without shell expansion (windows).
1711 # platforms without shell expansion (windows).
1712 pctx = repo[None]
1712 pctx = repo[None]
1713 match, pats = scmutil.matchandpats(pctx, pats, opts)
1713 match, pats = scmutil.matchandpats(pctx, pats, opts)
1714 slowpath = match.anypats() or (match.files() and opts.get('removed'))
1714 slowpath = match.anypats() or (match.files() and opts.get('removed'))
1715 if not slowpath:
1715 if not slowpath:
1716 for f in match.files():
1716 for f in match.files():
1717 if follow and f not in pctx:
1717 if follow and f not in pctx:
1718 # If the file exists, it may be a directory, so let it
1718 # If the file exists, it may be a directory, so let it
1719 # take the slow path.
1719 # take the slow path.
1720 if os.path.exists(repo.wjoin(f)):
1720 if os.path.exists(repo.wjoin(f)):
1721 slowpath = True
1721 slowpath = True
1722 continue
1722 continue
1723 else:
1723 else:
1724 raise util.Abort(_('cannot follow file not in parent '
1724 raise util.Abort(_('cannot follow file not in parent '
1725 'revision: "%s"') % f)
1725 'revision: "%s"') % f)
1726 filelog = repo.file(f)
1726 filelog = repo.file(f)
1727 if not filelog:
1727 if not filelog:
1728 # A zero count may be a directory or deleted file, so
1728 # A zero count may be a directory or deleted file, so
1729 # try to find matching entries on the slow path.
1729 # try to find matching entries on the slow path.
1730 if follow:
1730 if follow:
1731 raise util.Abort(
1731 raise util.Abort(
1732 _('cannot follow nonexistent file: "%s"') % f)
1732 _('cannot follow nonexistent file: "%s"') % f)
1733 slowpath = True
1733 slowpath = True
1734
1734
1735 # We decided to fall back to the slowpath because at least one
1735 # We decided to fall back to the slowpath because at least one
1736 # of the paths was not a file. Check to see if at least one of them
1736 # of the paths was not a file. Check to see if at least one of them
1737 # existed in history - in that case, we'll continue down the
1737 # existed in history - in that case, we'll continue down the
1738 # slowpath; otherwise, we can turn off the slowpath
1738 # slowpath; otherwise, we can turn off the slowpath
1739 if slowpath:
1739 if slowpath:
1740 for path in match.files():
1740 for path in match.files():
1741 if path == '.' or path in repo.store:
1741 if path == '.' or path in repo.store:
1742 break
1742 break
1743 else:
1743 else:
1744 slowpath = False
1744 slowpath = False
1745
1745
1746 if slowpath:
1746 if slowpath:
1747 # See walkchangerevs() slow path.
1747 # See walkchangerevs() slow path.
1748 #
1748 #
1749 # pats/include/exclude cannot be represented as separate
1749 # pats/include/exclude cannot be represented as separate
1750 # revset expressions as their filtering logic applies at file
1750 # revset expressions as their filtering logic applies at file
1751 # level. For instance "-I a -X a" matches a revision touching
1751 # level. For instance "-I a -X a" matches a revision touching
1752 # "a" and "b" while "file(a) and not file(b)" does
1752 # "a" and "b" while "file(a) and not file(b)" does
1753 # not. Besides, filesets are evaluated against the working
1753 # not. Besides, filesets are evaluated against the working
1754 # directory.
1754 # directory.
1755 matchargs = ['r:', 'd:relpath']
1755 matchargs = ['r:', 'd:relpath']
1756 for p in pats:
1756 for p in pats:
1757 matchargs.append('p:' + p)
1757 matchargs.append('p:' + p)
1758 for p in opts.get('include', []):
1758 for p in opts.get('include', []):
1759 matchargs.append('i:' + p)
1759 matchargs.append('i:' + p)
1760 for p in opts.get('exclude', []):
1760 for p in opts.get('exclude', []):
1761 matchargs.append('x:' + p)
1761 matchargs.append('x:' + p)
1762 matchargs = ','.join(('%r' % p) for p in matchargs)
1762 matchargs = ','.join(('%r' % p) for p in matchargs)
1763 opts['_matchfiles'] = matchargs
1763 opts['_matchfiles'] = matchargs
1764 else:
1764 else:
1765 if follow:
1765 if follow:
1766 fpats = ('_patsfollow', '_patsfollowfirst')
1766 fpats = ('_patsfollow', '_patsfollowfirst')
1767 fnopats = (('_ancestors', '_fancestors'),
1767 fnopats = (('_ancestors', '_fancestors'),
1768 ('_descendants', '_fdescendants'))
1768 ('_descendants', '_fdescendants'))
1769 if pats:
1769 if pats:
1770 # follow() revset interprets its file argument as a
1770 # follow() revset interprets its file argument as a
1771 # manifest entry, so use match.files(), not pats.
1771 # manifest entry, so use match.files(), not pats.
1772 opts[fpats[followfirst]] = list(match.files())
1772 opts[fpats[followfirst]] = list(match.files())
1773 else:
1773 else:
1774 opts[fnopats[followdescendants][followfirst]] = str(startrev)
1774 opts[fnopats[followdescendants][followfirst]] = str(startrev)
1775 else:
1775 else:
1776 opts['_patslog'] = list(pats)
1776 opts['_patslog'] = list(pats)
1777
1777
1778 filematcher = None
1778 filematcher = None
1779 if opts.get('patch') or opts.get('stat'):
1779 if opts.get('patch') or opts.get('stat'):
1780 # When following files, track renames via a special matcher.
1780 # When following files, track renames via a special matcher.
1781 # If we're forced to take the slowpath it means we're following
1781 # If we're forced to take the slowpath it means we're following
1782 # at least one pattern/directory, so don't bother with rename tracking.
1782 # at least one pattern/directory, so don't bother with rename tracking.
1783 if follow and not match.always() and not slowpath:
1783 if follow and not match.always() and not slowpath:
1784 # _makelogfilematcher expects its files argument to be relative to
1784 # _makelogfilematcher expects its files argument to be relative to
1785 # the repo root, so use match.files(), not pats.
1785 # the repo root, so use match.files(), not pats.
1786 filematcher = _makefollowlogfilematcher(repo, match.files(),
1786 filematcher = _makefollowlogfilematcher(repo, match.files(),
1787 followfirst)
1787 followfirst)
1788 else:
1788 else:
1789 filematcher = _makenofollowlogfilematcher(repo, pats, opts)
1789 filematcher = _makenofollowlogfilematcher(repo, pats, opts)
1790 if filematcher is None:
1790 if filematcher is None:
1791 filematcher = lambda rev: match
1791 filematcher = lambda rev: match
1792
1792
1793 expr = []
1793 expr = []
1794 for op, val in opts.iteritems():
1794 for op, val in opts.iteritems():
1795 if not val:
1795 if not val:
1796 continue
1796 continue
1797 if op not in opt2revset:
1797 if op not in opt2revset:
1798 continue
1798 continue
1799 revop, andor = opt2revset[op]
1799 revop, andor = opt2revset[op]
1800 if '%(val)' not in revop:
1800 if '%(val)' not in revop:
1801 expr.append(revop)
1801 expr.append(revop)
1802 else:
1802 else:
1803 if not isinstance(val, list):
1803 if not isinstance(val, list):
1804 e = revop % {'val': val}
1804 e = revop % {'val': val}
1805 else:
1805 else:
1806 e = '(' + andor.join((revop % {'val': v}) for v in val) + ')'
1806 e = '(' + andor.join((revop % {'val': v}) for v in val) + ')'
1807 expr.append(e)
1807 expr.append(e)
1808
1808
1809 if expr:
1809 if expr:
1810 expr = '(' + ' and '.join(expr) + ')'
1810 expr = '(' + ' and '.join(expr) + ')'
1811 else:
1811 else:
1812 expr = None
1812 expr = None
1813 return expr, filematcher
1813 return expr, filematcher
1814
1814
1815 def getgraphlogrevs(repo, pats, opts):
1815 def getgraphlogrevs(repo, pats, opts):
1816 """Return (revs, expr, filematcher) where revs is an iterable of
1816 """Return (revs, expr, filematcher) where revs is an iterable of
1817 revision numbers, expr is a revset string built from log options
1817 revision numbers, expr is a revset string built from log options
1818 and file patterns or None, and used to filter 'revs'. If --stat or
1818 and file patterns or None, and used to filter 'revs'. If --stat or
1819 --patch are not passed filematcher is None. Otherwise it is a
1819 --patch are not passed filematcher is None. Otherwise it is a
1820 callable taking a revision number and returning a match objects
1820 callable taking a revision number and returning a match objects
1821 filtering the files to be detailed when displaying the revision.
1821 filtering the files to be detailed when displaying the revision.
1822 """
1822 """
1823 if not len(repo):
1823 if not len(repo):
1824 return [], None, None
1824 return [], None, None
1825 limit = loglimit(opts)
1825 limit = loglimit(opts)
1826 # Default --rev value depends on --follow but --follow behaviour
1826 # Default --rev value depends on --follow but --follow behaviour
1827 # depends on revisions resolved from --rev...
1827 # depends on revisions resolved from --rev...
1828 follow = opts.get('follow') or opts.get('follow_first')
1828 follow = opts.get('follow') or opts.get('follow_first')
1829 possiblyunsorted = False # whether revs might need sorting
1829 possiblyunsorted = False # whether revs might need sorting
1830 if opts.get('rev'):
1830 if opts.get('rev'):
1831 revs = scmutil.revrange(repo, opts['rev'])
1831 revs = scmutil.revrange(repo, opts['rev'])
1832 # Don't sort here because _makelogrevset might depend on the
1832 # Don't sort here because _makelogrevset might depend on the
1833 # order of revs
1833 # order of revs
1834 possiblyunsorted = True
1834 possiblyunsorted = True
1835 else:
1835 else:
1836 if follow and len(repo) > 0:
1836 if follow and len(repo) > 0:
1837 revs = repo.revs('reverse(:.)')
1837 revs = repo.revs('reverse(:.)')
1838 else:
1838 else:
1839 revs = revset.spanset(repo)
1839 revs = revset.spanset(repo)
1840 revs.reverse()
1840 revs.reverse()
1841 if not revs:
1841 if not revs:
1842 return revset.baseset(), None, None
1842 return revset.baseset(), None, None
1843 expr, filematcher = _makelogrevset(repo, pats, opts, revs)
1843 expr, filematcher = _makelogrevset(repo, pats, opts, revs)
1844 if possiblyunsorted:
1844 if possiblyunsorted:
1845 revs.sort(reverse=True)
1845 revs.sort(reverse=True)
1846 if expr:
1846 if expr:
1847 # Revset matchers often operate faster on revisions in changelog
1847 # Revset matchers often operate faster on revisions in changelog
1848 # order, because most filters deal with the changelog.
1848 # order, because most filters deal with the changelog.
1849 revs.reverse()
1849 revs.reverse()
1850 matcher = revset.match(repo.ui, expr)
1850 matcher = revset.match(repo.ui, expr)
1851 # Revset matches can reorder revisions. "A or B" typically returns
1851 # Revset matches can reorder revisions. "A or B" typically returns
1852 # returns the revision matching A then the revision matching B. Sort
1852 # returns the revision matching A then the revision matching B. Sort
1853 # again to fix that.
1853 # again to fix that.
1854 revs = matcher(repo, revs)
1854 revs = matcher(repo, revs)
1855 revs.sort(reverse=True)
1855 revs.sort(reverse=True)
1856 if limit is not None:
1856 if limit is not None:
1857 limitedrevs = revset.baseset()
1857 limitedrevs = revset.baseset()
1858 for idx, rev in enumerate(revs):
1858 for idx, rev in enumerate(revs):
1859 if idx >= limit:
1859 if idx >= limit:
1860 break
1860 break
1861 limitedrevs.append(rev)
1861 limitedrevs.append(rev)
1862 revs = limitedrevs
1862 revs = limitedrevs
1863
1863
1864 return revs, expr, filematcher
1864 return revs, expr, filematcher
1865
1865
1866 def getlogrevs(repo, pats, opts):
1866 def getlogrevs(repo, pats, opts):
1867 """Return (revs, expr, filematcher) where revs is an iterable of
1867 """Return (revs, expr, filematcher) where revs is an iterable of
1868 revision numbers, expr is a revset string built from log options
1868 revision numbers, expr is a revset string built from log options
1869 and file patterns or None, and used to filter 'revs'. If --stat or
1869 and file patterns or None, and used to filter 'revs'. If --stat or
1870 --patch are not passed filematcher is None. Otherwise it is a
1870 --patch are not passed filematcher is None. Otherwise it is a
1871 callable taking a revision number and returning a match objects
1871 callable taking a revision number and returning a match objects
1872 filtering the files to be detailed when displaying the revision.
1872 filtering the files to be detailed when displaying the revision.
1873 """
1873 """
1874 limit = loglimit(opts)
1874 limit = loglimit(opts)
1875 # Default --rev value depends on --follow but --follow behaviour
1875 # Default --rev value depends on --follow but --follow behaviour
1876 # depends on revisions resolved from --rev...
1876 # depends on revisions resolved from --rev...
1877 follow = opts.get('follow') or opts.get('follow_first')
1877 follow = opts.get('follow') or opts.get('follow_first')
1878 if opts.get('rev'):
1878 if opts.get('rev'):
1879 revs = scmutil.revrange(repo, opts['rev'])
1879 revs = scmutil.revrange(repo, opts['rev'])
1880 elif follow:
1880 elif follow:
1881 revs = repo.revs('reverse(:.)')
1881 revs = repo.revs('reverse(:.)')
1882 else:
1882 else:
1883 revs = revset.spanset(repo)
1883 revs = revset.spanset(repo)
1884 revs.reverse()
1884 revs.reverse()
1885 if not revs:
1885 if not revs:
1886 return revset.baseset([]), None, None
1886 return revset.baseset([]), None, None
1887 expr, filematcher = _makelogrevset(repo, pats, opts, revs)
1887 expr, filematcher = _makelogrevset(repo, pats, opts, revs)
1888 if expr:
1888 if expr:
1889 # Revset matchers often operate faster on revisions in changelog
1889 # Revset matchers often operate faster on revisions in changelog
1890 # order, because most filters deal with the changelog.
1890 # order, because most filters deal with the changelog.
1891 if not opts.get('rev'):
1891 if not opts.get('rev'):
1892 revs.reverse()
1892 revs.reverse()
1893 matcher = revset.match(repo.ui, expr)
1893 matcher = revset.match(repo.ui, expr)
1894 # Revset matches can reorder revisions. "A or B" typically returns
1894 # Revset matches can reorder revisions. "A or B" typically returns
1895 # returns the revision matching A then the revision matching B. Sort
1895 # returns the revision matching A then the revision matching B. Sort
1896 # again to fix that.
1896 # again to fix that.
1897 revs = matcher(repo, revs)
1897 revs = matcher(repo, revs)
1898 if not opts.get('rev'):
1898 if not opts.get('rev'):
1899 revs.sort(reverse=True)
1899 revs.sort(reverse=True)
1900 if limit is not None:
1900 if limit is not None:
1901 count = 0
1901 count = 0
1902 limitedrevs = revset.baseset([])
1902 limitedrevs = revset.baseset([])
1903 it = iter(revs)
1903 it = iter(revs)
1904 while count < limit:
1904 while count < limit:
1905 try:
1905 try:
1906 limitedrevs.append(it.next())
1906 limitedrevs.append(it.next())
1907 except (StopIteration):
1907 except (StopIteration):
1908 break
1908 break
1909 count += 1
1909 count += 1
1910 revs = limitedrevs
1910 revs = limitedrevs
1911
1911
1912 return revs, expr, filematcher
1912 return revs, expr, filematcher
1913
1913
1914 def displaygraph(ui, dag, displayer, showparents, edgefn, getrenamed=None,
1914 def displaygraph(ui, dag, displayer, showparents, edgefn, getrenamed=None,
1915 filematcher=None):
1915 filematcher=None):
1916 seen, state = [], graphmod.asciistate()
1916 seen, state = [], graphmod.asciistate()
1917 for rev, type, ctx, parents in dag:
1917 for rev, type, ctx, parents in dag:
1918 char = 'o'
1918 char = 'o'
1919 if ctx.node() in showparents:
1919 if ctx.node() in showparents:
1920 char = '@'
1920 char = '@'
1921 elif ctx.obsolete():
1921 elif ctx.obsolete():
1922 char = 'x'
1922 char = 'x'
1923 copies = None
1923 copies = None
1924 if getrenamed and ctx.rev():
1924 if getrenamed and ctx.rev():
1925 copies = []
1925 copies = []
1926 for fn in ctx.files():
1926 for fn in ctx.files():
1927 rename = getrenamed(fn, ctx.rev())
1927 rename = getrenamed(fn, ctx.rev())
1928 if rename:
1928 if rename:
1929 copies.append((fn, rename[0]))
1929 copies.append((fn, rename[0]))
1930 revmatchfn = None
1930 revmatchfn = None
1931 if filematcher is not None:
1931 if filematcher is not None:
1932 revmatchfn = filematcher(ctx.rev())
1932 revmatchfn = filematcher(ctx.rev())
1933 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
1933 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
1934 lines = displayer.hunk.pop(rev).split('\n')
1934 lines = displayer.hunk.pop(rev).split('\n')
1935 if not lines[-1]:
1935 if not lines[-1]:
1936 del lines[-1]
1936 del lines[-1]
1937 displayer.flush(rev)
1937 displayer.flush(rev)
1938 edges = edgefn(type, char, lines, seen, rev, parents)
1938 edges = edgefn(type, char, lines, seen, rev, parents)
1939 for type, char, lines, coldata in edges:
1939 for type, char, lines, coldata in edges:
1940 graphmod.ascii(ui, state, type, char, lines, coldata)
1940 graphmod.ascii(ui, state, type, char, lines, coldata)
1941 displayer.close()
1941 displayer.close()
1942
1942
1943 def graphlog(ui, repo, *pats, **opts):
1943 def graphlog(ui, repo, *pats, **opts):
1944 # Parameters are identical to log command ones
1944 # Parameters are identical to log command ones
1945 revs, expr, filematcher = getgraphlogrevs(repo, pats, opts)
1945 revs, expr, filematcher = getgraphlogrevs(repo, pats, opts)
1946 revdag = graphmod.dagwalker(repo, revs)
1946 revdag = graphmod.dagwalker(repo, revs)
1947
1947
1948 getrenamed = None
1948 getrenamed = None
1949 if opts.get('copies'):
1949 if opts.get('copies'):
1950 endrev = None
1950 endrev = None
1951 if opts.get('rev'):
1951 if opts.get('rev'):
1952 endrev = scmutil.revrange(repo, opts.get('rev')).max() + 1
1952 endrev = scmutil.revrange(repo, opts.get('rev')).max() + 1
1953 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
1953 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
1954 displayer = show_changeset(ui, repo, opts, buffered=True)
1954 displayer = show_changeset(ui, repo, opts, buffered=True)
1955 showparents = [ctx.node() for ctx in repo[None].parents()]
1955 showparents = [ctx.node() for ctx in repo[None].parents()]
1956 displaygraph(ui, revdag, displayer, showparents,
1956 displaygraph(ui, revdag, displayer, showparents,
1957 graphmod.asciiedges, getrenamed, filematcher)
1957 graphmod.asciiedges, getrenamed, filematcher)
1958
1958
1959 def checkunsupportedgraphflags(pats, opts):
1959 def checkunsupportedgraphflags(pats, opts):
1960 for op in ["newest_first"]:
1960 for op in ["newest_first"]:
1961 if op in opts and opts[op]:
1961 if op in opts and opts[op]:
1962 raise util.Abort(_("-G/--graph option is incompatible with --%s")
1962 raise util.Abort(_("-G/--graph option is incompatible with --%s")
1963 % op.replace("_", "-"))
1963 % op.replace("_", "-"))
1964
1964
1965 def graphrevs(repo, nodes, opts):
1965 def graphrevs(repo, nodes, opts):
1966 limit = loglimit(opts)
1966 limit = loglimit(opts)
1967 nodes.reverse()
1967 nodes.reverse()
1968 if limit is not None:
1968 if limit is not None:
1969 nodes = nodes[:limit]
1969 nodes = nodes[:limit]
1970 return graphmod.nodes(repo, nodes)
1970 return graphmod.nodes(repo, nodes)
1971
1971
1972 def add(ui, repo, match, dryrun, listsubrepos, prefix, explicitonly):
1972 def add(ui, repo, match, dryrun, listsubrepos, prefix, explicitonly):
1973 join = lambda f: os.path.join(prefix, f)
1973 join = lambda f: os.path.join(prefix, f)
1974 bad = []
1974 bad = []
1975 oldbad = match.bad
1975 oldbad = match.bad
1976 match.bad = lambda x, y: bad.append(x) or oldbad(x, y)
1976 match.bad = lambda x, y: bad.append(x) or oldbad(x, y)
1977 names = []
1977 names = []
1978 wctx = repo[None]
1978 wctx = repo[None]
1979 cca = None
1979 cca = None
1980 abort, warn = scmutil.checkportabilityalert(ui)
1980 abort, warn = scmutil.checkportabilityalert(ui)
1981 if abort or warn:
1981 if abort or warn:
1982 cca = scmutil.casecollisionauditor(ui, abort, repo.dirstate)
1982 cca = scmutil.casecollisionauditor(ui, abort, repo.dirstate)
1983 for f in repo.walk(match):
1983 for f in repo.walk(match):
1984 exact = match.exact(f)
1984 exact = match.exact(f)
1985 if exact or not explicitonly and f not in repo.dirstate:
1985 if exact or not explicitonly and f not in repo.dirstate:
1986 if cca:
1986 if cca:
1987 cca(f)
1987 cca(f)
1988 names.append(f)
1988 names.append(f)
1989 if ui.verbose or not exact:
1989 if ui.verbose or not exact:
1990 ui.status(_('adding %s\n') % match.rel(join(f)))
1990 ui.status(_('adding %s\n') % match.rel(join(f)))
1991
1991
1992 for subpath in sorted(wctx.substate):
1992 for subpath in sorted(wctx.substate):
1993 sub = wctx.sub(subpath)
1993 sub = wctx.sub(subpath)
1994 try:
1994 try:
1995 submatch = matchmod.narrowmatcher(subpath, match)
1995 submatch = matchmod.narrowmatcher(subpath, match)
1996 if listsubrepos:
1996 if listsubrepos:
1997 bad.extend(sub.add(ui, submatch, dryrun, listsubrepos, prefix,
1997 bad.extend(sub.add(ui, submatch, dryrun, listsubrepos, prefix,
1998 False))
1998 False))
1999 else:
1999 else:
2000 bad.extend(sub.add(ui, submatch, dryrun, listsubrepos, prefix,
2000 bad.extend(sub.add(ui, submatch, dryrun, listsubrepos, prefix,
2001 True))
2001 True))
2002 except error.LookupError:
2002 except error.LookupError:
2003 ui.status(_("skipping missing subrepository: %s\n")
2003 ui.status(_("skipping missing subrepository: %s\n")
2004 % join(subpath))
2004 % join(subpath))
2005
2005
2006 if not dryrun:
2006 if not dryrun:
2007 rejected = wctx.add(names, prefix)
2007 rejected = wctx.add(names, prefix)
2008 bad.extend(f for f in rejected if f in match.files())
2008 bad.extend(f for f in rejected if f in match.files())
2009 return bad
2009 return bad
2010
2010
2011 def forget(ui, repo, match, prefix, explicitonly):
2011 def forget(ui, repo, match, prefix, explicitonly):
2012 join = lambda f: os.path.join(prefix, f)
2012 join = lambda f: os.path.join(prefix, f)
2013 bad = []
2013 bad = []
2014 oldbad = match.bad
2014 oldbad = match.bad
2015 match.bad = lambda x, y: bad.append(x) or oldbad(x, y)
2015 match.bad = lambda x, y: bad.append(x) or oldbad(x, y)
2016 wctx = repo[None]
2016 wctx = repo[None]
2017 forgot = []
2017 forgot = []
2018 s = repo.status(match=match, clean=True)
2018 s = repo.status(match=match, clean=True)
2019 forget = sorted(s[0] + s[1] + s[3] + s[6])
2019 forget = sorted(s[0] + s[1] + s[3] + s[6])
2020 if explicitonly:
2020 if explicitonly:
2021 forget = [f for f in forget if match.exact(f)]
2021 forget = [f for f in forget if match.exact(f)]
2022
2022
2023 for subpath in sorted(wctx.substate):
2023 for subpath in sorted(wctx.substate):
2024 sub = wctx.sub(subpath)
2024 sub = wctx.sub(subpath)
2025 try:
2025 try:
2026 submatch = matchmod.narrowmatcher(subpath, match)
2026 submatch = matchmod.narrowmatcher(subpath, match)
2027 subbad, subforgot = sub.forget(ui, submatch, prefix)
2027 subbad, subforgot = sub.forget(ui, submatch, prefix)
2028 bad.extend([subpath + '/' + f for f in subbad])
2028 bad.extend([subpath + '/' + f for f in subbad])
2029 forgot.extend([subpath + '/' + f for f in subforgot])
2029 forgot.extend([subpath + '/' + f for f in subforgot])
2030 except error.LookupError:
2030 except error.LookupError:
2031 ui.status(_("skipping missing subrepository: %s\n")
2031 ui.status(_("skipping missing subrepository: %s\n")
2032 % join(subpath))
2032 % join(subpath))
2033
2033
2034 if not explicitonly:
2034 if not explicitonly:
2035 for f in match.files():
2035 for f in match.files():
2036 if f not in repo.dirstate and not os.path.isdir(match.rel(join(f))):
2036 if f not in repo.dirstate and not os.path.isdir(match.rel(join(f))):
2037 if f not in forgot:
2037 if f not in forgot:
2038 if os.path.exists(match.rel(join(f))):
2038 if os.path.exists(match.rel(join(f))):
2039 ui.warn(_('not removing %s: '
2039 ui.warn(_('not removing %s: '
2040 'file is already untracked\n')
2040 'file is already untracked\n')
2041 % match.rel(join(f)))
2041 % match.rel(join(f)))
2042 bad.append(f)
2042 bad.append(f)
2043
2043
2044 for f in forget:
2044 for f in forget:
2045 if ui.verbose or not match.exact(f):
2045 if ui.verbose or not match.exact(f):
2046 ui.status(_('removing %s\n') % match.rel(join(f)))
2046 ui.status(_('removing %s\n') % match.rel(join(f)))
2047
2047
2048 rejected = wctx.forget(forget, prefix)
2048 rejected = wctx.forget(forget, prefix)
2049 bad.extend(f for f in rejected if f in match.files())
2049 bad.extend(f for f in rejected if f in match.files())
2050 forgot.extend(forget)
2050 forgot.extend(forget)
2051 return bad, forgot
2051 return bad, forgot
2052
2052
2053 def cat(ui, repo, ctx, matcher, prefix, **opts):
2053 def cat(ui, repo, ctx, matcher, prefix, **opts):
2054 err = 1
2054 err = 1
2055
2055
2056 def write(path):
2056 def write(path):
2057 fp = makefileobj(repo, opts.get('output'), ctx.node(),
2057 fp = makefileobj(repo, opts.get('output'), ctx.node(),
2058 pathname=os.path.join(prefix, path))
2058 pathname=os.path.join(prefix, path))
2059 data = ctx[path].data()
2059 data = ctx[path].data()
2060 if opts.get('decode'):
2060 if opts.get('decode'):
2061 data = repo.wwritedata(path, data)
2061 data = repo.wwritedata(path, data)
2062 fp.write(data)
2062 fp.write(data)
2063 fp.close()
2063 fp.close()
2064
2064
2065 # Automation often uses hg cat on single files, so special case it
2065 # Automation often uses hg cat on single files, so special case it
2066 # for performance to avoid the cost of parsing the manifest.
2066 # for performance to avoid the cost of parsing the manifest.
2067 if len(matcher.files()) == 1 and not matcher.anypats():
2067 if len(matcher.files()) == 1 and not matcher.anypats():
2068 file = matcher.files()[0]
2068 file = matcher.files()[0]
2069 mf = repo.manifest
2069 mf = repo.manifest
2070 mfnode = ctx._changeset[0]
2070 mfnode = ctx._changeset[0]
2071 if mf.find(mfnode, file)[0]:
2071 if mf.find(mfnode, file)[0]:
2072 write(file)
2072 write(file)
2073 return 0
2073 return 0
2074
2074
2075 # Don't warn about "missing" files that are really in subrepos
2075 # Don't warn about "missing" files that are really in subrepos
2076 bad = matcher.bad
2076 bad = matcher.bad
2077
2077
2078 def badfn(path, msg):
2078 def badfn(path, msg):
2079 for subpath in ctx.substate:
2079 for subpath in ctx.substate:
2080 if path.startswith(subpath):
2080 if path.startswith(subpath):
2081 return
2081 return
2082 bad(path, msg)
2082 bad(path, msg)
2083
2083
2084 matcher.bad = badfn
2084 matcher.bad = badfn
2085
2085
2086 for abs in ctx.walk(matcher):
2086 for abs in ctx.walk(matcher):
2087 write(abs)
2087 write(abs)
2088 err = 0
2088 err = 0
2089
2089
2090 matcher.bad = bad
2090 matcher.bad = bad
2091
2091
2092 for subpath in sorted(ctx.substate):
2092 for subpath in sorted(ctx.substate):
2093 sub = ctx.sub(subpath)
2093 sub = ctx.sub(subpath)
2094 try:
2094 try:
2095 submatch = matchmod.narrowmatcher(subpath, matcher)
2095 submatch = matchmod.narrowmatcher(subpath, matcher)
2096
2096
2097 if not sub.cat(ui, submatch, os.path.join(prefix, sub._path),
2097 if not sub.cat(ui, submatch, os.path.join(prefix, sub._path),
2098 **opts):
2098 **opts):
2099 err = 0
2099 err = 0
2100 except error.RepoLookupError:
2100 except error.RepoLookupError:
2101 ui.status(_("skipping missing subrepository: %s\n")
2101 ui.status(_("skipping missing subrepository: %s\n")
2102 % os.path.join(prefix, subpath))
2102 % os.path.join(prefix, subpath))
2103
2103
2104 return err
2104 return err
2105
2105
2106 def duplicatecopies(repo, rev, fromrev, skiprev=None):
2106 def duplicatecopies(repo, rev, fromrev, skiprev=None):
2107 '''reproduce copies from fromrev to rev in the dirstate
2107 '''reproduce copies from fromrev to rev in the dirstate
2108
2108
2109 If skiprev is specified, it's a revision that should be used to
2109 If skiprev is specified, it's a revision that should be used to
2110 filter copy records. Any copies that occur between fromrev and
2110 filter copy records. Any copies that occur between fromrev and
2111 skiprev will not be duplicated, even if they appear in the set of
2111 skiprev will not be duplicated, even if they appear in the set of
2112 copies between fromrev and rev.
2112 copies between fromrev and rev.
2113 '''
2113 '''
2114 exclude = {}
2114 exclude = {}
2115 if skiprev is not None:
2115 if skiprev is not None:
2116 exclude = copies.pathcopies(repo[fromrev], repo[skiprev])
2116 exclude = copies.pathcopies(repo[fromrev], repo[skiprev])
2117 for dst, src in copies.pathcopies(repo[fromrev], repo[rev]).iteritems():
2117 for dst, src in copies.pathcopies(repo[fromrev], repo[rev]).iteritems():
2118 # copies.pathcopies returns backward renames, so dst might not
2118 # copies.pathcopies returns backward renames, so dst might not
2119 # actually be in the dirstate
2119 # actually be in the dirstate
2120 if dst in exclude:
2120 if dst in exclude:
2121 continue
2121 continue
2122 if repo.dirstate[dst] in "nma":
2122 if repo.dirstate[dst] in "nma":
2123 repo.dirstate.copy(src, dst)
2123 repo.dirstate.copy(src, dst)
2124
2124
2125 def commit(ui, repo, commitfunc, pats, opts):
2125 def commit(ui, repo, commitfunc, pats, opts):
2126 '''commit the specified files or all outstanding changes'''
2126 '''commit the specified files or all outstanding changes'''
2127 date = opts.get('date')
2127 date = opts.get('date')
2128 if date:
2128 if date:
2129 opts['date'] = util.parsedate(date)
2129 opts['date'] = util.parsedate(date)
2130 message = logmessage(ui, opts)
2130 message = logmessage(ui, opts)
2131
2131
2132 # extract addremove carefully -- this function can be called from a command
2132 # extract addremove carefully -- this function can be called from a command
2133 # that doesn't support addremove
2133 # that doesn't support addremove
2134 if opts.get('addremove'):
2134 if opts.get('addremove'):
2135 scmutil.addremove(repo, pats, opts)
2135 scmutil.addremove(repo, pats, opts)
2136
2136
2137 return commitfunc(ui, repo, message,
2137 return commitfunc(ui, repo, message,
2138 scmutil.match(repo[None], pats, opts), opts)
2138 scmutil.match(repo[None], pats, opts), opts)
2139
2139
2140 def amend(ui, repo, commitfunc, old, extra, pats, opts):
2140 def amend(ui, repo, commitfunc, old, extra, pats, opts):
2141 ui.note(_('amending changeset %s\n') % old)
2141 ui.note(_('amending changeset %s\n') % old)
2142 base = old.p1()
2142 base = old.p1()
2143
2143
2144 wlock = lock = newid = None
2144 wlock = lock = newid = None
2145 try:
2145 try:
2146 wlock = repo.wlock()
2146 wlock = repo.wlock()
2147 lock = repo.lock()
2147 lock = repo.lock()
2148 tr = repo.transaction('amend')
2148 tr = repo.transaction('amend')
2149 try:
2149 try:
2150 # See if we got a message from -m or -l, if not, open the editor
2150 # See if we got a message from -m or -l, if not, open the editor
2151 # with the message of the changeset to amend
2151 # with the message of the changeset to amend
2152 message = logmessage(ui, opts)
2152 message = logmessage(ui, opts)
2153 # ensure logfile does not conflict with later enforcement of the
2153 # ensure logfile does not conflict with later enforcement of the
2154 # message. potential logfile content has been processed by
2154 # message. potential logfile content has been processed by
2155 # `logmessage` anyway.
2155 # `logmessage` anyway.
2156 opts.pop('logfile')
2156 opts.pop('logfile')
2157 # First, do a regular commit to record all changes in the working
2157 # First, do a regular commit to record all changes in the working
2158 # directory (if there are any)
2158 # directory (if there are any)
2159 ui.callhooks = False
2159 ui.callhooks = False
2160 currentbookmark = repo._bookmarkcurrent
2160 currentbookmark = repo._bookmarkcurrent
2161 try:
2161 try:
2162 repo._bookmarkcurrent = None
2162 repo._bookmarkcurrent = None
2163 opts['message'] = 'temporary amend commit for %s' % old
2163 opts['message'] = 'temporary amend commit for %s' % old
2164 node = commit(ui, repo, commitfunc, pats, opts)
2164 node = commit(ui, repo, commitfunc, pats, opts)
2165 finally:
2165 finally:
2166 repo._bookmarkcurrent = currentbookmark
2166 repo._bookmarkcurrent = currentbookmark
2167 ui.callhooks = True
2167 ui.callhooks = True
2168 ctx = repo[node]
2168 ctx = repo[node]
2169
2169
2170 # Participating changesets:
2170 # Participating changesets:
2171 #
2171 #
2172 # node/ctx o - new (intermediate) commit that contains changes
2172 # node/ctx o - new (intermediate) commit that contains changes
2173 # | from working dir to go into amending commit
2173 # | from working dir to go into amending commit
2174 # | (or a workingctx if there were no changes)
2174 # | (or a workingctx if there were no changes)
2175 # |
2175 # |
2176 # old o - changeset to amend
2176 # old o - changeset to amend
2177 # |
2177 # |
2178 # base o - parent of amending changeset
2178 # base o - parent of amending changeset
2179
2179
2180 # Update extra dict from amended commit (e.g. to preserve graft
2180 # Update extra dict from amended commit (e.g. to preserve graft
2181 # source)
2181 # source)
2182 extra.update(old.extra())
2182 extra.update(old.extra())
2183
2183
2184 # Also update it from the intermediate commit or from the wctx
2184 # Also update it from the intermediate commit or from the wctx
2185 extra.update(ctx.extra())
2185 extra.update(ctx.extra())
2186
2186
2187 if len(old.parents()) > 1:
2187 if len(old.parents()) > 1:
2188 # ctx.files() isn't reliable for merges, so fall back to the
2188 # ctx.files() isn't reliable for merges, so fall back to the
2189 # slower repo.status() method
2189 # slower repo.status() method
2190 files = set([fn for st in repo.status(base, old)[:3]
2190 files = set([fn for st in repo.status(base, old)[:3]
2191 for fn in st])
2191 for fn in st])
2192 else:
2192 else:
2193 files = set(old.files())
2193 files = set(old.files())
2194
2194
2195 # Second, we use either the commit we just did, or if there were no
2195 # Second, we use either the commit we just did, or if there were no
2196 # changes the parent of the working directory as the version of the
2196 # changes the parent of the working directory as the version of the
2197 # files in the final amend commit
2197 # files in the final amend commit
2198 if node:
2198 if node:
2199 ui.note(_('copying changeset %s to %s\n') % (ctx, base))
2199 ui.note(_('copying changeset %s to %s\n') % (ctx, base))
2200
2200
2201 user = ctx.user()
2201 user = ctx.user()
2202 date = ctx.date()
2202 date = ctx.date()
2203 # Recompute copies (avoid recording a -> b -> a)
2203 # Recompute copies (avoid recording a -> b -> a)
2204 copied = copies.pathcopies(base, ctx)
2204 copied = copies.pathcopies(base, ctx)
2205
2205
2206 # Prune files which were reverted by the updates: if old
2206 # Prune files which were reverted by the updates: if old
2207 # introduced file X and our intermediate commit, node,
2207 # introduced file X and our intermediate commit, node,
2208 # renamed that file, then those two files are the same and
2208 # renamed that file, then those two files are the same and
2209 # we can discard X from our list of files. Likewise if X
2209 # we can discard X from our list of files. Likewise if X
2210 # was deleted, it's no longer relevant
2210 # was deleted, it's no longer relevant
2211 files.update(ctx.files())
2211 files.update(ctx.files())
2212
2212
2213 def samefile(f):
2213 def samefile(f):
2214 if f in ctx.manifest():
2214 if f in ctx.manifest():
2215 a = ctx.filectx(f)
2215 a = ctx.filectx(f)
2216 if f in base.manifest():
2216 if f in base.manifest():
2217 b = base.filectx(f)
2217 b = base.filectx(f)
2218 return (not a.cmp(b)
2218 return (not a.cmp(b)
2219 and a.flags() == b.flags())
2219 and a.flags() == b.flags())
2220 else:
2220 else:
2221 return False
2221 return False
2222 else:
2222 else:
2223 return f not in base.manifest()
2223 return f not in base.manifest()
2224 files = [f for f in files if not samefile(f)]
2224 files = [f for f in files if not samefile(f)]
2225
2225
2226 def filectxfn(repo, ctx_, path):
2226 def filectxfn(repo, ctx_, path):
2227 try:
2227 try:
2228 fctx = ctx[path]
2228 fctx = ctx[path]
2229 flags = fctx.flags()
2229 flags = fctx.flags()
2230 mctx = context.memfilectx(repo,
2230 mctx = context.memfilectx(repo,
2231 fctx.path(), fctx.data(),
2231 fctx.path(), fctx.data(),
2232 islink='l' in flags,
2232 islink='l' in flags,
2233 isexec='x' in flags,
2233 isexec='x' in flags,
2234 copied=copied.get(path))
2234 copied=copied.get(path))
2235 return mctx
2235 return mctx
2236 except KeyError:
2236 except KeyError:
2237 return None
2237 return None
2238 else:
2238 else:
2239 ui.note(_('copying changeset %s to %s\n') % (old, base))
2239 ui.note(_('copying changeset %s to %s\n') % (old, base))
2240
2240
2241 # Use version of files as in the old cset
2241 # Use version of files as in the old cset
2242 def filectxfn(repo, ctx_, path):
2242 def filectxfn(repo, ctx_, path):
2243 try:
2243 try:
2244 return old.filectx(path)
2244 return old.filectx(path)
2245 except KeyError:
2245 except KeyError:
2246 return None
2246 return None
2247
2247
2248 user = opts.get('user') or old.user()
2248 user = opts.get('user') or old.user()
2249 date = opts.get('date') or old.date()
2249 date = opts.get('date') or old.date()
2250 editform = mergeeditform(old, 'commit.amend')
2250 editform = mergeeditform(old, 'commit.amend')
2251 editor = getcommiteditor(editform=editform, **opts)
2251 editor = getcommiteditor(editform=editform, **opts)
2252 if not message:
2252 if not message:
2253 editor = getcommiteditor(edit=True, editform=editform)
2253 editor = getcommiteditor(edit=True, editform=editform)
2254 message = old.description()
2254 message = old.description()
2255
2255
2256 pureextra = extra.copy()
2256 pureextra = extra.copy()
2257 extra['amend_source'] = old.hex()
2257 extra['amend_source'] = old.hex()
2258
2258
2259 new = context.memctx(repo,
2259 new = context.memctx(repo,
2260 parents=[base.node(), old.p2().node()],
2260 parents=[base.node(), old.p2().node()],
2261 text=message,
2261 text=message,
2262 files=files,
2262 files=files,
2263 filectxfn=filectxfn,
2263 filectxfn=filectxfn,
2264 user=user,
2264 user=user,
2265 date=date,
2265 date=date,
2266 extra=extra,
2266 extra=extra,
2267 editor=editor)
2267 editor=editor)
2268
2268
2269 newdesc = changelog.stripdesc(new.description())
2269 newdesc = changelog.stripdesc(new.description())
2270 if ((not node)
2270 if ((not node)
2271 and newdesc == old.description()
2271 and newdesc == old.description()
2272 and user == old.user()
2272 and user == old.user()
2273 and date == old.date()
2273 and date == old.date()
2274 and pureextra == old.extra()):
2274 and pureextra == old.extra()):
2275 # nothing changed. continuing here would create a new node
2275 # nothing changed. continuing here would create a new node
2276 # anyway because of the amend_source noise.
2276 # anyway because of the amend_source noise.
2277 #
2277 #
2278 # This not what we expect from amend.
2278 # This not what we expect from amend.
2279 return old.node()
2279 return old.node()
2280
2280
2281 ph = repo.ui.config('phases', 'new-commit', phases.draft)
2281 ph = repo.ui.config('phases', 'new-commit', phases.draft)
2282 try:
2282 try:
2283 if opts.get('secret'):
2283 if opts.get('secret'):
2284 commitphase = 'secret'
2284 commitphase = 'secret'
2285 else:
2285 else:
2286 commitphase = old.phase()
2286 commitphase = old.phase()
2287 repo.ui.setconfig('phases', 'new-commit', commitphase, 'amend')
2287 repo.ui.setconfig('phases', 'new-commit', commitphase, 'amend')
2288 newid = repo.commitctx(new)
2288 newid = repo.commitctx(new)
2289 finally:
2289 finally:
2290 repo.ui.setconfig('phases', 'new-commit', ph, 'amend')
2290 repo.ui.setconfig('phases', 'new-commit', ph, 'amend')
2291 if newid != old.node():
2291 if newid != old.node():
2292 # Reroute the working copy parent to the new changeset
2292 # Reroute the working copy parent to the new changeset
2293 repo.setparents(newid, nullid)
2293 repo.setparents(newid, nullid)
2294
2294
2295 # Move bookmarks from old parent to amend commit
2295 # Move bookmarks from old parent to amend commit
2296 bms = repo.nodebookmarks(old.node())
2296 bms = repo.nodebookmarks(old.node())
2297 if bms:
2297 if bms:
2298 marks = repo._bookmarks
2298 marks = repo._bookmarks
2299 for bm in bms:
2299 for bm in bms:
2300 marks[bm] = newid
2300 marks[bm] = newid
2301 marks.write()
2301 marks.write()
2302 #commit the whole amend process
2302 #commit the whole amend process
2303 if obsolete._enabled and newid != old.node():
2303 if obsolete._enabled and newid != old.node():
2304 # mark the new changeset as successor of the rewritten one
2304 # mark the new changeset as successor of the rewritten one
2305 new = repo[newid]
2305 new = repo[newid]
2306 obs = [(old, (new,))]
2306 obs = [(old, (new,))]
2307 if node:
2307 if node:
2308 obs.append((ctx, ()))
2308 obs.append((ctx, ()))
2309
2309
2310 obsolete.createmarkers(repo, obs)
2310 obsolete.createmarkers(repo, obs)
2311 tr.close()
2311 tr.close()
2312 finally:
2312 finally:
2313 tr.release()
2313 tr.release()
2314 if (not obsolete._enabled) and newid != old.node():
2314 if (not obsolete._enabled) and newid != old.node():
2315 # Strip the intermediate commit (if there was one) and the amended
2315 # Strip the intermediate commit (if there was one) and the amended
2316 # commit
2316 # commit
2317 if node:
2317 if node:
2318 ui.note(_('stripping intermediate changeset %s\n') % ctx)
2318 ui.note(_('stripping intermediate changeset %s\n') % ctx)
2319 ui.note(_('stripping amended changeset %s\n') % old)
2319 ui.note(_('stripping amended changeset %s\n') % old)
2320 repair.strip(ui, repo, old.node(), topic='amend-backup')
2320 repair.strip(ui, repo, old.node(), topic='amend-backup')
2321 finally:
2321 finally:
2322 if newid is None:
2322 if newid is None:
2323 repo.dirstate.invalidate()
2323 repo.dirstate.invalidate()
2324 lockmod.release(lock, wlock)
2324 lockmod.release(lock, wlock)
2325 return newid
2325 return newid
2326
2326
2327 def commiteditor(repo, ctx, subs, editform=''):
2327 def commiteditor(repo, ctx, subs, editform=''):
2328 if ctx.description():
2328 if ctx.description():
2329 return ctx.description()
2329 return ctx.description()
2330 return commitforceeditor(repo, ctx, subs, editform=editform)
2330 return commitforceeditor(repo, ctx, subs, editform=editform)
2331
2331
2332 def commitforceeditor(repo, ctx, subs, finishdesc=None, extramsg=None,
2332 def commitforceeditor(repo, ctx, subs, finishdesc=None, extramsg=None,
2333 editform=''):
2333 editform=''):
2334 if not extramsg:
2334 if not extramsg:
2335 extramsg = _("Leave message empty to abort commit.")
2335 extramsg = _("Leave message empty to abort commit.")
2336
2336
2337 forms = [e for e in editform.split('.') if e]
2337 forms = [e for e in editform.split('.') if e]
2338 forms.insert(0, 'changeset')
2338 forms.insert(0, 'changeset')
2339 while forms:
2339 while forms:
2340 tmpl = repo.ui.config('committemplate', '.'.join(forms))
2340 tmpl = repo.ui.config('committemplate', '.'.join(forms))
2341 if tmpl:
2341 if tmpl:
2342 committext = buildcommittemplate(repo, ctx, subs, extramsg, tmpl)
2342 committext = buildcommittemplate(repo, ctx, subs, extramsg, tmpl)
2343 break
2343 break
2344 forms.pop()
2344 forms.pop()
2345 else:
2345 else:
2346 committext = buildcommittext(repo, ctx, subs, extramsg)
2346 committext = buildcommittext(repo, ctx, subs, extramsg)
2347
2347
2348 # run editor in the repository root
2348 # run editor in the repository root
2349 olddir = os.getcwd()
2349 olddir = os.getcwd()
2350 os.chdir(repo.root)
2350 os.chdir(repo.root)
2351 text = repo.ui.edit(committext, ctx.user(), ctx.extra(), editform=editform)
2351 text = repo.ui.edit(committext, ctx.user(), ctx.extra(), editform=editform)
2352 text = re.sub("(?m)^HG:.*(\n|$)", "", text)
2352 text = re.sub("(?m)^HG:.*(\n|$)", "", text)
2353 os.chdir(olddir)
2353 os.chdir(olddir)
2354
2354
2355 if finishdesc:
2355 if finishdesc:
2356 text = finishdesc(text)
2356 text = finishdesc(text)
2357 if not text.strip():
2357 if not text.strip():
2358 raise util.Abort(_("empty commit message"))
2358 raise util.Abort(_("empty commit message"))
2359
2359
2360 return text
2360 return text
2361
2361
2362 def buildcommittemplate(repo, ctx, subs, extramsg, tmpl):
2362 def buildcommittemplate(repo, ctx, subs, extramsg, tmpl):
2363 ui = repo.ui
2363 ui = repo.ui
2364 tmpl, mapfile = gettemplate(ui, tmpl, None)
2364 tmpl, mapfile = gettemplate(ui, tmpl, None)
2365
2365
2366 try:
2366 try:
2367 t = changeset_templater(ui, repo, None, {}, tmpl, mapfile, False)
2367 t = changeset_templater(ui, repo, None, {}, tmpl, mapfile, False)
2368 except SyntaxError, inst:
2368 except SyntaxError, inst:
2369 raise util.Abort(inst.args[0])
2369 raise util.Abort(inst.args[0])
2370
2370
2371 for k, v in repo.ui.configitems('committemplate'):
2371 for k, v in repo.ui.configitems('committemplate'):
2372 if k != 'changeset':
2372 if k != 'changeset':
2373 t.t.cache[k] = v
2373 t.t.cache[k] = v
2374
2374
2375 if not extramsg:
2375 if not extramsg:
2376 extramsg = '' # ensure that extramsg is string
2376 extramsg = '' # ensure that extramsg is string
2377
2377
2378 ui.pushbuffer()
2378 ui.pushbuffer()
2379 t.show(ctx, extramsg=extramsg)
2379 t.show(ctx, extramsg=extramsg)
2380 return ui.popbuffer()
2380 return ui.popbuffer()
2381
2381
2382 def buildcommittext(repo, ctx, subs, extramsg):
2382 def buildcommittext(repo, ctx, subs, extramsg):
2383 edittext = []
2383 edittext = []
2384 modified, added, removed = ctx.modified(), ctx.added(), ctx.removed()
2384 modified, added, removed = ctx.modified(), ctx.added(), ctx.removed()
2385 if ctx.description():
2385 if ctx.description():
2386 edittext.append(ctx.description())
2386 edittext.append(ctx.description())
2387 edittext.append("")
2387 edittext.append("")
2388 edittext.append("") # Empty line between message and comments.
2388 edittext.append("") # Empty line between message and comments.
2389 edittext.append(_("HG: Enter commit message."
2389 edittext.append(_("HG: Enter commit message."
2390 " Lines beginning with 'HG:' are removed."))
2390 " Lines beginning with 'HG:' are removed."))
2391 edittext.append("HG: %s" % extramsg)
2391 edittext.append("HG: %s" % extramsg)
2392 edittext.append("HG: --")
2392 edittext.append("HG: --")
2393 edittext.append(_("HG: user: %s") % ctx.user())
2393 edittext.append(_("HG: user: %s") % ctx.user())
2394 if ctx.p2():
2394 if ctx.p2():
2395 edittext.append(_("HG: branch merge"))
2395 edittext.append(_("HG: branch merge"))
2396 if ctx.branch():
2396 if ctx.branch():
2397 edittext.append(_("HG: branch '%s'") % ctx.branch())
2397 edittext.append(_("HG: branch '%s'") % ctx.branch())
2398 if bookmarks.iscurrent(repo):
2398 if bookmarks.iscurrent(repo):
2399 edittext.append(_("HG: bookmark '%s'") % repo._bookmarkcurrent)
2399 edittext.append(_("HG: bookmark '%s'") % repo._bookmarkcurrent)
2400 edittext.extend([_("HG: subrepo %s") % s for s in subs])
2400 edittext.extend([_("HG: subrepo %s") % s for s in subs])
2401 edittext.extend([_("HG: added %s") % f for f in added])
2401 edittext.extend([_("HG: added %s") % f for f in added])
2402 edittext.extend([_("HG: changed %s") % f for f in modified])
2402 edittext.extend([_("HG: changed %s") % f for f in modified])
2403 edittext.extend([_("HG: removed %s") % f for f in removed])
2403 edittext.extend([_("HG: removed %s") % f for f in removed])
2404 if not added and not modified and not removed:
2404 if not added and not modified and not removed:
2405 edittext.append(_("HG: no files changed"))
2405 edittext.append(_("HG: no files changed"))
2406 edittext.append("")
2406 edittext.append("")
2407
2407
2408 return "\n".join(edittext)
2408 return "\n".join(edittext)
2409
2409
2410 def commitstatus(repo, node, branch, bheads=None, opts={}):
2410 def commitstatus(repo, node, branch, bheads=None, opts={}):
2411 ctx = repo[node]
2411 ctx = repo[node]
2412 parents = ctx.parents()
2412 parents = ctx.parents()
2413
2413
2414 if (not opts.get('amend') and bheads and node not in bheads and not
2414 if (not opts.get('amend') and bheads and node not in bheads and not
2415 [x for x in parents if x.node() in bheads and x.branch() == branch]):
2415 [x for x in parents if x.node() in bheads and x.branch() == branch]):
2416 repo.ui.status(_('created new head\n'))
2416 repo.ui.status(_('created new head\n'))
2417 # The message is not printed for initial roots. For the other
2417 # The message is not printed for initial roots. For the other
2418 # changesets, it is printed in the following situations:
2418 # changesets, it is printed in the following situations:
2419 #
2419 #
2420 # Par column: for the 2 parents with ...
2420 # Par column: for the 2 parents with ...
2421 # N: null or no parent
2421 # N: null or no parent
2422 # B: parent is on another named branch
2422 # B: parent is on another named branch
2423 # C: parent is a regular non head changeset
2423 # C: parent is a regular non head changeset
2424 # H: parent was a branch head of the current branch
2424 # H: parent was a branch head of the current branch
2425 # Msg column: whether we print "created new head" message
2425 # Msg column: whether we print "created new head" message
2426 # In the following, it is assumed that there already exists some
2426 # In the following, it is assumed that there already exists some
2427 # initial branch heads of the current branch, otherwise nothing is
2427 # initial branch heads of the current branch, otherwise nothing is
2428 # printed anyway.
2428 # printed anyway.
2429 #
2429 #
2430 # Par Msg Comment
2430 # Par Msg Comment
2431 # N N y additional topo root
2431 # N N y additional topo root
2432 #
2432 #
2433 # B N y additional branch root
2433 # B N y additional branch root
2434 # C N y additional topo head
2434 # C N y additional topo head
2435 # H N n usual case
2435 # H N n usual case
2436 #
2436 #
2437 # B B y weird additional branch root
2437 # B B y weird additional branch root
2438 # C B y branch merge
2438 # C B y branch merge
2439 # H B n merge with named branch
2439 # H B n merge with named branch
2440 #
2440 #
2441 # C C y additional head from merge
2441 # C C y additional head from merge
2442 # C H n merge with a head
2442 # C H n merge with a head
2443 #
2443 #
2444 # H H n head merge: head count decreases
2444 # H H n head merge: head count decreases
2445
2445
2446 if not opts.get('close_branch'):
2446 if not opts.get('close_branch'):
2447 for r in parents:
2447 for r in parents:
2448 if r.closesbranch() and r.branch() == branch:
2448 if r.closesbranch() and r.branch() == branch:
2449 repo.ui.status(_('reopening closed branch head %d\n') % r)
2449 repo.ui.status(_('reopening closed branch head %d\n') % r)
2450
2450
2451 if repo.ui.debugflag:
2451 if repo.ui.debugflag:
2452 repo.ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
2452 repo.ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
2453 elif repo.ui.verbose:
2453 elif repo.ui.verbose:
2454 repo.ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
2454 repo.ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
2455
2455
2456 def revert(ui, repo, ctx, parents, *pats, **opts):
2456 def revert(ui, repo, ctx, parents, *pats, **opts):
2457 parent, p2 = parents
2457 parent, p2 = parents
2458 node = ctx.node()
2458 node = ctx.node()
2459
2459
2460 mf = ctx.manifest()
2460 mf = ctx.manifest()
2461 if node == p2:
2461 if node == p2:
2462 parent = p2
2462 parent = p2
2463 if node == parent:
2463 if node == parent:
2464 pmf = mf
2464 pmf = mf
2465 else:
2465 else:
2466 pmf = None
2466 pmf = None
2467
2467
2468 # need all matching names in dirstate and manifest of target rev,
2468 # need all matching names in dirstate and manifest of target rev,
2469 # so have to walk both. do not print errors if files exist in one
2469 # so have to walk both. do not print errors if files exist in one
2470 # but not other.
2470 # but not other.
2471
2471
2472 # `names` is a mapping for all elements in working copy and target revision
2472 # `names` is a mapping for all elements in working copy and target revision
2473 # The mapping is in the form:
2473 # The mapping is in the form:
2474 # <asb path in repo> -> (<path from CWD>, <exactly specified by matcher?>)
2474 # <asb path in repo> -> (<path from CWD>, <exactly specified by matcher?>)
2475 names = {}
2475 names = {}
2476
2476
2477 wlock = repo.wlock()
2477 wlock = repo.wlock()
2478 try:
2478 try:
2479 ## filling of the `names` mapping
2479 ## filling of the `names` mapping
2480 # walk dirstate to fill `names`
2480 # walk dirstate to fill `names`
2481
2481
2482 m = scmutil.match(repo[None], pats, opts)
2482 m = scmutil.match(repo[None], pats, opts)
2483 if not m.always() or node != parent:
2483 if not m.always() or node != parent:
2484 m.bad = lambda x, y: False
2484 m.bad = lambda x, y: False
2485 for abs in repo.walk(m):
2485 for abs in repo.walk(m):
2486 names[abs] = m.rel(abs), m.exact(abs)
2486 names[abs] = m.rel(abs), m.exact(abs)
2487
2487
2488 # walk target manifest to fill `names`
2488 # walk target manifest to fill `names`
2489
2489
2490 def badfn(path, msg):
2490 def badfn(path, msg):
2491 if path in names:
2491 if path in names:
2492 return
2492 return
2493 if path in ctx.substate:
2493 if path in ctx.substate:
2494 return
2494 return
2495 path_ = path + '/'
2495 path_ = path + '/'
2496 for f in names:
2496 for f in names:
2497 if f.startswith(path_):
2497 if f.startswith(path_):
2498 return
2498 return
2499 ui.warn("%s: %s\n" % (m.rel(path), msg))
2499 ui.warn("%s: %s\n" % (m.rel(path), msg))
2500
2500
2501 m = scmutil.match(ctx, pats, opts)
2501 m = scmutil.match(ctx, pats, opts)
2502 m.bad = badfn
2502 m.bad = badfn
2503 for abs in ctx.walk(m):
2503 for abs in ctx.walk(m):
2504 if abs not in names:
2504 if abs not in names:
2505 names[abs] = m.rel(abs), m.exact(abs)
2505 names[abs] = m.rel(abs), m.exact(abs)
2506
2506
2507 # Find status of all file in `names`.
2507 # Find status of all file in `names`.
2508 m = scmutil.matchfiles(repo, names)
2508 m = scmutil.matchfiles(repo, names)
2509
2509
2510 changes = repo.status(node1=node, match=m,
2510 changes = repo.status(node1=node, match=m,
2511 unknown=True, ignored=True, clean=True)
2511 unknown=True, ignored=True, clean=True)
2512 else:
2512 else:
2513 changes = repo.status(match=m)
2513 changes = repo.status(match=m)
2514 for kind in changes:
2514 for kind in changes:
2515 for abs in kind:
2515 for abs in kind:
2516 names[abs] = m.rel(abs), m.exact(abs)
2516 names[abs] = m.rel(abs), m.exact(abs)
2517
2517
2518 m = scmutil.matchfiles(repo, names)
2518 m = scmutil.matchfiles(repo, names)
2519
2519
2520 modified = set(changes[0])
2520 modified = set(changes[0])
2521 added = set(changes[1])
2521 added = set(changes[1])
2522 removed = set(changes[2])
2522 removed = set(changes[2])
2523 _deleted = set(changes[3])
2523 _deleted = set(changes[3])
2524 unknown = set(changes[4])
2524 unknown = set(changes[4])
2525 unknown.update(changes[5])
2525 unknown.update(changes[5])
2526 clean = set(changes[6])
2526 clean = set(changes[6])
2527 modadded = set()
2527 modadded = set()
2528
2528
2529 # split between files known in target manifest and the others
2529 # split between files known in target manifest and the others
2530 smf = set(mf)
2530 smf = set(mf)
2531
2531
2532 # determine the exact nature of the deleted changesets
2532 # determine the exact nature of the deleted changesets
2533 deladded = _deleted - smf
2533 deladded = _deleted - smf
2534 deleted = _deleted - deladded
2534 deleted = _deleted - deladded
2535
2535
2536 # We need to account for the state of file in the dirstate
2536 # We need to account for the state of file in the dirstate
2537 #
2537 #
2538 # Even, when we revert agains something else than parent. this will
2538 # Even, when we revert agains something else than parent. this will
2539 # slightly alter the behavior of revert (doing back up or not, delete
2539 # slightly alter the behavior of revert (doing back up or not, delete
2540 # or just forget etc)
2540 # or just forget etc)
2541 if parent == node:
2541 if parent == node:
2542 dsmodified = modified
2542 dsmodified = modified
2543 dsadded = added
2543 dsadded = added
2544 dsremoved = removed
2544 dsremoved = removed
2545 modified, added, removed = set(), set(), set()
2545 modified, added, removed = set(), set(), set()
2546 else:
2546 else:
2547 changes = repo.status(node1=parent, match=m)
2547 changes = repo.status(node1=parent, match=m)
2548 dsmodified = set(changes[0])
2548 dsmodified = set(changes[0])
2549 dsadded = set(changes[1])
2549 dsadded = set(changes[1])
2550 dsremoved = set(changes[2])
2550 dsremoved = set(changes[2])
2551
2551
2552 # only take into account for removes between wc and target
2552 # only take into account for removes between wc and target
2553 clean |= dsremoved - removed
2553 clean |= dsremoved - removed
2554 dsremoved &= removed
2554 dsremoved &= removed
2555 # distinct between dirstate remove and other
2555 # distinct between dirstate remove and other
2556 removed -= dsremoved
2556 removed -= dsremoved
2557
2557
2558 modadded = added & dsmodified
2558 modadded = added & dsmodified
2559 added -= modadded
2559 added -= modadded
2560
2560
2561 # tell newly modified apart.
2561 # tell newly modified apart.
2562 dsmodified &= modified
2562 dsmodified &= modified
2563 dsmodified |= modified & dsadded # dirstate added may needs backup
2563 dsmodified |= modified & dsadded # dirstate added may needs backup
2564 modified -= dsmodified
2564 modified -= dsmodified
2565
2565
2566 # We need to wait for some post-processing to update this set
2566 # We need to wait for some post-processing to update this set
2567 # before making the distinction. The dirstate will be used for
2567 # before making the distinction. The dirstate will be used for
2568 # that purpose.
2568 # that purpose.
2569 dsadded = added
2569 dsadded = added
2570
2570
2571 # in case of merge, files that are actually added can be reported as
2571 # in case of merge, files that are actually added can be reported as
2572 # modified, we need to post process the result
2572 # modified, we need to post process the result
2573 if p2 != nullid:
2573 if p2 != nullid:
2574 if pmf is None:
2574 if pmf is None:
2575 # only need parent manifest in the merge case,
2575 # only need parent manifest in the merge case,
2576 # so do not read by default
2576 # so do not read by default
2577 pmf = repo[parent].manifest()
2577 pmf = repo[parent].manifest()
2578 mergeadd = dsmodified - set(pmf)
2578 mergeadd = dsmodified - set(pmf)
2579 dsadded |= mergeadd
2579 dsadded |= mergeadd
2580 dsmodified -= mergeadd
2580 dsmodified -= mergeadd
2581
2581
2582 # if f is a rename, update `names` to also revert the source
2582 # if f is a rename, update `names` to also revert the source
2583 cwd = repo.getcwd()
2583 cwd = repo.getcwd()
2584 for f in dsadded:
2584 for f in dsadded:
2585 src = repo.dirstate.copied(f)
2585 src = repo.dirstate.copied(f)
2586 # XXX should we check for rename down to target node?
2586 # XXX should we check for rename down to target node?
2587 if src and src not in names and repo.dirstate[src] == 'r':
2587 if src and src not in names and repo.dirstate[src] == 'r':
2588 dsremoved.add(src)
2588 dsremoved.add(src)
2589 names[src] = (repo.pathto(src, cwd), True)
2589 names[src] = (repo.pathto(src, cwd), True)
2590
2590
2591 # distinguish between file to forget and the other
2591 # distinguish between file to forget and the other
2592 added = set()
2592 added = set()
2593 for abs in dsadded:
2593 for abs in dsadded:
2594 if repo.dirstate[abs] != 'a':
2594 if repo.dirstate[abs] != 'a':
2595 added.add(abs)
2595 added.add(abs)
2596 dsadded -= added
2596 dsadded -= added
2597
2597
2598 for abs in deladded:
2598 for abs in deladded:
2599 if repo.dirstate[abs] == 'a':
2599 if repo.dirstate[abs] == 'a':
2600 dsadded.add(abs)
2600 dsadded.add(abs)
2601 deladded -= dsadded
2601 deladded -= dsadded
2602
2602
2603 # For files marked as removed, we check if an unknown file is present at
2603 # For files marked as removed, we check if an unknown file is present at
2604 # the same path. If a such file exists it may need to be backed up.
2604 # the same path. If a such file exists it may need to be backed up.
2605 # Making the distinction at this stage helps have simpler backup
2605 # Making the distinction at this stage helps have simpler backup
2606 # logic.
2606 # logic.
2607 removunk = set()
2607 removunk = set()
2608 for abs in removed:
2608 for abs in removed:
2609 target = repo.wjoin(abs)
2609 target = repo.wjoin(abs)
2610 if os.path.lexists(target):
2610 if os.path.lexists(target):
2611 removunk.add(abs)
2611 removunk.add(abs)
2612 removed -= removunk
2612 removed -= removunk
2613
2613
2614 dsremovunk = set()
2614 dsremovunk = set()
2615 for abs in dsremoved:
2615 for abs in dsremoved:
2616 target = repo.wjoin(abs)
2616 target = repo.wjoin(abs)
2617 if os.path.lexists(target):
2617 if os.path.lexists(target):
2618 dsremovunk.add(abs)
2618 dsremovunk.add(abs)
2619 dsremoved -= dsremovunk
2619 dsremoved -= dsremovunk
2620
2620
2621 # action to be actually performed by revert
2621 # action to be actually performed by revert
2622 # (<list of file>, message>) tuple
2622 # (<list of file>, message>) tuple
2623 actions = {'revert': ([], _('reverting %s\n')),
2623 actions = {'revert': ([], _('reverting %s\n')),
2624 'add': ([], _('adding %s\n')),
2624 'add': ([], _('adding %s\n')),
2625 'remove': ([], _('removing %s\n')),
2625 'remove': ([], _('removing %s\n')),
2626 'drop': ([], _('removing %s\n')),
2626 'drop': ([], _('removing %s\n')),
2627 'forget': ([], _('forgetting %s\n')),
2627 'forget': ([], _('forgetting %s\n')),
2628 'undelete': ([], _('undeleting %s\n')),
2628 'undelete': ([], _('undeleting %s\n')),
2629 'noop': (None, _('no changes needed to %s\n')),
2629 'noop': (None, _('no changes needed to %s\n')),
2630 'unknown': (None, _('file not managed: %s\n')),
2630 'unknown': (None, _('file not managed: %s\n')),
2631 }
2631 }
2632
2632
2633 # "constant" that convey the backup strategy.
2633 # "constant" that convey the backup strategy.
2634 # All set to `discard` if `no-backup` is set do avoid checking
2634 # All set to `discard` if `no-backup` is set do avoid checking
2635 # no_backup lower in the code.
2635 # no_backup lower in the code.
2636 # These values are ordered for comparison purposes
2636 # These values are ordered for comparison purposes
2637 backup = 2 # unconditionally do backup
2637 backup = 2 # unconditionally do backup
2638 check = 1 # check if the existing file differs from target
2638 check = 1 # check if the existing file differs from target
2639 discard = 0 # never do backup
2639 discard = 0 # never do backup
2640 if opts.get('no_backup'):
2640 if opts.get('no_backup'):
2641 backup = check = discard
2641 backup = check = discard
2642
2642
2643 backupanddel = actions['remove']
2644 if not opts.get('no_backup'):
2645 backupanddel = actions['drop']
2646
2643 disptable = (
2647 disptable = (
2644 # dispatch table:
2648 # dispatch table:
2645 # file state
2649 # file state
2646 # action
2650 # action
2647 # make backup
2651 # make backup
2648
2652
2649 ## Sets that results that will change file on disk
2653 ## Sets that results that will change file on disk
2650 # Modified compared to target, no local change
2654 # Modified compared to target, no local change
2651 (modified, actions['revert'], discard),
2655 (modified, actions['revert'], discard),
2652 # Modified compared to target, but local file is deleted
2656 # Modified compared to target, but local file is deleted
2653 (deleted, actions['revert'], discard),
2657 (deleted, actions['revert'], discard),
2654 # Modified compared to target, local change
2658 # Modified compared to target, local change
2655 (dsmodified, actions['revert'], backup),
2659 (dsmodified, actions['revert'], backup),
2656 # Added since target
2660 # Added since target
2657 (added, actions['remove'], discard),
2661 (added, actions['remove'], discard),
2658 # Added in working directory
2662 # Added in working directory
2659 (dsadded, actions['forget'], discard),
2663 (dsadded, actions['forget'], discard),
2660 # Added since target, have local modification
2664 # Added since target, have local modification
2661 (modadded, actions['remove'], discard),
2665 (modadded, backupanddel, backup),
2662 # Added since target but file is missing in working directory
2666 # Added since target but file is missing in working directory
2663 (deladded, actions['drop'], discard),
2667 (deladded, actions['drop'], discard),
2664 # Removed since target, before working copy parent
2668 # Removed since target, before working copy parent
2665 (removed, actions['add'], discard),
2669 (removed, actions['add'], discard),
2666 # Same as `removed` but an unknown file exists at the same path
2670 # Same as `removed` but an unknown file exists at the same path
2667 (removunk, actions['add'], check),
2671 (removunk, actions['add'], check),
2668 # Removed since targe, marked as such in working copy parent
2672 # Removed since targe, marked as such in working copy parent
2669 (dsremoved, actions['undelete'], discard),
2673 (dsremoved, actions['undelete'], discard),
2670 # Same as `dsremoved` but an unknown file exists at the same path
2674 # Same as `dsremoved` but an unknown file exists at the same path
2671 (dsremovunk, actions['undelete'], check),
2675 (dsremovunk, actions['undelete'], check),
2672 ## the following sets does not result in any file changes
2676 ## the following sets does not result in any file changes
2673 # File with no modification
2677 # File with no modification
2674 (clean, actions['noop'], discard),
2678 (clean, actions['noop'], discard),
2675 # Existing file, not tracked anywhere
2679 # Existing file, not tracked anywhere
2676 (unknown, actions['unknown'], discard),
2680 (unknown, actions['unknown'], discard),
2677 )
2681 )
2678
2682
2679 needdata = ('revert', 'add', 'undelete')
2683 needdata = ('revert', 'add', 'undelete')
2680 _revertprefetch(repo, ctx, *[actions[name][0] for name in needdata])
2684 _revertprefetch(repo, ctx, *[actions[name][0] for name in needdata])
2681
2685
2682 wctx = repo[None]
2686 wctx = repo[None]
2683 for abs, (rel, exact) in sorted(names.items()):
2687 for abs, (rel, exact) in sorted(names.items()):
2684 # target file to be touch on disk (relative to cwd)
2688 # target file to be touch on disk (relative to cwd)
2685 target = repo.wjoin(abs)
2689 target = repo.wjoin(abs)
2686 # search the entry in the dispatch table.
2690 # search the entry in the dispatch table.
2687 # if the file is in any of these sets, it was touched in the working
2691 # if the file is in any of these sets, it was touched in the working
2688 # directory parent and we are sure it needs to be reverted.
2692 # directory parent and we are sure it needs to be reverted.
2689 for table, (xlist, msg), dobackup in disptable:
2693 for table, (xlist, msg), dobackup in disptable:
2690 if abs not in table:
2694 if abs not in table:
2691 continue
2695 continue
2692 if xlist is not None:
2696 if xlist is not None:
2693 xlist.append(abs)
2697 xlist.append(abs)
2694 if dobackup and (backup <= dobackup
2698 if dobackup and (backup <= dobackup
2695 or wctx[abs].cmp(ctx[abs])):
2699 or wctx[abs].cmp(ctx[abs])):
2696 bakname = "%s.orig" % rel
2700 bakname = "%s.orig" % rel
2697 ui.note(_('saving current version of %s as %s\n') %
2701 ui.note(_('saving current version of %s as %s\n') %
2698 (rel, bakname))
2702 (rel, bakname))
2699 if not opts.get('dry_run'):
2703 if not opts.get('dry_run'):
2700 util.rename(target, bakname)
2704 util.rename(target, bakname)
2701 if ui.verbose or not exact:
2705 if ui.verbose or not exact:
2702 if not isinstance(msg, basestring):
2706 if not isinstance(msg, basestring):
2703 msg = msg(abs)
2707 msg = msg(abs)
2704 ui.status(msg % rel)
2708 ui.status(msg % rel)
2705 elif exact:
2709 elif exact:
2706 ui.warn(msg % rel)
2710 ui.warn(msg % rel)
2707 break
2711 break
2708
2712
2709
2713
2710 if not opts.get('dry_run'):
2714 if not opts.get('dry_run'):
2711 _performrevert(repo, parents, ctx, actions)
2715 _performrevert(repo, parents, ctx, actions)
2712
2716
2713 # get the list of subrepos that must be reverted
2717 # get the list of subrepos that must be reverted
2714 subrepomatch = scmutil.match(ctx, pats, opts)
2718 subrepomatch = scmutil.match(ctx, pats, opts)
2715 targetsubs = sorted(s for s in ctx.substate if subrepomatch(s))
2719 targetsubs = sorted(s for s in ctx.substate if subrepomatch(s))
2716
2720
2717 if targetsubs:
2721 if targetsubs:
2718 # Revert the subrepos on the revert list
2722 # Revert the subrepos on the revert list
2719 for sub in targetsubs:
2723 for sub in targetsubs:
2720 ctx.sub(sub).revert(ui, ctx.substate[sub], *pats, **opts)
2724 ctx.sub(sub).revert(ui, ctx.substate[sub], *pats, **opts)
2721 finally:
2725 finally:
2722 wlock.release()
2726 wlock.release()
2723
2727
2724 def _revertprefetch(repo, ctx, *files):
2728 def _revertprefetch(repo, ctx, *files):
2725 """Let extension changing the storage layer prefetch content"""
2729 """Let extension changing the storage layer prefetch content"""
2726 pass
2730 pass
2727
2731
2728 def _performrevert(repo, parents, ctx, actions):
2732 def _performrevert(repo, parents, ctx, actions):
2729 """function that actually perform all the actions computed for revert
2733 """function that actually perform all the actions computed for revert
2730
2734
2731 This is an independent function to let extension to plug in and react to
2735 This is an independent function to let extension to plug in and react to
2732 the imminent revert.
2736 the imminent revert.
2733
2737
2734 Make sure you have the working directory locked when calling this function.
2738 Make sure you have the working directory locked when calling this function.
2735 """
2739 """
2736 parent, p2 = parents
2740 parent, p2 = parents
2737 node = ctx.node()
2741 node = ctx.node()
2738 def checkout(f):
2742 def checkout(f):
2739 fc = ctx[f]
2743 fc = ctx[f]
2740 repo.wwrite(f, fc.data(), fc.flags())
2744 repo.wwrite(f, fc.data(), fc.flags())
2741
2745
2742 audit_path = pathutil.pathauditor(repo.root)
2746 audit_path = pathutil.pathauditor(repo.root)
2743 for f in actions['forget'][0]:
2747 for f in actions['forget'][0]:
2744 repo.dirstate.drop(f)
2748 repo.dirstate.drop(f)
2745 for f in actions['remove'][0]:
2749 for f in actions['remove'][0]:
2746 audit_path(f)
2750 audit_path(f)
2747 util.unlinkpath(repo.wjoin(f))
2751 util.unlinkpath(repo.wjoin(f))
2748 repo.dirstate.remove(f)
2752 repo.dirstate.remove(f)
2749 for f in actions['drop'][0]:
2753 for f in actions['drop'][0]:
2750 audit_path(f)
2754 audit_path(f)
2751 repo.dirstate.remove(f)
2755 repo.dirstate.remove(f)
2752
2756
2753 normal = None
2757 normal = None
2754 if node == parent:
2758 if node == parent:
2755 # We're reverting to our parent. If possible, we'd like status
2759 # We're reverting to our parent. If possible, we'd like status
2756 # to report the file as clean. We have to use normallookup for
2760 # to report the file as clean. We have to use normallookup for
2757 # merges to avoid losing information about merged/dirty files.
2761 # merges to avoid losing information about merged/dirty files.
2758 if p2 != nullid:
2762 if p2 != nullid:
2759 normal = repo.dirstate.normallookup
2763 normal = repo.dirstate.normallookup
2760 else:
2764 else:
2761 normal = repo.dirstate.normal
2765 normal = repo.dirstate.normal
2762 for f in actions['revert'][0]:
2766 for f in actions['revert'][0]:
2763 checkout(f)
2767 checkout(f)
2764 if normal:
2768 if normal:
2765 normal(f)
2769 normal(f)
2766
2770
2767 for f in actions['add'][0]:
2771 for f in actions['add'][0]:
2768 checkout(f)
2772 checkout(f)
2769 repo.dirstate.add(f)
2773 repo.dirstate.add(f)
2770
2774
2771 normal = repo.dirstate.normallookup
2775 normal = repo.dirstate.normallookup
2772 if node == parent and p2 == nullid:
2776 if node == parent and p2 == nullid:
2773 normal = repo.dirstate.normal
2777 normal = repo.dirstate.normal
2774 for f in actions['undelete'][0]:
2778 for f in actions['undelete'][0]:
2775 checkout(f)
2779 checkout(f)
2776 normal(f)
2780 normal(f)
2777
2781
2778 copied = copies.pathcopies(repo[parent], ctx)
2782 copied = copies.pathcopies(repo[parent], ctx)
2779
2783
2780 for f in actions['add'][0] + actions['undelete'][0] + actions['revert'][0]:
2784 for f in actions['add'][0] + actions['undelete'][0] + actions['revert'][0]:
2781 if f in copied:
2785 if f in copied:
2782 repo.dirstate.copy(copied[f], f)
2786 repo.dirstate.copy(copied[f], f)
2783
2787
2784 def command(table):
2788 def command(table):
2785 """Returns a function object to be used as a decorator for making commands.
2789 """Returns a function object to be used as a decorator for making commands.
2786
2790
2787 This function receives a command table as its argument. The table should
2791 This function receives a command table as its argument. The table should
2788 be a dict.
2792 be a dict.
2789
2793
2790 The returned function can be used as a decorator for adding commands
2794 The returned function can be used as a decorator for adding commands
2791 to that command table. This function accepts multiple arguments to define
2795 to that command table. This function accepts multiple arguments to define
2792 a command.
2796 a command.
2793
2797
2794 The first argument is the command name.
2798 The first argument is the command name.
2795
2799
2796 The options argument is an iterable of tuples defining command arguments.
2800 The options argument is an iterable of tuples defining command arguments.
2797 See ``mercurial.fancyopts.fancyopts()`` for the format of each tuple.
2801 See ``mercurial.fancyopts.fancyopts()`` for the format of each tuple.
2798
2802
2799 The synopsis argument defines a short, one line summary of how to use the
2803 The synopsis argument defines a short, one line summary of how to use the
2800 command. This shows up in the help output.
2804 command. This shows up in the help output.
2801
2805
2802 The norepo argument defines whether the command does not require a
2806 The norepo argument defines whether the command does not require a
2803 local repository. Most commands operate against a repository, thus the
2807 local repository. Most commands operate against a repository, thus the
2804 default is False.
2808 default is False.
2805
2809
2806 The optionalrepo argument defines whether the command optionally requires
2810 The optionalrepo argument defines whether the command optionally requires
2807 a local repository.
2811 a local repository.
2808
2812
2809 The inferrepo argument defines whether to try to find a repository from the
2813 The inferrepo argument defines whether to try to find a repository from the
2810 command line arguments. If True, arguments will be examined for potential
2814 command line arguments. If True, arguments will be examined for potential
2811 repository locations. See ``findrepo()``. If a repository is found, it
2815 repository locations. See ``findrepo()``. If a repository is found, it
2812 will be used.
2816 will be used.
2813 """
2817 """
2814 def cmd(name, options=(), synopsis=None, norepo=False, optionalrepo=False,
2818 def cmd(name, options=(), synopsis=None, norepo=False, optionalrepo=False,
2815 inferrepo=False):
2819 inferrepo=False):
2816 def decorator(func):
2820 def decorator(func):
2817 if synopsis:
2821 if synopsis:
2818 table[name] = func, list(options), synopsis
2822 table[name] = func, list(options), synopsis
2819 else:
2823 else:
2820 table[name] = func, list(options)
2824 table[name] = func, list(options)
2821
2825
2822 if norepo:
2826 if norepo:
2823 # Avoid import cycle.
2827 # Avoid import cycle.
2824 import commands
2828 import commands
2825 commands.norepo += ' %s' % ' '.join(parsealiases(name))
2829 commands.norepo += ' %s' % ' '.join(parsealiases(name))
2826
2830
2827 if optionalrepo:
2831 if optionalrepo:
2828 import commands
2832 import commands
2829 commands.optionalrepo += ' %s' % ' '.join(parsealiases(name))
2833 commands.optionalrepo += ' %s' % ' '.join(parsealiases(name))
2830
2834
2831 if inferrepo:
2835 if inferrepo:
2832 import commands
2836 import commands
2833 commands.inferrepo += ' %s' % ' '.join(parsealiases(name))
2837 commands.inferrepo += ' %s' % ' '.join(parsealiases(name))
2834
2838
2835 return func
2839 return func
2836 return decorator
2840 return decorator
2837
2841
2838 return cmd
2842 return cmd
2839
2843
2840 # a list of (ui, repo, otherpeer, opts, missing) functions called by
2844 # a list of (ui, repo, otherpeer, opts, missing) functions called by
2841 # commands.outgoing. "missing" is "missing" of the result of
2845 # commands.outgoing. "missing" is "missing" of the result of
2842 # "findcommonoutgoing()"
2846 # "findcommonoutgoing()"
2843 outgoinghooks = util.hooks()
2847 outgoinghooks = util.hooks()
2844
2848
2845 # a list of (ui, repo) functions called by commands.summary
2849 # a list of (ui, repo) functions called by commands.summary
2846 summaryhooks = util.hooks()
2850 summaryhooks = util.hooks()
2847
2851
2848 # a list of (ui, repo, opts, changes) functions called by commands.summary.
2852 # a list of (ui, repo, opts, changes) functions called by commands.summary.
2849 #
2853 #
2850 # functions should return tuple of booleans below, if 'changes' is None:
2854 # functions should return tuple of booleans below, if 'changes' is None:
2851 # (whether-incomings-are-needed, whether-outgoings-are-needed)
2855 # (whether-incomings-are-needed, whether-outgoings-are-needed)
2852 #
2856 #
2853 # otherwise, 'changes' is a tuple of tuples below:
2857 # otherwise, 'changes' is a tuple of tuples below:
2854 # - (sourceurl, sourcebranch, sourcepeer, incoming)
2858 # - (sourceurl, sourcebranch, sourcepeer, incoming)
2855 # - (desturl, destbranch, destpeer, outgoing)
2859 # - (desturl, destbranch, destpeer, outgoing)
2856 summaryremotehooks = util.hooks()
2860 summaryremotehooks = util.hooks()
2857
2861
2858 # A list of state files kept by multistep operations like graft.
2862 # A list of state files kept by multistep operations like graft.
2859 # Since graft cannot be aborted, it is considered 'clearable' by update.
2863 # Since graft cannot be aborted, it is considered 'clearable' by update.
2860 # note: bisect is intentionally excluded
2864 # note: bisect is intentionally excluded
2861 # (state file, clearable, allowcommit, error, hint)
2865 # (state file, clearable, allowcommit, error, hint)
2862 unfinishedstates = [
2866 unfinishedstates = [
2863 ('graftstate', True, False, _('graft in progress'),
2867 ('graftstate', True, False, _('graft in progress'),
2864 _("use 'hg graft --continue' or 'hg update' to abort")),
2868 _("use 'hg graft --continue' or 'hg update' to abort")),
2865 ('updatestate', True, False, _('last update was interrupted'),
2869 ('updatestate', True, False, _('last update was interrupted'),
2866 _("use 'hg update' to get a consistent checkout"))
2870 _("use 'hg update' to get a consistent checkout"))
2867 ]
2871 ]
2868
2872
2869 def checkunfinished(repo, commit=False):
2873 def checkunfinished(repo, commit=False):
2870 '''Look for an unfinished multistep operation, like graft, and abort
2874 '''Look for an unfinished multistep operation, like graft, and abort
2871 if found. It's probably good to check this right before
2875 if found. It's probably good to check this right before
2872 bailifchanged().
2876 bailifchanged().
2873 '''
2877 '''
2874 for f, clearable, allowcommit, msg, hint in unfinishedstates:
2878 for f, clearable, allowcommit, msg, hint in unfinishedstates:
2875 if commit and allowcommit:
2879 if commit and allowcommit:
2876 continue
2880 continue
2877 if repo.vfs.exists(f):
2881 if repo.vfs.exists(f):
2878 raise util.Abort(msg, hint=hint)
2882 raise util.Abort(msg, hint=hint)
2879
2883
2880 def clearunfinished(repo):
2884 def clearunfinished(repo):
2881 '''Check for unfinished operations (as above), and clear the ones
2885 '''Check for unfinished operations (as above), and clear the ones
2882 that are clearable.
2886 that are clearable.
2883 '''
2887 '''
2884 for f, clearable, allowcommit, msg, hint in unfinishedstates:
2888 for f, clearable, allowcommit, msg, hint in unfinishedstates:
2885 if not clearable and repo.vfs.exists(f):
2889 if not clearable and repo.vfs.exists(f):
2886 raise util.Abort(msg, hint=hint)
2890 raise util.Abort(msg, hint=hint)
2887 for f, clearable, allowcommit, msg, hint in unfinishedstates:
2891 for f, clearable, allowcommit, msg, hint in unfinishedstates:
2888 if clearable and repo.vfs.exists(f):
2892 if clearable and repo.vfs.exists(f):
2889 util.unlink(repo.join(f))
2893 util.unlink(repo.join(f))
@@ -1,1201 +1,1197 b''
1 $ hg init repo
1 $ hg init repo
2 $ cd repo
2 $ cd repo
3 $ echo 123 > a
3 $ echo 123 > a
4 $ echo 123 > c
4 $ echo 123 > c
5 $ echo 123 > e
5 $ echo 123 > e
6 $ hg add a c e
6 $ hg add a c e
7 $ hg commit -m "first" a c e
7 $ hg commit -m "first" a c e
8
8
9 nothing changed
9 nothing changed
10
10
11 $ hg revert
11 $ hg revert
12 abort: no files or directories specified
12 abort: no files or directories specified
13 (use --all to revert all files)
13 (use --all to revert all files)
14 [255]
14 [255]
15 $ hg revert --all
15 $ hg revert --all
16
16
17 Introduce some changes and revert them
17 Introduce some changes and revert them
18 --------------------------------------
18 --------------------------------------
19
19
20 $ echo 123 > b
20 $ echo 123 > b
21
21
22 $ hg status
22 $ hg status
23 ? b
23 ? b
24 $ echo 12 > c
24 $ echo 12 > c
25
25
26 $ hg status
26 $ hg status
27 M c
27 M c
28 ? b
28 ? b
29 $ hg add b
29 $ hg add b
30
30
31 $ hg status
31 $ hg status
32 M c
32 M c
33 A b
33 A b
34 $ hg rm a
34 $ hg rm a
35
35
36 $ hg status
36 $ hg status
37 M c
37 M c
38 A b
38 A b
39 R a
39 R a
40
40
41 revert removal of a file
41 revert removal of a file
42
42
43 $ hg revert a
43 $ hg revert a
44 $ hg status
44 $ hg status
45 M c
45 M c
46 A b
46 A b
47
47
48 revert addition of a file
48 revert addition of a file
49
49
50 $ hg revert b
50 $ hg revert b
51 $ hg status
51 $ hg status
52 M c
52 M c
53 ? b
53 ? b
54
54
55 revert modification of a file (--no-backup)
55 revert modification of a file (--no-backup)
56
56
57 $ hg revert --no-backup c
57 $ hg revert --no-backup c
58 $ hg status
58 $ hg status
59 ? b
59 ? b
60
60
61 revert deletion (! status) of a added file
61 revert deletion (! status) of a added file
62 ------------------------------------------
62 ------------------------------------------
63
63
64 $ hg add b
64 $ hg add b
65
65
66 $ hg status b
66 $ hg status b
67 A b
67 A b
68 $ rm b
68 $ rm b
69 $ hg status b
69 $ hg status b
70 ! b
70 ! b
71 $ hg revert -v b
71 $ hg revert -v b
72 forgetting b
72 forgetting b
73 $ hg status b
73 $ hg status b
74 b: * (glob)
74 b: * (glob)
75
75
76 $ ls
76 $ ls
77 a
77 a
78 c
78 c
79 e
79 e
80
80
81 Test creation of backup (.orig) files
81 Test creation of backup (.orig) files
82 -------------------------------------
82 -------------------------------------
83
83
84 $ echo z > e
84 $ echo z > e
85 $ hg revert --all -v
85 $ hg revert --all -v
86 saving current version of e as e.orig
86 saving current version of e as e.orig
87 reverting e
87 reverting e
88
88
89 revert on clean file (no change)
89 revert on clean file (no change)
90 --------------------------------
90 --------------------------------
91
91
92 $ hg revert a
92 $ hg revert a
93 no changes needed to a
93 no changes needed to a
94
94
95 revert on an untracked file
95 revert on an untracked file
96 ---------------------------
96 ---------------------------
97
97
98 $ echo q > q
98 $ echo q > q
99 $ hg revert q
99 $ hg revert q
100 file not managed: q
100 file not managed: q
101 $ rm q
101 $ rm q
102
102
103 revert on file that does not exists
103 revert on file that does not exists
104 -----------------------------------
104 -----------------------------------
105
105
106 $ hg revert notfound
106 $ hg revert notfound
107 notfound: no such file in rev 334a9e57682c
107 notfound: no such file in rev 334a9e57682c
108 $ touch d
108 $ touch d
109 $ hg add d
109 $ hg add d
110 $ hg rm a
110 $ hg rm a
111 $ hg commit -m "second"
111 $ hg commit -m "second"
112 $ echo z > z
112 $ echo z > z
113 $ hg add z
113 $ hg add z
114 $ hg st
114 $ hg st
115 A z
115 A z
116 ? e.orig
116 ? e.orig
117
117
118 revert to another revision (--rev)
118 revert to another revision (--rev)
119 ----------------------------------
119 ----------------------------------
120
120
121 $ hg revert --all -r0
121 $ hg revert --all -r0
122 adding a
122 adding a
123 removing d
123 removing d
124 forgetting z
124 forgetting z
125
125
126 revert explicitly to parent (--rev)
126 revert explicitly to parent (--rev)
127 -----------------------------------
127 -----------------------------------
128
128
129 $ hg revert --all -rtip
129 $ hg revert --all -rtip
130 forgetting a
130 forgetting a
131 undeleting d
131 undeleting d
132 $ rm a *.orig
132 $ rm a *.orig
133
133
134 revert to another revision (--rev) and exact match
134 revert to another revision (--rev) and exact match
135 --------------------------------------------------
135 --------------------------------------------------
136
136
137 exact match are more silent
137 exact match are more silent
138
138
139 $ hg revert -r0 a
139 $ hg revert -r0 a
140 $ hg st a
140 $ hg st a
141 A a
141 A a
142 $ hg rm d
142 $ hg rm d
143 $ hg st d
143 $ hg st d
144 R d
144 R d
145
145
146 should keep d removed
146 should keep d removed
147
147
148 $ hg revert -r0 d
148 $ hg revert -r0 d
149 no changes needed to d
149 no changes needed to d
150 $ hg st d
150 $ hg st d
151 R d
151 R d
152
152
153 $ hg update -C
153 $ hg update -C
154 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
154 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
155
155
156 revert of exec bit
156 revert of exec bit
157 ------------------
157 ------------------
158
158
159 #if execbit
159 #if execbit
160 $ chmod +x c
160 $ chmod +x c
161 $ hg revert --all
161 $ hg revert --all
162 reverting c
162 reverting c
163
163
164 $ test -x c || echo non-executable
164 $ test -x c || echo non-executable
165 non-executable
165 non-executable
166
166
167 $ chmod +x c
167 $ chmod +x c
168 $ hg commit -m exe
168 $ hg commit -m exe
169
169
170 $ chmod -x c
170 $ chmod -x c
171 $ hg revert --all
171 $ hg revert --all
172 reverting c
172 reverting c
173
173
174 $ test -x c && echo executable
174 $ test -x c && echo executable
175 executable
175 executable
176 #endif
176 #endif
177
177
178 $ cd ..
178 $ cd ..
179
179
180
180
181 Issue241: update and revert produces inconsistent repositories
181 Issue241: update and revert produces inconsistent repositories
182 --------------------------------------------------------------
182 --------------------------------------------------------------
183
183
184 $ hg init a
184 $ hg init a
185 $ cd a
185 $ cd a
186 $ echo a >> a
186 $ echo a >> a
187 $ hg commit -A -d '1 0' -m a
187 $ hg commit -A -d '1 0' -m a
188 adding a
188 adding a
189 $ echo a >> a
189 $ echo a >> a
190 $ hg commit -d '2 0' -m a
190 $ hg commit -d '2 0' -m a
191 $ hg update 0
191 $ hg update 0
192 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
192 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
193 $ mkdir b
193 $ mkdir b
194 $ echo b > b/b
194 $ echo b > b/b
195
195
196 call `hg revert` with no file specified
196 call `hg revert` with no file specified
197 ---------------------------------------
197 ---------------------------------------
198
198
199 $ hg revert -rtip
199 $ hg revert -rtip
200 abort: no files or directories specified
200 abort: no files or directories specified
201 (use --all to revert all files, or 'hg update 1' to update)
201 (use --all to revert all files, or 'hg update 1' to update)
202 [255]
202 [255]
203
203
204 call `hg revert` with --all
204 call `hg revert` with --all
205 ---------------------------
205 ---------------------------
206
206
207 $ hg revert --all -rtip
207 $ hg revert --all -rtip
208 reverting a
208 reverting a
209
209
210
210
211 Issue332: confusing message when reverting directory
211 Issue332: confusing message when reverting directory
212 ----------------------------------------------------
212 ----------------------------------------------------
213
213
214 $ hg ci -A -m b
214 $ hg ci -A -m b
215 adding b/b
215 adding b/b
216 created new head
216 created new head
217 $ echo foobar > b/b
217 $ echo foobar > b/b
218 $ mkdir newdir
218 $ mkdir newdir
219 $ echo foo > newdir/newfile
219 $ echo foo > newdir/newfile
220 $ hg add newdir/newfile
220 $ hg add newdir/newfile
221 $ hg revert b newdir
221 $ hg revert b newdir
222 reverting b/b (glob)
222 reverting b/b (glob)
223 forgetting newdir/newfile (glob)
223 forgetting newdir/newfile (glob)
224 $ echo foobar > b/b
224 $ echo foobar > b/b
225 $ hg revert .
225 $ hg revert .
226 reverting b/b (glob)
226 reverting b/b (glob)
227
227
228
228
229 reverting a rename target should revert the source
229 reverting a rename target should revert the source
230 --------------------------------------------------
230 --------------------------------------------------
231
231
232 $ hg mv a newa
232 $ hg mv a newa
233 $ hg revert newa
233 $ hg revert newa
234 $ hg st a newa
234 $ hg st a newa
235 ? newa
235 ? newa
236
236
237 $ cd ..
237 $ cd ..
238
238
239 $ hg init ignored
239 $ hg init ignored
240 $ cd ignored
240 $ cd ignored
241 $ echo '^ignored$' > .hgignore
241 $ echo '^ignored$' > .hgignore
242 $ echo '^ignoreddir$' >> .hgignore
242 $ echo '^ignoreddir$' >> .hgignore
243 $ echo '^removed$' >> .hgignore
243 $ echo '^removed$' >> .hgignore
244
244
245 $ mkdir ignoreddir
245 $ mkdir ignoreddir
246 $ touch ignoreddir/file
246 $ touch ignoreddir/file
247 $ touch ignoreddir/removed
247 $ touch ignoreddir/removed
248 $ touch ignored
248 $ touch ignored
249 $ touch removed
249 $ touch removed
250
250
251 4 ignored files (we will add/commit everything)
251 4 ignored files (we will add/commit everything)
252
252
253 $ hg st -A -X .hgignore
253 $ hg st -A -X .hgignore
254 I ignored
254 I ignored
255 I ignoreddir/file
255 I ignoreddir/file
256 I ignoreddir/removed
256 I ignoreddir/removed
257 I removed
257 I removed
258 $ hg ci -qAm 'add files' ignored ignoreddir/file ignoreddir/removed removed
258 $ hg ci -qAm 'add files' ignored ignoreddir/file ignoreddir/removed removed
259
259
260 $ echo >> ignored
260 $ echo >> ignored
261 $ echo >> ignoreddir/file
261 $ echo >> ignoreddir/file
262 $ hg rm removed ignoreddir/removed
262 $ hg rm removed ignoreddir/removed
263
263
264 should revert ignored* and undelete *removed
264 should revert ignored* and undelete *removed
265 --------------------------------------------
265 --------------------------------------------
266
266
267 $ hg revert -a --no-backup
267 $ hg revert -a --no-backup
268 reverting ignored
268 reverting ignored
269 reverting ignoreddir/file (glob)
269 reverting ignoreddir/file (glob)
270 undeleting ignoreddir/removed (glob)
270 undeleting ignoreddir/removed (glob)
271 undeleting removed
271 undeleting removed
272 $ hg st -mardi
272 $ hg st -mardi
273
273
274 $ hg up -qC
274 $ hg up -qC
275 $ echo >> ignored
275 $ echo >> ignored
276 $ hg rm removed
276 $ hg rm removed
277
277
278 should silently revert the named files
278 should silently revert the named files
279 --------------------------------------
279 --------------------------------------
280
280
281 $ hg revert --no-backup ignored removed
281 $ hg revert --no-backup ignored removed
282 $ hg st -mardi
282 $ hg st -mardi
283
283
284 Reverting copy (issue3920)
284 Reverting copy (issue3920)
285 --------------------------
285 --------------------------
286
286
287 someone set up us the copies
287 someone set up us the copies
288
288
289 $ rm .hgignore
289 $ rm .hgignore
290 $ hg update -C
290 $ hg update -C
291 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
291 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
292 $ hg mv ignored allyour
292 $ hg mv ignored allyour
293 $ hg copy removed base
293 $ hg copy removed base
294 $ hg commit -m rename
294 $ hg commit -m rename
295
295
296 copies and renames, you have no chance to survive make your time (issue3920)
296 copies and renames, you have no chance to survive make your time (issue3920)
297
297
298 $ hg update '.^'
298 $ hg update '.^'
299 1 files updated, 0 files merged, 2 files removed, 0 files unresolved
299 1 files updated, 0 files merged, 2 files removed, 0 files unresolved
300 $ hg revert -rtip -a
300 $ hg revert -rtip -a
301 adding allyour
301 adding allyour
302 adding base
302 adding base
303 removing ignored
303 removing ignored
304 $ hg status -C
304 $ hg status -C
305 A allyour
305 A allyour
306 ignored
306 ignored
307 A base
307 A base
308 removed
308 removed
309 R ignored
309 R ignored
310
310
311 Test revert of a file added by one side of the merge
311 Test revert of a file added by one side of the merge
312 ====================================================
312 ====================================================
313
313
314 remove any pending change
314 remove any pending change
315
315
316 $ hg revert --all
316 $ hg revert --all
317 forgetting allyour
317 forgetting allyour
318 forgetting base
318 forgetting base
319 undeleting ignored
319 undeleting ignored
320 $ hg purge --all --config extensions.purge=
320 $ hg purge --all --config extensions.purge=
321
321
322 Adds a new commit
322 Adds a new commit
323
323
324 $ echo foo > newadd
324 $ echo foo > newadd
325 $ hg add newadd
325 $ hg add newadd
326 $ hg commit -m 'other adds'
326 $ hg commit -m 'other adds'
327 created new head
327 created new head
328
328
329
329
330 merge it with the other head
330 merge it with the other head
331
331
332 $ hg merge # merge 1 into 2
332 $ hg merge # merge 1 into 2
333 2 files updated, 0 files merged, 1 files removed, 0 files unresolved
333 2 files updated, 0 files merged, 1 files removed, 0 files unresolved
334 (branch merge, don't forget to commit)
334 (branch merge, don't forget to commit)
335 $ hg summary
335 $ hg summary
336 parent: 2:b8ec310b2d4e tip
336 parent: 2:b8ec310b2d4e tip
337 other adds
337 other adds
338 parent: 1:f6180deb8fbe
338 parent: 1:f6180deb8fbe
339 rename
339 rename
340 branch: default
340 branch: default
341 commit: 2 modified, 1 removed (merge)
341 commit: 2 modified, 1 removed (merge)
342 update: (current)
342 update: (current)
343
343
344 clarifies who added what
344 clarifies who added what
345
345
346 $ hg status
346 $ hg status
347 M allyour
347 M allyour
348 M base
348 M base
349 R ignored
349 R ignored
350 $ hg status --change 'p1()'
350 $ hg status --change 'p1()'
351 A newadd
351 A newadd
352 $ hg status --change 'p2()'
352 $ hg status --change 'p2()'
353 A allyour
353 A allyour
354 A base
354 A base
355 R ignored
355 R ignored
356
356
357 revert file added by p1() to p1() state
357 revert file added by p1() to p1() state
358 -----------------------------------------
358 -----------------------------------------
359
359
360 $ hg revert -r 'p1()' 'glob:newad?'
360 $ hg revert -r 'p1()' 'glob:newad?'
361 $ hg status
361 $ hg status
362 M allyour
362 M allyour
363 M base
363 M base
364 R ignored
364 R ignored
365
365
366 revert file added by p1() to p2() state
366 revert file added by p1() to p2() state
367 ------------------------------------------
367 ------------------------------------------
368
368
369 $ hg revert -r 'p2()' 'glob:newad?'
369 $ hg revert -r 'p2()' 'glob:newad?'
370 removing newadd
370 removing newadd
371 $ hg status
371 $ hg status
372 M allyour
372 M allyour
373 M base
373 M base
374 R ignored
374 R ignored
375 R newadd
375 R newadd
376
376
377 revert file added by p2() to p2() state
377 revert file added by p2() to p2() state
378 ------------------------------------------
378 ------------------------------------------
379
379
380 $ hg revert -r 'p2()' 'glob:allyou?'
380 $ hg revert -r 'p2()' 'glob:allyou?'
381 $ hg status
381 $ hg status
382 M allyour
382 M allyour
383 M base
383 M base
384 R ignored
384 R ignored
385 R newadd
385 R newadd
386
386
387 revert file added by p2() to p1() state
387 revert file added by p2() to p1() state
388 ------------------------------------------
388 ------------------------------------------
389
389
390 $ hg revert -r 'p1()' 'glob:allyou?'
390 $ hg revert -r 'p1()' 'glob:allyou?'
391 removing allyour
391 removing allyour
392 $ hg status
392 $ hg status
393 M base
393 M base
394 R allyour
394 R allyour
395 R ignored
395 R ignored
396 R newadd
396 R newadd
397
397
398 Systematic behavior validation of most possible cases
398 Systematic behavior validation of most possible cases
399 =====================================================
399 =====================================================
400
400
401 This section tests most of the possible combinations of working directory
401 This section tests most of the possible combinations of working directory
402 changes and inter-revision changes. The number of possible cases is significant
402 changes and inter-revision changes. The number of possible cases is significant
403 but they all have a slighly different handling. So this section commits to
403 but they all have a slighly different handling. So this section commits to
404 generating and testing all of them to allow safe refactoring of the revert code.
404 generating and testing all of them to allow safe refactoring of the revert code.
405
405
406 A python script is used to generate a file history for each combination of
406 A python script is used to generate a file history for each combination of
407 changes between, on one side the working directory and its parent and on
407 changes between, on one side the working directory and its parent and on
408 the other side, changes between a revert target (--rev) and working directory
408 the other side, changes between a revert target (--rev) and working directory
409 parent. The three states generated are:
409 parent. The three states generated are:
410
410
411 - a "base" revision
411 - a "base" revision
412 - a "parent" revision
412 - a "parent" revision
413 - the working directory (based on "parent")
413 - the working directory (based on "parent")
414
414
415 The file generated have names of the form:
415 The file generated have names of the form:
416
416
417 <changeset-state>_<working-copy-state>
417 <changeset-state>_<working-copy-state>
418
418
419 Here, "changeset-state" conveys the state in "base" and "parent" (or the change
419 Here, "changeset-state" conveys the state in "base" and "parent" (or the change
420 that happen between them), "working-copy-state" is self explanatory.
420 that happen between them), "working-copy-state" is self explanatory.
421
421
422 All known states are not tested yet. See inline documentation for details.
422 All known states are not tested yet. See inline documentation for details.
423 Special cases from merge and rename are not tested by this section.
423 Special cases from merge and rename are not tested by this section.
424
424
425 There are also multiple cases where the current revert implementation is known to
425 There are also multiple cases where the current revert implementation is known to
426 slightly misbehave.
426 slightly misbehave.
427
427
428 Write the python script to disk
428 Write the python script to disk
429 -------------------------------
429 -------------------------------
430
430
431 $ cat << EOF > gen-revert-cases.py
431 $ cat << EOF > gen-revert-cases.py
432 > # generate proper file state to test revert behavior
432 > # generate proper file state to test revert behavior
433 > import sys
433 > import sys
434 > import os
434 > import os
435 >
435 >
436 > # content of the file in "base" and "parent"
436 > # content of the file in "base" and "parent"
437 > # None means no file at all
437 > # None means no file at all
438 > ctxcontent = {
438 > ctxcontent = {
439 > # clean: no change from base to parent
439 > # clean: no change from base to parent
440 > 'clean': ['base', 'base'],
440 > 'clean': ['base', 'base'],
441 > # modified: file content change from base to parent
441 > # modified: file content change from base to parent
442 > 'modified': ['base', 'parent'],
442 > 'modified': ['base', 'parent'],
443 > # added: file is missing from base and added in parent
443 > # added: file is missing from base and added in parent
444 > 'added': [None, 'parent'],
444 > 'added': [None, 'parent'],
445 > # removed: file exist in base but is removed from parent
445 > # removed: file exist in base but is removed from parent
446 > 'removed': ['base', None],
446 > 'removed': ['base', None],
447 > # file exist neither in base not in parent
447 > # file exist neither in base not in parent
448 > 'missing': [None, None],
448 > 'missing': [None, None],
449 > }
449 > }
450 >
450 >
451 > # content of file in working copy
451 > # content of file in working copy
452 > wccontent = {
452 > wccontent = {
453 > # clean: wc content is the same as parent
453 > # clean: wc content is the same as parent
454 > 'clean': lambda cc: cc[1],
454 > 'clean': lambda cc: cc[1],
455 > # revert: wc content is the same as base
455 > # revert: wc content is the same as base
456 > 'revert': lambda cc: cc[0],
456 > 'revert': lambda cc: cc[0],
457 > # wc: file exist with a content different from base and parent
457 > # wc: file exist with a content different from base and parent
458 > 'wc': lambda cc: 'wc',
458 > 'wc': lambda cc: 'wc',
459 > # removed: file is missing and marked as untracked
459 > # removed: file is missing and marked as untracked
460 > 'removed': lambda cc: None,
460 > 'removed': lambda cc: None,
461 > # deleted: file is recorded as tracked but missing
461 > # deleted: file is recorded as tracked but missing
462 > # rely on file deletion outside of this script
462 > # rely on file deletion outside of this script
463 > 'deleted': lambda cc:'TOBEDELETED',
463 > 'deleted': lambda cc:'TOBEDELETED',
464 > }
464 > }
465 > # untracked-X is a version of X where the file is not tracked (? unknown)
465 > # untracked-X is a version of X where the file is not tracked (? unknown)
466 > wccontent['untracked-clean'] = wccontent['clean']
466 > wccontent['untracked-clean'] = wccontent['clean']
467 > wccontent['untracked-revert'] = wccontent['revert']
467 > wccontent['untracked-revert'] = wccontent['revert']
468 > wccontent['untracked-wc'] = wccontent['wc']
468 > wccontent['untracked-wc'] = wccontent['wc']
469 >
469 >
470 > # build the combination of possible states
470 > # build the combination of possible states
471 > combination = []
471 > combination = []
472 > for ctxkey in ctxcontent:
472 > for ctxkey in ctxcontent:
473 > for wckey in wccontent:
473 > for wckey in wccontent:
474 > filename = "%s_%s" % (ctxkey, wckey)
474 > filename = "%s_%s" % (ctxkey, wckey)
475 > combination.append((filename, ctxkey, wckey))
475 > combination.append((filename, ctxkey, wckey))
476 >
476 >
477 > # make sure we have stable output
477 > # make sure we have stable output
478 > combination.sort()
478 > combination.sort()
479 >
479 >
480 > # retrieve the state we must generate
480 > # retrieve the state we must generate
481 > target = sys.argv[1]
481 > target = sys.argv[1]
482 >
482 >
483 > # compute file content
483 > # compute file content
484 > content = []
484 > content = []
485 > for filename, ctxkey, wckey in combination:
485 > for filename, ctxkey, wckey in combination:
486 > cc = ctxcontent[ctxkey]
486 > cc = ctxcontent[ctxkey]
487 > if target == 'filelist':
487 > if target == 'filelist':
488 > print filename
488 > print filename
489 > elif target == 'base':
489 > elif target == 'base':
490 > content.append((filename, cc[0]))
490 > content.append((filename, cc[0]))
491 > elif target == 'parent':
491 > elif target == 'parent':
492 > content.append((filename, cc[1]))
492 > content.append((filename, cc[1]))
493 > elif target == 'wc':
493 > elif target == 'wc':
494 > content.append((filename, wccontent[wckey](cc)))
494 > content.append((filename, wccontent[wckey](cc)))
495 > else:
495 > else:
496 > print >> sys.stderr, "unknown target:", target
496 > print >> sys.stderr, "unknown target:", target
497 > sys.exit(1)
497 > sys.exit(1)
498 >
498 >
499 > # write actual content
499 > # write actual content
500 > for filename, data in content:
500 > for filename, data in content:
501 > if data is not None:
501 > if data is not None:
502 > f = open(filename, 'w')
502 > f = open(filename, 'w')
503 > f.write(data + '\n')
503 > f.write(data + '\n')
504 > f.close()
504 > f.close()
505 > elif os.path.exists(filename):
505 > elif os.path.exists(filename):
506 > os.remove(filename)
506 > os.remove(filename)
507 > EOF
507 > EOF
508
508
509 check list of planned files
509 check list of planned files
510
510
511 $ python gen-revert-cases.py filelist
511 $ python gen-revert-cases.py filelist
512 added_clean
512 added_clean
513 added_deleted
513 added_deleted
514 added_removed
514 added_removed
515 added_revert
515 added_revert
516 added_untracked-clean
516 added_untracked-clean
517 added_untracked-revert
517 added_untracked-revert
518 added_untracked-wc
518 added_untracked-wc
519 added_wc
519 added_wc
520 clean_clean
520 clean_clean
521 clean_deleted
521 clean_deleted
522 clean_removed
522 clean_removed
523 clean_revert
523 clean_revert
524 clean_untracked-clean
524 clean_untracked-clean
525 clean_untracked-revert
525 clean_untracked-revert
526 clean_untracked-wc
526 clean_untracked-wc
527 clean_wc
527 clean_wc
528 missing_clean
528 missing_clean
529 missing_deleted
529 missing_deleted
530 missing_removed
530 missing_removed
531 missing_revert
531 missing_revert
532 missing_untracked-clean
532 missing_untracked-clean
533 missing_untracked-revert
533 missing_untracked-revert
534 missing_untracked-wc
534 missing_untracked-wc
535 missing_wc
535 missing_wc
536 modified_clean
536 modified_clean
537 modified_deleted
537 modified_deleted
538 modified_removed
538 modified_removed
539 modified_revert
539 modified_revert
540 modified_untracked-clean
540 modified_untracked-clean
541 modified_untracked-revert
541 modified_untracked-revert
542 modified_untracked-wc
542 modified_untracked-wc
543 modified_wc
543 modified_wc
544 removed_clean
544 removed_clean
545 removed_deleted
545 removed_deleted
546 removed_removed
546 removed_removed
547 removed_revert
547 removed_revert
548 removed_untracked-clean
548 removed_untracked-clean
549 removed_untracked-revert
549 removed_untracked-revert
550 removed_untracked-wc
550 removed_untracked-wc
551 removed_wc
551 removed_wc
552
552
553 Script to make a simple text version of the content
553 Script to make a simple text version of the content
554 ---------------------------------------------------
554 ---------------------------------------------------
555
555
556 $ cat << EOF >> dircontent.py
556 $ cat << EOF >> dircontent.py
557 > # generate a simple text view of the directory for easy comparison
557 > # generate a simple text view of the directory for easy comparison
558 > import os
558 > import os
559 > files = os.listdir('.')
559 > files = os.listdir('.')
560 > files.sort()
560 > files.sort()
561 > for filename in files:
561 > for filename in files:
562 > if os.path.isdir(filename):
562 > if os.path.isdir(filename):
563 > continue
563 > continue
564 > content = open(filename).read()
564 > content = open(filename).read()
565 > print '%-6s %s' % (content.strip(), filename)
565 > print '%-6s %s' % (content.strip(), filename)
566 > EOF
566 > EOF
567
567
568 Generate appropriate repo state
568 Generate appropriate repo state
569 -------------------------------
569 -------------------------------
570
570
571 $ hg init revert-ref
571 $ hg init revert-ref
572 $ cd revert-ref
572 $ cd revert-ref
573
573
574 Generate base changeset
574 Generate base changeset
575
575
576 $ python ../gen-revert-cases.py base
576 $ python ../gen-revert-cases.py base
577 $ hg addremove --similarity 0
577 $ hg addremove --similarity 0
578 adding clean_clean
578 adding clean_clean
579 adding clean_deleted
579 adding clean_deleted
580 adding clean_removed
580 adding clean_removed
581 adding clean_revert
581 adding clean_revert
582 adding clean_untracked-clean
582 adding clean_untracked-clean
583 adding clean_untracked-revert
583 adding clean_untracked-revert
584 adding clean_untracked-wc
584 adding clean_untracked-wc
585 adding clean_wc
585 adding clean_wc
586 adding modified_clean
586 adding modified_clean
587 adding modified_deleted
587 adding modified_deleted
588 adding modified_removed
588 adding modified_removed
589 adding modified_revert
589 adding modified_revert
590 adding modified_untracked-clean
590 adding modified_untracked-clean
591 adding modified_untracked-revert
591 adding modified_untracked-revert
592 adding modified_untracked-wc
592 adding modified_untracked-wc
593 adding modified_wc
593 adding modified_wc
594 adding removed_clean
594 adding removed_clean
595 adding removed_deleted
595 adding removed_deleted
596 adding removed_removed
596 adding removed_removed
597 adding removed_revert
597 adding removed_revert
598 adding removed_untracked-clean
598 adding removed_untracked-clean
599 adding removed_untracked-revert
599 adding removed_untracked-revert
600 adding removed_untracked-wc
600 adding removed_untracked-wc
601 adding removed_wc
601 adding removed_wc
602 $ hg status
602 $ hg status
603 A clean_clean
603 A clean_clean
604 A clean_deleted
604 A clean_deleted
605 A clean_removed
605 A clean_removed
606 A clean_revert
606 A clean_revert
607 A clean_untracked-clean
607 A clean_untracked-clean
608 A clean_untracked-revert
608 A clean_untracked-revert
609 A clean_untracked-wc
609 A clean_untracked-wc
610 A clean_wc
610 A clean_wc
611 A modified_clean
611 A modified_clean
612 A modified_deleted
612 A modified_deleted
613 A modified_removed
613 A modified_removed
614 A modified_revert
614 A modified_revert
615 A modified_untracked-clean
615 A modified_untracked-clean
616 A modified_untracked-revert
616 A modified_untracked-revert
617 A modified_untracked-wc
617 A modified_untracked-wc
618 A modified_wc
618 A modified_wc
619 A removed_clean
619 A removed_clean
620 A removed_deleted
620 A removed_deleted
621 A removed_removed
621 A removed_removed
622 A removed_revert
622 A removed_revert
623 A removed_untracked-clean
623 A removed_untracked-clean
624 A removed_untracked-revert
624 A removed_untracked-revert
625 A removed_untracked-wc
625 A removed_untracked-wc
626 A removed_wc
626 A removed_wc
627 $ hg commit -m 'base'
627 $ hg commit -m 'base'
628
628
629 (create a simple text version of the content)
629 (create a simple text version of the content)
630
630
631 $ python ../dircontent.py > ../content-base.txt
631 $ python ../dircontent.py > ../content-base.txt
632 $ cat ../content-base.txt
632 $ cat ../content-base.txt
633 base clean_clean
633 base clean_clean
634 base clean_deleted
634 base clean_deleted
635 base clean_removed
635 base clean_removed
636 base clean_revert
636 base clean_revert
637 base clean_untracked-clean
637 base clean_untracked-clean
638 base clean_untracked-revert
638 base clean_untracked-revert
639 base clean_untracked-wc
639 base clean_untracked-wc
640 base clean_wc
640 base clean_wc
641 base modified_clean
641 base modified_clean
642 base modified_deleted
642 base modified_deleted
643 base modified_removed
643 base modified_removed
644 base modified_revert
644 base modified_revert
645 base modified_untracked-clean
645 base modified_untracked-clean
646 base modified_untracked-revert
646 base modified_untracked-revert
647 base modified_untracked-wc
647 base modified_untracked-wc
648 base modified_wc
648 base modified_wc
649 base removed_clean
649 base removed_clean
650 base removed_deleted
650 base removed_deleted
651 base removed_removed
651 base removed_removed
652 base removed_revert
652 base removed_revert
653 base removed_untracked-clean
653 base removed_untracked-clean
654 base removed_untracked-revert
654 base removed_untracked-revert
655 base removed_untracked-wc
655 base removed_untracked-wc
656 base removed_wc
656 base removed_wc
657
657
658 Create parent changeset
658 Create parent changeset
659
659
660 $ python ../gen-revert-cases.py parent
660 $ python ../gen-revert-cases.py parent
661 $ hg addremove --similarity 0
661 $ hg addremove --similarity 0
662 adding added_clean
662 adding added_clean
663 adding added_deleted
663 adding added_deleted
664 adding added_removed
664 adding added_removed
665 adding added_revert
665 adding added_revert
666 adding added_untracked-clean
666 adding added_untracked-clean
667 adding added_untracked-revert
667 adding added_untracked-revert
668 adding added_untracked-wc
668 adding added_untracked-wc
669 adding added_wc
669 adding added_wc
670 removing removed_clean
670 removing removed_clean
671 removing removed_deleted
671 removing removed_deleted
672 removing removed_removed
672 removing removed_removed
673 removing removed_revert
673 removing removed_revert
674 removing removed_untracked-clean
674 removing removed_untracked-clean
675 removing removed_untracked-revert
675 removing removed_untracked-revert
676 removing removed_untracked-wc
676 removing removed_untracked-wc
677 removing removed_wc
677 removing removed_wc
678 $ hg status
678 $ hg status
679 M modified_clean
679 M modified_clean
680 M modified_deleted
680 M modified_deleted
681 M modified_removed
681 M modified_removed
682 M modified_revert
682 M modified_revert
683 M modified_untracked-clean
683 M modified_untracked-clean
684 M modified_untracked-revert
684 M modified_untracked-revert
685 M modified_untracked-wc
685 M modified_untracked-wc
686 M modified_wc
686 M modified_wc
687 A added_clean
687 A added_clean
688 A added_deleted
688 A added_deleted
689 A added_removed
689 A added_removed
690 A added_revert
690 A added_revert
691 A added_untracked-clean
691 A added_untracked-clean
692 A added_untracked-revert
692 A added_untracked-revert
693 A added_untracked-wc
693 A added_untracked-wc
694 A added_wc
694 A added_wc
695 R removed_clean
695 R removed_clean
696 R removed_deleted
696 R removed_deleted
697 R removed_removed
697 R removed_removed
698 R removed_revert
698 R removed_revert
699 R removed_untracked-clean
699 R removed_untracked-clean
700 R removed_untracked-revert
700 R removed_untracked-revert
701 R removed_untracked-wc
701 R removed_untracked-wc
702 R removed_wc
702 R removed_wc
703 $ hg commit -m 'parent'
703 $ hg commit -m 'parent'
704
704
705 (create a simple text version of the content)
705 (create a simple text version of the content)
706
706
707 $ python ../dircontent.py > ../content-parent.txt
707 $ python ../dircontent.py > ../content-parent.txt
708 $ cat ../content-parent.txt
708 $ cat ../content-parent.txt
709 parent added_clean
709 parent added_clean
710 parent added_deleted
710 parent added_deleted
711 parent added_removed
711 parent added_removed
712 parent added_revert
712 parent added_revert
713 parent added_untracked-clean
713 parent added_untracked-clean
714 parent added_untracked-revert
714 parent added_untracked-revert
715 parent added_untracked-wc
715 parent added_untracked-wc
716 parent added_wc
716 parent added_wc
717 base clean_clean
717 base clean_clean
718 base clean_deleted
718 base clean_deleted
719 base clean_removed
719 base clean_removed
720 base clean_revert
720 base clean_revert
721 base clean_untracked-clean
721 base clean_untracked-clean
722 base clean_untracked-revert
722 base clean_untracked-revert
723 base clean_untracked-wc
723 base clean_untracked-wc
724 base clean_wc
724 base clean_wc
725 parent modified_clean
725 parent modified_clean
726 parent modified_deleted
726 parent modified_deleted
727 parent modified_removed
727 parent modified_removed
728 parent modified_revert
728 parent modified_revert
729 parent modified_untracked-clean
729 parent modified_untracked-clean
730 parent modified_untracked-revert
730 parent modified_untracked-revert
731 parent modified_untracked-wc
731 parent modified_untracked-wc
732 parent modified_wc
732 parent modified_wc
733
733
734 Setup working directory
734 Setup working directory
735
735
736 $ python ../gen-revert-cases.py wc | cat
736 $ python ../gen-revert-cases.py wc | cat
737 $ hg addremove --similarity 0
737 $ hg addremove --similarity 0
738 removing added_removed
738 removing added_removed
739 removing added_revert
739 removing added_revert
740 removing added_untracked-revert
740 removing added_untracked-revert
741 removing clean_removed
741 removing clean_removed
742 adding missing_deleted
742 adding missing_deleted
743 adding missing_untracked-wc
743 adding missing_untracked-wc
744 adding missing_wc
744 adding missing_wc
745 removing modified_removed
745 removing modified_removed
746 adding removed_deleted
746 adding removed_deleted
747 adding removed_revert
747 adding removed_revert
748 adding removed_untracked-revert
748 adding removed_untracked-revert
749 adding removed_untracked-wc
749 adding removed_untracked-wc
750 adding removed_wc
750 adding removed_wc
751 $ hg forget *untracked*
751 $ hg forget *untracked*
752 $ rm *deleted*
752 $ rm *deleted*
753 $ hg status
753 $ hg status
754 M added_wc
754 M added_wc
755 M clean_wc
755 M clean_wc
756 M modified_revert
756 M modified_revert
757 M modified_wc
757 M modified_wc
758 A missing_wc
758 A missing_wc
759 A removed_revert
759 A removed_revert
760 A removed_wc
760 A removed_wc
761 R added_removed
761 R added_removed
762 R added_revert
762 R added_revert
763 R added_untracked-clean
763 R added_untracked-clean
764 R added_untracked-revert
764 R added_untracked-revert
765 R added_untracked-wc
765 R added_untracked-wc
766 R clean_removed
766 R clean_removed
767 R clean_untracked-clean
767 R clean_untracked-clean
768 R clean_untracked-revert
768 R clean_untracked-revert
769 R clean_untracked-wc
769 R clean_untracked-wc
770 R modified_removed
770 R modified_removed
771 R modified_untracked-clean
771 R modified_untracked-clean
772 R modified_untracked-revert
772 R modified_untracked-revert
773 R modified_untracked-wc
773 R modified_untracked-wc
774 ! added_deleted
774 ! added_deleted
775 ! clean_deleted
775 ! clean_deleted
776 ! missing_deleted
776 ! missing_deleted
777 ! modified_deleted
777 ! modified_deleted
778 ! removed_deleted
778 ! removed_deleted
779 ? missing_untracked-wc
779 ? missing_untracked-wc
780 ? removed_untracked-revert
780 ? removed_untracked-revert
781 ? removed_untracked-wc
781 ? removed_untracked-wc
782
782
783 $ hg status --rev 'desc("base")'
783 $ hg status --rev 'desc("base")'
784 M clean_wc
784 M clean_wc
785 M modified_clean
785 M modified_clean
786 M modified_wc
786 M modified_wc
787 M removed_wc
787 M removed_wc
788 A added_clean
788 A added_clean
789 A added_wc
789 A added_wc
790 A missing_wc
790 A missing_wc
791 R clean_removed
791 R clean_removed
792 R clean_untracked-clean
792 R clean_untracked-clean
793 R clean_untracked-revert
793 R clean_untracked-revert
794 R clean_untracked-wc
794 R clean_untracked-wc
795 R modified_removed
795 R modified_removed
796 R modified_untracked-clean
796 R modified_untracked-clean
797 R modified_untracked-revert
797 R modified_untracked-revert
798 R modified_untracked-wc
798 R modified_untracked-wc
799 R removed_clean
799 R removed_clean
800 R removed_deleted
800 R removed_deleted
801 R removed_removed
801 R removed_removed
802 R removed_untracked-clean
802 R removed_untracked-clean
803 R removed_untracked-revert
803 R removed_untracked-revert
804 R removed_untracked-wc
804 R removed_untracked-wc
805 ! added_deleted
805 ! added_deleted
806 ! clean_deleted
806 ! clean_deleted
807 ! missing_deleted
807 ! missing_deleted
808 ! modified_deleted
808 ! modified_deleted
809 ! removed_deleted
809 ! removed_deleted
810 ? missing_untracked-wc
810 ? missing_untracked-wc
811
811
812 (create a simple text version of the content)
812 (create a simple text version of the content)
813
813
814 $ python ../dircontent.py > ../content-wc.txt
814 $ python ../dircontent.py > ../content-wc.txt
815 $ cat ../content-wc.txt
815 $ cat ../content-wc.txt
816 parent added_clean
816 parent added_clean
817 parent added_untracked-clean
817 parent added_untracked-clean
818 wc added_untracked-wc
818 wc added_untracked-wc
819 wc added_wc
819 wc added_wc
820 base clean_clean
820 base clean_clean
821 base clean_revert
821 base clean_revert
822 base clean_untracked-clean
822 base clean_untracked-clean
823 base clean_untracked-revert
823 base clean_untracked-revert
824 wc clean_untracked-wc
824 wc clean_untracked-wc
825 wc clean_wc
825 wc clean_wc
826 wc missing_untracked-wc
826 wc missing_untracked-wc
827 wc missing_wc
827 wc missing_wc
828 parent modified_clean
828 parent modified_clean
829 base modified_revert
829 base modified_revert
830 parent modified_untracked-clean
830 parent modified_untracked-clean
831 base modified_untracked-revert
831 base modified_untracked-revert
832 wc modified_untracked-wc
832 wc modified_untracked-wc
833 wc modified_wc
833 wc modified_wc
834 base removed_revert
834 base removed_revert
835 base removed_untracked-revert
835 base removed_untracked-revert
836 wc removed_untracked-wc
836 wc removed_untracked-wc
837 wc removed_wc
837 wc removed_wc
838
838
839 $ cd ..
839 $ cd ..
840
840
841 Test revert --all to parent content
841 Test revert --all to parent content
842 -----------------------------------
842 -----------------------------------
843
843
844 (setup from reference repo)
844 (setup from reference repo)
845
845
846 $ cp -r revert-ref revert-parent-all
846 $ cp -r revert-ref revert-parent-all
847 $ cd revert-parent-all
847 $ cd revert-parent-all
848
848
849 check revert output
849 check revert output
850
850
851 $ hg revert --all
851 $ hg revert --all
852 reverting added_deleted
852 reverting added_deleted
853 undeleting added_removed
853 undeleting added_removed
854 undeleting added_revert
854 undeleting added_revert
855 undeleting added_untracked-clean
855 undeleting added_untracked-clean
856 undeleting added_untracked-revert
856 undeleting added_untracked-revert
857 undeleting added_untracked-wc
857 undeleting added_untracked-wc
858 reverting added_wc
858 reverting added_wc
859 reverting clean_deleted
859 reverting clean_deleted
860 undeleting clean_removed
860 undeleting clean_removed
861 undeleting clean_untracked-clean
861 undeleting clean_untracked-clean
862 undeleting clean_untracked-revert
862 undeleting clean_untracked-revert
863 undeleting clean_untracked-wc
863 undeleting clean_untracked-wc
864 reverting clean_wc
864 reverting clean_wc
865 forgetting missing_deleted
865 forgetting missing_deleted
866 forgetting missing_wc
866 forgetting missing_wc
867 reverting modified_deleted
867 reverting modified_deleted
868 undeleting modified_removed
868 undeleting modified_removed
869 reverting modified_revert
869 reverting modified_revert
870 undeleting modified_untracked-clean
870 undeleting modified_untracked-clean
871 undeleting modified_untracked-revert
871 undeleting modified_untracked-revert
872 undeleting modified_untracked-wc
872 undeleting modified_untracked-wc
873 reverting modified_wc
873 reverting modified_wc
874 forgetting removed_deleted
874 forgetting removed_deleted
875 forgetting removed_revert
875 forgetting removed_revert
876 forgetting removed_wc
876 forgetting removed_wc
877
877
878 Compare resulting directory with revert target.
878 Compare resulting directory with revert target.
879
879
880 The diff is filtered to include change only. The only difference should be
880 The diff is filtered to include change only. The only difference should be
881 additional `.orig` backup file when applicable.
881 additional `.orig` backup file when applicable.
882
882
883 $ python ../dircontent.py > ../content-parent-all.txt
883 $ python ../dircontent.py > ../content-parent-all.txt
884 $ cd ..
884 $ cd ..
885 $ diff -U 0 -- content-parent.txt content-parent-all.txt | grep _
885 $ diff -U 0 -- content-parent.txt content-parent-all.txt | grep _
886 +wc added_untracked-wc.orig
886 +wc added_untracked-wc.orig
887 +wc added_wc.orig
887 +wc added_wc.orig
888 +wc clean_untracked-wc.orig
888 +wc clean_untracked-wc.orig
889 +wc clean_wc.orig
889 +wc clean_wc.orig
890 +wc missing_untracked-wc
890 +wc missing_untracked-wc
891 +wc missing_wc
891 +wc missing_wc
892 +base modified_revert.orig
892 +base modified_revert.orig
893 +base modified_untracked-revert.orig
893 +base modified_untracked-revert.orig
894 +wc modified_untracked-wc.orig
894 +wc modified_untracked-wc.orig
895 +wc modified_wc.orig
895 +wc modified_wc.orig
896 +base removed_revert
896 +base removed_revert
897 +base removed_untracked-revert
897 +base removed_untracked-revert
898 +wc removed_untracked-wc
898 +wc removed_untracked-wc
899 +wc removed_wc
899 +wc removed_wc
900
900
901 Test revert --all to "base" content
901 Test revert --all to "base" content
902 -----------------------------------
902 -----------------------------------
903
903
904 (setup from reference repo)
904 (setup from reference repo)
905
905
906 $ cp -r revert-ref revert-base-all
906 $ cp -r revert-ref revert-base-all
907 $ cd revert-base-all
907 $ cd revert-base-all
908
908
909 check revert output
909 check revert output
910
910
911 $ hg revert --all --rev 'desc(base)'
911 $ hg revert --all --rev 'desc(base)'
912 removing added_clean
912 removing added_clean
913 removing added_deleted
913 removing added_deleted
914 removing added_wc
914 removing added_wc
915 reverting clean_deleted
915 reverting clean_deleted
916 undeleting clean_removed
916 undeleting clean_removed
917 undeleting clean_untracked-clean
917 undeleting clean_untracked-clean
918 undeleting clean_untracked-revert
918 undeleting clean_untracked-revert
919 undeleting clean_untracked-wc
919 undeleting clean_untracked-wc
920 reverting clean_wc
920 reverting clean_wc
921 forgetting missing_deleted
921 forgetting missing_deleted
922 forgetting missing_wc
922 forgetting missing_wc
923 reverting modified_clean
923 reverting modified_clean
924 reverting modified_deleted
924 reverting modified_deleted
925 undeleting modified_removed
925 undeleting modified_removed
926 undeleting modified_untracked-clean
926 undeleting modified_untracked-clean
927 undeleting modified_untracked-revert
927 undeleting modified_untracked-revert
928 undeleting modified_untracked-wc
928 undeleting modified_untracked-wc
929 reverting modified_wc
929 reverting modified_wc
930 adding removed_clean
930 adding removed_clean
931 reverting removed_deleted
931 reverting removed_deleted
932 adding removed_removed
932 adding removed_removed
933 adding removed_untracked-clean
933 adding removed_untracked-clean
934 adding removed_untracked-revert
934 adding removed_untracked-revert
935 adding removed_untracked-wc
935 adding removed_untracked-wc
936 reverting removed_wc
936 reverting removed_wc
937
937
938 Compare resulting directory with revert target.
938 Compare resulting directory with revert target.
939
939
940 The diff is filtered to include change only. The only difference should be
940 The diff is filtered to include change only. The only difference should be
941 additional `.orig` backup file when applicable.
941 additional `.orig` backup file when applicable.
942
942
943 Misbehavior:
944
945 - no backup for
946 | - added_wc (DATA LOSS)
947
948 $ python ../dircontent.py > ../content-base-all.txt
943 $ python ../dircontent.py > ../content-base-all.txt
949 $ cd ..
944 $ cd ..
950 $ diff -U 0 -- content-base.txt content-base-all.txt | grep _
945 $ diff -U 0 -- content-base.txt content-base-all.txt | grep _
951 +parent added_untracked-clean
946 +parent added_untracked-clean
952 +wc added_untracked-wc
947 +wc added_untracked-wc
948 +wc added_wc.orig
953 +wc clean_untracked-wc.orig
949 +wc clean_untracked-wc.orig
954 +wc clean_wc.orig
950 +wc clean_wc.orig
955 +wc missing_untracked-wc
951 +wc missing_untracked-wc
956 +wc missing_wc
952 +wc missing_wc
957 +parent modified_untracked-clean.orig
953 +parent modified_untracked-clean.orig
958 +wc modified_untracked-wc.orig
954 +wc modified_untracked-wc.orig
959 +wc modified_wc.orig
955 +wc modified_wc.orig
960 +wc removed_untracked-wc.orig
956 +wc removed_untracked-wc.orig
961 +wc removed_wc.orig
957 +wc removed_wc.orig
962
958
963 Test revert to parent content with explicit file name
959 Test revert to parent content with explicit file name
964 -----------------------------------------------------
960 -----------------------------------------------------
965
961
966 (setup from reference repo)
962 (setup from reference repo)
967
963
968 $ cp -r revert-ref revert-parent-explicit
964 $ cp -r revert-ref revert-parent-explicit
969 $ cd revert-parent-explicit
965 $ cd revert-parent-explicit
970
966
971 revert all files individually and check the output
967 revert all files individually and check the output
972 (output is expected to be different than in the --all case)
968 (output is expected to be different than in the --all case)
973
969
974 $ for file in `python ../gen-revert-cases.py filelist`; do
970 $ for file in `python ../gen-revert-cases.py filelist`; do
975 > echo '### revert for:' $file;
971 > echo '### revert for:' $file;
976 > hg revert $file;
972 > hg revert $file;
977 > echo
973 > echo
978 > done
974 > done
979 ### revert for: added_clean
975 ### revert for: added_clean
980 no changes needed to added_clean
976 no changes needed to added_clean
981
977
982 ### revert for: added_deleted
978 ### revert for: added_deleted
983
979
984 ### revert for: added_removed
980 ### revert for: added_removed
985
981
986 ### revert for: added_revert
982 ### revert for: added_revert
987
983
988 ### revert for: added_untracked-clean
984 ### revert for: added_untracked-clean
989
985
990 ### revert for: added_untracked-revert
986 ### revert for: added_untracked-revert
991
987
992 ### revert for: added_untracked-wc
988 ### revert for: added_untracked-wc
993
989
994 ### revert for: added_wc
990 ### revert for: added_wc
995
991
996 ### revert for: clean_clean
992 ### revert for: clean_clean
997 no changes needed to clean_clean
993 no changes needed to clean_clean
998
994
999 ### revert for: clean_deleted
995 ### revert for: clean_deleted
1000
996
1001 ### revert for: clean_removed
997 ### revert for: clean_removed
1002
998
1003 ### revert for: clean_revert
999 ### revert for: clean_revert
1004 no changes needed to clean_revert
1000 no changes needed to clean_revert
1005
1001
1006 ### revert for: clean_untracked-clean
1002 ### revert for: clean_untracked-clean
1007
1003
1008 ### revert for: clean_untracked-revert
1004 ### revert for: clean_untracked-revert
1009
1005
1010 ### revert for: clean_untracked-wc
1006 ### revert for: clean_untracked-wc
1011
1007
1012 ### revert for: clean_wc
1008 ### revert for: clean_wc
1013
1009
1014 ### revert for: missing_clean
1010 ### revert for: missing_clean
1015 missing_clean: no such file in rev * (glob)
1011 missing_clean: no such file in rev * (glob)
1016
1012
1017 ### revert for: missing_deleted
1013 ### revert for: missing_deleted
1018
1014
1019 ### revert for: missing_removed
1015 ### revert for: missing_removed
1020 missing_removed: no such file in rev * (glob)
1016 missing_removed: no such file in rev * (glob)
1021
1017
1022 ### revert for: missing_revert
1018 ### revert for: missing_revert
1023 missing_revert: no such file in rev * (glob)
1019 missing_revert: no such file in rev * (glob)
1024
1020
1025 ### revert for: missing_untracked-clean
1021 ### revert for: missing_untracked-clean
1026 missing_untracked-clean: no such file in rev * (glob)
1022 missing_untracked-clean: no such file in rev * (glob)
1027
1023
1028 ### revert for: missing_untracked-revert
1024 ### revert for: missing_untracked-revert
1029 missing_untracked-revert: no such file in rev * (glob)
1025 missing_untracked-revert: no such file in rev * (glob)
1030
1026
1031 ### revert for: missing_untracked-wc
1027 ### revert for: missing_untracked-wc
1032 file not managed: missing_untracked-wc
1028 file not managed: missing_untracked-wc
1033
1029
1034 ### revert for: missing_wc
1030 ### revert for: missing_wc
1035
1031
1036 ### revert for: modified_clean
1032 ### revert for: modified_clean
1037 no changes needed to modified_clean
1033 no changes needed to modified_clean
1038
1034
1039 ### revert for: modified_deleted
1035 ### revert for: modified_deleted
1040
1036
1041 ### revert for: modified_removed
1037 ### revert for: modified_removed
1042
1038
1043 ### revert for: modified_revert
1039 ### revert for: modified_revert
1044
1040
1045 ### revert for: modified_untracked-clean
1041 ### revert for: modified_untracked-clean
1046
1042
1047 ### revert for: modified_untracked-revert
1043 ### revert for: modified_untracked-revert
1048
1044
1049 ### revert for: modified_untracked-wc
1045 ### revert for: modified_untracked-wc
1050
1046
1051 ### revert for: modified_wc
1047 ### revert for: modified_wc
1052
1048
1053 ### revert for: removed_clean
1049 ### revert for: removed_clean
1054 removed_clean: no such file in rev * (glob)
1050 removed_clean: no such file in rev * (glob)
1055
1051
1056 ### revert for: removed_deleted
1052 ### revert for: removed_deleted
1057
1053
1058 ### revert for: removed_removed
1054 ### revert for: removed_removed
1059 removed_removed: no such file in rev * (glob)
1055 removed_removed: no such file in rev * (glob)
1060
1056
1061 ### revert for: removed_revert
1057 ### revert for: removed_revert
1062
1058
1063 ### revert for: removed_untracked-clean
1059 ### revert for: removed_untracked-clean
1064 removed_untracked-clean: no such file in rev * (glob)
1060 removed_untracked-clean: no such file in rev * (glob)
1065
1061
1066 ### revert for: removed_untracked-revert
1062 ### revert for: removed_untracked-revert
1067 file not managed: removed_untracked-revert
1063 file not managed: removed_untracked-revert
1068
1064
1069 ### revert for: removed_untracked-wc
1065 ### revert for: removed_untracked-wc
1070 file not managed: removed_untracked-wc
1066 file not managed: removed_untracked-wc
1071
1067
1072 ### revert for: removed_wc
1068 ### revert for: removed_wc
1073
1069
1074
1070
1075 check resulting directory againt the --all run
1071 check resulting directory againt the --all run
1076 (There should be no difference)
1072 (There should be no difference)
1077
1073
1078 $ python ../dircontent.py > ../content-parent-explicit.txt
1074 $ python ../dircontent.py > ../content-parent-explicit.txt
1079 $ cd ..
1075 $ cd ..
1080 $ diff -U 0 -- content-parent-all.txt content-parent-explicit.txt | grep _
1076 $ diff -U 0 -- content-parent-all.txt content-parent-explicit.txt | grep _
1081 [1]
1077 [1]
1082
1078
1083 Test revert to "base" content with explicit file name
1079 Test revert to "base" content with explicit file name
1084 -----------------------------------------------------
1080 -----------------------------------------------------
1085
1081
1086 (setup from reference repo)
1082 (setup from reference repo)
1087
1083
1088 $ cp -r revert-ref revert-base-explicit
1084 $ cp -r revert-ref revert-base-explicit
1089 $ cd revert-base-explicit
1085 $ cd revert-base-explicit
1090
1086
1091 revert all files individually and check the output
1087 revert all files individually and check the output
1092 (output is expected to be different than in the --all case)
1088 (output is expected to be different than in the --all case)
1093
1089
1094 $ for file in `python ../gen-revert-cases.py filelist`; do
1090 $ for file in `python ../gen-revert-cases.py filelist`; do
1095 > echo '### revert for:' $file;
1091 > echo '### revert for:' $file;
1096 > hg revert $file --rev 'desc(base)';
1092 > hg revert $file --rev 'desc(base)';
1097 > echo
1093 > echo
1098 > done
1094 > done
1099 ### revert for: added_clean
1095 ### revert for: added_clean
1100
1096
1101 ### revert for: added_deleted
1097 ### revert for: added_deleted
1102
1098
1103 ### revert for: added_removed
1099 ### revert for: added_removed
1104 no changes needed to added_removed
1100 no changes needed to added_removed
1105
1101
1106 ### revert for: added_revert
1102 ### revert for: added_revert
1107 no changes needed to added_revert
1103 no changes needed to added_revert
1108
1104
1109 ### revert for: added_untracked-clean
1105 ### revert for: added_untracked-clean
1110 no changes needed to added_untracked-clean
1106 no changes needed to added_untracked-clean
1111
1107
1112 ### revert for: added_untracked-revert
1108 ### revert for: added_untracked-revert
1113 no changes needed to added_untracked-revert
1109 no changes needed to added_untracked-revert
1114
1110
1115 ### revert for: added_untracked-wc
1111 ### revert for: added_untracked-wc
1116 no changes needed to added_untracked-wc
1112 no changes needed to added_untracked-wc
1117
1113
1118 ### revert for: added_wc
1114 ### revert for: added_wc
1119
1115
1120 ### revert for: clean_clean
1116 ### revert for: clean_clean
1121 no changes needed to clean_clean
1117 no changes needed to clean_clean
1122
1118
1123 ### revert for: clean_deleted
1119 ### revert for: clean_deleted
1124
1120
1125 ### revert for: clean_removed
1121 ### revert for: clean_removed
1126
1122
1127 ### revert for: clean_revert
1123 ### revert for: clean_revert
1128 no changes needed to clean_revert
1124 no changes needed to clean_revert
1129
1125
1130 ### revert for: clean_untracked-clean
1126 ### revert for: clean_untracked-clean
1131
1127
1132 ### revert for: clean_untracked-revert
1128 ### revert for: clean_untracked-revert
1133
1129
1134 ### revert for: clean_untracked-wc
1130 ### revert for: clean_untracked-wc
1135
1131
1136 ### revert for: clean_wc
1132 ### revert for: clean_wc
1137
1133
1138 ### revert for: missing_clean
1134 ### revert for: missing_clean
1139 missing_clean: no such file in rev * (glob)
1135 missing_clean: no such file in rev * (glob)
1140
1136
1141 ### revert for: missing_deleted
1137 ### revert for: missing_deleted
1142
1138
1143 ### revert for: missing_removed
1139 ### revert for: missing_removed
1144 missing_removed: no such file in rev * (glob)
1140 missing_removed: no such file in rev * (glob)
1145
1141
1146 ### revert for: missing_revert
1142 ### revert for: missing_revert
1147 missing_revert: no such file in rev * (glob)
1143 missing_revert: no such file in rev * (glob)
1148
1144
1149 ### revert for: missing_untracked-clean
1145 ### revert for: missing_untracked-clean
1150 missing_untracked-clean: no such file in rev * (glob)
1146 missing_untracked-clean: no such file in rev * (glob)
1151
1147
1152 ### revert for: missing_untracked-revert
1148 ### revert for: missing_untracked-revert
1153 missing_untracked-revert: no such file in rev * (glob)
1149 missing_untracked-revert: no such file in rev * (glob)
1154
1150
1155 ### revert for: missing_untracked-wc
1151 ### revert for: missing_untracked-wc
1156 file not managed: missing_untracked-wc
1152 file not managed: missing_untracked-wc
1157
1153
1158 ### revert for: missing_wc
1154 ### revert for: missing_wc
1159
1155
1160 ### revert for: modified_clean
1156 ### revert for: modified_clean
1161
1157
1162 ### revert for: modified_deleted
1158 ### revert for: modified_deleted
1163
1159
1164 ### revert for: modified_removed
1160 ### revert for: modified_removed
1165
1161
1166 ### revert for: modified_revert
1162 ### revert for: modified_revert
1167 no changes needed to modified_revert
1163 no changes needed to modified_revert
1168
1164
1169 ### revert for: modified_untracked-clean
1165 ### revert for: modified_untracked-clean
1170
1166
1171 ### revert for: modified_untracked-revert
1167 ### revert for: modified_untracked-revert
1172
1168
1173 ### revert for: modified_untracked-wc
1169 ### revert for: modified_untracked-wc
1174
1170
1175 ### revert for: modified_wc
1171 ### revert for: modified_wc
1176
1172
1177 ### revert for: removed_clean
1173 ### revert for: removed_clean
1178
1174
1179 ### revert for: removed_deleted
1175 ### revert for: removed_deleted
1180
1176
1181 ### revert for: removed_removed
1177 ### revert for: removed_removed
1182
1178
1183 ### revert for: removed_revert
1179 ### revert for: removed_revert
1184 no changes needed to removed_revert
1180 no changes needed to removed_revert
1185
1181
1186 ### revert for: removed_untracked-clean
1182 ### revert for: removed_untracked-clean
1187
1183
1188 ### revert for: removed_untracked-revert
1184 ### revert for: removed_untracked-revert
1189
1185
1190 ### revert for: removed_untracked-wc
1186 ### revert for: removed_untracked-wc
1191
1187
1192 ### revert for: removed_wc
1188 ### revert for: removed_wc
1193
1189
1194
1190
1195 check resulting directory againt the --all run
1191 check resulting directory againt the --all run
1196 (There should be no difference)
1192 (There should be no difference)
1197
1193
1198 $ python ../dircontent.py > ../content-base-explicit.txt
1194 $ python ../dircontent.py > ../content-base-explicit.txt
1199 $ cd ..
1195 $ cd ..
1200 $ diff -U 0 -- content-base-all.txt content-base-explicit.txt | grep _
1196 $ diff -U 0 -- content-base-all.txt content-base-explicit.txt | grep _
1201 [1]
1197 [1]
General Comments 0
You need to be logged in to leave comments. Login now