##// END OF EJS Templates
add: add back forgotten files even when not matching exactly (BC)...
Martin von Zweigbergk -
r23258:10697f29 default
parent child Browse files
Show More
@@ -1,2882 +1,2882 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 'ctxorbool' is one of a ctx to be committed, or a bool whether
116 'ctxorbool' 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:
919 if self.ui.debugflag:
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()),
1155 parents = [[('rev', p.rev()),
1156 ('node', p.hex()),
1156 ('node', p.hex()),
1157 ('phase', p.phasestr())]
1157 ('phase', p.phasestr())]
1158 for p in self._meaningful_parentrevs(ctx)]
1158 for p in self._meaningful_parentrevs(ctx)]
1159 return showlist('parent', parents, **args)
1159 return showlist('parent', parents, **args)
1160
1160
1161 props = props.copy()
1161 props = props.copy()
1162 props.update(templatekw.keywords)
1162 props.update(templatekw.keywords)
1163 props['parents'] = showparents
1163 props['parents'] = showparents
1164 props['templ'] = self.t
1164 props['templ'] = self.t
1165 props['ctx'] = ctx
1165 props['ctx'] = ctx
1166 props['repo'] = self.repo
1166 props['repo'] = self.repo
1167 props['revcache'] = {'copies': copies}
1167 props['revcache'] = {'copies': copies}
1168 props['cache'] = self.cache
1168 props['cache'] = self.cache
1169
1169
1170 # find correct templates for current mode
1170 # find correct templates for current mode
1171
1171
1172 tmplmodes = [
1172 tmplmodes = [
1173 (True, None),
1173 (True, None),
1174 (self.ui.verbose, 'verbose'),
1174 (self.ui.verbose, 'verbose'),
1175 (self.ui.quiet, 'quiet'),
1175 (self.ui.quiet, 'quiet'),
1176 (self.ui.debugflag, 'debug'),
1176 (self.ui.debugflag, 'debug'),
1177 ]
1177 ]
1178
1178
1179 types = {'header': '', 'footer':'', 'changeset': 'changeset'}
1179 types = {'header': '', 'footer':'', 'changeset': 'changeset'}
1180 for mode, postfix in tmplmodes:
1180 for mode, postfix in tmplmodes:
1181 for type in types:
1181 for type in types:
1182 cur = postfix and ('%s_%s' % (type, postfix)) or type
1182 cur = postfix and ('%s_%s' % (type, postfix)) or type
1183 if mode and cur in self.t:
1183 if mode and cur in self.t:
1184 types[type] = cur
1184 types[type] = cur
1185
1185
1186 try:
1186 try:
1187
1187
1188 # write header
1188 # write header
1189 if types['header']:
1189 if types['header']:
1190 h = templater.stringify(self.t(types['header'], **props))
1190 h = templater.stringify(self.t(types['header'], **props))
1191 if self.buffered:
1191 if self.buffered:
1192 self.header[ctx.rev()] = h
1192 self.header[ctx.rev()] = h
1193 else:
1193 else:
1194 if self.lastheader != h:
1194 if self.lastheader != h:
1195 self.lastheader = h
1195 self.lastheader = h
1196 self.ui.write(h)
1196 self.ui.write(h)
1197
1197
1198 # write changeset metadata, then patch if requested
1198 # write changeset metadata, then patch if requested
1199 key = types['changeset']
1199 key = types['changeset']
1200 self.ui.write(templater.stringify(self.t(key, **props)))
1200 self.ui.write(templater.stringify(self.t(key, **props)))
1201 self.showpatch(ctx.node(), matchfn)
1201 self.showpatch(ctx.node(), matchfn)
1202
1202
1203 if types['footer']:
1203 if types['footer']:
1204 if not self.footer:
1204 if not self.footer:
1205 self.footer = templater.stringify(self.t(types['footer'],
1205 self.footer = templater.stringify(self.t(types['footer'],
1206 **props))
1206 **props))
1207
1207
1208 except KeyError, inst:
1208 except KeyError, inst:
1209 msg = _("%s: no key named '%s'")
1209 msg = _("%s: no key named '%s'")
1210 raise util.Abort(msg % (self.t.mapfile, inst.args[0]))
1210 raise util.Abort(msg % (self.t.mapfile, inst.args[0]))
1211 except SyntaxError, inst:
1211 except SyntaxError, inst:
1212 raise util.Abort('%s: %s' % (self.t.mapfile, inst.args[0]))
1212 raise util.Abort('%s: %s' % (self.t.mapfile, inst.args[0]))
1213
1213
1214 def gettemplate(ui, tmpl, style):
1214 def gettemplate(ui, tmpl, style):
1215 """
1215 """
1216 Find the template matching the given template spec or style.
1216 Find the template matching the given template spec or style.
1217 """
1217 """
1218
1218
1219 # ui settings
1219 # ui settings
1220 if not tmpl and not style: # template are stronger than style
1220 if not tmpl and not style: # template are stronger than style
1221 tmpl = ui.config('ui', 'logtemplate')
1221 tmpl = ui.config('ui', 'logtemplate')
1222 if tmpl:
1222 if tmpl:
1223 try:
1223 try:
1224 tmpl = templater.parsestring(tmpl)
1224 tmpl = templater.parsestring(tmpl)
1225 except SyntaxError:
1225 except SyntaxError:
1226 tmpl = templater.parsestring(tmpl, quoted=False)
1226 tmpl = templater.parsestring(tmpl, quoted=False)
1227 return tmpl, None
1227 return tmpl, None
1228 else:
1228 else:
1229 style = util.expandpath(ui.config('ui', 'style', ''))
1229 style = util.expandpath(ui.config('ui', 'style', ''))
1230
1230
1231 if not tmpl and style:
1231 if not tmpl and style:
1232 mapfile = style
1232 mapfile = style
1233 if not os.path.split(mapfile)[0]:
1233 if not os.path.split(mapfile)[0]:
1234 mapname = (templater.templatepath('map-cmdline.' + mapfile)
1234 mapname = (templater.templatepath('map-cmdline.' + mapfile)
1235 or templater.templatepath(mapfile))
1235 or templater.templatepath(mapfile))
1236 if mapname:
1236 if mapname:
1237 mapfile = mapname
1237 mapfile = mapname
1238 return None, mapfile
1238 return None, mapfile
1239
1239
1240 if not tmpl:
1240 if not tmpl:
1241 return None, None
1241 return None, None
1242
1242
1243 # looks like a literal template?
1243 # looks like a literal template?
1244 if '{' in tmpl:
1244 if '{' in tmpl:
1245 return tmpl, None
1245 return tmpl, None
1246
1246
1247 # perhaps a stock style?
1247 # perhaps a stock style?
1248 if not os.path.split(tmpl)[0]:
1248 if not os.path.split(tmpl)[0]:
1249 mapname = (templater.templatepath('map-cmdline.' + tmpl)
1249 mapname = (templater.templatepath('map-cmdline.' + tmpl)
1250 or templater.templatepath(tmpl))
1250 or templater.templatepath(tmpl))
1251 if mapname and os.path.isfile(mapname):
1251 if mapname and os.path.isfile(mapname):
1252 return None, mapname
1252 return None, mapname
1253
1253
1254 # perhaps it's a reference to [templates]
1254 # perhaps it's a reference to [templates]
1255 t = ui.config('templates', tmpl)
1255 t = ui.config('templates', tmpl)
1256 if t:
1256 if t:
1257 try:
1257 try:
1258 tmpl = templater.parsestring(t)
1258 tmpl = templater.parsestring(t)
1259 except SyntaxError:
1259 except SyntaxError:
1260 tmpl = templater.parsestring(t, quoted=False)
1260 tmpl = templater.parsestring(t, quoted=False)
1261 return tmpl, None
1261 return tmpl, None
1262
1262
1263 if tmpl == 'list':
1263 if tmpl == 'list':
1264 ui.write(_("available styles: %s\n") % templater.stylelist())
1264 ui.write(_("available styles: %s\n") % templater.stylelist())
1265 raise util.Abort(_("specify a template"))
1265 raise util.Abort(_("specify a template"))
1266
1266
1267 # perhaps it's a path to a map or a template
1267 # perhaps it's a path to a map or a template
1268 if ('/' in tmpl or '\\' in tmpl) and os.path.isfile(tmpl):
1268 if ('/' in tmpl or '\\' in tmpl) and os.path.isfile(tmpl):
1269 # is it a mapfile for a style?
1269 # is it a mapfile for a style?
1270 if os.path.basename(tmpl).startswith("map-"):
1270 if os.path.basename(tmpl).startswith("map-"):
1271 return None, os.path.realpath(tmpl)
1271 return None, os.path.realpath(tmpl)
1272 tmpl = open(tmpl).read()
1272 tmpl = open(tmpl).read()
1273 return tmpl, None
1273 return tmpl, None
1274
1274
1275 # constant string?
1275 # constant string?
1276 return tmpl, None
1276 return tmpl, None
1277
1277
1278 def show_changeset(ui, repo, opts, buffered=False):
1278 def show_changeset(ui, repo, opts, buffered=False):
1279 """show one changeset using template or regular display.
1279 """show one changeset using template or regular display.
1280
1280
1281 Display format will be the first non-empty hit of:
1281 Display format will be the first non-empty hit of:
1282 1. option 'template'
1282 1. option 'template'
1283 2. option 'style'
1283 2. option 'style'
1284 3. [ui] setting 'logtemplate'
1284 3. [ui] setting 'logtemplate'
1285 4. [ui] setting 'style'
1285 4. [ui] setting 'style'
1286 If all of these values are either the unset or the empty string,
1286 If all of these values are either the unset or the empty string,
1287 regular display via changeset_printer() is done.
1287 regular display via changeset_printer() is done.
1288 """
1288 """
1289 # options
1289 # options
1290 matchfn = None
1290 matchfn = None
1291 if opts.get('patch') or opts.get('stat'):
1291 if opts.get('patch') or opts.get('stat'):
1292 matchfn = scmutil.matchall(repo)
1292 matchfn = scmutil.matchall(repo)
1293
1293
1294 if opts.get('template') == 'json':
1294 if opts.get('template') == 'json':
1295 return jsonchangeset(ui, repo, matchfn, opts, buffered)
1295 return jsonchangeset(ui, repo, matchfn, opts, buffered)
1296
1296
1297 tmpl, mapfile = gettemplate(ui, opts.get('template'), opts.get('style'))
1297 tmpl, mapfile = gettemplate(ui, opts.get('template'), opts.get('style'))
1298
1298
1299 if not tmpl and not mapfile:
1299 if not tmpl and not mapfile:
1300 return changeset_printer(ui, repo, matchfn, opts, buffered)
1300 return changeset_printer(ui, repo, matchfn, opts, buffered)
1301
1301
1302 try:
1302 try:
1303 t = changeset_templater(ui, repo, matchfn, opts, tmpl, mapfile,
1303 t = changeset_templater(ui, repo, matchfn, opts, tmpl, mapfile,
1304 buffered)
1304 buffered)
1305 except SyntaxError, inst:
1305 except SyntaxError, inst:
1306 raise util.Abort(inst.args[0])
1306 raise util.Abort(inst.args[0])
1307 return t
1307 return t
1308
1308
1309 def showmarker(ui, marker):
1309 def showmarker(ui, marker):
1310 """utility function to display obsolescence marker in a readable way
1310 """utility function to display obsolescence marker in a readable way
1311
1311
1312 To be used by debug function."""
1312 To be used by debug function."""
1313 ui.write(hex(marker.precnode()))
1313 ui.write(hex(marker.precnode()))
1314 for repl in marker.succnodes():
1314 for repl in marker.succnodes():
1315 ui.write(' ')
1315 ui.write(' ')
1316 ui.write(hex(repl))
1316 ui.write(hex(repl))
1317 ui.write(' %X ' % marker.flags())
1317 ui.write(' %X ' % marker.flags())
1318 parents = marker.parentnodes()
1318 parents = marker.parentnodes()
1319 if parents is not None:
1319 if parents is not None:
1320 ui.write('{%s} ' % ', '.join(hex(p) for p in parents))
1320 ui.write('{%s} ' % ', '.join(hex(p) for p in parents))
1321 ui.write('(%s) ' % util.datestr(marker.date()))
1321 ui.write('(%s) ' % util.datestr(marker.date()))
1322 ui.write('{%s}' % (', '.join('%r: %r' % t for t in
1322 ui.write('{%s}' % (', '.join('%r: %r' % t for t in
1323 sorted(marker.metadata().items())
1323 sorted(marker.metadata().items())
1324 if t[0] != 'date')))
1324 if t[0] != 'date')))
1325 ui.write('\n')
1325 ui.write('\n')
1326
1326
1327 def finddate(ui, repo, date):
1327 def finddate(ui, repo, date):
1328 """Find the tipmost changeset that matches the given date spec"""
1328 """Find the tipmost changeset that matches the given date spec"""
1329
1329
1330 df = util.matchdate(date)
1330 df = util.matchdate(date)
1331 m = scmutil.matchall(repo)
1331 m = scmutil.matchall(repo)
1332 results = {}
1332 results = {}
1333
1333
1334 def prep(ctx, fns):
1334 def prep(ctx, fns):
1335 d = ctx.date()
1335 d = ctx.date()
1336 if df(d[0]):
1336 if df(d[0]):
1337 results[ctx.rev()] = d
1337 results[ctx.rev()] = d
1338
1338
1339 for ctx in walkchangerevs(repo, m, {'rev': None}, prep):
1339 for ctx in walkchangerevs(repo, m, {'rev': None}, prep):
1340 rev = ctx.rev()
1340 rev = ctx.rev()
1341 if rev in results:
1341 if rev in results:
1342 ui.status(_("found revision %s from %s\n") %
1342 ui.status(_("found revision %s from %s\n") %
1343 (rev, util.datestr(results[rev])))
1343 (rev, util.datestr(results[rev])))
1344 return str(rev)
1344 return str(rev)
1345
1345
1346 raise util.Abort(_("revision matching date not found"))
1346 raise util.Abort(_("revision matching date not found"))
1347
1347
1348 def increasingwindows(windowsize=8, sizelimit=512):
1348 def increasingwindows(windowsize=8, sizelimit=512):
1349 while True:
1349 while True:
1350 yield windowsize
1350 yield windowsize
1351 if windowsize < sizelimit:
1351 if windowsize < sizelimit:
1352 windowsize *= 2
1352 windowsize *= 2
1353
1353
1354 class FileWalkError(Exception):
1354 class FileWalkError(Exception):
1355 pass
1355 pass
1356
1356
1357 def walkfilerevs(repo, match, follow, revs, fncache):
1357 def walkfilerevs(repo, match, follow, revs, fncache):
1358 '''Walks the file history for the matched files.
1358 '''Walks the file history for the matched files.
1359
1359
1360 Returns the changeset revs that are involved in the file history.
1360 Returns the changeset revs that are involved in the file history.
1361
1361
1362 Throws FileWalkError if the file history can't be walked using
1362 Throws FileWalkError if the file history can't be walked using
1363 filelogs alone.
1363 filelogs alone.
1364 '''
1364 '''
1365 wanted = set()
1365 wanted = set()
1366 copies = []
1366 copies = []
1367 minrev, maxrev = min(revs), max(revs)
1367 minrev, maxrev = min(revs), max(revs)
1368 def filerevgen(filelog, last):
1368 def filerevgen(filelog, last):
1369 """
1369 """
1370 Only files, no patterns. Check the history of each file.
1370 Only files, no patterns. Check the history of each file.
1371
1371
1372 Examines filelog entries within minrev, maxrev linkrev range
1372 Examines filelog entries within minrev, maxrev linkrev range
1373 Returns an iterator yielding (linkrev, parentlinkrevs, copied)
1373 Returns an iterator yielding (linkrev, parentlinkrevs, copied)
1374 tuples in backwards order
1374 tuples in backwards order
1375 """
1375 """
1376 cl_count = len(repo)
1376 cl_count = len(repo)
1377 revs = []
1377 revs = []
1378 for j in xrange(0, last + 1):
1378 for j in xrange(0, last + 1):
1379 linkrev = filelog.linkrev(j)
1379 linkrev = filelog.linkrev(j)
1380 if linkrev < minrev:
1380 if linkrev < minrev:
1381 continue
1381 continue
1382 # only yield rev for which we have the changelog, it can
1382 # only yield rev for which we have the changelog, it can
1383 # happen while doing "hg log" during a pull or commit
1383 # happen while doing "hg log" during a pull or commit
1384 if linkrev >= cl_count:
1384 if linkrev >= cl_count:
1385 break
1385 break
1386
1386
1387 parentlinkrevs = []
1387 parentlinkrevs = []
1388 for p in filelog.parentrevs(j):
1388 for p in filelog.parentrevs(j):
1389 if p != nullrev:
1389 if p != nullrev:
1390 parentlinkrevs.append(filelog.linkrev(p))
1390 parentlinkrevs.append(filelog.linkrev(p))
1391 n = filelog.node(j)
1391 n = filelog.node(j)
1392 revs.append((linkrev, parentlinkrevs,
1392 revs.append((linkrev, parentlinkrevs,
1393 follow and filelog.renamed(n)))
1393 follow and filelog.renamed(n)))
1394
1394
1395 return reversed(revs)
1395 return reversed(revs)
1396 def iterfiles():
1396 def iterfiles():
1397 pctx = repo['.']
1397 pctx = repo['.']
1398 for filename in match.files():
1398 for filename in match.files():
1399 if follow:
1399 if follow:
1400 if filename not in pctx:
1400 if filename not in pctx:
1401 raise util.Abort(_('cannot follow file not in parent '
1401 raise util.Abort(_('cannot follow file not in parent '
1402 'revision: "%s"') % filename)
1402 'revision: "%s"') % filename)
1403 yield filename, pctx[filename].filenode()
1403 yield filename, pctx[filename].filenode()
1404 else:
1404 else:
1405 yield filename, None
1405 yield filename, None
1406 for filename_node in copies:
1406 for filename_node in copies:
1407 yield filename_node
1407 yield filename_node
1408
1408
1409 for file_, node in iterfiles():
1409 for file_, node in iterfiles():
1410 filelog = repo.file(file_)
1410 filelog = repo.file(file_)
1411 if not len(filelog):
1411 if not len(filelog):
1412 if node is None:
1412 if node is None:
1413 # A zero count may be a directory or deleted file, so
1413 # A zero count may be a directory or deleted file, so
1414 # try to find matching entries on the slow path.
1414 # try to find matching entries on the slow path.
1415 if follow:
1415 if follow:
1416 raise util.Abort(
1416 raise util.Abort(
1417 _('cannot follow nonexistent file: "%s"') % file_)
1417 _('cannot follow nonexistent file: "%s"') % file_)
1418 raise FileWalkError("Cannot walk via filelog")
1418 raise FileWalkError("Cannot walk via filelog")
1419 else:
1419 else:
1420 continue
1420 continue
1421
1421
1422 if node is None:
1422 if node is None:
1423 last = len(filelog) - 1
1423 last = len(filelog) - 1
1424 else:
1424 else:
1425 last = filelog.rev(node)
1425 last = filelog.rev(node)
1426
1426
1427
1427
1428 # keep track of all ancestors of the file
1428 # keep track of all ancestors of the file
1429 ancestors = set([filelog.linkrev(last)])
1429 ancestors = set([filelog.linkrev(last)])
1430
1430
1431 # iterate from latest to oldest revision
1431 # iterate from latest to oldest revision
1432 for rev, flparentlinkrevs, copied in filerevgen(filelog, last):
1432 for rev, flparentlinkrevs, copied in filerevgen(filelog, last):
1433 if not follow:
1433 if not follow:
1434 if rev > maxrev:
1434 if rev > maxrev:
1435 continue
1435 continue
1436 else:
1436 else:
1437 # Note that last might not be the first interesting
1437 # Note that last might not be the first interesting
1438 # rev to us:
1438 # rev to us:
1439 # if the file has been changed after maxrev, we'll
1439 # if the file has been changed after maxrev, we'll
1440 # have linkrev(last) > maxrev, and we still need
1440 # have linkrev(last) > maxrev, and we still need
1441 # to explore the file graph
1441 # to explore the file graph
1442 if rev not in ancestors:
1442 if rev not in ancestors:
1443 continue
1443 continue
1444 # XXX insert 1327 fix here
1444 # XXX insert 1327 fix here
1445 if flparentlinkrevs:
1445 if flparentlinkrevs:
1446 ancestors.update(flparentlinkrevs)
1446 ancestors.update(flparentlinkrevs)
1447
1447
1448 fncache.setdefault(rev, []).append(file_)
1448 fncache.setdefault(rev, []).append(file_)
1449 wanted.add(rev)
1449 wanted.add(rev)
1450 if copied:
1450 if copied:
1451 copies.append(copied)
1451 copies.append(copied)
1452
1452
1453 return wanted
1453 return wanted
1454
1454
1455 def walkchangerevs(repo, match, opts, prepare):
1455 def walkchangerevs(repo, match, opts, prepare):
1456 '''Iterate over files and the revs in which they changed.
1456 '''Iterate over files and the revs in which they changed.
1457
1457
1458 Callers most commonly need to iterate backwards over the history
1458 Callers most commonly need to iterate backwards over the history
1459 in which they are interested. Doing so has awful (quadratic-looking)
1459 in which they are interested. Doing so has awful (quadratic-looking)
1460 performance, so we use iterators in a "windowed" way.
1460 performance, so we use iterators in a "windowed" way.
1461
1461
1462 We walk a window of revisions in the desired order. Within the
1462 We walk a window of revisions in the desired order. Within the
1463 window, we first walk forwards to gather data, then in the desired
1463 window, we first walk forwards to gather data, then in the desired
1464 order (usually backwards) to display it.
1464 order (usually backwards) to display it.
1465
1465
1466 This function returns an iterator yielding contexts. Before
1466 This function returns an iterator yielding contexts. Before
1467 yielding each context, the iterator will first call the prepare
1467 yielding each context, the iterator will first call the prepare
1468 function on each context in the window in forward order.'''
1468 function on each context in the window in forward order.'''
1469
1469
1470 follow = opts.get('follow') or opts.get('follow_first')
1470 follow = opts.get('follow') or opts.get('follow_first')
1471
1471
1472 if opts.get('rev'):
1472 if opts.get('rev'):
1473 revs = scmutil.revrange(repo, opts.get('rev'))
1473 revs = scmutil.revrange(repo, opts.get('rev'))
1474 elif follow:
1474 elif follow:
1475 revs = repo.revs('reverse(:.)')
1475 revs = repo.revs('reverse(:.)')
1476 else:
1476 else:
1477 revs = revset.spanset(repo)
1477 revs = revset.spanset(repo)
1478 revs.reverse()
1478 revs.reverse()
1479 if not revs:
1479 if not revs:
1480 return []
1480 return []
1481 wanted = set()
1481 wanted = set()
1482 slowpath = match.anypats() or (match.files() and opts.get('removed'))
1482 slowpath = match.anypats() or (match.files() and opts.get('removed'))
1483 fncache = {}
1483 fncache = {}
1484 change = repo.changectx
1484 change = repo.changectx
1485
1485
1486 # First step is to fill wanted, the set of revisions that we want to yield.
1486 # First step is to fill wanted, the set of revisions that we want to yield.
1487 # When it does not induce extra cost, we also fill fncache for revisions in
1487 # When it does not induce extra cost, we also fill fncache for revisions in
1488 # wanted: a cache of filenames that were changed (ctx.files()) and that
1488 # wanted: a cache of filenames that were changed (ctx.files()) and that
1489 # match the file filtering conditions.
1489 # match the file filtering conditions.
1490
1490
1491 if not slowpath and not match.files():
1491 if not slowpath and not match.files():
1492 # No files, no patterns. Display all revs.
1492 # No files, no patterns. Display all revs.
1493 wanted = revs
1493 wanted = revs
1494
1494
1495 if not slowpath and match.files():
1495 if not slowpath and match.files():
1496 # We only have to read through the filelog to find wanted revisions
1496 # We only have to read through the filelog to find wanted revisions
1497
1497
1498 try:
1498 try:
1499 wanted = walkfilerevs(repo, match, follow, revs, fncache)
1499 wanted = walkfilerevs(repo, match, follow, revs, fncache)
1500 except FileWalkError:
1500 except FileWalkError:
1501 slowpath = True
1501 slowpath = True
1502
1502
1503 # We decided to fall back to the slowpath because at least one
1503 # We decided to fall back to the slowpath because at least one
1504 # of the paths was not a file. Check to see if at least one of them
1504 # of the paths was not a file. Check to see if at least one of them
1505 # existed in history, otherwise simply return
1505 # existed in history, otherwise simply return
1506 for path in match.files():
1506 for path in match.files():
1507 if path == '.' or path in repo.store:
1507 if path == '.' or path in repo.store:
1508 break
1508 break
1509 else:
1509 else:
1510 return []
1510 return []
1511
1511
1512 if slowpath:
1512 if slowpath:
1513 # We have to read the changelog to match filenames against
1513 # We have to read the changelog to match filenames against
1514 # changed files
1514 # changed files
1515
1515
1516 if follow:
1516 if follow:
1517 raise util.Abort(_('can only follow copies/renames for explicit '
1517 raise util.Abort(_('can only follow copies/renames for explicit '
1518 'filenames'))
1518 'filenames'))
1519
1519
1520 # The slow path checks files modified in every changeset.
1520 # The slow path checks files modified in every changeset.
1521 # This is really slow on large repos, so compute the set lazily.
1521 # This is really slow on large repos, so compute the set lazily.
1522 class lazywantedset(object):
1522 class lazywantedset(object):
1523 def __init__(self):
1523 def __init__(self):
1524 self.set = set()
1524 self.set = set()
1525 self.revs = set(revs)
1525 self.revs = set(revs)
1526
1526
1527 # No need to worry about locality here because it will be accessed
1527 # No need to worry about locality here because it will be accessed
1528 # in the same order as the increasing window below.
1528 # in the same order as the increasing window below.
1529 def __contains__(self, value):
1529 def __contains__(self, value):
1530 if value in self.set:
1530 if value in self.set:
1531 return True
1531 return True
1532 elif not value in self.revs:
1532 elif not value in self.revs:
1533 return False
1533 return False
1534 else:
1534 else:
1535 self.revs.discard(value)
1535 self.revs.discard(value)
1536 ctx = change(value)
1536 ctx = change(value)
1537 matches = filter(match, ctx.files())
1537 matches = filter(match, ctx.files())
1538 if matches:
1538 if matches:
1539 fncache[value] = matches
1539 fncache[value] = matches
1540 self.set.add(value)
1540 self.set.add(value)
1541 return True
1541 return True
1542 return False
1542 return False
1543
1543
1544 def discard(self, value):
1544 def discard(self, value):
1545 self.revs.discard(value)
1545 self.revs.discard(value)
1546 self.set.discard(value)
1546 self.set.discard(value)
1547
1547
1548 wanted = lazywantedset()
1548 wanted = lazywantedset()
1549
1549
1550 class followfilter(object):
1550 class followfilter(object):
1551 def __init__(self, onlyfirst=False):
1551 def __init__(self, onlyfirst=False):
1552 self.startrev = nullrev
1552 self.startrev = nullrev
1553 self.roots = set()
1553 self.roots = set()
1554 self.onlyfirst = onlyfirst
1554 self.onlyfirst = onlyfirst
1555
1555
1556 def match(self, rev):
1556 def match(self, rev):
1557 def realparents(rev):
1557 def realparents(rev):
1558 if self.onlyfirst:
1558 if self.onlyfirst:
1559 return repo.changelog.parentrevs(rev)[0:1]
1559 return repo.changelog.parentrevs(rev)[0:1]
1560 else:
1560 else:
1561 return filter(lambda x: x != nullrev,
1561 return filter(lambda x: x != nullrev,
1562 repo.changelog.parentrevs(rev))
1562 repo.changelog.parentrevs(rev))
1563
1563
1564 if self.startrev == nullrev:
1564 if self.startrev == nullrev:
1565 self.startrev = rev
1565 self.startrev = rev
1566 return True
1566 return True
1567
1567
1568 if rev > self.startrev:
1568 if rev > self.startrev:
1569 # forward: all descendants
1569 # forward: all descendants
1570 if not self.roots:
1570 if not self.roots:
1571 self.roots.add(self.startrev)
1571 self.roots.add(self.startrev)
1572 for parent in realparents(rev):
1572 for parent in realparents(rev):
1573 if parent in self.roots:
1573 if parent in self.roots:
1574 self.roots.add(rev)
1574 self.roots.add(rev)
1575 return True
1575 return True
1576 else:
1576 else:
1577 # backwards: all parents
1577 # backwards: all parents
1578 if not self.roots:
1578 if not self.roots:
1579 self.roots.update(realparents(self.startrev))
1579 self.roots.update(realparents(self.startrev))
1580 if rev in self.roots:
1580 if rev in self.roots:
1581 self.roots.remove(rev)
1581 self.roots.remove(rev)
1582 self.roots.update(realparents(rev))
1582 self.roots.update(realparents(rev))
1583 return True
1583 return True
1584
1584
1585 return False
1585 return False
1586
1586
1587 # it might be worthwhile to do this in the iterator if the rev range
1587 # it might be worthwhile to do this in the iterator if the rev range
1588 # is descending and the prune args are all within that range
1588 # is descending and the prune args are all within that range
1589 for rev in opts.get('prune', ()):
1589 for rev in opts.get('prune', ()):
1590 rev = repo[rev].rev()
1590 rev = repo[rev].rev()
1591 ff = followfilter()
1591 ff = followfilter()
1592 stop = min(revs[0], revs[-1])
1592 stop = min(revs[0], revs[-1])
1593 for x in xrange(rev, stop - 1, -1):
1593 for x in xrange(rev, stop - 1, -1):
1594 if ff.match(x):
1594 if ff.match(x):
1595 wanted = wanted - [x]
1595 wanted = wanted - [x]
1596
1596
1597 # Now that wanted is correctly initialized, we can iterate over the
1597 # Now that wanted is correctly initialized, we can iterate over the
1598 # revision range, yielding only revisions in wanted.
1598 # revision range, yielding only revisions in wanted.
1599 def iterate():
1599 def iterate():
1600 if follow and not match.files():
1600 if follow and not match.files():
1601 ff = followfilter(onlyfirst=opts.get('follow_first'))
1601 ff = followfilter(onlyfirst=opts.get('follow_first'))
1602 def want(rev):
1602 def want(rev):
1603 return ff.match(rev) and rev in wanted
1603 return ff.match(rev) and rev in wanted
1604 else:
1604 else:
1605 def want(rev):
1605 def want(rev):
1606 return rev in wanted
1606 return rev in wanted
1607
1607
1608 it = iter(revs)
1608 it = iter(revs)
1609 stopiteration = False
1609 stopiteration = False
1610 for windowsize in increasingwindows():
1610 for windowsize in increasingwindows():
1611 nrevs = []
1611 nrevs = []
1612 for i in xrange(windowsize):
1612 for i in xrange(windowsize):
1613 try:
1613 try:
1614 rev = it.next()
1614 rev = it.next()
1615 if want(rev):
1615 if want(rev):
1616 nrevs.append(rev)
1616 nrevs.append(rev)
1617 except (StopIteration):
1617 except (StopIteration):
1618 stopiteration = True
1618 stopiteration = True
1619 break
1619 break
1620 for rev in sorted(nrevs):
1620 for rev in sorted(nrevs):
1621 fns = fncache.get(rev)
1621 fns = fncache.get(rev)
1622 ctx = change(rev)
1622 ctx = change(rev)
1623 if not fns:
1623 if not fns:
1624 def fns_generator():
1624 def fns_generator():
1625 for f in ctx.files():
1625 for f in ctx.files():
1626 if match(f):
1626 if match(f):
1627 yield f
1627 yield f
1628 fns = fns_generator()
1628 fns = fns_generator()
1629 prepare(ctx, fns)
1629 prepare(ctx, fns)
1630 for rev in nrevs:
1630 for rev in nrevs:
1631 yield change(rev)
1631 yield change(rev)
1632
1632
1633 if stopiteration:
1633 if stopiteration:
1634 break
1634 break
1635
1635
1636 return iterate()
1636 return iterate()
1637
1637
1638 def _makefollowlogfilematcher(repo, files, followfirst):
1638 def _makefollowlogfilematcher(repo, files, followfirst):
1639 # When displaying a revision with --patch --follow FILE, we have
1639 # When displaying a revision with --patch --follow FILE, we have
1640 # to know which file of the revision must be diffed. With
1640 # to know which file of the revision must be diffed. With
1641 # --follow, we want the names of the ancestors of FILE in the
1641 # --follow, we want the names of the ancestors of FILE in the
1642 # revision, stored in "fcache". "fcache" is populated by
1642 # revision, stored in "fcache". "fcache" is populated by
1643 # reproducing the graph traversal already done by --follow revset
1643 # reproducing the graph traversal already done by --follow revset
1644 # and relating linkrevs to file names (which is not "correct" but
1644 # and relating linkrevs to file names (which is not "correct" but
1645 # good enough).
1645 # good enough).
1646 fcache = {}
1646 fcache = {}
1647 fcacheready = [False]
1647 fcacheready = [False]
1648 pctx = repo['.']
1648 pctx = repo['.']
1649
1649
1650 def populate():
1650 def populate():
1651 for fn in files:
1651 for fn in files:
1652 for i in ((pctx[fn],), pctx[fn].ancestors(followfirst=followfirst)):
1652 for i in ((pctx[fn],), pctx[fn].ancestors(followfirst=followfirst)):
1653 for c in i:
1653 for c in i:
1654 fcache.setdefault(c.linkrev(), set()).add(c.path())
1654 fcache.setdefault(c.linkrev(), set()).add(c.path())
1655
1655
1656 def filematcher(rev):
1656 def filematcher(rev):
1657 if not fcacheready[0]:
1657 if not fcacheready[0]:
1658 # Lazy initialization
1658 # Lazy initialization
1659 fcacheready[0] = True
1659 fcacheready[0] = True
1660 populate()
1660 populate()
1661 return scmutil.matchfiles(repo, fcache.get(rev, []))
1661 return scmutil.matchfiles(repo, fcache.get(rev, []))
1662
1662
1663 return filematcher
1663 return filematcher
1664
1664
1665 def _makenofollowlogfilematcher(repo, pats, opts):
1665 def _makenofollowlogfilematcher(repo, pats, opts):
1666 '''hook for extensions to override the filematcher for non-follow cases'''
1666 '''hook for extensions to override the filematcher for non-follow cases'''
1667 return None
1667 return None
1668
1668
1669 def _makelogrevset(repo, pats, opts, revs):
1669 def _makelogrevset(repo, pats, opts, revs):
1670 """Return (expr, filematcher) where expr is a revset string built
1670 """Return (expr, filematcher) where expr is a revset string built
1671 from log options and file patterns or None. If --stat or --patch
1671 from log options and file patterns or None. If --stat or --patch
1672 are not passed filematcher is None. Otherwise it is a callable
1672 are not passed filematcher is None. Otherwise it is a callable
1673 taking a revision number and returning a match objects filtering
1673 taking a revision number and returning a match objects filtering
1674 the files to be detailed when displaying the revision.
1674 the files to be detailed when displaying the revision.
1675 """
1675 """
1676 opt2revset = {
1676 opt2revset = {
1677 'no_merges': ('not merge()', None),
1677 'no_merges': ('not merge()', None),
1678 'only_merges': ('merge()', None),
1678 'only_merges': ('merge()', None),
1679 '_ancestors': ('ancestors(%(val)s)', None),
1679 '_ancestors': ('ancestors(%(val)s)', None),
1680 '_fancestors': ('_firstancestors(%(val)s)', None),
1680 '_fancestors': ('_firstancestors(%(val)s)', None),
1681 '_descendants': ('descendants(%(val)s)', None),
1681 '_descendants': ('descendants(%(val)s)', None),
1682 '_fdescendants': ('_firstdescendants(%(val)s)', None),
1682 '_fdescendants': ('_firstdescendants(%(val)s)', None),
1683 '_matchfiles': ('_matchfiles(%(val)s)', None),
1683 '_matchfiles': ('_matchfiles(%(val)s)', None),
1684 'date': ('date(%(val)r)', None),
1684 'date': ('date(%(val)r)', None),
1685 'branch': ('branch(%(val)r)', ' or '),
1685 'branch': ('branch(%(val)r)', ' or '),
1686 '_patslog': ('filelog(%(val)r)', ' or '),
1686 '_patslog': ('filelog(%(val)r)', ' or '),
1687 '_patsfollow': ('follow(%(val)r)', ' or '),
1687 '_patsfollow': ('follow(%(val)r)', ' or '),
1688 '_patsfollowfirst': ('_followfirst(%(val)r)', ' or '),
1688 '_patsfollowfirst': ('_followfirst(%(val)r)', ' or '),
1689 'keyword': ('keyword(%(val)r)', ' or '),
1689 'keyword': ('keyword(%(val)r)', ' or '),
1690 'prune': ('not (%(val)r or ancestors(%(val)r))', ' and '),
1690 'prune': ('not (%(val)r or ancestors(%(val)r))', ' and '),
1691 'user': ('user(%(val)r)', ' or '),
1691 'user': ('user(%(val)r)', ' or '),
1692 }
1692 }
1693
1693
1694 opts = dict(opts)
1694 opts = dict(opts)
1695 # follow or not follow?
1695 # follow or not follow?
1696 follow = opts.get('follow') or opts.get('follow_first')
1696 follow = opts.get('follow') or opts.get('follow_first')
1697 followfirst = opts.get('follow_first') and 1 or 0
1697 followfirst = opts.get('follow_first') and 1 or 0
1698 # --follow with FILE behaviour depends on revs...
1698 # --follow with FILE behaviour depends on revs...
1699 it = iter(revs)
1699 it = iter(revs)
1700 startrev = it.next()
1700 startrev = it.next()
1701 try:
1701 try:
1702 followdescendants = startrev < it.next()
1702 followdescendants = startrev < it.next()
1703 except (StopIteration):
1703 except (StopIteration):
1704 followdescendants = False
1704 followdescendants = False
1705
1705
1706 # branch and only_branch are really aliases and must be handled at
1706 # branch and only_branch are really aliases and must be handled at
1707 # the same time
1707 # the same time
1708 opts['branch'] = opts.get('branch', []) + opts.get('only_branch', [])
1708 opts['branch'] = opts.get('branch', []) + opts.get('only_branch', [])
1709 opts['branch'] = [repo.lookupbranch(b) for b in opts['branch']]
1709 opts['branch'] = [repo.lookupbranch(b) for b in opts['branch']]
1710 # pats/include/exclude are passed to match.match() directly in
1710 # pats/include/exclude are passed to match.match() directly in
1711 # _matchfiles() revset but walkchangerevs() builds its matcher with
1711 # _matchfiles() revset but walkchangerevs() builds its matcher with
1712 # scmutil.match(). The difference is input pats are globbed on
1712 # scmutil.match(). The difference is input pats are globbed on
1713 # platforms without shell expansion (windows).
1713 # platforms without shell expansion (windows).
1714 pctx = repo[None]
1714 pctx = repo[None]
1715 match, pats = scmutil.matchandpats(pctx, pats, opts)
1715 match, pats = scmutil.matchandpats(pctx, pats, opts)
1716 slowpath = match.anypats() or (match.files() and opts.get('removed'))
1716 slowpath = match.anypats() or (match.files() and opts.get('removed'))
1717 if not slowpath:
1717 if not slowpath:
1718 for f in match.files():
1718 for f in match.files():
1719 if follow and f not in pctx:
1719 if follow and f not in pctx:
1720 # If the file exists, it may be a directory, so let it
1720 # If the file exists, it may be a directory, so let it
1721 # take the slow path.
1721 # take the slow path.
1722 if os.path.exists(repo.wjoin(f)):
1722 if os.path.exists(repo.wjoin(f)):
1723 slowpath = True
1723 slowpath = True
1724 continue
1724 continue
1725 else:
1725 else:
1726 raise util.Abort(_('cannot follow file not in parent '
1726 raise util.Abort(_('cannot follow file not in parent '
1727 'revision: "%s"') % f)
1727 'revision: "%s"') % f)
1728 filelog = repo.file(f)
1728 filelog = repo.file(f)
1729 if not filelog:
1729 if not filelog:
1730 # A zero count may be a directory or deleted file, so
1730 # A zero count may be a directory or deleted file, so
1731 # try to find matching entries on the slow path.
1731 # try to find matching entries on the slow path.
1732 if follow:
1732 if follow:
1733 raise util.Abort(
1733 raise util.Abort(
1734 _('cannot follow nonexistent file: "%s"') % f)
1734 _('cannot follow nonexistent file: "%s"') % f)
1735 slowpath = True
1735 slowpath = True
1736
1736
1737 # We decided to fall back to the slowpath because at least one
1737 # We decided to fall back to the slowpath because at least one
1738 # of the paths was not a file. Check to see if at least one of them
1738 # of the paths was not a file. Check to see if at least one of them
1739 # existed in history - in that case, we'll continue down the
1739 # existed in history - in that case, we'll continue down the
1740 # slowpath; otherwise, we can turn off the slowpath
1740 # slowpath; otherwise, we can turn off the slowpath
1741 if slowpath:
1741 if slowpath:
1742 for path in match.files():
1742 for path in match.files():
1743 if path == '.' or path in repo.store:
1743 if path == '.' or path in repo.store:
1744 break
1744 break
1745 else:
1745 else:
1746 slowpath = False
1746 slowpath = False
1747
1747
1748 if slowpath:
1748 if slowpath:
1749 # See walkchangerevs() slow path.
1749 # See walkchangerevs() slow path.
1750 #
1750 #
1751 # pats/include/exclude cannot be represented as separate
1751 # pats/include/exclude cannot be represented as separate
1752 # revset expressions as their filtering logic applies at file
1752 # revset expressions as their filtering logic applies at file
1753 # level. For instance "-I a -X a" matches a revision touching
1753 # level. For instance "-I a -X a" matches a revision touching
1754 # "a" and "b" while "file(a) and not file(b)" does
1754 # "a" and "b" while "file(a) and not file(b)" does
1755 # not. Besides, filesets are evaluated against the working
1755 # not. Besides, filesets are evaluated against the working
1756 # directory.
1756 # directory.
1757 matchargs = ['r:', 'd:relpath']
1757 matchargs = ['r:', 'd:relpath']
1758 for p in pats:
1758 for p in pats:
1759 matchargs.append('p:' + p)
1759 matchargs.append('p:' + p)
1760 for p in opts.get('include', []):
1760 for p in opts.get('include', []):
1761 matchargs.append('i:' + p)
1761 matchargs.append('i:' + p)
1762 for p in opts.get('exclude', []):
1762 for p in opts.get('exclude', []):
1763 matchargs.append('x:' + p)
1763 matchargs.append('x:' + p)
1764 matchargs = ','.join(('%r' % p) for p in matchargs)
1764 matchargs = ','.join(('%r' % p) for p in matchargs)
1765 opts['_matchfiles'] = matchargs
1765 opts['_matchfiles'] = matchargs
1766 else:
1766 else:
1767 if follow:
1767 if follow:
1768 fpats = ('_patsfollow', '_patsfollowfirst')
1768 fpats = ('_patsfollow', '_patsfollowfirst')
1769 fnopats = (('_ancestors', '_fancestors'),
1769 fnopats = (('_ancestors', '_fancestors'),
1770 ('_descendants', '_fdescendants'))
1770 ('_descendants', '_fdescendants'))
1771 if pats:
1771 if pats:
1772 # follow() revset interprets its file argument as a
1772 # follow() revset interprets its file argument as a
1773 # manifest entry, so use match.files(), not pats.
1773 # manifest entry, so use match.files(), not pats.
1774 opts[fpats[followfirst]] = list(match.files())
1774 opts[fpats[followfirst]] = list(match.files())
1775 else:
1775 else:
1776 opts[fnopats[followdescendants][followfirst]] = str(startrev)
1776 opts[fnopats[followdescendants][followfirst]] = str(startrev)
1777 else:
1777 else:
1778 opts['_patslog'] = list(pats)
1778 opts['_patslog'] = list(pats)
1779
1779
1780 filematcher = None
1780 filematcher = None
1781 if opts.get('patch') or opts.get('stat'):
1781 if opts.get('patch') or opts.get('stat'):
1782 # When following files, track renames via a special matcher.
1782 # When following files, track renames via a special matcher.
1783 # If we're forced to take the slowpath it means we're following
1783 # If we're forced to take the slowpath it means we're following
1784 # at least one pattern/directory, so don't bother with rename tracking.
1784 # at least one pattern/directory, so don't bother with rename tracking.
1785 if follow and not match.always() and not slowpath:
1785 if follow and not match.always() and not slowpath:
1786 # _makefollowlogfilematcher expects its files argument to be
1786 # _makefollowlogfilematcher expects its files argument to be
1787 # relative to the repo root, so use match.files(), not pats.
1787 # relative to the repo root, so use match.files(), not pats.
1788 filematcher = _makefollowlogfilematcher(repo, match.files(),
1788 filematcher = _makefollowlogfilematcher(repo, match.files(),
1789 followfirst)
1789 followfirst)
1790 else:
1790 else:
1791 filematcher = _makenofollowlogfilematcher(repo, pats, opts)
1791 filematcher = _makenofollowlogfilematcher(repo, pats, opts)
1792 if filematcher is None:
1792 if filematcher is None:
1793 filematcher = lambda rev: match
1793 filematcher = lambda rev: match
1794
1794
1795 expr = []
1795 expr = []
1796 for op, val in opts.iteritems():
1796 for op, val in opts.iteritems():
1797 if not val:
1797 if not val:
1798 continue
1798 continue
1799 if op not in opt2revset:
1799 if op not in opt2revset:
1800 continue
1800 continue
1801 revop, andor = opt2revset[op]
1801 revop, andor = opt2revset[op]
1802 if '%(val)' not in revop:
1802 if '%(val)' not in revop:
1803 expr.append(revop)
1803 expr.append(revop)
1804 else:
1804 else:
1805 if not isinstance(val, list):
1805 if not isinstance(val, list):
1806 e = revop % {'val': val}
1806 e = revop % {'val': val}
1807 else:
1807 else:
1808 e = '(' + andor.join((revop % {'val': v}) for v in val) + ')'
1808 e = '(' + andor.join((revop % {'val': v}) for v in val) + ')'
1809 expr.append(e)
1809 expr.append(e)
1810
1810
1811 if expr:
1811 if expr:
1812 expr = '(' + ' and '.join(expr) + ')'
1812 expr = '(' + ' and '.join(expr) + ')'
1813 else:
1813 else:
1814 expr = None
1814 expr = None
1815 return expr, filematcher
1815 return expr, filematcher
1816
1816
1817 def getgraphlogrevs(repo, pats, opts):
1817 def getgraphlogrevs(repo, pats, opts):
1818 """Return (revs, expr, filematcher) where revs is an iterable of
1818 """Return (revs, expr, filematcher) where revs is an iterable of
1819 revision numbers, expr is a revset string built from log options
1819 revision numbers, expr is a revset string built from log options
1820 and file patterns or None, and used to filter 'revs'. If --stat or
1820 and file patterns or None, and used to filter 'revs'. If --stat or
1821 --patch are not passed filematcher is None. Otherwise it is a
1821 --patch are not passed filematcher is None. Otherwise it is a
1822 callable taking a revision number and returning a match objects
1822 callable taking a revision number and returning a match objects
1823 filtering the files to be detailed when displaying the revision.
1823 filtering the files to be detailed when displaying the revision.
1824 """
1824 """
1825 if not len(repo):
1825 if not len(repo):
1826 return [], None, None
1826 return [], None, None
1827 limit = loglimit(opts)
1827 limit = loglimit(opts)
1828 # Default --rev value depends on --follow but --follow behaviour
1828 # Default --rev value depends on --follow but --follow behaviour
1829 # depends on revisions resolved from --rev...
1829 # depends on revisions resolved from --rev...
1830 follow = opts.get('follow') or opts.get('follow_first')
1830 follow = opts.get('follow') or opts.get('follow_first')
1831 possiblyunsorted = False # whether revs might need sorting
1831 possiblyunsorted = False # whether revs might need sorting
1832 if opts.get('rev'):
1832 if opts.get('rev'):
1833 revs = scmutil.revrange(repo, opts['rev'])
1833 revs = scmutil.revrange(repo, opts['rev'])
1834 # Don't sort here because _makelogrevset might depend on the
1834 # Don't sort here because _makelogrevset might depend on the
1835 # order of revs
1835 # order of revs
1836 possiblyunsorted = True
1836 possiblyunsorted = True
1837 else:
1837 else:
1838 if follow and len(repo) > 0:
1838 if follow and len(repo) > 0:
1839 revs = repo.revs('reverse(:.)')
1839 revs = repo.revs('reverse(:.)')
1840 else:
1840 else:
1841 revs = revset.spanset(repo)
1841 revs = revset.spanset(repo)
1842 revs.reverse()
1842 revs.reverse()
1843 if not revs:
1843 if not revs:
1844 return revset.baseset(), None, None
1844 return revset.baseset(), None, None
1845 expr, filematcher = _makelogrevset(repo, pats, opts, revs)
1845 expr, filematcher = _makelogrevset(repo, pats, opts, revs)
1846 if possiblyunsorted:
1846 if possiblyunsorted:
1847 revs.sort(reverse=True)
1847 revs.sort(reverse=True)
1848 if expr:
1848 if expr:
1849 # Revset matchers often operate faster on revisions in changelog
1849 # Revset matchers often operate faster on revisions in changelog
1850 # order, because most filters deal with the changelog.
1850 # order, because most filters deal with the changelog.
1851 revs.reverse()
1851 revs.reverse()
1852 matcher = revset.match(repo.ui, expr)
1852 matcher = revset.match(repo.ui, expr)
1853 # Revset matches can reorder revisions. "A or B" typically returns
1853 # Revset matches can reorder revisions. "A or B" typically returns
1854 # returns the revision matching A then the revision matching B. Sort
1854 # returns the revision matching A then the revision matching B. Sort
1855 # again to fix that.
1855 # again to fix that.
1856 revs = matcher(repo, revs)
1856 revs = matcher(repo, revs)
1857 revs.sort(reverse=True)
1857 revs.sort(reverse=True)
1858 if limit is not None:
1858 if limit is not None:
1859 limitedrevs = []
1859 limitedrevs = []
1860 for idx, rev in enumerate(revs):
1860 for idx, rev in enumerate(revs):
1861 if idx >= limit:
1861 if idx >= limit:
1862 break
1862 break
1863 limitedrevs.append(rev)
1863 limitedrevs.append(rev)
1864 revs = revset.baseset(limitedrevs)
1864 revs = revset.baseset(limitedrevs)
1865
1865
1866 return revs, expr, filematcher
1866 return revs, expr, filematcher
1867
1867
1868 def getlogrevs(repo, pats, opts):
1868 def getlogrevs(repo, pats, opts):
1869 """Return (revs, expr, filematcher) where revs is an iterable of
1869 """Return (revs, expr, filematcher) where revs is an iterable of
1870 revision numbers, expr is a revset string built from log options
1870 revision numbers, expr is a revset string built from log options
1871 and file patterns or None, and used to filter 'revs'. If --stat or
1871 and file patterns or None, and used to filter 'revs'. If --stat or
1872 --patch are not passed filematcher is None. Otherwise it is a
1872 --patch are not passed filematcher is None. Otherwise it is a
1873 callable taking a revision number and returning a match objects
1873 callable taking a revision number and returning a match objects
1874 filtering the files to be detailed when displaying the revision.
1874 filtering the files to be detailed when displaying the revision.
1875 """
1875 """
1876 limit = loglimit(opts)
1876 limit = loglimit(opts)
1877 # Default --rev value depends on --follow but --follow behaviour
1877 # Default --rev value depends on --follow but --follow behaviour
1878 # depends on revisions resolved from --rev...
1878 # depends on revisions resolved from --rev...
1879 follow = opts.get('follow') or opts.get('follow_first')
1879 follow = opts.get('follow') or opts.get('follow_first')
1880 if opts.get('rev'):
1880 if opts.get('rev'):
1881 revs = scmutil.revrange(repo, opts['rev'])
1881 revs = scmutil.revrange(repo, opts['rev'])
1882 elif follow:
1882 elif follow:
1883 revs = repo.revs('reverse(:.)')
1883 revs = repo.revs('reverse(:.)')
1884 else:
1884 else:
1885 revs = revset.spanset(repo)
1885 revs = revset.spanset(repo)
1886 revs.reverse()
1886 revs.reverse()
1887 if not revs:
1887 if not revs:
1888 return revset.baseset([]), None, None
1888 return revset.baseset([]), None, None
1889 expr, filematcher = _makelogrevset(repo, pats, opts, revs)
1889 expr, filematcher = _makelogrevset(repo, pats, opts, revs)
1890 if expr:
1890 if expr:
1891 # Revset matchers often operate faster on revisions in changelog
1891 # Revset matchers often operate faster on revisions in changelog
1892 # order, because most filters deal with the changelog.
1892 # order, because most filters deal with the changelog.
1893 if not opts.get('rev'):
1893 if not opts.get('rev'):
1894 revs.reverse()
1894 revs.reverse()
1895 matcher = revset.match(repo.ui, expr)
1895 matcher = revset.match(repo.ui, expr)
1896 # Revset matches can reorder revisions. "A or B" typically returns
1896 # Revset matches can reorder revisions. "A or B" typically returns
1897 # returns the revision matching A then the revision matching B. Sort
1897 # returns the revision matching A then the revision matching B. Sort
1898 # again to fix that.
1898 # again to fix that.
1899 revs = matcher(repo, revs)
1899 revs = matcher(repo, revs)
1900 if not opts.get('rev'):
1900 if not opts.get('rev'):
1901 revs.sort(reverse=True)
1901 revs.sort(reverse=True)
1902 if limit is not None:
1902 if limit is not None:
1903 count = 0
1903 count = 0
1904 limitedrevs = []
1904 limitedrevs = []
1905 it = iter(revs)
1905 it = iter(revs)
1906 while count < limit:
1906 while count < limit:
1907 try:
1907 try:
1908 limitedrevs.append(it.next())
1908 limitedrevs.append(it.next())
1909 except (StopIteration):
1909 except (StopIteration):
1910 break
1910 break
1911 count += 1
1911 count += 1
1912 revs = revset.baseset(limitedrevs)
1912 revs = revset.baseset(limitedrevs)
1913
1913
1914 return revs, expr, filematcher
1914 return revs, expr, filematcher
1915
1915
1916 def displaygraph(ui, dag, displayer, showparents, edgefn, getrenamed=None,
1916 def displaygraph(ui, dag, displayer, showparents, edgefn, getrenamed=None,
1917 filematcher=None):
1917 filematcher=None):
1918 seen, state = [], graphmod.asciistate()
1918 seen, state = [], graphmod.asciistate()
1919 for rev, type, ctx, parents in dag:
1919 for rev, type, ctx, parents in dag:
1920 char = 'o'
1920 char = 'o'
1921 if ctx.node() in showparents:
1921 if ctx.node() in showparents:
1922 char = '@'
1922 char = '@'
1923 elif ctx.obsolete():
1923 elif ctx.obsolete():
1924 char = 'x'
1924 char = 'x'
1925 copies = None
1925 copies = None
1926 if getrenamed and ctx.rev():
1926 if getrenamed and ctx.rev():
1927 copies = []
1927 copies = []
1928 for fn in ctx.files():
1928 for fn in ctx.files():
1929 rename = getrenamed(fn, ctx.rev())
1929 rename = getrenamed(fn, ctx.rev())
1930 if rename:
1930 if rename:
1931 copies.append((fn, rename[0]))
1931 copies.append((fn, rename[0]))
1932 revmatchfn = None
1932 revmatchfn = None
1933 if filematcher is not None:
1933 if filematcher is not None:
1934 revmatchfn = filematcher(ctx.rev())
1934 revmatchfn = filematcher(ctx.rev())
1935 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
1935 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
1936 lines = displayer.hunk.pop(rev).split('\n')
1936 lines = displayer.hunk.pop(rev).split('\n')
1937 if not lines[-1]:
1937 if not lines[-1]:
1938 del lines[-1]
1938 del lines[-1]
1939 displayer.flush(rev)
1939 displayer.flush(rev)
1940 edges = edgefn(type, char, lines, seen, rev, parents)
1940 edges = edgefn(type, char, lines, seen, rev, parents)
1941 for type, char, lines, coldata in edges:
1941 for type, char, lines, coldata in edges:
1942 graphmod.ascii(ui, state, type, char, lines, coldata)
1942 graphmod.ascii(ui, state, type, char, lines, coldata)
1943 displayer.close()
1943 displayer.close()
1944
1944
1945 def graphlog(ui, repo, *pats, **opts):
1945 def graphlog(ui, repo, *pats, **opts):
1946 # Parameters are identical to log command ones
1946 # Parameters are identical to log command ones
1947 revs, expr, filematcher = getgraphlogrevs(repo, pats, opts)
1947 revs, expr, filematcher = getgraphlogrevs(repo, pats, opts)
1948 revdag = graphmod.dagwalker(repo, revs)
1948 revdag = graphmod.dagwalker(repo, revs)
1949
1949
1950 getrenamed = None
1950 getrenamed = None
1951 if opts.get('copies'):
1951 if opts.get('copies'):
1952 endrev = None
1952 endrev = None
1953 if opts.get('rev'):
1953 if opts.get('rev'):
1954 endrev = scmutil.revrange(repo, opts.get('rev')).max() + 1
1954 endrev = scmutil.revrange(repo, opts.get('rev')).max() + 1
1955 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
1955 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
1956 displayer = show_changeset(ui, repo, opts, buffered=True)
1956 displayer = show_changeset(ui, repo, opts, buffered=True)
1957 showparents = [ctx.node() for ctx in repo[None].parents()]
1957 showparents = [ctx.node() for ctx in repo[None].parents()]
1958 displaygraph(ui, revdag, displayer, showparents,
1958 displaygraph(ui, revdag, displayer, showparents,
1959 graphmod.asciiedges, getrenamed, filematcher)
1959 graphmod.asciiedges, getrenamed, filematcher)
1960
1960
1961 def checkunsupportedgraphflags(pats, opts):
1961 def checkunsupportedgraphflags(pats, opts):
1962 for op in ["newest_first"]:
1962 for op in ["newest_first"]:
1963 if op in opts and opts[op]:
1963 if op in opts and opts[op]:
1964 raise util.Abort(_("-G/--graph option is incompatible with --%s")
1964 raise util.Abort(_("-G/--graph option is incompatible with --%s")
1965 % op.replace("_", "-"))
1965 % op.replace("_", "-"))
1966
1966
1967 def graphrevs(repo, nodes, opts):
1967 def graphrevs(repo, nodes, opts):
1968 limit = loglimit(opts)
1968 limit = loglimit(opts)
1969 nodes.reverse()
1969 nodes.reverse()
1970 if limit is not None:
1970 if limit is not None:
1971 nodes = nodes[:limit]
1971 nodes = nodes[:limit]
1972 return graphmod.nodes(repo, nodes)
1972 return graphmod.nodes(repo, nodes)
1973
1973
1974 def add(ui, repo, match, dryrun, listsubrepos, prefix, explicitonly):
1974 def add(ui, repo, match, dryrun, listsubrepos, prefix, explicitonly):
1975 join = lambda f: os.path.join(prefix, f)
1975 join = lambda f: os.path.join(prefix, f)
1976 bad = []
1976 bad = []
1977 oldbad = match.bad
1977 oldbad = match.bad
1978 match.bad = lambda x, y: bad.append(x) or oldbad(x, y)
1978 match.bad = lambda x, y: bad.append(x) or oldbad(x, y)
1979 names = []
1979 names = []
1980 wctx = repo[None]
1980 wctx = repo[None]
1981 cca = None
1981 cca = None
1982 abort, warn = scmutil.checkportabilityalert(ui)
1982 abort, warn = scmutil.checkportabilityalert(ui)
1983 if abort or warn:
1983 if abort or warn:
1984 cca = scmutil.casecollisionauditor(ui, abort, repo.dirstate)
1984 cca = scmutil.casecollisionauditor(ui, abort, repo.dirstate)
1985 for f in repo.walk(match):
1985 for f in wctx.walk(match):
1986 exact = match.exact(f)
1986 exact = match.exact(f)
1987 if exact or not explicitonly and f not in repo.dirstate:
1987 if exact or not explicitonly and f not in wctx:
1988 if cca:
1988 if cca:
1989 cca(f)
1989 cca(f)
1990 names.append(f)
1990 names.append(f)
1991 if ui.verbose or not exact:
1991 if ui.verbose or not exact:
1992 ui.status(_('adding %s\n') % match.rel(join(f)))
1992 ui.status(_('adding %s\n') % match.rel(join(f)))
1993
1993
1994 for subpath in sorted(wctx.substate):
1994 for subpath in sorted(wctx.substate):
1995 sub = wctx.sub(subpath)
1995 sub = wctx.sub(subpath)
1996 try:
1996 try:
1997 submatch = matchmod.narrowmatcher(subpath, match)
1997 submatch = matchmod.narrowmatcher(subpath, match)
1998 if listsubrepos:
1998 if listsubrepos:
1999 bad.extend(sub.add(ui, submatch, dryrun, listsubrepos, prefix,
1999 bad.extend(sub.add(ui, submatch, dryrun, listsubrepos, prefix,
2000 False))
2000 False))
2001 else:
2001 else:
2002 bad.extend(sub.add(ui, submatch, dryrun, listsubrepos, prefix,
2002 bad.extend(sub.add(ui, submatch, dryrun, listsubrepos, prefix,
2003 True))
2003 True))
2004 except error.LookupError:
2004 except error.LookupError:
2005 ui.status(_("skipping missing subrepository: %s\n")
2005 ui.status(_("skipping missing subrepository: %s\n")
2006 % join(subpath))
2006 % join(subpath))
2007
2007
2008 if not dryrun:
2008 if not dryrun:
2009 rejected = wctx.add(names, prefix)
2009 rejected = wctx.add(names, prefix)
2010 bad.extend(f for f in rejected if f in match.files())
2010 bad.extend(f for f in rejected if f in match.files())
2011 return bad
2011 return bad
2012
2012
2013 def forget(ui, repo, match, prefix, explicitonly):
2013 def forget(ui, repo, match, prefix, explicitonly):
2014 join = lambda f: os.path.join(prefix, f)
2014 join = lambda f: os.path.join(prefix, f)
2015 bad = []
2015 bad = []
2016 oldbad = match.bad
2016 oldbad = match.bad
2017 match.bad = lambda x, y: bad.append(x) or oldbad(x, y)
2017 match.bad = lambda x, y: bad.append(x) or oldbad(x, y)
2018 wctx = repo[None]
2018 wctx = repo[None]
2019 forgot = []
2019 forgot = []
2020 s = repo.status(match=match, clean=True)
2020 s = repo.status(match=match, clean=True)
2021 forget = sorted(s[0] + s[1] + s[3] + s[6])
2021 forget = sorted(s[0] + s[1] + s[3] + s[6])
2022 if explicitonly:
2022 if explicitonly:
2023 forget = [f for f in forget if match.exact(f)]
2023 forget = [f for f in forget if match.exact(f)]
2024
2024
2025 for subpath in sorted(wctx.substate):
2025 for subpath in sorted(wctx.substate):
2026 sub = wctx.sub(subpath)
2026 sub = wctx.sub(subpath)
2027 try:
2027 try:
2028 submatch = matchmod.narrowmatcher(subpath, match)
2028 submatch = matchmod.narrowmatcher(subpath, match)
2029 subbad, subforgot = sub.forget(ui, submatch, prefix)
2029 subbad, subforgot = sub.forget(ui, submatch, prefix)
2030 bad.extend([subpath + '/' + f for f in subbad])
2030 bad.extend([subpath + '/' + f for f in subbad])
2031 forgot.extend([subpath + '/' + f for f in subforgot])
2031 forgot.extend([subpath + '/' + f for f in subforgot])
2032 except error.LookupError:
2032 except error.LookupError:
2033 ui.status(_("skipping missing subrepository: %s\n")
2033 ui.status(_("skipping missing subrepository: %s\n")
2034 % join(subpath))
2034 % join(subpath))
2035
2035
2036 if not explicitonly:
2036 if not explicitonly:
2037 for f in match.files():
2037 for f in match.files():
2038 if f not in repo.dirstate and not os.path.isdir(match.rel(join(f))):
2038 if f not in repo.dirstate and not os.path.isdir(match.rel(join(f))):
2039 if f not in forgot:
2039 if f not in forgot:
2040 if os.path.exists(match.rel(join(f))):
2040 if os.path.exists(match.rel(join(f))):
2041 ui.warn(_('not removing %s: '
2041 ui.warn(_('not removing %s: '
2042 'file is already untracked\n')
2042 'file is already untracked\n')
2043 % match.rel(join(f)))
2043 % match.rel(join(f)))
2044 bad.append(f)
2044 bad.append(f)
2045
2045
2046 for f in forget:
2046 for f in forget:
2047 if ui.verbose or not match.exact(f):
2047 if ui.verbose or not match.exact(f):
2048 ui.status(_('removing %s\n') % match.rel(join(f)))
2048 ui.status(_('removing %s\n') % match.rel(join(f)))
2049
2049
2050 rejected = wctx.forget(forget, prefix)
2050 rejected = wctx.forget(forget, prefix)
2051 bad.extend(f for f in rejected if f in match.files())
2051 bad.extend(f for f in rejected if f in match.files())
2052 forgot.extend(forget)
2052 forgot.extend(forget)
2053 return bad, forgot
2053 return bad, forgot
2054
2054
2055 def cat(ui, repo, ctx, matcher, prefix, **opts):
2055 def cat(ui, repo, ctx, matcher, prefix, **opts):
2056 err = 1
2056 err = 1
2057
2057
2058 def write(path):
2058 def write(path):
2059 fp = makefileobj(repo, opts.get('output'), ctx.node(),
2059 fp = makefileobj(repo, opts.get('output'), ctx.node(),
2060 pathname=os.path.join(prefix, path))
2060 pathname=os.path.join(prefix, path))
2061 data = ctx[path].data()
2061 data = ctx[path].data()
2062 if opts.get('decode'):
2062 if opts.get('decode'):
2063 data = repo.wwritedata(path, data)
2063 data = repo.wwritedata(path, data)
2064 fp.write(data)
2064 fp.write(data)
2065 fp.close()
2065 fp.close()
2066
2066
2067 # Automation often uses hg cat on single files, so special case it
2067 # Automation often uses hg cat on single files, so special case it
2068 # for performance to avoid the cost of parsing the manifest.
2068 # for performance to avoid the cost of parsing the manifest.
2069 if len(matcher.files()) == 1 and not matcher.anypats():
2069 if len(matcher.files()) == 1 and not matcher.anypats():
2070 file = matcher.files()[0]
2070 file = matcher.files()[0]
2071 mf = repo.manifest
2071 mf = repo.manifest
2072 mfnode = ctx._changeset[0]
2072 mfnode = ctx._changeset[0]
2073 if mf.find(mfnode, file)[0]:
2073 if mf.find(mfnode, file)[0]:
2074 write(file)
2074 write(file)
2075 return 0
2075 return 0
2076
2076
2077 # Don't warn about "missing" files that are really in subrepos
2077 # Don't warn about "missing" files that are really in subrepos
2078 bad = matcher.bad
2078 bad = matcher.bad
2079
2079
2080 def badfn(path, msg):
2080 def badfn(path, msg):
2081 for subpath in ctx.substate:
2081 for subpath in ctx.substate:
2082 if path.startswith(subpath):
2082 if path.startswith(subpath):
2083 return
2083 return
2084 bad(path, msg)
2084 bad(path, msg)
2085
2085
2086 matcher.bad = badfn
2086 matcher.bad = badfn
2087
2087
2088 for abs in ctx.walk(matcher):
2088 for abs in ctx.walk(matcher):
2089 write(abs)
2089 write(abs)
2090 err = 0
2090 err = 0
2091
2091
2092 matcher.bad = bad
2092 matcher.bad = bad
2093
2093
2094 for subpath in sorted(ctx.substate):
2094 for subpath in sorted(ctx.substate):
2095 sub = ctx.sub(subpath)
2095 sub = ctx.sub(subpath)
2096 try:
2096 try:
2097 submatch = matchmod.narrowmatcher(subpath, matcher)
2097 submatch = matchmod.narrowmatcher(subpath, matcher)
2098
2098
2099 if not sub.cat(ui, submatch, os.path.join(prefix, sub._path),
2099 if not sub.cat(ui, submatch, os.path.join(prefix, sub._path),
2100 **opts):
2100 **opts):
2101 err = 0
2101 err = 0
2102 except error.RepoLookupError:
2102 except error.RepoLookupError:
2103 ui.status(_("skipping missing subrepository: %s\n")
2103 ui.status(_("skipping missing subrepository: %s\n")
2104 % os.path.join(prefix, subpath))
2104 % os.path.join(prefix, subpath))
2105
2105
2106 return err
2106 return err
2107
2107
2108 def commit(ui, repo, commitfunc, pats, opts):
2108 def commit(ui, repo, commitfunc, pats, opts):
2109 '''commit the specified files or all outstanding changes'''
2109 '''commit the specified files or all outstanding changes'''
2110 date = opts.get('date')
2110 date = opts.get('date')
2111 if date:
2111 if date:
2112 opts['date'] = util.parsedate(date)
2112 opts['date'] = util.parsedate(date)
2113 message = logmessage(ui, opts)
2113 message = logmessage(ui, opts)
2114
2114
2115 # extract addremove carefully -- this function can be called from a command
2115 # extract addremove carefully -- this function can be called from a command
2116 # that doesn't support addremove
2116 # that doesn't support addremove
2117 if opts.get('addremove'):
2117 if opts.get('addremove'):
2118 scmutil.addremove(repo, pats, opts)
2118 scmutil.addremove(repo, pats, opts)
2119
2119
2120 return commitfunc(ui, repo, message,
2120 return commitfunc(ui, repo, message,
2121 scmutil.match(repo[None], pats, opts), opts)
2121 scmutil.match(repo[None], pats, opts), opts)
2122
2122
2123 def amend(ui, repo, commitfunc, old, extra, pats, opts):
2123 def amend(ui, repo, commitfunc, old, extra, pats, opts):
2124 # amend will reuse the existing user if not specified, but the obsolete
2124 # amend will reuse the existing user if not specified, but the obsolete
2125 # marker creation requires that the current user's name is specified.
2125 # marker creation requires that the current user's name is specified.
2126 if obsolete._enabled:
2126 if obsolete._enabled:
2127 ui.username() # raise exception if username not set
2127 ui.username() # raise exception if username not set
2128
2128
2129 ui.note(_('amending changeset %s\n') % old)
2129 ui.note(_('amending changeset %s\n') % old)
2130 base = old.p1()
2130 base = old.p1()
2131
2131
2132 wlock = lock = newid = None
2132 wlock = lock = newid = None
2133 try:
2133 try:
2134 wlock = repo.wlock()
2134 wlock = repo.wlock()
2135 lock = repo.lock()
2135 lock = repo.lock()
2136 tr = repo.transaction('amend')
2136 tr = repo.transaction('amend')
2137 try:
2137 try:
2138 # See if we got a message from -m or -l, if not, open the editor
2138 # See if we got a message from -m or -l, if not, open the editor
2139 # with the message of the changeset to amend
2139 # with the message of the changeset to amend
2140 message = logmessage(ui, opts)
2140 message = logmessage(ui, opts)
2141 # ensure logfile does not conflict with later enforcement of the
2141 # ensure logfile does not conflict with later enforcement of the
2142 # message. potential logfile content has been processed by
2142 # message. potential logfile content has been processed by
2143 # `logmessage` anyway.
2143 # `logmessage` anyway.
2144 opts.pop('logfile')
2144 opts.pop('logfile')
2145 # First, do a regular commit to record all changes in the working
2145 # First, do a regular commit to record all changes in the working
2146 # directory (if there are any)
2146 # directory (if there are any)
2147 ui.callhooks = False
2147 ui.callhooks = False
2148 currentbookmark = repo._bookmarkcurrent
2148 currentbookmark = repo._bookmarkcurrent
2149 try:
2149 try:
2150 repo._bookmarkcurrent = None
2150 repo._bookmarkcurrent = None
2151 opts['message'] = 'temporary amend commit for %s' % old
2151 opts['message'] = 'temporary amend commit for %s' % old
2152 node = commit(ui, repo, commitfunc, pats, opts)
2152 node = commit(ui, repo, commitfunc, pats, opts)
2153 finally:
2153 finally:
2154 repo._bookmarkcurrent = currentbookmark
2154 repo._bookmarkcurrent = currentbookmark
2155 ui.callhooks = True
2155 ui.callhooks = True
2156 ctx = repo[node]
2156 ctx = repo[node]
2157
2157
2158 # Participating changesets:
2158 # Participating changesets:
2159 #
2159 #
2160 # node/ctx o - new (intermediate) commit that contains changes
2160 # node/ctx o - new (intermediate) commit that contains changes
2161 # | from working dir to go into amending commit
2161 # | from working dir to go into amending commit
2162 # | (or a workingctx if there were no changes)
2162 # | (or a workingctx if there were no changes)
2163 # |
2163 # |
2164 # old o - changeset to amend
2164 # old o - changeset to amend
2165 # |
2165 # |
2166 # base o - parent of amending changeset
2166 # base o - parent of amending changeset
2167
2167
2168 # Update extra dict from amended commit (e.g. to preserve graft
2168 # Update extra dict from amended commit (e.g. to preserve graft
2169 # source)
2169 # source)
2170 extra.update(old.extra())
2170 extra.update(old.extra())
2171
2171
2172 # Also update it from the intermediate commit or from the wctx
2172 # Also update it from the intermediate commit or from the wctx
2173 extra.update(ctx.extra())
2173 extra.update(ctx.extra())
2174
2174
2175 if len(old.parents()) > 1:
2175 if len(old.parents()) > 1:
2176 # ctx.files() isn't reliable for merges, so fall back to the
2176 # ctx.files() isn't reliable for merges, so fall back to the
2177 # slower repo.status() method
2177 # slower repo.status() method
2178 files = set([fn for st in repo.status(base, old)[:3]
2178 files = set([fn for st in repo.status(base, old)[:3]
2179 for fn in st])
2179 for fn in st])
2180 else:
2180 else:
2181 files = set(old.files())
2181 files = set(old.files())
2182
2182
2183 # Second, we use either the commit we just did, or if there were no
2183 # Second, we use either the commit we just did, or if there were no
2184 # changes the parent of the working directory as the version of the
2184 # changes the parent of the working directory as the version of the
2185 # files in the final amend commit
2185 # files in the final amend commit
2186 if node:
2186 if node:
2187 ui.note(_('copying changeset %s to %s\n') % (ctx, base))
2187 ui.note(_('copying changeset %s to %s\n') % (ctx, base))
2188
2188
2189 user = ctx.user()
2189 user = ctx.user()
2190 date = ctx.date()
2190 date = ctx.date()
2191 # Recompute copies (avoid recording a -> b -> a)
2191 # Recompute copies (avoid recording a -> b -> a)
2192 copied = copies.pathcopies(base, ctx)
2192 copied = copies.pathcopies(base, ctx)
2193
2193
2194 # Prune files which were reverted by the updates: if old
2194 # Prune files which were reverted by the updates: if old
2195 # introduced file X and our intermediate commit, node,
2195 # introduced file X and our intermediate commit, node,
2196 # renamed that file, then those two files are the same and
2196 # renamed that file, then those two files are the same and
2197 # we can discard X from our list of files. Likewise if X
2197 # we can discard X from our list of files. Likewise if X
2198 # was deleted, it's no longer relevant
2198 # was deleted, it's no longer relevant
2199 files.update(ctx.files())
2199 files.update(ctx.files())
2200
2200
2201 def samefile(f):
2201 def samefile(f):
2202 if f in ctx.manifest():
2202 if f in ctx.manifest():
2203 a = ctx.filectx(f)
2203 a = ctx.filectx(f)
2204 if f in base.manifest():
2204 if f in base.manifest():
2205 b = base.filectx(f)
2205 b = base.filectx(f)
2206 return (not a.cmp(b)
2206 return (not a.cmp(b)
2207 and a.flags() == b.flags())
2207 and a.flags() == b.flags())
2208 else:
2208 else:
2209 return False
2209 return False
2210 else:
2210 else:
2211 return f not in base.manifest()
2211 return f not in base.manifest()
2212 files = [f for f in files if not samefile(f)]
2212 files = [f for f in files if not samefile(f)]
2213
2213
2214 def filectxfn(repo, ctx_, path):
2214 def filectxfn(repo, ctx_, path):
2215 try:
2215 try:
2216 fctx = ctx[path]
2216 fctx = ctx[path]
2217 flags = fctx.flags()
2217 flags = fctx.flags()
2218 mctx = context.memfilectx(repo,
2218 mctx = context.memfilectx(repo,
2219 fctx.path(), fctx.data(),
2219 fctx.path(), fctx.data(),
2220 islink='l' in flags,
2220 islink='l' in flags,
2221 isexec='x' in flags,
2221 isexec='x' in flags,
2222 copied=copied.get(path))
2222 copied=copied.get(path))
2223 return mctx
2223 return mctx
2224 except KeyError:
2224 except KeyError:
2225 return None
2225 return None
2226 else:
2226 else:
2227 ui.note(_('copying changeset %s to %s\n') % (old, base))
2227 ui.note(_('copying changeset %s to %s\n') % (old, base))
2228
2228
2229 # Use version of files as in the old cset
2229 # Use version of files as in the old cset
2230 def filectxfn(repo, ctx_, path):
2230 def filectxfn(repo, ctx_, path):
2231 try:
2231 try:
2232 return old.filectx(path)
2232 return old.filectx(path)
2233 except KeyError:
2233 except KeyError:
2234 return None
2234 return None
2235
2235
2236 user = opts.get('user') or old.user()
2236 user = opts.get('user') or old.user()
2237 date = opts.get('date') or old.date()
2237 date = opts.get('date') or old.date()
2238 editform = mergeeditform(old, 'commit.amend')
2238 editform = mergeeditform(old, 'commit.amend')
2239 editor = getcommiteditor(editform=editform, **opts)
2239 editor = getcommiteditor(editform=editform, **opts)
2240 if not message:
2240 if not message:
2241 editor = getcommiteditor(edit=True, editform=editform)
2241 editor = getcommiteditor(edit=True, editform=editform)
2242 message = old.description()
2242 message = old.description()
2243
2243
2244 pureextra = extra.copy()
2244 pureextra = extra.copy()
2245 extra['amend_source'] = old.hex()
2245 extra['amend_source'] = old.hex()
2246
2246
2247 new = context.memctx(repo,
2247 new = context.memctx(repo,
2248 parents=[base.node(), old.p2().node()],
2248 parents=[base.node(), old.p2().node()],
2249 text=message,
2249 text=message,
2250 files=files,
2250 files=files,
2251 filectxfn=filectxfn,
2251 filectxfn=filectxfn,
2252 user=user,
2252 user=user,
2253 date=date,
2253 date=date,
2254 extra=extra,
2254 extra=extra,
2255 editor=editor)
2255 editor=editor)
2256
2256
2257 newdesc = changelog.stripdesc(new.description())
2257 newdesc = changelog.stripdesc(new.description())
2258 if ((not node)
2258 if ((not node)
2259 and newdesc == old.description()
2259 and newdesc == old.description()
2260 and user == old.user()
2260 and user == old.user()
2261 and date == old.date()
2261 and date == old.date()
2262 and pureextra == old.extra()):
2262 and pureextra == old.extra()):
2263 # nothing changed. continuing here would create a new node
2263 # nothing changed. continuing here would create a new node
2264 # anyway because of the amend_source noise.
2264 # anyway because of the amend_source noise.
2265 #
2265 #
2266 # This not what we expect from amend.
2266 # This not what we expect from amend.
2267 return old.node()
2267 return old.node()
2268
2268
2269 ph = repo.ui.config('phases', 'new-commit', phases.draft)
2269 ph = repo.ui.config('phases', 'new-commit', phases.draft)
2270 try:
2270 try:
2271 if opts.get('secret'):
2271 if opts.get('secret'):
2272 commitphase = 'secret'
2272 commitphase = 'secret'
2273 else:
2273 else:
2274 commitphase = old.phase()
2274 commitphase = old.phase()
2275 repo.ui.setconfig('phases', 'new-commit', commitphase, 'amend')
2275 repo.ui.setconfig('phases', 'new-commit', commitphase, 'amend')
2276 newid = repo.commitctx(new)
2276 newid = repo.commitctx(new)
2277 finally:
2277 finally:
2278 repo.ui.setconfig('phases', 'new-commit', ph, 'amend')
2278 repo.ui.setconfig('phases', 'new-commit', ph, 'amend')
2279 if newid != old.node():
2279 if newid != old.node():
2280 # Reroute the working copy parent to the new changeset
2280 # Reroute the working copy parent to the new changeset
2281 repo.setparents(newid, nullid)
2281 repo.setparents(newid, nullid)
2282
2282
2283 # Move bookmarks from old parent to amend commit
2283 # Move bookmarks from old parent to amend commit
2284 bms = repo.nodebookmarks(old.node())
2284 bms = repo.nodebookmarks(old.node())
2285 if bms:
2285 if bms:
2286 marks = repo._bookmarks
2286 marks = repo._bookmarks
2287 for bm in bms:
2287 for bm in bms:
2288 marks[bm] = newid
2288 marks[bm] = newid
2289 marks.write()
2289 marks.write()
2290 #commit the whole amend process
2290 #commit the whole amend process
2291 createmarkers = obsolete.isenabled(repo, obsolete.createmarkersopt)
2291 createmarkers = obsolete.isenabled(repo, obsolete.createmarkersopt)
2292 if createmarkers and newid != old.node():
2292 if createmarkers and newid != old.node():
2293 # mark the new changeset as successor of the rewritten one
2293 # mark the new changeset as successor of the rewritten one
2294 new = repo[newid]
2294 new = repo[newid]
2295 obs = [(old, (new,))]
2295 obs = [(old, (new,))]
2296 if node:
2296 if node:
2297 obs.append((ctx, ()))
2297 obs.append((ctx, ()))
2298
2298
2299 obsolete.createmarkers(repo, obs)
2299 obsolete.createmarkers(repo, obs)
2300 tr.close()
2300 tr.close()
2301 finally:
2301 finally:
2302 tr.release()
2302 tr.release()
2303 if not createmarkers and newid != old.node():
2303 if not createmarkers and newid != old.node():
2304 # Strip the intermediate commit (if there was one) and the amended
2304 # Strip the intermediate commit (if there was one) and the amended
2305 # commit
2305 # commit
2306 if node:
2306 if node:
2307 ui.note(_('stripping intermediate changeset %s\n') % ctx)
2307 ui.note(_('stripping intermediate changeset %s\n') % ctx)
2308 ui.note(_('stripping amended changeset %s\n') % old)
2308 ui.note(_('stripping amended changeset %s\n') % old)
2309 repair.strip(ui, repo, old.node(), topic='amend-backup')
2309 repair.strip(ui, repo, old.node(), topic='amend-backup')
2310 finally:
2310 finally:
2311 if newid is None:
2311 if newid is None:
2312 repo.dirstate.invalidate()
2312 repo.dirstate.invalidate()
2313 lockmod.release(lock, wlock)
2313 lockmod.release(lock, wlock)
2314 return newid
2314 return newid
2315
2315
2316 def commiteditor(repo, ctx, subs, editform=''):
2316 def commiteditor(repo, ctx, subs, editform=''):
2317 if ctx.description():
2317 if ctx.description():
2318 return ctx.description()
2318 return ctx.description()
2319 return commitforceeditor(repo, ctx, subs, editform=editform)
2319 return commitforceeditor(repo, ctx, subs, editform=editform)
2320
2320
2321 def commitforceeditor(repo, ctx, subs, finishdesc=None, extramsg=None,
2321 def commitforceeditor(repo, ctx, subs, finishdesc=None, extramsg=None,
2322 editform=''):
2322 editform=''):
2323 if not extramsg:
2323 if not extramsg:
2324 extramsg = _("Leave message empty to abort commit.")
2324 extramsg = _("Leave message empty to abort commit.")
2325
2325
2326 forms = [e for e in editform.split('.') if e]
2326 forms = [e for e in editform.split('.') if e]
2327 forms.insert(0, 'changeset')
2327 forms.insert(0, 'changeset')
2328 while forms:
2328 while forms:
2329 tmpl = repo.ui.config('committemplate', '.'.join(forms))
2329 tmpl = repo.ui.config('committemplate', '.'.join(forms))
2330 if tmpl:
2330 if tmpl:
2331 committext = buildcommittemplate(repo, ctx, subs, extramsg, tmpl)
2331 committext = buildcommittemplate(repo, ctx, subs, extramsg, tmpl)
2332 break
2332 break
2333 forms.pop()
2333 forms.pop()
2334 else:
2334 else:
2335 committext = buildcommittext(repo, ctx, subs, extramsg)
2335 committext = buildcommittext(repo, ctx, subs, extramsg)
2336
2336
2337 # run editor in the repository root
2337 # run editor in the repository root
2338 olddir = os.getcwd()
2338 olddir = os.getcwd()
2339 os.chdir(repo.root)
2339 os.chdir(repo.root)
2340 text = repo.ui.edit(committext, ctx.user(), ctx.extra(), editform=editform)
2340 text = repo.ui.edit(committext, ctx.user(), ctx.extra(), editform=editform)
2341 text = re.sub("(?m)^HG:.*(\n|$)", "", text)
2341 text = re.sub("(?m)^HG:.*(\n|$)", "", text)
2342 os.chdir(olddir)
2342 os.chdir(olddir)
2343
2343
2344 if finishdesc:
2344 if finishdesc:
2345 text = finishdesc(text)
2345 text = finishdesc(text)
2346 if not text.strip():
2346 if not text.strip():
2347 raise util.Abort(_("empty commit message"))
2347 raise util.Abort(_("empty commit message"))
2348
2348
2349 return text
2349 return text
2350
2350
2351 def buildcommittemplate(repo, ctx, subs, extramsg, tmpl):
2351 def buildcommittemplate(repo, ctx, subs, extramsg, tmpl):
2352 ui = repo.ui
2352 ui = repo.ui
2353 tmpl, mapfile = gettemplate(ui, tmpl, None)
2353 tmpl, mapfile = gettemplate(ui, tmpl, None)
2354
2354
2355 try:
2355 try:
2356 t = changeset_templater(ui, repo, None, {}, tmpl, mapfile, False)
2356 t = changeset_templater(ui, repo, None, {}, tmpl, mapfile, False)
2357 except SyntaxError, inst:
2357 except SyntaxError, inst:
2358 raise util.Abort(inst.args[0])
2358 raise util.Abort(inst.args[0])
2359
2359
2360 for k, v in repo.ui.configitems('committemplate'):
2360 for k, v in repo.ui.configitems('committemplate'):
2361 if k != 'changeset':
2361 if k != 'changeset':
2362 t.t.cache[k] = v
2362 t.t.cache[k] = v
2363
2363
2364 if not extramsg:
2364 if not extramsg:
2365 extramsg = '' # ensure that extramsg is string
2365 extramsg = '' # ensure that extramsg is string
2366
2366
2367 ui.pushbuffer()
2367 ui.pushbuffer()
2368 t.show(ctx, extramsg=extramsg)
2368 t.show(ctx, extramsg=extramsg)
2369 return ui.popbuffer()
2369 return ui.popbuffer()
2370
2370
2371 def buildcommittext(repo, ctx, subs, extramsg):
2371 def buildcommittext(repo, ctx, subs, extramsg):
2372 edittext = []
2372 edittext = []
2373 modified, added, removed = ctx.modified(), ctx.added(), ctx.removed()
2373 modified, added, removed = ctx.modified(), ctx.added(), ctx.removed()
2374 if ctx.description():
2374 if ctx.description():
2375 edittext.append(ctx.description())
2375 edittext.append(ctx.description())
2376 edittext.append("")
2376 edittext.append("")
2377 edittext.append("") # Empty line between message and comments.
2377 edittext.append("") # Empty line between message and comments.
2378 edittext.append(_("HG: Enter commit message."
2378 edittext.append(_("HG: Enter commit message."
2379 " Lines beginning with 'HG:' are removed."))
2379 " Lines beginning with 'HG:' are removed."))
2380 edittext.append("HG: %s" % extramsg)
2380 edittext.append("HG: %s" % extramsg)
2381 edittext.append("HG: --")
2381 edittext.append("HG: --")
2382 edittext.append(_("HG: user: %s") % ctx.user())
2382 edittext.append(_("HG: user: %s") % ctx.user())
2383 if ctx.p2():
2383 if ctx.p2():
2384 edittext.append(_("HG: branch merge"))
2384 edittext.append(_("HG: branch merge"))
2385 if ctx.branch():
2385 if ctx.branch():
2386 edittext.append(_("HG: branch '%s'") % ctx.branch())
2386 edittext.append(_("HG: branch '%s'") % ctx.branch())
2387 if bookmarks.iscurrent(repo):
2387 if bookmarks.iscurrent(repo):
2388 edittext.append(_("HG: bookmark '%s'") % repo._bookmarkcurrent)
2388 edittext.append(_("HG: bookmark '%s'") % repo._bookmarkcurrent)
2389 edittext.extend([_("HG: subrepo %s") % s for s in subs])
2389 edittext.extend([_("HG: subrepo %s") % s for s in subs])
2390 edittext.extend([_("HG: added %s") % f for f in added])
2390 edittext.extend([_("HG: added %s") % f for f in added])
2391 edittext.extend([_("HG: changed %s") % f for f in modified])
2391 edittext.extend([_("HG: changed %s") % f for f in modified])
2392 edittext.extend([_("HG: removed %s") % f for f in removed])
2392 edittext.extend([_("HG: removed %s") % f for f in removed])
2393 if not added and not modified and not removed:
2393 if not added and not modified and not removed:
2394 edittext.append(_("HG: no files changed"))
2394 edittext.append(_("HG: no files changed"))
2395 edittext.append("")
2395 edittext.append("")
2396
2396
2397 return "\n".join(edittext)
2397 return "\n".join(edittext)
2398
2398
2399 def commitstatus(repo, node, branch, bheads=None, opts={}):
2399 def commitstatus(repo, node, branch, bheads=None, opts={}):
2400 ctx = repo[node]
2400 ctx = repo[node]
2401 parents = ctx.parents()
2401 parents = ctx.parents()
2402
2402
2403 if (not opts.get('amend') and bheads and node not in bheads and not
2403 if (not opts.get('amend') and bheads and node not in bheads and not
2404 [x for x in parents if x.node() in bheads and x.branch() == branch]):
2404 [x for x in parents if x.node() in bheads and x.branch() == branch]):
2405 repo.ui.status(_('created new head\n'))
2405 repo.ui.status(_('created new head\n'))
2406 # The message is not printed for initial roots. For the other
2406 # The message is not printed for initial roots. For the other
2407 # changesets, it is printed in the following situations:
2407 # changesets, it is printed in the following situations:
2408 #
2408 #
2409 # Par column: for the 2 parents with ...
2409 # Par column: for the 2 parents with ...
2410 # N: null or no parent
2410 # N: null or no parent
2411 # B: parent is on another named branch
2411 # B: parent is on another named branch
2412 # C: parent is a regular non head changeset
2412 # C: parent is a regular non head changeset
2413 # H: parent was a branch head of the current branch
2413 # H: parent was a branch head of the current branch
2414 # Msg column: whether we print "created new head" message
2414 # Msg column: whether we print "created new head" message
2415 # In the following, it is assumed that there already exists some
2415 # In the following, it is assumed that there already exists some
2416 # initial branch heads of the current branch, otherwise nothing is
2416 # initial branch heads of the current branch, otherwise nothing is
2417 # printed anyway.
2417 # printed anyway.
2418 #
2418 #
2419 # Par Msg Comment
2419 # Par Msg Comment
2420 # N N y additional topo root
2420 # N N y additional topo root
2421 #
2421 #
2422 # B N y additional branch root
2422 # B N y additional branch root
2423 # C N y additional topo head
2423 # C N y additional topo head
2424 # H N n usual case
2424 # H N n usual case
2425 #
2425 #
2426 # B B y weird additional branch root
2426 # B B y weird additional branch root
2427 # C B y branch merge
2427 # C B y branch merge
2428 # H B n merge with named branch
2428 # H B n merge with named branch
2429 #
2429 #
2430 # C C y additional head from merge
2430 # C C y additional head from merge
2431 # C H n merge with a head
2431 # C H n merge with a head
2432 #
2432 #
2433 # H H n head merge: head count decreases
2433 # H H n head merge: head count decreases
2434
2434
2435 if not opts.get('close_branch'):
2435 if not opts.get('close_branch'):
2436 for r in parents:
2436 for r in parents:
2437 if r.closesbranch() and r.branch() == branch:
2437 if r.closesbranch() and r.branch() == branch:
2438 repo.ui.status(_('reopening closed branch head %d\n') % r)
2438 repo.ui.status(_('reopening closed branch head %d\n') % r)
2439
2439
2440 if repo.ui.debugflag:
2440 if repo.ui.debugflag:
2441 repo.ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
2441 repo.ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
2442 elif repo.ui.verbose:
2442 elif repo.ui.verbose:
2443 repo.ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
2443 repo.ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
2444
2444
2445 def revert(ui, repo, ctx, parents, *pats, **opts):
2445 def revert(ui, repo, ctx, parents, *pats, **opts):
2446 parent, p2 = parents
2446 parent, p2 = parents
2447 node = ctx.node()
2447 node = ctx.node()
2448
2448
2449 mf = ctx.manifest()
2449 mf = ctx.manifest()
2450 if node == p2:
2450 if node == p2:
2451 parent = p2
2451 parent = p2
2452 if node == parent:
2452 if node == parent:
2453 pmf = mf
2453 pmf = mf
2454 else:
2454 else:
2455 pmf = None
2455 pmf = None
2456
2456
2457 # need all matching names in dirstate and manifest of target rev,
2457 # need all matching names in dirstate and manifest of target rev,
2458 # so have to walk both. do not print errors if files exist in one
2458 # so have to walk both. do not print errors if files exist in one
2459 # but not other.
2459 # but not other.
2460
2460
2461 # `names` is a mapping for all elements in working copy and target revision
2461 # `names` is a mapping for all elements in working copy and target revision
2462 # The mapping is in the form:
2462 # The mapping is in the form:
2463 # <asb path in repo> -> (<path from CWD>, <exactly specified by matcher?>)
2463 # <asb path in repo> -> (<path from CWD>, <exactly specified by matcher?>)
2464 names = {}
2464 names = {}
2465
2465
2466 wlock = repo.wlock()
2466 wlock = repo.wlock()
2467 try:
2467 try:
2468 ## filling of the `names` mapping
2468 ## filling of the `names` mapping
2469 # walk dirstate to fill `names`
2469 # walk dirstate to fill `names`
2470
2470
2471 m = scmutil.match(repo[None], pats, opts)
2471 m = scmutil.match(repo[None], pats, opts)
2472 if not m.always() or node != parent:
2472 if not m.always() or node != parent:
2473 m.bad = lambda x, y: False
2473 m.bad = lambda x, y: False
2474 for abs in repo.walk(m):
2474 for abs in repo.walk(m):
2475 names[abs] = m.rel(abs), m.exact(abs)
2475 names[abs] = m.rel(abs), m.exact(abs)
2476
2476
2477 # walk target manifest to fill `names`
2477 # walk target manifest to fill `names`
2478
2478
2479 def badfn(path, msg):
2479 def badfn(path, msg):
2480 if path in names:
2480 if path in names:
2481 return
2481 return
2482 if path in ctx.substate:
2482 if path in ctx.substate:
2483 return
2483 return
2484 path_ = path + '/'
2484 path_ = path + '/'
2485 for f in names:
2485 for f in names:
2486 if f.startswith(path_):
2486 if f.startswith(path_):
2487 return
2487 return
2488 ui.warn("%s: %s\n" % (m.rel(path), msg))
2488 ui.warn("%s: %s\n" % (m.rel(path), msg))
2489
2489
2490 m = scmutil.match(ctx, pats, opts)
2490 m = scmutil.match(ctx, pats, opts)
2491 m.bad = badfn
2491 m.bad = badfn
2492 for abs in ctx.walk(m):
2492 for abs in ctx.walk(m):
2493 if abs not in names:
2493 if abs not in names:
2494 names[abs] = m.rel(abs), m.exact(abs)
2494 names[abs] = m.rel(abs), m.exact(abs)
2495
2495
2496 # Find status of all file in `names`.
2496 # Find status of all file in `names`.
2497 m = scmutil.matchfiles(repo, names)
2497 m = scmutil.matchfiles(repo, names)
2498
2498
2499 changes = repo.status(node1=node, match=m,
2499 changes = repo.status(node1=node, match=m,
2500 unknown=True, ignored=True, clean=True)
2500 unknown=True, ignored=True, clean=True)
2501 else:
2501 else:
2502 changes = repo.status(match=m)
2502 changes = repo.status(match=m)
2503 for kind in changes:
2503 for kind in changes:
2504 for abs in kind:
2504 for abs in kind:
2505 names[abs] = m.rel(abs), m.exact(abs)
2505 names[abs] = m.rel(abs), m.exact(abs)
2506
2506
2507 m = scmutil.matchfiles(repo, names)
2507 m = scmutil.matchfiles(repo, names)
2508
2508
2509 modified = set(changes[0])
2509 modified = set(changes[0])
2510 added = set(changes[1])
2510 added = set(changes[1])
2511 removed = set(changes[2])
2511 removed = set(changes[2])
2512 _deleted = set(changes[3])
2512 _deleted = set(changes[3])
2513 unknown = set(changes[4])
2513 unknown = set(changes[4])
2514 unknown.update(changes[5])
2514 unknown.update(changes[5])
2515 clean = set(changes[6])
2515 clean = set(changes[6])
2516 modadded = set()
2516 modadded = set()
2517
2517
2518 # split between files known in target manifest and the others
2518 # split between files known in target manifest and the others
2519 smf = set(mf)
2519 smf = set(mf)
2520
2520
2521 # determine the exact nature of the deleted changesets
2521 # determine the exact nature of the deleted changesets
2522 deladded = _deleted - smf
2522 deladded = _deleted - smf
2523 deleted = _deleted - deladded
2523 deleted = _deleted - deladded
2524
2524
2525 # We need to account for the state of file in the dirstate.
2525 # We need to account for the state of file in the dirstate.
2526 #
2526 #
2527 # Even, when we revert against something else than parent. This will
2527 # Even, when we revert against something else than parent. This will
2528 # slightly alter the behavior of revert (doing back up or not, delete
2528 # slightly alter the behavior of revert (doing back up or not, delete
2529 # or just forget etc).
2529 # or just forget etc).
2530 if parent == node:
2530 if parent == node:
2531 dsmodified = modified
2531 dsmodified = modified
2532 dsadded = added
2532 dsadded = added
2533 dsremoved = removed
2533 dsremoved = removed
2534 modified, added, removed = set(), set(), set()
2534 modified, added, removed = set(), set(), set()
2535 else:
2535 else:
2536 changes = repo.status(node1=parent, match=m)
2536 changes = repo.status(node1=parent, match=m)
2537 dsmodified = set(changes[0])
2537 dsmodified = set(changes[0])
2538 dsadded = set(changes[1])
2538 dsadded = set(changes[1])
2539 dsremoved = set(changes[2])
2539 dsremoved = set(changes[2])
2540
2540
2541 # only take into account for removes between wc and target
2541 # only take into account for removes between wc and target
2542 clean |= dsremoved - removed
2542 clean |= dsremoved - removed
2543 dsremoved &= removed
2543 dsremoved &= removed
2544 # distinct between dirstate remove and other
2544 # distinct between dirstate remove and other
2545 removed -= dsremoved
2545 removed -= dsremoved
2546
2546
2547 modadded = added & dsmodified
2547 modadded = added & dsmodified
2548 added -= modadded
2548 added -= modadded
2549
2549
2550 # tell newly modified apart.
2550 # tell newly modified apart.
2551 dsmodified &= modified
2551 dsmodified &= modified
2552 dsmodified |= modified & dsadded # dirstate added may needs backup
2552 dsmodified |= modified & dsadded # dirstate added may needs backup
2553 modified -= dsmodified
2553 modified -= dsmodified
2554
2554
2555 # We need to wait for some post-processing to update this set
2555 # We need to wait for some post-processing to update this set
2556 # before making the distinction. The dirstate will be used for
2556 # before making the distinction. The dirstate will be used for
2557 # that purpose.
2557 # that purpose.
2558 dsadded = added
2558 dsadded = added
2559
2559
2560 # in case of merge, files that are actually added can be reported as
2560 # in case of merge, files that are actually added can be reported as
2561 # modified, we need to post process the result
2561 # modified, we need to post process the result
2562 if p2 != nullid:
2562 if p2 != nullid:
2563 if pmf is None:
2563 if pmf is None:
2564 # only need parent manifest in the merge case,
2564 # only need parent manifest in the merge case,
2565 # so do not read by default
2565 # so do not read by default
2566 pmf = repo[parent].manifest()
2566 pmf = repo[parent].manifest()
2567 mergeadd = dsmodified - set(pmf)
2567 mergeadd = dsmodified - set(pmf)
2568 dsadded |= mergeadd
2568 dsadded |= mergeadd
2569 dsmodified -= mergeadd
2569 dsmodified -= mergeadd
2570
2570
2571 # if f is a rename, update `names` to also revert the source
2571 # if f is a rename, update `names` to also revert the source
2572 cwd = repo.getcwd()
2572 cwd = repo.getcwd()
2573 for f in dsadded:
2573 for f in dsadded:
2574 src = repo.dirstate.copied(f)
2574 src = repo.dirstate.copied(f)
2575 # XXX should we check for rename down to target node?
2575 # XXX should we check for rename down to target node?
2576 if src and src not in names and repo.dirstate[src] == 'r':
2576 if src and src not in names and repo.dirstate[src] == 'r':
2577 dsremoved.add(src)
2577 dsremoved.add(src)
2578 names[src] = (repo.pathto(src, cwd), True)
2578 names[src] = (repo.pathto(src, cwd), True)
2579
2579
2580 # distinguish between file to forget and the other
2580 # distinguish between file to forget and the other
2581 added = set()
2581 added = set()
2582 for abs in dsadded:
2582 for abs in dsadded:
2583 if repo.dirstate[abs] != 'a':
2583 if repo.dirstate[abs] != 'a':
2584 added.add(abs)
2584 added.add(abs)
2585 dsadded -= added
2585 dsadded -= added
2586
2586
2587 for abs in deladded:
2587 for abs in deladded:
2588 if repo.dirstate[abs] == 'a':
2588 if repo.dirstate[abs] == 'a':
2589 dsadded.add(abs)
2589 dsadded.add(abs)
2590 deladded -= dsadded
2590 deladded -= dsadded
2591
2591
2592 # For files marked as removed, we check if an unknown file is present at
2592 # For files marked as removed, we check if an unknown file is present at
2593 # the same path. If a such file exists it may need to be backed up.
2593 # the same path. If a such file exists it may need to be backed up.
2594 # Making the distinction at this stage helps have simpler backup
2594 # Making the distinction at this stage helps have simpler backup
2595 # logic.
2595 # logic.
2596 removunk = set()
2596 removunk = set()
2597 for abs in removed:
2597 for abs in removed:
2598 target = repo.wjoin(abs)
2598 target = repo.wjoin(abs)
2599 if os.path.lexists(target):
2599 if os.path.lexists(target):
2600 removunk.add(abs)
2600 removunk.add(abs)
2601 removed -= removunk
2601 removed -= removunk
2602
2602
2603 dsremovunk = set()
2603 dsremovunk = set()
2604 for abs in dsremoved:
2604 for abs in dsremoved:
2605 target = repo.wjoin(abs)
2605 target = repo.wjoin(abs)
2606 if os.path.lexists(target):
2606 if os.path.lexists(target):
2607 dsremovunk.add(abs)
2607 dsremovunk.add(abs)
2608 dsremoved -= dsremovunk
2608 dsremoved -= dsremovunk
2609
2609
2610 # action to be actually performed by revert
2610 # action to be actually performed by revert
2611 # (<list of file>, message>) tuple
2611 # (<list of file>, message>) tuple
2612 actions = {'revert': ([], _('reverting %s\n')),
2612 actions = {'revert': ([], _('reverting %s\n')),
2613 'add': ([], _('adding %s\n')),
2613 'add': ([], _('adding %s\n')),
2614 'remove': ([], _('removing %s\n')),
2614 'remove': ([], _('removing %s\n')),
2615 'drop': ([], _('removing %s\n')),
2615 'drop': ([], _('removing %s\n')),
2616 'forget': ([], _('forgetting %s\n')),
2616 'forget': ([], _('forgetting %s\n')),
2617 'undelete': ([], _('undeleting %s\n')),
2617 'undelete': ([], _('undeleting %s\n')),
2618 'noop': (None, _('no changes needed to %s\n')),
2618 'noop': (None, _('no changes needed to %s\n')),
2619 'unknown': (None, _('file not managed: %s\n')),
2619 'unknown': (None, _('file not managed: %s\n')),
2620 }
2620 }
2621
2621
2622 # "constant" that convey the backup strategy.
2622 # "constant" that convey the backup strategy.
2623 # All set to `discard` if `no-backup` is set do avoid checking
2623 # All set to `discard` if `no-backup` is set do avoid checking
2624 # no_backup lower in the code.
2624 # no_backup lower in the code.
2625 # These values are ordered for comparison purposes
2625 # These values are ordered for comparison purposes
2626 backup = 2 # unconditionally do backup
2626 backup = 2 # unconditionally do backup
2627 check = 1 # check if the existing file differs from target
2627 check = 1 # check if the existing file differs from target
2628 discard = 0 # never do backup
2628 discard = 0 # never do backup
2629 if opts.get('no_backup'):
2629 if opts.get('no_backup'):
2630 backup = check = discard
2630 backup = check = discard
2631
2631
2632 backupanddel = actions['remove']
2632 backupanddel = actions['remove']
2633 if not opts.get('no_backup'):
2633 if not opts.get('no_backup'):
2634 backupanddel = actions['drop']
2634 backupanddel = actions['drop']
2635
2635
2636 disptable = (
2636 disptable = (
2637 # dispatch table:
2637 # dispatch table:
2638 # file state
2638 # file state
2639 # action
2639 # action
2640 # make backup
2640 # make backup
2641
2641
2642 ## Sets that results that will change file on disk
2642 ## Sets that results that will change file on disk
2643 # Modified compared to target, no local change
2643 # Modified compared to target, no local change
2644 (modified, actions['revert'], discard),
2644 (modified, actions['revert'], discard),
2645 # Modified compared to target, but local file is deleted
2645 # Modified compared to target, but local file is deleted
2646 (deleted, actions['revert'], discard),
2646 (deleted, actions['revert'], discard),
2647 # Modified compared to target, local change
2647 # Modified compared to target, local change
2648 (dsmodified, actions['revert'], backup),
2648 (dsmodified, actions['revert'], backup),
2649 # Added since target
2649 # Added since target
2650 (added, actions['remove'], discard),
2650 (added, actions['remove'], discard),
2651 # Added in working directory
2651 # Added in working directory
2652 (dsadded, actions['forget'], discard),
2652 (dsadded, actions['forget'], discard),
2653 # Added since target, have local modification
2653 # Added since target, have local modification
2654 (modadded, backupanddel, backup),
2654 (modadded, backupanddel, backup),
2655 # Added since target but file is missing in working directory
2655 # Added since target but file is missing in working directory
2656 (deladded, actions['drop'], discard),
2656 (deladded, actions['drop'], discard),
2657 # Removed since target, before working copy parent
2657 # Removed since target, before working copy parent
2658 (removed, actions['add'], discard),
2658 (removed, actions['add'], discard),
2659 # Same as `removed` but an unknown file exists at the same path
2659 # Same as `removed` but an unknown file exists at the same path
2660 (removunk, actions['add'], check),
2660 (removunk, actions['add'], check),
2661 # Removed since targe, marked as such in working copy parent
2661 # Removed since targe, marked as such in working copy parent
2662 (dsremoved, actions['undelete'], discard),
2662 (dsremoved, actions['undelete'], discard),
2663 # Same as `dsremoved` but an unknown file exists at the same path
2663 # Same as `dsremoved` but an unknown file exists at the same path
2664 (dsremovunk, actions['undelete'], check),
2664 (dsremovunk, actions['undelete'], check),
2665 ## the following sets does not result in any file changes
2665 ## the following sets does not result in any file changes
2666 # File with no modification
2666 # File with no modification
2667 (clean, actions['noop'], discard),
2667 (clean, actions['noop'], discard),
2668 # Existing file, not tracked anywhere
2668 # Existing file, not tracked anywhere
2669 (unknown, actions['unknown'], discard),
2669 (unknown, actions['unknown'], discard),
2670 )
2670 )
2671
2671
2672 needdata = ('revert', 'add', 'undelete')
2672 needdata = ('revert', 'add', 'undelete')
2673 _revertprefetch(repo, ctx, *[actions[name][0] for name in needdata])
2673 _revertprefetch(repo, ctx, *[actions[name][0] for name in needdata])
2674
2674
2675 wctx = repo[None]
2675 wctx = repo[None]
2676 for abs, (rel, exact) in sorted(names.items()):
2676 for abs, (rel, exact) in sorted(names.items()):
2677 # target file to be touch on disk (relative to cwd)
2677 # target file to be touch on disk (relative to cwd)
2678 target = repo.wjoin(abs)
2678 target = repo.wjoin(abs)
2679 # search the entry in the dispatch table.
2679 # search the entry in the dispatch table.
2680 # if the file is in any of these sets, it was touched in the working
2680 # if the file is in any of these sets, it was touched in the working
2681 # directory parent and we are sure it needs to be reverted.
2681 # directory parent and we are sure it needs to be reverted.
2682 for table, (xlist, msg), dobackup in disptable:
2682 for table, (xlist, msg), dobackup in disptable:
2683 if abs not in table:
2683 if abs not in table:
2684 continue
2684 continue
2685 if xlist is not None:
2685 if xlist is not None:
2686 xlist.append(abs)
2686 xlist.append(abs)
2687 if dobackup and (backup <= dobackup
2687 if dobackup and (backup <= dobackup
2688 or wctx[abs].cmp(ctx[abs])):
2688 or wctx[abs].cmp(ctx[abs])):
2689 bakname = "%s.orig" % rel
2689 bakname = "%s.orig" % rel
2690 ui.note(_('saving current version of %s as %s\n') %
2690 ui.note(_('saving current version of %s as %s\n') %
2691 (rel, bakname))
2691 (rel, bakname))
2692 if not opts.get('dry_run'):
2692 if not opts.get('dry_run'):
2693 util.rename(target, bakname)
2693 util.rename(target, bakname)
2694 if ui.verbose or not exact:
2694 if ui.verbose or not exact:
2695 if not isinstance(msg, basestring):
2695 if not isinstance(msg, basestring):
2696 msg = msg(abs)
2696 msg = msg(abs)
2697 ui.status(msg % rel)
2697 ui.status(msg % rel)
2698 elif exact:
2698 elif exact:
2699 ui.warn(msg % rel)
2699 ui.warn(msg % rel)
2700 break
2700 break
2701
2701
2702
2702
2703 if not opts.get('dry_run'):
2703 if not opts.get('dry_run'):
2704 _performrevert(repo, parents, ctx, actions)
2704 _performrevert(repo, parents, ctx, actions)
2705
2705
2706 # get the list of subrepos that must be reverted
2706 # get the list of subrepos that must be reverted
2707 subrepomatch = scmutil.match(ctx, pats, opts)
2707 subrepomatch = scmutil.match(ctx, pats, opts)
2708 targetsubs = sorted(s for s in ctx.substate if subrepomatch(s))
2708 targetsubs = sorted(s for s in ctx.substate if subrepomatch(s))
2709
2709
2710 if targetsubs:
2710 if targetsubs:
2711 # Revert the subrepos on the revert list
2711 # Revert the subrepos on the revert list
2712 for sub in targetsubs:
2712 for sub in targetsubs:
2713 ctx.sub(sub).revert(ui, ctx.substate[sub], *pats, **opts)
2713 ctx.sub(sub).revert(ui, ctx.substate[sub], *pats, **opts)
2714 finally:
2714 finally:
2715 wlock.release()
2715 wlock.release()
2716
2716
2717 def _revertprefetch(repo, ctx, *files):
2717 def _revertprefetch(repo, ctx, *files):
2718 """Let extension changing the storage layer prefetch content"""
2718 """Let extension changing the storage layer prefetch content"""
2719 pass
2719 pass
2720
2720
2721 def _performrevert(repo, parents, ctx, actions):
2721 def _performrevert(repo, parents, ctx, actions):
2722 """function that actually perform all the actions computed for revert
2722 """function that actually perform all the actions computed for revert
2723
2723
2724 This is an independent function to let extension to plug in and react to
2724 This is an independent function to let extension to plug in and react to
2725 the imminent revert.
2725 the imminent revert.
2726
2726
2727 Make sure you have the working directory locked when calling this function.
2727 Make sure you have the working directory locked when calling this function.
2728 """
2728 """
2729 parent, p2 = parents
2729 parent, p2 = parents
2730 node = ctx.node()
2730 node = ctx.node()
2731 def checkout(f):
2731 def checkout(f):
2732 fc = ctx[f]
2732 fc = ctx[f]
2733 repo.wwrite(f, fc.data(), fc.flags())
2733 repo.wwrite(f, fc.data(), fc.flags())
2734
2734
2735 audit_path = pathutil.pathauditor(repo.root)
2735 audit_path = pathutil.pathauditor(repo.root)
2736 for f in actions['forget'][0]:
2736 for f in actions['forget'][0]:
2737 repo.dirstate.drop(f)
2737 repo.dirstate.drop(f)
2738 for f in actions['remove'][0]:
2738 for f in actions['remove'][0]:
2739 audit_path(f)
2739 audit_path(f)
2740 util.unlinkpath(repo.wjoin(f))
2740 util.unlinkpath(repo.wjoin(f))
2741 repo.dirstate.remove(f)
2741 repo.dirstate.remove(f)
2742 for f in actions['drop'][0]:
2742 for f in actions['drop'][0]:
2743 audit_path(f)
2743 audit_path(f)
2744 repo.dirstate.remove(f)
2744 repo.dirstate.remove(f)
2745
2745
2746 normal = None
2746 normal = None
2747 if node == parent:
2747 if node == parent:
2748 # We're reverting to our parent. If possible, we'd like status
2748 # We're reverting to our parent. If possible, we'd like status
2749 # to report the file as clean. We have to use normallookup for
2749 # to report the file as clean. We have to use normallookup for
2750 # merges to avoid losing information about merged/dirty files.
2750 # merges to avoid losing information about merged/dirty files.
2751 if p2 != nullid:
2751 if p2 != nullid:
2752 normal = repo.dirstate.normallookup
2752 normal = repo.dirstate.normallookup
2753 else:
2753 else:
2754 normal = repo.dirstate.normal
2754 normal = repo.dirstate.normal
2755 for f in actions['revert'][0]:
2755 for f in actions['revert'][0]:
2756 checkout(f)
2756 checkout(f)
2757 if normal:
2757 if normal:
2758 normal(f)
2758 normal(f)
2759
2759
2760 for f in actions['add'][0]:
2760 for f in actions['add'][0]:
2761 checkout(f)
2761 checkout(f)
2762 repo.dirstate.add(f)
2762 repo.dirstate.add(f)
2763
2763
2764 normal = repo.dirstate.normallookup
2764 normal = repo.dirstate.normallookup
2765 if node == parent and p2 == nullid:
2765 if node == parent and p2 == nullid:
2766 normal = repo.dirstate.normal
2766 normal = repo.dirstate.normal
2767 for f in actions['undelete'][0]:
2767 for f in actions['undelete'][0]:
2768 checkout(f)
2768 checkout(f)
2769 normal(f)
2769 normal(f)
2770
2770
2771 copied = copies.pathcopies(repo[parent], ctx)
2771 copied = copies.pathcopies(repo[parent], ctx)
2772
2772
2773 for f in actions['add'][0] + actions['undelete'][0] + actions['revert'][0]:
2773 for f in actions['add'][0] + actions['undelete'][0] + actions['revert'][0]:
2774 if f in copied:
2774 if f in copied:
2775 repo.dirstate.copy(copied[f], f)
2775 repo.dirstate.copy(copied[f], f)
2776
2776
2777 def command(table):
2777 def command(table):
2778 """Returns a function object to be used as a decorator for making commands.
2778 """Returns a function object to be used as a decorator for making commands.
2779
2779
2780 This function receives a command table as its argument. The table should
2780 This function receives a command table as its argument. The table should
2781 be a dict.
2781 be a dict.
2782
2782
2783 The returned function can be used as a decorator for adding commands
2783 The returned function can be used as a decorator for adding commands
2784 to that command table. This function accepts multiple arguments to define
2784 to that command table. This function accepts multiple arguments to define
2785 a command.
2785 a command.
2786
2786
2787 The first argument is the command name.
2787 The first argument is the command name.
2788
2788
2789 The options argument is an iterable of tuples defining command arguments.
2789 The options argument is an iterable of tuples defining command arguments.
2790 See ``mercurial.fancyopts.fancyopts()`` for the format of each tuple.
2790 See ``mercurial.fancyopts.fancyopts()`` for the format of each tuple.
2791
2791
2792 The synopsis argument defines a short, one line summary of how to use the
2792 The synopsis argument defines a short, one line summary of how to use the
2793 command. This shows up in the help output.
2793 command. This shows up in the help output.
2794
2794
2795 The norepo argument defines whether the command does not require a
2795 The norepo argument defines whether the command does not require a
2796 local repository. Most commands operate against a repository, thus the
2796 local repository. Most commands operate against a repository, thus the
2797 default is False.
2797 default is False.
2798
2798
2799 The optionalrepo argument defines whether the command optionally requires
2799 The optionalrepo argument defines whether the command optionally requires
2800 a local repository.
2800 a local repository.
2801
2801
2802 The inferrepo argument defines whether to try to find a repository from the
2802 The inferrepo argument defines whether to try to find a repository from the
2803 command line arguments. If True, arguments will be examined for potential
2803 command line arguments. If True, arguments will be examined for potential
2804 repository locations. See ``findrepo()``. If a repository is found, it
2804 repository locations. See ``findrepo()``. If a repository is found, it
2805 will be used.
2805 will be used.
2806 """
2806 """
2807 def cmd(name, options=(), synopsis=None, norepo=False, optionalrepo=False,
2807 def cmd(name, options=(), synopsis=None, norepo=False, optionalrepo=False,
2808 inferrepo=False):
2808 inferrepo=False):
2809 def decorator(func):
2809 def decorator(func):
2810 if synopsis:
2810 if synopsis:
2811 table[name] = func, list(options), synopsis
2811 table[name] = func, list(options), synopsis
2812 else:
2812 else:
2813 table[name] = func, list(options)
2813 table[name] = func, list(options)
2814
2814
2815 if norepo:
2815 if norepo:
2816 # Avoid import cycle.
2816 # Avoid import cycle.
2817 import commands
2817 import commands
2818 commands.norepo += ' %s' % ' '.join(parsealiases(name))
2818 commands.norepo += ' %s' % ' '.join(parsealiases(name))
2819
2819
2820 if optionalrepo:
2820 if optionalrepo:
2821 import commands
2821 import commands
2822 commands.optionalrepo += ' %s' % ' '.join(parsealiases(name))
2822 commands.optionalrepo += ' %s' % ' '.join(parsealiases(name))
2823
2823
2824 if inferrepo:
2824 if inferrepo:
2825 import commands
2825 import commands
2826 commands.inferrepo += ' %s' % ' '.join(parsealiases(name))
2826 commands.inferrepo += ' %s' % ' '.join(parsealiases(name))
2827
2827
2828 return func
2828 return func
2829 return decorator
2829 return decorator
2830
2830
2831 return cmd
2831 return cmd
2832
2832
2833 # a list of (ui, repo, otherpeer, opts, missing) functions called by
2833 # a list of (ui, repo, otherpeer, opts, missing) functions called by
2834 # commands.outgoing. "missing" is "missing" of the result of
2834 # commands.outgoing. "missing" is "missing" of the result of
2835 # "findcommonoutgoing()"
2835 # "findcommonoutgoing()"
2836 outgoinghooks = util.hooks()
2836 outgoinghooks = util.hooks()
2837
2837
2838 # a list of (ui, repo) functions called by commands.summary
2838 # a list of (ui, repo) functions called by commands.summary
2839 summaryhooks = util.hooks()
2839 summaryhooks = util.hooks()
2840
2840
2841 # a list of (ui, repo, opts, changes) functions called by commands.summary.
2841 # a list of (ui, repo, opts, changes) functions called by commands.summary.
2842 #
2842 #
2843 # functions should return tuple of booleans below, if 'changes' is None:
2843 # functions should return tuple of booleans below, if 'changes' is None:
2844 # (whether-incomings-are-needed, whether-outgoings-are-needed)
2844 # (whether-incomings-are-needed, whether-outgoings-are-needed)
2845 #
2845 #
2846 # otherwise, 'changes' is a tuple of tuples below:
2846 # otherwise, 'changes' is a tuple of tuples below:
2847 # - (sourceurl, sourcebranch, sourcepeer, incoming)
2847 # - (sourceurl, sourcebranch, sourcepeer, incoming)
2848 # - (desturl, destbranch, destpeer, outgoing)
2848 # - (desturl, destbranch, destpeer, outgoing)
2849 summaryremotehooks = util.hooks()
2849 summaryremotehooks = util.hooks()
2850
2850
2851 # A list of state files kept by multistep operations like graft.
2851 # A list of state files kept by multistep operations like graft.
2852 # Since graft cannot be aborted, it is considered 'clearable' by update.
2852 # Since graft cannot be aborted, it is considered 'clearable' by update.
2853 # note: bisect is intentionally excluded
2853 # note: bisect is intentionally excluded
2854 # (state file, clearable, allowcommit, error, hint)
2854 # (state file, clearable, allowcommit, error, hint)
2855 unfinishedstates = [
2855 unfinishedstates = [
2856 ('graftstate', True, False, _('graft in progress'),
2856 ('graftstate', True, False, _('graft in progress'),
2857 _("use 'hg graft --continue' or 'hg update' to abort")),
2857 _("use 'hg graft --continue' or 'hg update' to abort")),
2858 ('updatestate', True, False, _('last update was interrupted'),
2858 ('updatestate', True, False, _('last update was interrupted'),
2859 _("use 'hg update' to get a consistent checkout"))
2859 _("use 'hg update' to get a consistent checkout"))
2860 ]
2860 ]
2861
2861
2862 def checkunfinished(repo, commit=False):
2862 def checkunfinished(repo, commit=False):
2863 '''Look for an unfinished multistep operation, like graft, and abort
2863 '''Look for an unfinished multistep operation, like graft, and abort
2864 if found. It's probably good to check this right before
2864 if found. It's probably good to check this right before
2865 bailifchanged().
2865 bailifchanged().
2866 '''
2866 '''
2867 for f, clearable, allowcommit, msg, hint in unfinishedstates:
2867 for f, clearable, allowcommit, msg, hint in unfinishedstates:
2868 if commit and allowcommit:
2868 if commit and allowcommit:
2869 continue
2869 continue
2870 if repo.vfs.exists(f):
2870 if repo.vfs.exists(f):
2871 raise util.Abort(msg, hint=hint)
2871 raise util.Abort(msg, hint=hint)
2872
2872
2873 def clearunfinished(repo):
2873 def clearunfinished(repo):
2874 '''Check for unfinished operations (as above), and clear the ones
2874 '''Check for unfinished operations (as above), and clear the ones
2875 that are clearable.
2875 that are clearable.
2876 '''
2876 '''
2877 for f, clearable, allowcommit, msg, hint in unfinishedstates:
2877 for f, clearable, allowcommit, msg, hint in unfinishedstates:
2878 if not clearable and repo.vfs.exists(f):
2878 if not clearable and repo.vfs.exists(f):
2879 raise util.Abort(msg, hint=hint)
2879 raise util.Abort(msg, hint=hint)
2880 for f, clearable, allowcommit, msg, hint in unfinishedstates:
2880 for f, clearable, allowcommit, msg, hint in unfinishedstates:
2881 if clearable and repo.vfs.exists(f):
2881 if clearable and repo.vfs.exists(f):
2882 util.unlink(repo.join(f))
2882 util.unlink(repo.join(f))
@@ -1,159 +1,172 b''
1 $ hg init a
1 $ hg init a
2 $ cd a
2 $ cd a
3 $ echo a > a
3 $ echo a > a
4 $ hg add -n
4 $ hg add -n
5 adding a
5 adding a
6 $ hg st
6 $ hg st
7 ? a
7 ? a
8 $ hg add
8 $ hg add
9 adding a
9 adding a
10 $ hg st
10 $ hg st
11 A a
11 A a
12 $ hg forget a
12 $ hg forget a
13 $ hg add
13 $ hg add
14 adding a
14 adding a
15 $ hg st
15 $ hg st
16 A a
16 A a
17
17
18 $ echo b > b
18 $ echo b > b
19 $ hg add -n b
19 $ hg add -n b
20 $ hg st
20 $ hg st
21 A a
21 A a
22 ? b
22 ? b
23 $ hg add b
23 $ hg add b
24 $ hg st
24 $ hg st
25 A a
25 A a
26 A b
26 A b
27
27
28 should fail
28 should fail
29
29
30 $ hg add b
30 $ hg add b
31 b already tracked!
31 b already tracked!
32 $ hg st
32 $ hg st
33 A a
33 A a
34 A b
34 A b
35
35
36 #if no-windows
36 #if no-windows
37 $ echo foo > con.xml
37 $ echo foo > con.xml
38 $ hg --config ui.portablefilenames=jump add con.xml
38 $ hg --config ui.portablefilenames=jump add con.xml
39 abort: ui.portablefilenames value is invalid ('jump')
39 abort: ui.portablefilenames value is invalid ('jump')
40 [255]
40 [255]
41 $ hg --config ui.portablefilenames=abort add con.xml
41 $ hg --config ui.portablefilenames=abort add con.xml
42 abort: filename contains 'con', which is reserved on Windows: 'con.xml'
42 abort: filename contains 'con', which is reserved on Windows: 'con.xml'
43 [255]
43 [255]
44 $ hg st
44 $ hg st
45 A a
45 A a
46 A b
46 A b
47 ? con.xml
47 ? con.xml
48 $ hg add con.xml
48 $ hg add con.xml
49 warning: filename contains 'con', which is reserved on Windows: 'con.xml'
49 warning: filename contains 'con', which is reserved on Windows: 'con.xml'
50 $ hg st
50 $ hg st
51 A a
51 A a
52 A b
52 A b
53 A con.xml
53 A con.xml
54 $ hg forget con.xml
54 $ hg forget con.xml
55 $ rm con.xml
55 $ rm con.xml
56 #endif
56 #endif
57
57
58 #if eol-in-paths
58 #if eol-in-paths
59 $ echo bla > 'hello:world'
59 $ echo bla > 'hello:world'
60 $ hg --config ui.portablefilenames=abort add
60 $ hg --config ui.portablefilenames=abort add
61 adding hello:world
61 adding hello:world
62 abort: filename contains ':', which is reserved on Windows: 'hello:world'
62 abort: filename contains ':', which is reserved on Windows: 'hello:world'
63 [255]
63 [255]
64 $ hg st
64 $ hg st
65 A a
65 A a
66 A b
66 A b
67 ? hello:world
67 ? hello:world
68 $ hg --config ui.portablefilenames=ignore add
68 $ hg --config ui.portablefilenames=ignore add
69 adding hello:world
69 adding hello:world
70 $ hg st
70 $ hg st
71 A a
71 A a
72 A b
72 A b
73 A hello:world
73 A hello:world
74 #endif
74 #endif
75
75
76 $ hg ci -m 0 --traceback
76 $ hg ci -m 0 --traceback
77
77
78 should fail
78 should fail
79
79
80 $ hg add a
80 $ hg add a
81 a already tracked!
81 a already tracked!
82
82
83 $ echo aa > a
83 $ echo aa > a
84 $ hg ci -m 1
84 $ hg ci -m 1
85 $ hg up 0
85 $ hg up 0
86 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
86 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
87 $ echo aaa > a
87 $ echo aaa > a
88 $ hg ci -m 2
88 $ hg ci -m 2
89 created new head
89 created new head
90
90
91 $ hg merge
91 $ hg merge
92 merging a
92 merging a
93 warning: conflicts during merge.
93 warning: conflicts during merge.
94 merging a incomplete! (edit conflicts, then use 'hg resolve --mark')
94 merging a incomplete! (edit conflicts, then use 'hg resolve --mark')
95 0 files updated, 0 files merged, 0 files removed, 1 files unresolved
95 0 files updated, 0 files merged, 0 files removed, 1 files unresolved
96 use 'hg resolve' to retry unresolved file merges or 'hg update -C .' to abandon
96 use 'hg resolve' to retry unresolved file merges or 'hg update -C .' to abandon
97 [1]
97 [1]
98 $ hg st
98 $ hg st
99 M a
99 M a
100 ? a.orig
100 ? a.orig
101
101
102 should fail
102 should fail
103
103
104 $ hg add a
104 $ hg add a
105 a already tracked!
105 a already tracked!
106 $ hg st
106 $ hg st
107 M a
107 M a
108 ? a.orig
108 ? a.orig
109 $ hg resolve -m a
109 $ hg resolve -m a
110 (no more unresolved files)
110 (no more unresolved files)
111 $ hg ci -m merge
111 $ hg ci -m merge
112
112
113 Issue683: peculiarity with hg revert of an removed then added file
113 Issue683: peculiarity with hg revert of an removed then added file
114
114
115 $ hg forget a
115 $ hg forget a
116 $ hg add a
116 $ hg add a
117 $ hg st
117 $ hg st
118 ? a.orig
118 ? a.orig
119 $ hg rm a
119 $ hg rm a
120 $ hg st
120 $ hg st
121 R a
121 R a
122 ? a.orig
122 ? a.orig
123 $ echo a > a
123 $ echo a > a
124 $ hg add a
124 $ hg add a
125 $ hg st
125 $ hg st
126 M a
126 M a
127 ? a.orig
127 ? a.orig
128
128
129 Forgotten file can be added back (as either clean or modified)
130
131 $ hg forget b
132 $ hg add b
133 $ hg st -A b
134 C b
135 $ hg forget b
136 $ echo modified > b
137 $ hg add b
138 $ hg st -A b
139 M b
140 $ hg revert -qC b
141
129 $ hg add c && echo "unexpected addition of missing file"
142 $ hg add c && echo "unexpected addition of missing file"
130 c: * (glob)
143 c: * (glob)
131 [1]
144 [1]
132 $ echo c > c
145 $ echo c > c
133 $ hg add d c && echo "unexpected addition of missing file"
146 $ hg add d c && echo "unexpected addition of missing file"
134 d: * (glob)
147 d: * (glob)
135 [1]
148 [1]
136 $ hg st
149 $ hg st
137 M a
150 M a
138 A c
151 A c
139 ? a.orig
152 ? a.orig
140 $ hg up -C
153 $ hg up -C
141 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
142
155
143 forget and get should have the right order: added but missing dir should be
156 forget and get should have the right order: added but missing dir should be
144 forgotten before file with same name is added
157 forgotten before file with same name is added
145
158
146 $ echo file d > d
159 $ echo file d > d
147 $ hg add d
160 $ hg add d
148 $ hg ci -md
161 $ hg ci -md
149 $ hg rm d
162 $ hg rm d
150 $ mkdir d
163 $ mkdir d
151 $ echo a > d/a
164 $ echo a > d/a
152 $ hg add d/a
165 $ hg add d/a
153 $ rm -r d
166 $ rm -r d
154 $ hg up -C
167 $ hg up -C
155 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
168 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
156 $ cat d
169 $ cat d
157 file d
170 file d
158
171
159 $ cd ..
172 $ cd ..
General Comments 0
You need to be logged in to leave comments. Login now