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