##// END OF EJS Templates
i18n: add "i18n" comment to column positioning messages of "hg log"...
FUJIWARA Katsunori -
r17891:8f85151c stable
parent child Browse files
Show More
@@ -1,2002 +1,2019
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 subrepo, context, repair, bookmarks, graphmod, revset, phases, obsolete
13 import subrepo, context, repair, bookmarks, graphmod, revset, phases, obsolete
14 import changelog
14 import changelog
15 import lock as lockmod
15 import lock as lockmod
16
16
17 def parsealiases(cmd):
17 def parsealiases(cmd):
18 return cmd.lstrip("^").split("|")
18 return cmd.lstrip("^").split("|")
19
19
20 def findpossible(cmd, table, strict=False):
20 def findpossible(cmd, table, strict=False):
21 """
21 """
22 Return cmd -> (aliases, command table entry)
22 Return cmd -> (aliases, command table entry)
23 for each matching command.
23 for each matching command.
24 Return debug commands (or their aliases) only if no normal command matches.
24 Return debug commands (or their aliases) only if no normal command matches.
25 """
25 """
26 choice = {}
26 choice = {}
27 debugchoice = {}
27 debugchoice = {}
28
28
29 if cmd in table:
29 if cmd in table:
30 # short-circuit exact matches, "log" alias beats "^log|history"
30 # short-circuit exact matches, "log" alias beats "^log|history"
31 keys = [cmd]
31 keys = [cmd]
32 else:
32 else:
33 keys = table.keys()
33 keys = table.keys()
34
34
35 for e in keys:
35 for e in keys:
36 aliases = parsealiases(e)
36 aliases = parsealiases(e)
37 found = None
37 found = None
38 if cmd in aliases:
38 if cmd in aliases:
39 found = cmd
39 found = cmd
40 elif not strict:
40 elif not strict:
41 for a in aliases:
41 for a in aliases:
42 if a.startswith(cmd):
42 if a.startswith(cmd):
43 found = a
43 found = a
44 break
44 break
45 if found is not None:
45 if found is not None:
46 if aliases[0].startswith("debug") or found.startswith("debug"):
46 if aliases[0].startswith("debug") or found.startswith("debug"):
47 debugchoice[found] = (aliases, table[e])
47 debugchoice[found] = (aliases, table[e])
48 else:
48 else:
49 choice[found] = (aliases, table[e])
49 choice[found] = (aliases, table[e])
50
50
51 if not choice and debugchoice:
51 if not choice and debugchoice:
52 choice = debugchoice
52 choice = debugchoice
53
53
54 return choice
54 return choice
55
55
56 def findcmd(cmd, table, strict=True):
56 def findcmd(cmd, table, strict=True):
57 """Return (aliases, command table entry) for command string."""
57 """Return (aliases, command table entry) for command string."""
58 choice = findpossible(cmd, table, strict)
58 choice = findpossible(cmd, table, strict)
59
59
60 if cmd in choice:
60 if cmd in choice:
61 return choice[cmd]
61 return choice[cmd]
62
62
63 if len(choice) > 1:
63 if len(choice) > 1:
64 clist = choice.keys()
64 clist = choice.keys()
65 clist.sort()
65 clist.sort()
66 raise error.AmbiguousCommand(cmd, clist)
66 raise error.AmbiguousCommand(cmd, clist)
67
67
68 if choice:
68 if choice:
69 return choice.values()[0]
69 return choice.values()[0]
70
70
71 raise error.UnknownCommand(cmd)
71 raise error.UnknownCommand(cmd)
72
72
73 def findrepo(p):
73 def findrepo(p):
74 while not os.path.isdir(os.path.join(p, ".hg")):
74 while not os.path.isdir(os.path.join(p, ".hg")):
75 oldp, p = p, os.path.dirname(p)
75 oldp, p = p, os.path.dirname(p)
76 if p == oldp:
76 if p == oldp:
77 return None
77 return None
78
78
79 return p
79 return p
80
80
81 def bailifchanged(repo):
81 def bailifchanged(repo):
82 if repo.dirstate.p2() != nullid:
82 if repo.dirstate.p2() != nullid:
83 raise util.Abort(_('outstanding uncommitted merge'))
83 raise util.Abort(_('outstanding uncommitted merge'))
84 modified, added, removed, deleted = repo.status()[:4]
84 modified, added, removed, deleted = repo.status()[:4]
85 if modified or added or removed or deleted:
85 if modified or added or removed or deleted:
86 raise util.Abort(_("outstanding uncommitted changes"))
86 raise util.Abort(_("outstanding uncommitted changes"))
87 ctx = repo[None]
87 ctx = repo[None]
88 for s in ctx.substate:
88 for s in ctx.substate:
89 if ctx.sub(s).dirty():
89 if ctx.sub(s).dirty():
90 raise util.Abort(_("uncommitted changes in subrepo %s") % s)
90 raise util.Abort(_("uncommitted changes in subrepo %s") % s)
91
91
92 def logmessage(ui, opts):
92 def logmessage(ui, opts):
93 """ get the log message according to -m and -l option """
93 """ get the log message according to -m and -l option """
94 message = opts.get('message')
94 message = opts.get('message')
95 logfile = opts.get('logfile')
95 logfile = opts.get('logfile')
96
96
97 if message and logfile:
97 if message and logfile:
98 raise util.Abort(_('options --message and --logfile are mutually '
98 raise util.Abort(_('options --message and --logfile are mutually '
99 'exclusive'))
99 'exclusive'))
100 if not message and logfile:
100 if not message and logfile:
101 try:
101 try:
102 if logfile == '-':
102 if logfile == '-':
103 message = ui.fin.read()
103 message = ui.fin.read()
104 else:
104 else:
105 message = '\n'.join(util.readfile(logfile).splitlines())
105 message = '\n'.join(util.readfile(logfile).splitlines())
106 except IOError, inst:
106 except IOError, inst:
107 raise util.Abort(_("can't read commit message '%s': %s") %
107 raise util.Abort(_("can't read commit message '%s': %s") %
108 (logfile, inst.strerror))
108 (logfile, inst.strerror))
109 return message
109 return message
110
110
111 def loglimit(opts):
111 def loglimit(opts):
112 """get the log limit according to option -l/--limit"""
112 """get the log limit according to option -l/--limit"""
113 limit = opts.get('limit')
113 limit = opts.get('limit')
114 if limit:
114 if limit:
115 try:
115 try:
116 limit = int(limit)
116 limit = int(limit)
117 except ValueError:
117 except ValueError:
118 raise util.Abort(_('limit must be a positive integer'))
118 raise util.Abort(_('limit must be a positive integer'))
119 if limit <= 0:
119 if limit <= 0:
120 raise util.Abort(_('limit must be positive'))
120 raise util.Abort(_('limit must be positive'))
121 else:
121 else:
122 limit = None
122 limit = None
123 return limit
123 return limit
124
124
125 def makefilename(repo, pat, node, desc=None,
125 def makefilename(repo, pat, node, desc=None,
126 total=None, seqno=None, revwidth=None, pathname=None):
126 total=None, seqno=None, revwidth=None, pathname=None):
127 node_expander = {
127 node_expander = {
128 'H': lambda: hex(node),
128 'H': lambda: hex(node),
129 'R': lambda: str(repo.changelog.rev(node)),
129 'R': lambda: str(repo.changelog.rev(node)),
130 'h': lambda: short(node),
130 'h': lambda: short(node),
131 'm': lambda: re.sub('[^\w]', '_', str(desc))
131 'm': lambda: re.sub('[^\w]', '_', str(desc))
132 }
132 }
133 expander = {
133 expander = {
134 '%': lambda: '%',
134 '%': lambda: '%',
135 'b': lambda: os.path.basename(repo.root),
135 'b': lambda: os.path.basename(repo.root),
136 }
136 }
137
137
138 try:
138 try:
139 if node:
139 if node:
140 expander.update(node_expander)
140 expander.update(node_expander)
141 if node:
141 if node:
142 expander['r'] = (lambda:
142 expander['r'] = (lambda:
143 str(repo.changelog.rev(node)).zfill(revwidth or 0))
143 str(repo.changelog.rev(node)).zfill(revwidth or 0))
144 if total is not None:
144 if total is not None:
145 expander['N'] = lambda: str(total)
145 expander['N'] = lambda: str(total)
146 if seqno is not None:
146 if seqno is not None:
147 expander['n'] = lambda: str(seqno)
147 expander['n'] = lambda: str(seqno)
148 if total is not None and seqno is not None:
148 if total is not None and seqno is not None:
149 expander['n'] = lambda: str(seqno).zfill(len(str(total)))
149 expander['n'] = lambda: str(seqno).zfill(len(str(total)))
150 if pathname is not None:
150 if pathname is not None:
151 expander['s'] = lambda: os.path.basename(pathname)
151 expander['s'] = lambda: os.path.basename(pathname)
152 expander['d'] = lambda: os.path.dirname(pathname) or '.'
152 expander['d'] = lambda: os.path.dirname(pathname) or '.'
153 expander['p'] = lambda: pathname
153 expander['p'] = lambda: pathname
154
154
155 newname = []
155 newname = []
156 patlen = len(pat)
156 patlen = len(pat)
157 i = 0
157 i = 0
158 while i < patlen:
158 while i < patlen:
159 c = pat[i]
159 c = pat[i]
160 if c == '%':
160 if c == '%':
161 i += 1
161 i += 1
162 c = pat[i]
162 c = pat[i]
163 c = expander[c]()
163 c = expander[c]()
164 newname.append(c)
164 newname.append(c)
165 i += 1
165 i += 1
166 return ''.join(newname)
166 return ''.join(newname)
167 except KeyError, inst:
167 except KeyError, inst:
168 raise util.Abort(_("invalid format spec '%%%s' in output filename") %
168 raise util.Abort(_("invalid format spec '%%%s' in output filename") %
169 inst.args[0])
169 inst.args[0])
170
170
171 def makefileobj(repo, pat, node=None, desc=None, total=None,
171 def makefileobj(repo, pat, node=None, desc=None, total=None,
172 seqno=None, revwidth=None, mode='wb', pathname=None):
172 seqno=None, revwidth=None, mode='wb', pathname=None):
173
173
174 writable = mode not in ('r', 'rb')
174 writable = mode not in ('r', 'rb')
175
175
176 if not pat or pat == '-':
176 if not pat or pat == '-':
177 fp = writable and repo.ui.fout or repo.ui.fin
177 fp = writable and repo.ui.fout or repo.ui.fin
178 if util.safehasattr(fp, 'fileno'):
178 if util.safehasattr(fp, 'fileno'):
179 return os.fdopen(os.dup(fp.fileno()), mode)
179 return os.fdopen(os.dup(fp.fileno()), mode)
180 else:
180 else:
181 # if this fp can't be duped properly, return
181 # if this fp can't be duped properly, return
182 # a dummy object that can be closed
182 # a dummy object that can be closed
183 class wrappedfileobj(object):
183 class wrappedfileobj(object):
184 noop = lambda x: None
184 noop = lambda x: None
185 def __init__(self, f):
185 def __init__(self, f):
186 self.f = f
186 self.f = f
187 def __getattr__(self, attr):
187 def __getattr__(self, attr):
188 if attr == 'close':
188 if attr == 'close':
189 return self.noop
189 return self.noop
190 else:
190 else:
191 return getattr(self.f, attr)
191 return getattr(self.f, attr)
192
192
193 return wrappedfileobj(fp)
193 return wrappedfileobj(fp)
194 if util.safehasattr(pat, 'write') and writable:
194 if util.safehasattr(pat, 'write') and writable:
195 return pat
195 return pat
196 if util.safehasattr(pat, 'read') and 'r' in mode:
196 if util.safehasattr(pat, 'read') and 'r' in mode:
197 return pat
197 return pat
198 return open(makefilename(repo, pat, node, desc, total, seqno, revwidth,
198 return open(makefilename(repo, pat, node, desc, total, seqno, revwidth,
199 pathname),
199 pathname),
200 mode)
200 mode)
201
201
202 def openrevlog(repo, cmd, file_, opts):
202 def openrevlog(repo, cmd, file_, opts):
203 """opens the changelog, manifest, a filelog or a given revlog"""
203 """opens the changelog, manifest, a filelog or a given revlog"""
204 cl = opts['changelog']
204 cl = opts['changelog']
205 mf = opts['manifest']
205 mf = opts['manifest']
206 msg = None
206 msg = None
207 if cl and mf:
207 if cl and mf:
208 msg = _('cannot specify --changelog and --manifest at the same time')
208 msg = _('cannot specify --changelog and --manifest at the same time')
209 elif cl or mf:
209 elif cl or mf:
210 if file_:
210 if file_:
211 msg = _('cannot specify filename with --changelog or --manifest')
211 msg = _('cannot specify filename with --changelog or --manifest')
212 elif not repo:
212 elif not repo:
213 msg = _('cannot specify --changelog or --manifest '
213 msg = _('cannot specify --changelog or --manifest '
214 'without a repository')
214 'without a repository')
215 if msg:
215 if msg:
216 raise util.Abort(msg)
216 raise util.Abort(msg)
217
217
218 r = None
218 r = None
219 if repo:
219 if repo:
220 if cl:
220 if cl:
221 r = repo.changelog
221 r = repo.changelog
222 elif mf:
222 elif mf:
223 r = repo.manifest
223 r = repo.manifest
224 elif file_:
224 elif file_:
225 filelog = repo.file(file_)
225 filelog = repo.file(file_)
226 if len(filelog):
226 if len(filelog):
227 r = filelog
227 r = filelog
228 if not r:
228 if not r:
229 if not file_:
229 if not file_:
230 raise error.CommandError(cmd, _('invalid arguments'))
230 raise error.CommandError(cmd, _('invalid arguments'))
231 if not os.path.isfile(file_):
231 if not os.path.isfile(file_):
232 raise util.Abort(_("revlog '%s' not found") % file_)
232 raise util.Abort(_("revlog '%s' not found") % file_)
233 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False),
233 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False),
234 file_[:-2] + ".i")
234 file_[:-2] + ".i")
235 return r
235 return r
236
236
237 def copy(ui, repo, pats, opts, rename=False):
237 def copy(ui, repo, pats, opts, rename=False):
238 # called with the repo lock held
238 # called with the repo lock held
239 #
239 #
240 # hgsep => pathname that uses "/" to separate directories
240 # hgsep => pathname that uses "/" to separate directories
241 # ossep => pathname that uses os.sep to separate directories
241 # ossep => pathname that uses os.sep to separate directories
242 cwd = repo.getcwd()
242 cwd = repo.getcwd()
243 targets = {}
243 targets = {}
244 after = opts.get("after")
244 after = opts.get("after")
245 dryrun = opts.get("dry_run")
245 dryrun = opts.get("dry_run")
246 wctx = repo[None]
246 wctx = repo[None]
247
247
248 def walkpat(pat):
248 def walkpat(pat):
249 srcs = []
249 srcs = []
250 badstates = after and '?' or '?r'
250 badstates = after and '?' or '?r'
251 m = scmutil.match(repo[None], [pat], opts, globbed=True)
251 m = scmutil.match(repo[None], [pat], opts, globbed=True)
252 for abs in repo.walk(m):
252 for abs in repo.walk(m):
253 state = repo.dirstate[abs]
253 state = repo.dirstate[abs]
254 rel = m.rel(abs)
254 rel = m.rel(abs)
255 exact = m.exact(abs)
255 exact = m.exact(abs)
256 if state in badstates:
256 if state in badstates:
257 if exact and state == '?':
257 if exact and state == '?':
258 ui.warn(_('%s: not copying - file is not managed\n') % rel)
258 ui.warn(_('%s: not copying - file is not managed\n') % rel)
259 if exact and state == 'r':
259 if exact and state == 'r':
260 ui.warn(_('%s: not copying - file has been marked for'
260 ui.warn(_('%s: not copying - file has been marked for'
261 ' remove\n') % rel)
261 ' remove\n') % rel)
262 continue
262 continue
263 # abs: hgsep
263 # abs: hgsep
264 # rel: ossep
264 # rel: ossep
265 srcs.append((abs, rel, exact))
265 srcs.append((abs, rel, exact))
266 return srcs
266 return srcs
267
267
268 # abssrc: hgsep
268 # abssrc: hgsep
269 # relsrc: ossep
269 # relsrc: ossep
270 # otarget: ossep
270 # otarget: ossep
271 def copyfile(abssrc, relsrc, otarget, exact):
271 def copyfile(abssrc, relsrc, otarget, exact):
272 abstarget = scmutil.canonpath(repo.root, cwd, otarget)
272 abstarget = scmutil.canonpath(repo.root, cwd, otarget)
273 if '/' in abstarget:
273 if '/' in abstarget:
274 # We cannot normalize abstarget itself, this would prevent
274 # We cannot normalize abstarget itself, this would prevent
275 # case only renames, like a => A.
275 # case only renames, like a => A.
276 abspath, absname = abstarget.rsplit('/', 1)
276 abspath, absname = abstarget.rsplit('/', 1)
277 abstarget = repo.dirstate.normalize(abspath) + '/' + absname
277 abstarget = repo.dirstate.normalize(abspath) + '/' + absname
278 reltarget = repo.pathto(abstarget, cwd)
278 reltarget = repo.pathto(abstarget, cwd)
279 target = repo.wjoin(abstarget)
279 target = repo.wjoin(abstarget)
280 src = repo.wjoin(abssrc)
280 src = repo.wjoin(abssrc)
281 state = repo.dirstate[abstarget]
281 state = repo.dirstate[abstarget]
282
282
283 scmutil.checkportable(ui, abstarget)
283 scmutil.checkportable(ui, abstarget)
284
284
285 # check for collisions
285 # check for collisions
286 prevsrc = targets.get(abstarget)
286 prevsrc = targets.get(abstarget)
287 if prevsrc is not None:
287 if prevsrc is not None:
288 ui.warn(_('%s: not overwriting - %s collides with %s\n') %
288 ui.warn(_('%s: not overwriting - %s collides with %s\n') %
289 (reltarget, repo.pathto(abssrc, cwd),
289 (reltarget, repo.pathto(abssrc, cwd),
290 repo.pathto(prevsrc, cwd)))
290 repo.pathto(prevsrc, cwd)))
291 return
291 return
292
292
293 # check for overwrites
293 # check for overwrites
294 exists = os.path.lexists(target)
294 exists = os.path.lexists(target)
295 samefile = False
295 samefile = False
296 if exists and abssrc != abstarget:
296 if exists and abssrc != abstarget:
297 if (repo.dirstate.normalize(abssrc) ==
297 if (repo.dirstate.normalize(abssrc) ==
298 repo.dirstate.normalize(abstarget)):
298 repo.dirstate.normalize(abstarget)):
299 if not rename:
299 if not rename:
300 ui.warn(_("%s: can't copy - same file\n") % reltarget)
300 ui.warn(_("%s: can't copy - same file\n") % reltarget)
301 return
301 return
302 exists = False
302 exists = False
303 samefile = True
303 samefile = True
304
304
305 if not after and exists or after and state in 'mn':
305 if not after and exists or after and state in 'mn':
306 if not opts['force']:
306 if not opts['force']:
307 ui.warn(_('%s: not overwriting - file exists\n') %
307 ui.warn(_('%s: not overwriting - file exists\n') %
308 reltarget)
308 reltarget)
309 return
309 return
310
310
311 if after:
311 if after:
312 if not exists:
312 if not exists:
313 if rename:
313 if rename:
314 ui.warn(_('%s: not recording move - %s does not exist\n') %
314 ui.warn(_('%s: not recording move - %s does not exist\n') %
315 (relsrc, reltarget))
315 (relsrc, reltarget))
316 else:
316 else:
317 ui.warn(_('%s: not recording copy - %s does not exist\n') %
317 ui.warn(_('%s: not recording copy - %s does not exist\n') %
318 (relsrc, reltarget))
318 (relsrc, reltarget))
319 return
319 return
320 elif not dryrun:
320 elif not dryrun:
321 try:
321 try:
322 if exists:
322 if exists:
323 os.unlink(target)
323 os.unlink(target)
324 targetdir = os.path.dirname(target) or '.'
324 targetdir = os.path.dirname(target) or '.'
325 if not os.path.isdir(targetdir):
325 if not os.path.isdir(targetdir):
326 os.makedirs(targetdir)
326 os.makedirs(targetdir)
327 if samefile:
327 if samefile:
328 tmp = target + "~hgrename"
328 tmp = target + "~hgrename"
329 os.rename(src, tmp)
329 os.rename(src, tmp)
330 os.rename(tmp, target)
330 os.rename(tmp, target)
331 else:
331 else:
332 util.copyfile(src, target)
332 util.copyfile(src, target)
333 srcexists = True
333 srcexists = True
334 except IOError, inst:
334 except IOError, inst:
335 if inst.errno == errno.ENOENT:
335 if inst.errno == errno.ENOENT:
336 ui.warn(_('%s: deleted in working copy\n') % relsrc)
336 ui.warn(_('%s: deleted in working copy\n') % relsrc)
337 srcexists = False
337 srcexists = False
338 else:
338 else:
339 ui.warn(_('%s: cannot copy - %s\n') %
339 ui.warn(_('%s: cannot copy - %s\n') %
340 (relsrc, inst.strerror))
340 (relsrc, inst.strerror))
341 return True # report a failure
341 return True # report a failure
342
342
343 if ui.verbose or not exact:
343 if ui.verbose or not exact:
344 if rename:
344 if rename:
345 ui.status(_('moving %s to %s\n') % (relsrc, reltarget))
345 ui.status(_('moving %s to %s\n') % (relsrc, reltarget))
346 else:
346 else:
347 ui.status(_('copying %s to %s\n') % (relsrc, reltarget))
347 ui.status(_('copying %s to %s\n') % (relsrc, reltarget))
348
348
349 targets[abstarget] = abssrc
349 targets[abstarget] = abssrc
350
350
351 # fix up dirstate
351 # fix up dirstate
352 scmutil.dirstatecopy(ui, repo, wctx, abssrc, abstarget,
352 scmutil.dirstatecopy(ui, repo, wctx, abssrc, abstarget,
353 dryrun=dryrun, cwd=cwd)
353 dryrun=dryrun, cwd=cwd)
354 if rename and not dryrun:
354 if rename and not dryrun:
355 if not after and srcexists and not samefile:
355 if not after and srcexists and not samefile:
356 util.unlinkpath(repo.wjoin(abssrc))
356 util.unlinkpath(repo.wjoin(abssrc))
357 wctx.forget([abssrc])
357 wctx.forget([abssrc])
358
358
359 # pat: ossep
359 # pat: ossep
360 # dest ossep
360 # dest ossep
361 # srcs: list of (hgsep, hgsep, ossep, bool)
361 # srcs: list of (hgsep, hgsep, ossep, bool)
362 # return: function that takes hgsep and returns ossep
362 # return: function that takes hgsep and returns ossep
363 def targetpathfn(pat, dest, srcs):
363 def targetpathfn(pat, dest, srcs):
364 if os.path.isdir(pat):
364 if os.path.isdir(pat):
365 abspfx = scmutil.canonpath(repo.root, cwd, pat)
365 abspfx = scmutil.canonpath(repo.root, cwd, pat)
366 abspfx = util.localpath(abspfx)
366 abspfx = util.localpath(abspfx)
367 if destdirexists:
367 if destdirexists:
368 striplen = len(os.path.split(abspfx)[0])
368 striplen = len(os.path.split(abspfx)[0])
369 else:
369 else:
370 striplen = len(abspfx)
370 striplen = len(abspfx)
371 if striplen:
371 if striplen:
372 striplen += len(os.sep)
372 striplen += len(os.sep)
373 res = lambda p: os.path.join(dest, util.localpath(p)[striplen:])
373 res = lambda p: os.path.join(dest, util.localpath(p)[striplen:])
374 elif destdirexists:
374 elif destdirexists:
375 res = lambda p: os.path.join(dest,
375 res = lambda p: os.path.join(dest,
376 os.path.basename(util.localpath(p)))
376 os.path.basename(util.localpath(p)))
377 else:
377 else:
378 res = lambda p: dest
378 res = lambda p: dest
379 return res
379 return res
380
380
381 # pat: ossep
381 # pat: ossep
382 # dest ossep
382 # dest ossep
383 # srcs: list of (hgsep, hgsep, ossep, bool)
383 # srcs: list of (hgsep, hgsep, ossep, bool)
384 # return: function that takes hgsep and returns ossep
384 # return: function that takes hgsep and returns ossep
385 def targetpathafterfn(pat, dest, srcs):
385 def targetpathafterfn(pat, dest, srcs):
386 if matchmod.patkind(pat):
386 if matchmod.patkind(pat):
387 # a mercurial pattern
387 # a mercurial pattern
388 res = lambda p: os.path.join(dest,
388 res = lambda p: os.path.join(dest,
389 os.path.basename(util.localpath(p)))
389 os.path.basename(util.localpath(p)))
390 else:
390 else:
391 abspfx = scmutil.canonpath(repo.root, cwd, pat)
391 abspfx = scmutil.canonpath(repo.root, cwd, pat)
392 if len(abspfx) < len(srcs[0][0]):
392 if len(abspfx) < len(srcs[0][0]):
393 # A directory. Either the target path contains the last
393 # A directory. Either the target path contains the last
394 # component of the source path or it does not.
394 # component of the source path or it does not.
395 def evalpath(striplen):
395 def evalpath(striplen):
396 score = 0
396 score = 0
397 for s in srcs:
397 for s in srcs:
398 t = os.path.join(dest, util.localpath(s[0])[striplen:])
398 t = os.path.join(dest, util.localpath(s[0])[striplen:])
399 if os.path.lexists(t):
399 if os.path.lexists(t):
400 score += 1
400 score += 1
401 return score
401 return score
402
402
403 abspfx = util.localpath(abspfx)
403 abspfx = util.localpath(abspfx)
404 striplen = len(abspfx)
404 striplen = len(abspfx)
405 if striplen:
405 if striplen:
406 striplen += len(os.sep)
406 striplen += len(os.sep)
407 if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])):
407 if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])):
408 score = evalpath(striplen)
408 score = evalpath(striplen)
409 striplen1 = len(os.path.split(abspfx)[0])
409 striplen1 = len(os.path.split(abspfx)[0])
410 if striplen1:
410 if striplen1:
411 striplen1 += len(os.sep)
411 striplen1 += len(os.sep)
412 if evalpath(striplen1) > score:
412 if evalpath(striplen1) > score:
413 striplen = striplen1
413 striplen = striplen1
414 res = lambda p: os.path.join(dest,
414 res = lambda p: os.path.join(dest,
415 util.localpath(p)[striplen:])
415 util.localpath(p)[striplen:])
416 else:
416 else:
417 # a file
417 # a file
418 if destdirexists:
418 if destdirexists:
419 res = lambda p: os.path.join(dest,
419 res = lambda p: os.path.join(dest,
420 os.path.basename(util.localpath(p)))
420 os.path.basename(util.localpath(p)))
421 else:
421 else:
422 res = lambda p: dest
422 res = lambda p: dest
423 return res
423 return res
424
424
425
425
426 pats = scmutil.expandpats(pats)
426 pats = scmutil.expandpats(pats)
427 if not pats:
427 if not pats:
428 raise util.Abort(_('no source or destination specified'))
428 raise util.Abort(_('no source or destination specified'))
429 if len(pats) == 1:
429 if len(pats) == 1:
430 raise util.Abort(_('no destination specified'))
430 raise util.Abort(_('no destination specified'))
431 dest = pats.pop()
431 dest = pats.pop()
432 destdirexists = os.path.isdir(dest) and not os.path.islink(dest)
432 destdirexists = os.path.isdir(dest) and not os.path.islink(dest)
433 if not destdirexists:
433 if not destdirexists:
434 if len(pats) > 1 or matchmod.patkind(pats[0]):
434 if len(pats) > 1 or matchmod.patkind(pats[0]):
435 raise util.Abort(_('with multiple sources, destination must be an '
435 raise util.Abort(_('with multiple sources, destination must be an '
436 'existing directory'))
436 'existing directory'))
437 if util.endswithsep(dest):
437 if util.endswithsep(dest):
438 raise util.Abort(_('destination %s is not a directory') % dest)
438 raise util.Abort(_('destination %s is not a directory') % dest)
439
439
440 tfn = targetpathfn
440 tfn = targetpathfn
441 if after:
441 if after:
442 tfn = targetpathafterfn
442 tfn = targetpathafterfn
443 copylist = []
443 copylist = []
444 for pat in pats:
444 for pat in pats:
445 srcs = walkpat(pat)
445 srcs = walkpat(pat)
446 if not srcs:
446 if not srcs:
447 continue
447 continue
448 copylist.append((tfn(pat, dest, srcs), srcs))
448 copylist.append((tfn(pat, dest, srcs), srcs))
449 if not copylist:
449 if not copylist:
450 raise util.Abort(_('no files to copy'))
450 raise util.Abort(_('no files to copy'))
451
451
452 errors = 0
452 errors = 0
453 for targetpath, srcs in copylist:
453 for targetpath, srcs in copylist:
454 for abssrc, relsrc, exact in srcs:
454 for abssrc, relsrc, exact in srcs:
455 if copyfile(abssrc, relsrc, targetpath(abssrc), exact):
455 if copyfile(abssrc, relsrc, targetpath(abssrc), exact):
456 errors += 1
456 errors += 1
457
457
458 if errors:
458 if errors:
459 ui.warn(_('(consider using --after)\n'))
459 ui.warn(_('(consider using --after)\n'))
460
460
461 return errors != 0
461 return errors != 0
462
462
463 def service(opts, parentfn=None, initfn=None, runfn=None, logfile=None,
463 def service(opts, parentfn=None, initfn=None, runfn=None, logfile=None,
464 runargs=None, appendpid=False):
464 runargs=None, appendpid=False):
465 '''Run a command as a service.'''
465 '''Run a command as a service.'''
466
466
467 if opts['daemon'] and not opts['daemon_pipefds']:
467 if opts['daemon'] and not opts['daemon_pipefds']:
468 # Signal child process startup with file removal
468 # Signal child process startup with file removal
469 lockfd, lockpath = tempfile.mkstemp(prefix='hg-service-')
469 lockfd, lockpath = tempfile.mkstemp(prefix='hg-service-')
470 os.close(lockfd)
470 os.close(lockfd)
471 try:
471 try:
472 if not runargs:
472 if not runargs:
473 runargs = util.hgcmd() + sys.argv[1:]
473 runargs = util.hgcmd() + sys.argv[1:]
474 runargs.append('--daemon-pipefds=%s' % lockpath)
474 runargs.append('--daemon-pipefds=%s' % lockpath)
475 # Don't pass --cwd to the child process, because we've already
475 # Don't pass --cwd to the child process, because we've already
476 # changed directory.
476 # changed directory.
477 for i in xrange(1, len(runargs)):
477 for i in xrange(1, len(runargs)):
478 if runargs[i].startswith('--cwd='):
478 if runargs[i].startswith('--cwd='):
479 del runargs[i]
479 del runargs[i]
480 break
480 break
481 elif runargs[i].startswith('--cwd'):
481 elif runargs[i].startswith('--cwd'):
482 del runargs[i:i + 2]
482 del runargs[i:i + 2]
483 break
483 break
484 def condfn():
484 def condfn():
485 return not os.path.exists(lockpath)
485 return not os.path.exists(lockpath)
486 pid = util.rundetached(runargs, condfn)
486 pid = util.rundetached(runargs, condfn)
487 if pid < 0:
487 if pid < 0:
488 raise util.Abort(_('child process failed to start'))
488 raise util.Abort(_('child process failed to start'))
489 finally:
489 finally:
490 try:
490 try:
491 os.unlink(lockpath)
491 os.unlink(lockpath)
492 except OSError, e:
492 except OSError, e:
493 if e.errno != errno.ENOENT:
493 if e.errno != errno.ENOENT:
494 raise
494 raise
495 if parentfn:
495 if parentfn:
496 return parentfn(pid)
496 return parentfn(pid)
497 else:
497 else:
498 return
498 return
499
499
500 if initfn:
500 if initfn:
501 initfn()
501 initfn()
502
502
503 if opts['pid_file']:
503 if opts['pid_file']:
504 mode = appendpid and 'a' or 'w'
504 mode = appendpid and 'a' or 'w'
505 fp = open(opts['pid_file'], mode)
505 fp = open(opts['pid_file'], mode)
506 fp.write(str(os.getpid()) + '\n')
506 fp.write(str(os.getpid()) + '\n')
507 fp.close()
507 fp.close()
508
508
509 if opts['daemon_pipefds']:
509 if opts['daemon_pipefds']:
510 lockpath = opts['daemon_pipefds']
510 lockpath = opts['daemon_pipefds']
511 try:
511 try:
512 os.setsid()
512 os.setsid()
513 except AttributeError:
513 except AttributeError:
514 pass
514 pass
515 os.unlink(lockpath)
515 os.unlink(lockpath)
516 util.hidewindow()
516 util.hidewindow()
517 sys.stdout.flush()
517 sys.stdout.flush()
518 sys.stderr.flush()
518 sys.stderr.flush()
519
519
520 nullfd = os.open(os.devnull, os.O_RDWR)
520 nullfd = os.open(os.devnull, os.O_RDWR)
521 logfilefd = nullfd
521 logfilefd = nullfd
522 if logfile:
522 if logfile:
523 logfilefd = os.open(logfile, os.O_RDWR | os.O_CREAT | os.O_APPEND)
523 logfilefd = os.open(logfile, os.O_RDWR | os.O_CREAT | os.O_APPEND)
524 os.dup2(nullfd, 0)
524 os.dup2(nullfd, 0)
525 os.dup2(logfilefd, 1)
525 os.dup2(logfilefd, 1)
526 os.dup2(logfilefd, 2)
526 os.dup2(logfilefd, 2)
527 if nullfd not in (0, 1, 2):
527 if nullfd not in (0, 1, 2):
528 os.close(nullfd)
528 os.close(nullfd)
529 if logfile and logfilefd not in (0, 1, 2):
529 if logfile and logfilefd not in (0, 1, 2):
530 os.close(logfilefd)
530 os.close(logfilefd)
531
531
532 if runfn:
532 if runfn:
533 return runfn()
533 return runfn()
534
534
535 def export(repo, revs, template='hg-%h.patch', fp=None, switch_parent=False,
535 def export(repo, revs, template='hg-%h.patch', fp=None, switch_parent=False,
536 opts=None):
536 opts=None):
537 '''export changesets as hg patches.'''
537 '''export changesets as hg patches.'''
538
538
539 total = len(revs)
539 total = len(revs)
540 revwidth = max([len(str(rev)) for rev in revs])
540 revwidth = max([len(str(rev)) for rev in revs])
541
541
542 def single(rev, seqno, fp):
542 def single(rev, seqno, fp):
543 ctx = repo[rev]
543 ctx = repo[rev]
544 node = ctx.node()
544 node = ctx.node()
545 parents = [p.node() for p in ctx.parents() if p]
545 parents = [p.node() for p in ctx.parents() if p]
546 branch = ctx.branch()
546 branch = ctx.branch()
547 if switch_parent:
547 if switch_parent:
548 parents.reverse()
548 parents.reverse()
549 prev = (parents and parents[0]) or nullid
549 prev = (parents and parents[0]) or nullid
550
550
551 shouldclose = False
551 shouldclose = False
552 if not fp and len(template) > 0:
552 if not fp and len(template) > 0:
553 desc_lines = ctx.description().rstrip().split('\n')
553 desc_lines = ctx.description().rstrip().split('\n')
554 desc = desc_lines[0] #Commit always has a first line.
554 desc = desc_lines[0] #Commit always has a first line.
555 fp = makefileobj(repo, template, node, desc=desc, total=total,
555 fp = makefileobj(repo, template, node, desc=desc, total=total,
556 seqno=seqno, revwidth=revwidth, mode='ab')
556 seqno=seqno, revwidth=revwidth, mode='ab')
557 if fp != template:
557 if fp != template:
558 shouldclose = True
558 shouldclose = True
559 if fp and fp != sys.stdout and util.safehasattr(fp, 'name'):
559 if fp and fp != sys.stdout and util.safehasattr(fp, 'name'):
560 repo.ui.note("%s\n" % fp.name)
560 repo.ui.note("%s\n" % fp.name)
561
561
562 if not fp:
562 if not fp:
563 write = repo.ui.write
563 write = repo.ui.write
564 else:
564 else:
565 def write(s, **kw):
565 def write(s, **kw):
566 fp.write(s)
566 fp.write(s)
567
567
568
568
569 write("# HG changeset patch\n")
569 write("# HG changeset patch\n")
570 write("# User %s\n" % ctx.user())
570 write("# User %s\n" % ctx.user())
571 write("# Date %d %d\n" % ctx.date())
571 write("# Date %d %d\n" % ctx.date())
572 if branch and branch != 'default':
572 if branch and branch != 'default':
573 write("# Branch %s\n" % branch)
573 write("# Branch %s\n" % branch)
574 write("# Node ID %s\n" % hex(node))
574 write("# Node ID %s\n" % hex(node))
575 write("# Parent %s\n" % hex(prev))
575 write("# Parent %s\n" % hex(prev))
576 if len(parents) > 1:
576 if len(parents) > 1:
577 write("# Parent %s\n" % hex(parents[1]))
577 write("# Parent %s\n" % hex(parents[1]))
578 write(ctx.description().rstrip())
578 write(ctx.description().rstrip())
579 write("\n\n")
579 write("\n\n")
580
580
581 for chunk, label in patch.diffui(repo, prev, node, opts=opts):
581 for chunk, label in patch.diffui(repo, prev, node, opts=opts):
582 write(chunk, label=label)
582 write(chunk, label=label)
583
583
584 if shouldclose:
584 if shouldclose:
585 fp.close()
585 fp.close()
586
586
587 for seqno, rev in enumerate(revs):
587 for seqno, rev in enumerate(revs):
588 single(rev, seqno + 1, fp)
588 single(rev, seqno + 1, fp)
589
589
590 def diffordiffstat(ui, repo, diffopts, node1, node2, match,
590 def diffordiffstat(ui, repo, diffopts, node1, node2, match,
591 changes=None, stat=False, fp=None, prefix='',
591 changes=None, stat=False, fp=None, prefix='',
592 listsubrepos=False):
592 listsubrepos=False):
593 '''show diff or diffstat.'''
593 '''show diff or diffstat.'''
594 if fp is None:
594 if fp is None:
595 write = ui.write
595 write = ui.write
596 else:
596 else:
597 def write(s, **kw):
597 def write(s, **kw):
598 fp.write(s)
598 fp.write(s)
599
599
600 if stat:
600 if stat:
601 diffopts = diffopts.copy(context=0)
601 diffopts = diffopts.copy(context=0)
602 width = 80
602 width = 80
603 if not ui.plain():
603 if not ui.plain():
604 width = ui.termwidth()
604 width = ui.termwidth()
605 chunks = patch.diff(repo, node1, node2, match, changes, diffopts,
605 chunks = patch.diff(repo, node1, node2, match, changes, diffopts,
606 prefix=prefix)
606 prefix=prefix)
607 for chunk, label in patch.diffstatui(util.iterlines(chunks),
607 for chunk, label in patch.diffstatui(util.iterlines(chunks),
608 width=width,
608 width=width,
609 git=diffopts.git):
609 git=diffopts.git):
610 write(chunk, label=label)
610 write(chunk, label=label)
611 else:
611 else:
612 for chunk, label in patch.diffui(repo, node1, node2, match,
612 for chunk, label in patch.diffui(repo, node1, node2, match,
613 changes, diffopts, prefix=prefix):
613 changes, diffopts, prefix=prefix):
614 write(chunk, label=label)
614 write(chunk, label=label)
615
615
616 if listsubrepos:
616 if listsubrepos:
617 ctx1 = repo[node1]
617 ctx1 = repo[node1]
618 ctx2 = repo[node2]
618 ctx2 = repo[node2]
619 for subpath, sub in subrepo.itersubrepos(ctx1, ctx2):
619 for subpath, sub in subrepo.itersubrepos(ctx1, ctx2):
620 tempnode2 = node2
620 tempnode2 = node2
621 try:
621 try:
622 if node2 is not None:
622 if node2 is not None:
623 tempnode2 = ctx2.substate[subpath][1]
623 tempnode2 = ctx2.substate[subpath][1]
624 except KeyError:
624 except KeyError:
625 # A subrepo that existed in node1 was deleted between node1 and
625 # A subrepo that existed in node1 was deleted between node1 and
626 # node2 (inclusive). Thus, ctx2's substate won't contain that
626 # node2 (inclusive). Thus, ctx2's substate won't contain that
627 # subpath. The best we can do is to ignore it.
627 # subpath. The best we can do is to ignore it.
628 tempnode2 = None
628 tempnode2 = None
629 submatch = matchmod.narrowmatcher(subpath, match)
629 submatch = matchmod.narrowmatcher(subpath, match)
630 sub.diff(diffopts, tempnode2, submatch, changes=changes,
630 sub.diff(diffopts, tempnode2, submatch, changes=changes,
631 stat=stat, fp=fp, prefix=prefix)
631 stat=stat, fp=fp, prefix=prefix)
632
632
633 class changeset_printer(object):
633 class changeset_printer(object):
634 '''show changeset information when templating not requested.'''
634 '''show changeset information when templating not requested.'''
635
635
636 def __init__(self, ui, repo, patch, diffopts, buffered):
636 def __init__(self, ui, repo, patch, diffopts, buffered):
637 self.ui = ui
637 self.ui = ui
638 self.repo = repo
638 self.repo = repo
639 self.buffered = buffered
639 self.buffered = buffered
640 self.patch = patch
640 self.patch = patch
641 self.diffopts = diffopts
641 self.diffopts = diffopts
642 self.header = {}
642 self.header = {}
643 self.hunk = {}
643 self.hunk = {}
644 self.lastheader = None
644 self.lastheader = None
645 self.footer = None
645 self.footer = None
646
646
647 def flush(self, rev):
647 def flush(self, rev):
648 if rev in self.header:
648 if rev in self.header:
649 h = self.header[rev]
649 h = self.header[rev]
650 if h != self.lastheader:
650 if h != self.lastheader:
651 self.lastheader = h
651 self.lastheader = h
652 self.ui.write(h)
652 self.ui.write(h)
653 del self.header[rev]
653 del self.header[rev]
654 if rev in self.hunk:
654 if rev in self.hunk:
655 self.ui.write(self.hunk[rev])
655 self.ui.write(self.hunk[rev])
656 del self.hunk[rev]
656 del self.hunk[rev]
657 return 1
657 return 1
658 return 0
658 return 0
659
659
660 def close(self):
660 def close(self):
661 if self.footer:
661 if self.footer:
662 self.ui.write(self.footer)
662 self.ui.write(self.footer)
663
663
664 def show(self, ctx, copies=None, matchfn=None, **props):
664 def show(self, ctx, copies=None, matchfn=None, **props):
665 if self.buffered:
665 if self.buffered:
666 self.ui.pushbuffer()
666 self.ui.pushbuffer()
667 self._show(ctx, copies, matchfn, props)
667 self._show(ctx, copies, matchfn, props)
668 self.hunk[ctx.rev()] = self.ui.popbuffer(labeled=True)
668 self.hunk[ctx.rev()] = self.ui.popbuffer(labeled=True)
669 else:
669 else:
670 self._show(ctx, copies, matchfn, props)
670 self._show(ctx, copies, matchfn, props)
671
671
672 def _show(self, ctx, copies, matchfn, props):
672 def _show(self, ctx, copies, matchfn, props):
673 '''show a single changeset or file revision'''
673 '''show a single changeset or file revision'''
674 changenode = ctx.node()
674 changenode = ctx.node()
675 rev = ctx.rev()
675 rev = ctx.rev()
676
676
677 if self.ui.quiet:
677 if self.ui.quiet:
678 self.ui.write("%d:%s\n" % (rev, short(changenode)),
678 self.ui.write("%d:%s\n" % (rev, short(changenode)),
679 label='log.node')
679 label='log.node')
680 return
680 return
681
681
682 log = self.repo.changelog
682 log = self.repo.changelog
683 date = util.datestr(ctx.date())
683 date = util.datestr(ctx.date())
684
684
685 hexfunc = self.ui.debugflag and hex or short
685 hexfunc = self.ui.debugflag and hex or short
686
686
687 parents = [(p, hexfunc(log.node(p)))
687 parents = [(p, hexfunc(log.node(p)))
688 for p in self._meaningful_parentrevs(log, rev)]
688 for p in self._meaningful_parentrevs(log, rev)]
689
689
690 # i18n: column positioning for "hg log"
690 self.ui.write(_("changeset: %d:%s\n") % (rev, hexfunc(changenode)),
691 self.ui.write(_("changeset: %d:%s\n") % (rev, hexfunc(changenode)),
691 label='log.changeset changeset.%s' % ctx.phasestr())
692 label='log.changeset changeset.%s' % ctx.phasestr())
692
693
693 branch = ctx.branch()
694 branch = ctx.branch()
694 # don't show the default branch name
695 # don't show the default branch name
695 if branch != 'default':
696 if branch != 'default':
697 # i18n: column positioning for "hg log"
696 self.ui.write(_("branch: %s\n") % branch,
698 self.ui.write(_("branch: %s\n") % branch,
697 label='log.branch')
699 label='log.branch')
698 for bookmark in self.repo.nodebookmarks(changenode):
700 for bookmark in self.repo.nodebookmarks(changenode):
701 # i18n: column positioning for "hg log"
699 self.ui.write(_("bookmark: %s\n") % bookmark,
702 self.ui.write(_("bookmark: %s\n") % bookmark,
700 label='log.bookmark')
703 label='log.bookmark')
701 for tag in self.repo.nodetags(changenode):
704 for tag in self.repo.nodetags(changenode):
705 # i18n: column positioning for "hg log"
702 self.ui.write(_("tag: %s\n") % tag,
706 self.ui.write(_("tag: %s\n") % tag,
703 label='log.tag')
707 label='log.tag')
704 if self.ui.debugflag and ctx.phase():
708 if self.ui.debugflag and ctx.phase():
709 # i18n: column positioning for "hg log"
705 self.ui.write(_("phase: %s\n") % _(ctx.phasestr()),
710 self.ui.write(_("phase: %s\n") % _(ctx.phasestr()),
706 label='log.phase')
711 label='log.phase')
707 for parent in parents:
712 for parent in parents:
713 # i18n: column positioning for "hg log"
708 self.ui.write(_("parent: %d:%s\n") % parent,
714 self.ui.write(_("parent: %d:%s\n") % parent,
709 label='log.parent changeset.%s' % ctx.phasestr())
715 label='log.parent changeset.%s' % ctx.phasestr())
710
716
711 if self.ui.debugflag:
717 if self.ui.debugflag:
712 mnode = ctx.manifestnode()
718 mnode = ctx.manifestnode()
719 # i18n: column positioning for "hg log"
713 self.ui.write(_("manifest: %d:%s\n") %
720 self.ui.write(_("manifest: %d:%s\n") %
714 (self.repo.manifest.rev(mnode), hex(mnode)),
721 (self.repo.manifest.rev(mnode), hex(mnode)),
715 label='ui.debug log.manifest')
722 label='ui.debug log.manifest')
723 # i18n: column positioning for "hg log"
716 self.ui.write(_("user: %s\n") % ctx.user(),
724 self.ui.write(_("user: %s\n") % ctx.user(),
717 label='log.user')
725 label='log.user')
726 # i18n: column positioning for "hg log"
718 self.ui.write(_("date: %s\n") % date,
727 self.ui.write(_("date: %s\n") % date,
719 label='log.date')
728 label='log.date')
720
729
721 if self.ui.debugflag:
730 if self.ui.debugflag:
722 files = self.repo.status(log.parents(changenode)[0], changenode)[:3]
731 files = self.repo.status(log.parents(changenode)[0], changenode)[:3]
723 for key, value in zip([_("files:"), _("files+:"), _("files-:")],
732 for key, value in zip([# i18n: column positioning for "hg log"
724 files):
733 _("files:"),
734 # i18n: column positioning for "hg log"
735 _("files+:"),
736 # i18n: column positioning for "hg log"
737 _("files-:")], files):
725 if value:
738 if value:
726 self.ui.write("%-12s %s\n" % (key, " ".join(value)),
739 self.ui.write("%-12s %s\n" % (key, " ".join(value)),
727 label='ui.debug log.files')
740 label='ui.debug log.files')
728 elif ctx.files() and self.ui.verbose:
741 elif ctx.files() and self.ui.verbose:
742 # i18n: column positioning for "hg log"
729 self.ui.write(_("files: %s\n") % " ".join(ctx.files()),
743 self.ui.write(_("files: %s\n") % " ".join(ctx.files()),
730 label='ui.note log.files')
744 label='ui.note log.files')
731 if copies and self.ui.verbose:
745 if copies and self.ui.verbose:
732 copies = ['%s (%s)' % c for c in copies]
746 copies = ['%s (%s)' % c for c in copies]
747 # i18n: column positioning for "hg log"
733 self.ui.write(_("copies: %s\n") % ' '.join(copies),
748 self.ui.write(_("copies: %s\n") % ' '.join(copies),
734 label='ui.note log.copies')
749 label='ui.note log.copies')
735
750
736 extra = ctx.extra()
751 extra = ctx.extra()
737 if extra and self.ui.debugflag:
752 if extra and self.ui.debugflag:
738 for key, value in sorted(extra.items()):
753 for key, value in sorted(extra.items()):
754 # i18n: column positioning for "hg log"
739 self.ui.write(_("extra: %s=%s\n")
755 self.ui.write(_("extra: %s=%s\n")
740 % (key, value.encode('string_escape')),
756 % (key, value.encode('string_escape')),
741 label='ui.debug log.extra')
757 label='ui.debug log.extra')
742
758
743 description = ctx.description().strip()
759 description = ctx.description().strip()
744 if description:
760 if description:
745 if self.ui.verbose:
761 if self.ui.verbose:
746 self.ui.write(_("description:\n"),
762 self.ui.write(_("description:\n"),
747 label='ui.note log.description')
763 label='ui.note log.description')
748 self.ui.write(description,
764 self.ui.write(description,
749 label='ui.note log.description')
765 label='ui.note log.description')
750 self.ui.write("\n\n")
766 self.ui.write("\n\n")
751 else:
767 else:
768 # i18n: column positioning for "hg log"
752 self.ui.write(_("summary: %s\n") %
769 self.ui.write(_("summary: %s\n") %
753 description.splitlines()[0],
770 description.splitlines()[0],
754 label='log.summary')
771 label='log.summary')
755 self.ui.write("\n")
772 self.ui.write("\n")
756
773
757 self.showpatch(changenode, matchfn)
774 self.showpatch(changenode, matchfn)
758
775
759 def showpatch(self, node, matchfn):
776 def showpatch(self, node, matchfn):
760 if not matchfn:
777 if not matchfn:
761 matchfn = self.patch
778 matchfn = self.patch
762 if matchfn:
779 if matchfn:
763 stat = self.diffopts.get('stat')
780 stat = self.diffopts.get('stat')
764 diff = self.diffopts.get('patch')
781 diff = self.diffopts.get('patch')
765 diffopts = patch.diffopts(self.ui, self.diffopts)
782 diffopts = patch.diffopts(self.ui, self.diffopts)
766 prev = self.repo.changelog.parents(node)[0]
783 prev = self.repo.changelog.parents(node)[0]
767 if stat:
784 if stat:
768 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
785 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
769 match=matchfn, stat=True)
786 match=matchfn, stat=True)
770 if diff:
787 if diff:
771 if stat:
788 if stat:
772 self.ui.write("\n")
789 self.ui.write("\n")
773 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
790 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
774 match=matchfn, stat=False)
791 match=matchfn, stat=False)
775 self.ui.write("\n")
792 self.ui.write("\n")
776
793
777 def _meaningful_parentrevs(self, log, rev):
794 def _meaningful_parentrevs(self, log, rev):
778 """Return list of meaningful (or all if debug) parentrevs for rev.
795 """Return list of meaningful (or all if debug) parentrevs for rev.
779
796
780 For merges (two non-nullrev revisions) both parents are meaningful.
797 For merges (two non-nullrev revisions) both parents are meaningful.
781 Otherwise the first parent revision is considered meaningful if it
798 Otherwise the first parent revision is considered meaningful if it
782 is not the preceding revision.
799 is not the preceding revision.
783 """
800 """
784 parents = log.parentrevs(rev)
801 parents = log.parentrevs(rev)
785 if not self.ui.debugflag and parents[1] == nullrev:
802 if not self.ui.debugflag and parents[1] == nullrev:
786 if parents[0] >= rev - 1:
803 if parents[0] >= rev - 1:
787 parents = []
804 parents = []
788 else:
805 else:
789 parents = [parents[0]]
806 parents = [parents[0]]
790 return parents
807 return parents
791
808
792
809
793 class changeset_templater(changeset_printer):
810 class changeset_templater(changeset_printer):
794 '''format changeset information.'''
811 '''format changeset information.'''
795
812
796 def __init__(self, ui, repo, patch, diffopts, mapfile, buffered):
813 def __init__(self, ui, repo, patch, diffopts, mapfile, buffered):
797 changeset_printer.__init__(self, ui, repo, patch, diffopts, buffered)
814 changeset_printer.__init__(self, ui, repo, patch, diffopts, buffered)
798 formatnode = ui.debugflag and (lambda x: x) or (lambda x: x[:12])
815 formatnode = ui.debugflag and (lambda x: x) or (lambda x: x[:12])
799 defaulttempl = {
816 defaulttempl = {
800 'parent': '{rev}:{node|formatnode} ',
817 'parent': '{rev}:{node|formatnode} ',
801 'manifest': '{rev}:{node|formatnode}',
818 'manifest': '{rev}:{node|formatnode}',
802 'file_copy': '{name} ({source})',
819 'file_copy': '{name} ({source})',
803 'extra': '{key}={value|stringescape}'
820 'extra': '{key}={value|stringescape}'
804 }
821 }
805 # filecopy is preserved for compatibility reasons
822 # filecopy is preserved for compatibility reasons
806 defaulttempl['filecopy'] = defaulttempl['file_copy']
823 defaulttempl['filecopy'] = defaulttempl['file_copy']
807 self.t = templater.templater(mapfile, {'formatnode': formatnode},
824 self.t = templater.templater(mapfile, {'formatnode': formatnode},
808 cache=defaulttempl)
825 cache=defaulttempl)
809 self.cache = {}
826 self.cache = {}
810
827
811 def use_template(self, t):
828 def use_template(self, t):
812 '''set template string to use'''
829 '''set template string to use'''
813 self.t.cache['changeset'] = t
830 self.t.cache['changeset'] = t
814
831
815 def _meaningful_parentrevs(self, ctx):
832 def _meaningful_parentrevs(self, ctx):
816 """Return list of meaningful (or all if debug) parentrevs for rev.
833 """Return list of meaningful (or all if debug) parentrevs for rev.
817 """
834 """
818 parents = ctx.parents()
835 parents = ctx.parents()
819 if len(parents) > 1:
836 if len(parents) > 1:
820 return parents
837 return parents
821 if self.ui.debugflag:
838 if self.ui.debugflag:
822 return [parents[0], self.repo['null']]
839 return [parents[0], self.repo['null']]
823 if parents[0].rev() >= ctx.rev() - 1:
840 if parents[0].rev() >= ctx.rev() - 1:
824 return []
841 return []
825 return parents
842 return parents
826
843
827 def _show(self, ctx, copies, matchfn, props):
844 def _show(self, ctx, copies, matchfn, props):
828 '''show a single changeset or file revision'''
845 '''show a single changeset or file revision'''
829
846
830 showlist = templatekw.showlist
847 showlist = templatekw.showlist
831
848
832 # showparents() behaviour depends on ui trace level which
849 # showparents() behaviour depends on ui trace level which
833 # causes unexpected behaviours at templating level and makes
850 # causes unexpected behaviours at templating level and makes
834 # it harder to extract it in a standalone function. Its
851 # it harder to extract it in a standalone function. Its
835 # behaviour cannot be changed so leave it here for now.
852 # behaviour cannot be changed so leave it here for now.
836 def showparents(**args):
853 def showparents(**args):
837 ctx = args['ctx']
854 ctx = args['ctx']
838 parents = [[('rev', p.rev()), ('node', p.hex())]
855 parents = [[('rev', p.rev()), ('node', p.hex())]
839 for p in self._meaningful_parentrevs(ctx)]
856 for p in self._meaningful_parentrevs(ctx)]
840 return showlist('parent', parents, **args)
857 return showlist('parent', parents, **args)
841
858
842 props = props.copy()
859 props = props.copy()
843 props.update(templatekw.keywords)
860 props.update(templatekw.keywords)
844 props['parents'] = showparents
861 props['parents'] = showparents
845 props['templ'] = self.t
862 props['templ'] = self.t
846 props['ctx'] = ctx
863 props['ctx'] = ctx
847 props['repo'] = self.repo
864 props['repo'] = self.repo
848 props['revcache'] = {'copies': copies}
865 props['revcache'] = {'copies': copies}
849 props['cache'] = self.cache
866 props['cache'] = self.cache
850
867
851 # find correct templates for current mode
868 # find correct templates for current mode
852
869
853 tmplmodes = [
870 tmplmodes = [
854 (True, None),
871 (True, None),
855 (self.ui.verbose, 'verbose'),
872 (self.ui.verbose, 'verbose'),
856 (self.ui.quiet, 'quiet'),
873 (self.ui.quiet, 'quiet'),
857 (self.ui.debugflag, 'debug'),
874 (self.ui.debugflag, 'debug'),
858 ]
875 ]
859
876
860 types = {'header': '', 'footer':'', 'changeset': 'changeset'}
877 types = {'header': '', 'footer':'', 'changeset': 'changeset'}
861 for mode, postfix in tmplmodes:
878 for mode, postfix in tmplmodes:
862 for type in types:
879 for type in types:
863 cur = postfix and ('%s_%s' % (type, postfix)) or type
880 cur = postfix and ('%s_%s' % (type, postfix)) or type
864 if mode and cur in self.t:
881 if mode and cur in self.t:
865 types[type] = cur
882 types[type] = cur
866
883
867 try:
884 try:
868
885
869 # write header
886 # write header
870 if types['header']:
887 if types['header']:
871 h = templater.stringify(self.t(types['header'], **props))
888 h = templater.stringify(self.t(types['header'], **props))
872 if self.buffered:
889 if self.buffered:
873 self.header[ctx.rev()] = h
890 self.header[ctx.rev()] = h
874 else:
891 else:
875 if self.lastheader != h:
892 if self.lastheader != h:
876 self.lastheader = h
893 self.lastheader = h
877 self.ui.write(h)
894 self.ui.write(h)
878
895
879 # write changeset metadata, then patch if requested
896 # write changeset metadata, then patch if requested
880 key = types['changeset']
897 key = types['changeset']
881 self.ui.write(templater.stringify(self.t(key, **props)))
898 self.ui.write(templater.stringify(self.t(key, **props)))
882 self.showpatch(ctx.node(), matchfn)
899 self.showpatch(ctx.node(), matchfn)
883
900
884 if types['footer']:
901 if types['footer']:
885 if not self.footer:
902 if not self.footer:
886 self.footer = templater.stringify(self.t(types['footer'],
903 self.footer = templater.stringify(self.t(types['footer'],
887 **props))
904 **props))
888
905
889 except KeyError, inst:
906 except KeyError, inst:
890 msg = _("%s: no key named '%s'")
907 msg = _("%s: no key named '%s'")
891 raise util.Abort(msg % (self.t.mapfile, inst.args[0]))
908 raise util.Abort(msg % (self.t.mapfile, inst.args[0]))
892 except SyntaxError, inst:
909 except SyntaxError, inst:
893 raise util.Abort('%s: %s' % (self.t.mapfile, inst.args[0]))
910 raise util.Abort('%s: %s' % (self.t.mapfile, inst.args[0]))
894
911
895 def show_changeset(ui, repo, opts, buffered=False):
912 def show_changeset(ui, repo, opts, buffered=False):
896 """show one changeset using template or regular display.
913 """show one changeset using template or regular display.
897
914
898 Display format will be the first non-empty hit of:
915 Display format will be the first non-empty hit of:
899 1. option 'template'
916 1. option 'template'
900 2. option 'style'
917 2. option 'style'
901 3. [ui] setting 'logtemplate'
918 3. [ui] setting 'logtemplate'
902 4. [ui] setting 'style'
919 4. [ui] setting 'style'
903 If all of these values are either the unset or the empty string,
920 If all of these values are either the unset or the empty string,
904 regular display via changeset_printer() is done.
921 regular display via changeset_printer() is done.
905 """
922 """
906 # options
923 # options
907 patch = False
924 patch = False
908 if opts.get('patch') or opts.get('stat'):
925 if opts.get('patch') or opts.get('stat'):
909 patch = scmutil.matchall(repo)
926 patch = scmutil.matchall(repo)
910
927
911 tmpl = opts.get('template')
928 tmpl = opts.get('template')
912 style = None
929 style = None
913 if tmpl:
930 if tmpl:
914 tmpl = templater.parsestring(tmpl, quoted=False)
931 tmpl = templater.parsestring(tmpl, quoted=False)
915 else:
932 else:
916 style = opts.get('style')
933 style = opts.get('style')
917
934
918 # ui settings
935 # ui settings
919 if not (tmpl or style):
936 if not (tmpl or style):
920 tmpl = ui.config('ui', 'logtemplate')
937 tmpl = ui.config('ui', 'logtemplate')
921 if tmpl:
938 if tmpl:
922 try:
939 try:
923 tmpl = templater.parsestring(tmpl)
940 tmpl = templater.parsestring(tmpl)
924 except SyntaxError:
941 except SyntaxError:
925 tmpl = templater.parsestring(tmpl, quoted=False)
942 tmpl = templater.parsestring(tmpl, quoted=False)
926 else:
943 else:
927 style = util.expandpath(ui.config('ui', 'style', ''))
944 style = util.expandpath(ui.config('ui', 'style', ''))
928
945
929 if not (tmpl or style):
946 if not (tmpl or style):
930 return changeset_printer(ui, repo, patch, opts, buffered)
947 return changeset_printer(ui, repo, patch, opts, buffered)
931
948
932 mapfile = None
949 mapfile = None
933 if style and not tmpl:
950 if style and not tmpl:
934 mapfile = style
951 mapfile = style
935 if not os.path.split(mapfile)[0]:
952 if not os.path.split(mapfile)[0]:
936 mapname = (templater.templatepath('map-cmdline.' + mapfile)
953 mapname = (templater.templatepath('map-cmdline.' + mapfile)
937 or templater.templatepath(mapfile))
954 or templater.templatepath(mapfile))
938 if mapname:
955 if mapname:
939 mapfile = mapname
956 mapfile = mapname
940
957
941 try:
958 try:
942 t = changeset_templater(ui, repo, patch, opts, mapfile, buffered)
959 t = changeset_templater(ui, repo, patch, opts, mapfile, buffered)
943 except SyntaxError, inst:
960 except SyntaxError, inst:
944 raise util.Abort(inst.args[0])
961 raise util.Abort(inst.args[0])
945 if tmpl:
962 if tmpl:
946 t.use_template(tmpl)
963 t.use_template(tmpl)
947 return t
964 return t
948
965
949 def finddate(ui, repo, date):
966 def finddate(ui, repo, date):
950 """Find the tipmost changeset that matches the given date spec"""
967 """Find the tipmost changeset that matches the given date spec"""
951
968
952 df = util.matchdate(date)
969 df = util.matchdate(date)
953 m = scmutil.matchall(repo)
970 m = scmutil.matchall(repo)
954 results = {}
971 results = {}
955
972
956 def prep(ctx, fns):
973 def prep(ctx, fns):
957 d = ctx.date()
974 d = ctx.date()
958 if df(d[0]):
975 if df(d[0]):
959 results[ctx.rev()] = d
976 results[ctx.rev()] = d
960
977
961 for ctx in walkchangerevs(repo, m, {'rev': None}, prep):
978 for ctx in walkchangerevs(repo, m, {'rev': None}, prep):
962 rev = ctx.rev()
979 rev = ctx.rev()
963 if rev in results:
980 if rev in results:
964 ui.status(_("found revision %s from %s\n") %
981 ui.status(_("found revision %s from %s\n") %
965 (rev, util.datestr(results[rev])))
982 (rev, util.datestr(results[rev])))
966 return str(rev)
983 return str(rev)
967
984
968 raise util.Abort(_("revision matching date not found"))
985 raise util.Abort(_("revision matching date not found"))
969
986
970 def increasingwindows(start, end, windowsize=8, sizelimit=512):
987 def increasingwindows(start, end, windowsize=8, sizelimit=512):
971 if start < end:
988 if start < end:
972 while start < end:
989 while start < end:
973 yield start, min(windowsize, end - start)
990 yield start, min(windowsize, end - start)
974 start += windowsize
991 start += windowsize
975 if windowsize < sizelimit:
992 if windowsize < sizelimit:
976 windowsize *= 2
993 windowsize *= 2
977 else:
994 else:
978 while start > end:
995 while start > end:
979 yield start, min(windowsize, start - end - 1)
996 yield start, min(windowsize, start - end - 1)
980 start -= windowsize
997 start -= windowsize
981 if windowsize < sizelimit:
998 if windowsize < sizelimit:
982 windowsize *= 2
999 windowsize *= 2
983
1000
984 def walkchangerevs(repo, match, opts, prepare):
1001 def walkchangerevs(repo, match, opts, prepare):
985 '''Iterate over files and the revs in which they changed.
1002 '''Iterate over files and the revs in which they changed.
986
1003
987 Callers most commonly need to iterate backwards over the history
1004 Callers most commonly need to iterate backwards over the history
988 in which they are interested. Doing so has awful (quadratic-looking)
1005 in which they are interested. Doing so has awful (quadratic-looking)
989 performance, so we use iterators in a "windowed" way.
1006 performance, so we use iterators in a "windowed" way.
990
1007
991 We walk a window of revisions in the desired order. Within the
1008 We walk a window of revisions in the desired order. Within the
992 window, we first walk forwards to gather data, then in the desired
1009 window, we first walk forwards to gather data, then in the desired
993 order (usually backwards) to display it.
1010 order (usually backwards) to display it.
994
1011
995 This function returns an iterator yielding contexts. Before
1012 This function returns an iterator yielding contexts. Before
996 yielding each context, the iterator will first call the prepare
1013 yielding each context, the iterator will first call the prepare
997 function on each context in the window in forward order.'''
1014 function on each context in the window in forward order.'''
998
1015
999 follow = opts.get('follow') or opts.get('follow_first')
1016 follow = opts.get('follow') or opts.get('follow_first')
1000
1017
1001 if not len(repo):
1018 if not len(repo):
1002 return []
1019 return []
1003 if opts.get('rev'):
1020 if opts.get('rev'):
1004 revs = scmutil.revrange(repo, opts.get('rev'))
1021 revs = scmutil.revrange(repo, opts.get('rev'))
1005 elif follow:
1022 elif follow:
1006 revs = repo.revs('reverse(:.)')
1023 revs = repo.revs('reverse(:.)')
1007 else:
1024 else:
1008 revs = list(repo)
1025 revs = list(repo)
1009 revs.reverse()
1026 revs.reverse()
1010 if not revs:
1027 if not revs:
1011 return []
1028 return []
1012 wanted = set()
1029 wanted = set()
1013 slowpath = match.anypats() or (match.files() and opts.get('removed'))
1030 slowpath = match.anypats() or (match.files() and opts.get('removed'))
1014 fncache = {}
1031 fncache = {}
1015 change = repo.changectx
1032 change = repo.changectx
1016
1033
1017 # First step is to fill wanted, the set of revisions that we want to yield.
1034 # First step is to fill wanted, the set of revisions that we want to yield.
1018 # When it does not induce extra cost, we also fill fncache for revisions in
1035 # When it does not induce extra cost, we also fill fncache for revisions in
1019 # wanted: a cache of filenames that were changed (ctx.files()) and that
1036 # wanted: a cache of filenames that were changed (ctx.files()) and that
1020 # match the file filtering conditions.
1037 # match the file filtering conditions.
1021
1038
1022 if not slowpath and not match.files():
1039 if not slowpath and not match.files():
1023 # No files, no patterns. Display all revs.
1040 # No files, no patterns. Display all revs.
1024 wanted = set(revs)
1041 wanted = set(revs)
1025 copies = []
1042 copies = []
1026
1043
1027 if not slowpath and match.files():
1044 if not slowpath and match.files():
1028 # We only have to read through the filelog to find wanted revisions
1045 # We only have to read through the filelog to find wanted revisions
1029
1046
1030 minrev, maxrev = min(revs), max(revs)
1047 minrev, maxrev = min(revs), max(revs)
1031 def filerevgen(filelog, last):
1048 def filerevgen(filelog, last):
1032 """
1049 """
1033 Only files, no patterns. Check the history of each file.
1050 Only files, no patterns. Check the history of each file.
1034
1051
1035 Examines filelog entries within minrev, maxrev linkrev range
1052 Examines filelog entries within minrev, maxrev linkrev range
1036 Returns an iterator yielding (linkrev, parentlinkrevs, copied)
1053 Returns an iterator yielding (linkrev, parentlinkrevs, copied)
1037 tuples in backwards order
1054 tuples in backwards order
1038 """
1055 """
1039 cl_count = len(repo)
1056 cl_count = len(repo)
1040 revs = []
1057 revs = []
1041 for j in xrange(0, last + 1):
1058 for j in xrange(0, last + 1):
1042 linkrev = filelog.linkrev(j)
1059 linkrev = filelog.linkrev(j)
1043 if linkrev < minrev:
1060 if linkrev < minrev:
1044 continue
1061 continue
1045 # only yield rev for which we have the changelog, it can
1062 # only yield rev for which we have the changelog, it can
1046 # happen while doing "hg log" during a pull or commit
1063 # happen while doing "hg log" during a pull or commit
1047 if linkrev >= cl_count:
1064 if linkrev >= cl_count:
1048 break
1065 break
1049
1066
1050 parentlinkrevs = []
1067 parentlinkrevs = []
1051 for p in filelog.parentrevs(j):
1068 for p in filelog.parentrevs(j):
1052 if p != nullrev:
1069 if p != nullrev:
1053 parentlinkrevs.append(filelog.linkrev(p))
1070 parentlinkrevs.append(filelog.linkrev(p))
1054 n = filelog.node(j)
1071 n = filelog.node(j)
1055 revs.append((linkrev, parentlinkrevs,
1072 revs.append((linkrev, parentlinkrevs,
1056 follow and filelog.renamed(n)))
1073 follow and filelog.renamed(n)))
1057
1074
1058 return reversed(revs)
1075 return reversed(revs)
1059 def iterfiles():
1076 def iterfiles():
1060 pctx = repo['.']
1077 pctx = repo['.']
1061 for filename in match.files():
1078 for filename in match.files():
1062 if follow:
1079 if follow:
1063 if filename not in pctx:
1080 if filename not in pctx:
1064 raise util.Abort(_('cannot follow file not in parent '
1081 raise util.Abort(_('cannot follow file not in parent '
1065 'revision: "%s"') % filename)
1082 'revision: "%s"') % filename)
1066 yield filename, pctx[filename].filenode()
1083 yield filename, pctx[filename].filenode()
1067 else:
1084 else:
1068 yield filename, None
1085 yield filename, None
1069 for filename_node in copies:
1086 for filename_node in copies:
1070 yield filename_node
1087 yield filename_node
1071 for file_, node in iterfiles():
1088 for file_, node in iterfiles():
1072 filelog = repo.file(file_)
1089 filelog = repo.file(file_)
1073 if not len(filelog):
1090 if not len(filelog):
1074 if node is None:
1091 if node is None:
1075 # A zero count may be a directory or deleted file, so
1092 # A zero count may be a directory or deleted file, so
1076 # try to find matching entries on the slow path.
1093 # try to find matching entries on the slow path.
1077 if follow:
1094 if follow:
1078 raise util.Abort(
1095 raise util.Abort(
1079 _('cannot follow nonexistent file: "%s"') % file_)
1096 _('cannot follow nonexistent file: "%s"') % file_)
1080 slowpath = True
1097 slowpath = True
1081 break
1098 break
1082 else:
1099 else:
1083 continue
1100 continue
1084
1101
1085 if node is None:
1102 if node is None:
1086 last = len(filelog) - 1
1103 last = len(filelog) - 1
1087 else:
1104 else:
1088 last = filelog.rev(node)
1105 last = filelog.rev(node)
1089
1106
1090
1107
1091 # keep track of all ancestors of the file
1108 # keep track of all ancestors of the file
1092 ancestors = set([filelog.linkrev(last)])
1109 ancestors = set([filelog.linkrev(last)])
1093
1110
1094 # iterate from latest to oldest revision
1111 # iterate from latest to oldest revision
1095 for rev, flparentlinkrevs, copied in filerevgen(filelog, last):
1112 for rev, flparentlinkrevs, copied in filerevgen(filelog, last):
1096 if not follow:
1113 if not follow:
1097 if rev > maxrev:
1114 if rev > maxrev:
1098 continue
1115 continue
1099 else:
1116 else:
1100 # Note that last might not be the first interesting
1117 # Note that last might not be the first interesting
1101 # rev to us:
1118 # rev to us:
1102 # if the file has been changed after maxrev, we'll
1119 # if the file has been changed after maxrev, we'll
1103 # have linkrev(last) > maxrev, and we still need
1120 # have linkrev(last) > maxrev, and we still need
1104 # to explore the file graph
1121 # to explore the file graph
1105 if rev not in ancestors:
1122 if rev not in ancestors:
1106 continue
1123 continue
1107 # XXX insert 1327 fix here
1124 # XXX insert 1327 fix here
1108 if flparentlinkrevs:
1125 if flparentlinkrevs:
1109 ancestors.update(flparentlinkrevs)
1126 ancestors.update(flparentlinkrevs)
1110
1127
1111 fncache.setdefault(rev, []).append(file_)
1128 fncache.setdefault(rev, []).append(file_)
1112 wanted.add(rev)
1129 wanted.add(rev)
1113 if copied:
1130 if copied:
1114 copies.append(copied)
1131 copies.append(copied)
1115
1132
1116 # We decided to fall back to the slowpath because at least one
1133 # We decided to fall back to the slowpath because at least one
1117 # of the paths was not a file. Check to see if at least one of them
1134 # of the paths was not a file. Check to see if at least one of them
1118 # existed in history, otherwise simply return
1135 # existed in history, otherwise simply return
1119 if slowpath:
1136 if slowpath:
1120 for path in match.files():
1137 for path in match.files():
1121 if path == '.' or path in repo.store:
1138 if path == '.' or path in repo.store:
1122 break
1139 break
1123 else:
1140 else:
1124 return []
1141 return []
1125
1142
1126 if slowpath:
1143 if slowpath:
1127 # We have to read the changelog to match filenames against
1144 # We have to read the changelog to match filenames against
1128 # changed files
1145 # changed files
1129
1146
1130 if follow:
1147 if follow:
1131 raise util.Abort(_('can only follow copies/renames for explicit '
1148 raise util.Abort(_('can only follow copies/renames for explicit '
1132 'filenames'))
1149 'filenames'))
1133
1150
1134 # The slow path checks files modified in every changeset.
1151 # The slow path checks files modified in every changeset.
1135 for i in sorted(revs):
1152 for i in sorted(revs):
1136 ctx = change(i)
1153 ctx = change(i)
1137 matches = filter(match, ctx.files())
1154 matches = filter(match, ctx.files())
1138 if matches:
1155 if matches:
1139 fncache[i] = matches
1156 fncache[i] = matches
1140 wanted.add(i)
1157 wanted.add(i)
1141
1158
1142 class followfilter(object):
1159 class followfilter(object):
1143 def __init__(self, onlyfirst=False):
1160 def __init__(self, onlyfirst=False):
1144 self.startrev = nullrev
1161 self.startrev = nullrev
1145 self.roots = set()
1162 self.roots = set()
1146 self.onlyfirst = onlyfirst
1163 self.onlyfirst = onlyfirst
1147
1164
1148 def match(self, rev):
1165 def match(self, rev):
1149 def realparents(rev):
1166 def realparents(rev):
1150 if self.onlyfirst:
1167 if self.onlyfirst:
1151 return repo.changelog.parentrevs(rev)[0:1]
1168 return repo.changelog.parentrevs(rev)[0:1]
1152 else:
1169 else:
1153 return filter(lambda x: x != nullrev,
1170 return filter(lambda x: x != nullrev,
1154 repo.changelog.parentrevs(rev))
1171 repo.changelog.parentrevs(rev))
1155
1172
1156 if self.startrev == nullrev:
1173 if self.startrev == nullrev:
1157 self.startrev = rev
1174 self.startrev = rev
1158 return True
1175 return True
1159
1176
1160 if rev > self.startrev:
1177 if rev > self.startrev:
1161 # forward: all descendants
1178 # forward: all descendants
1162 if not self.roots:
1179 if not self.roots:
1163 self.roots.add(self.startrev)
1180 self.roots.add(self.startrev)
1164 for parent in realparents(rev):
1181 for parent in realparents(rev):
1165 if parent in self.roots:
1182 if parent in self.roots:
1166 self.roots.add(rev)
1183 self.roots.add(rev)
1167 return True
1184 return True
1168 else:
1185 else:
1169 # backwards: all parents
1186 # backwards: all parents
1170 if not self.roots:
1187 if not self.roots:
1171 self.roots.update(realparents(self.startrev))
1188 self.roots.update(realparents(self.startrev))
1172 if rev in self.roots:
1189 if rev in self.roots:
1173 self.roots.remove(rev)
1190 self.roots.remove(rev)
1174 self.roots.update(realparents(rev))
1191 self.roots.update(realparents(rev))
1175 return True
1192 return True
1176
1193
1177 return False
1194 return False
1178
1195
1179 # it might be worthwhile to do this in the iterator if the rev range
1196 # it might be worthwhile to do this in the iterator if the rev range
1180 # is descending and the prune args are all within that range
1197 # is descending and the prune args are all within that range
1181 for rev in opts.get('prune', ()):
1198 for rev in opts.get('prune', ()):
1182 rev = repo[rev].rev()
1199 rev = repo[rev].rev()
1183 ff = followfilter()
1200 ff = followfilter()
1184 stop = min(revs[0], revs[-1])
1201 stop = min(revs[0], revs[-1])
1185 for x in xrange(rev, stop - 1, -1):
1202 for x in xrange(rev, stop - 1, -1):
1186 if ff.match(x):
1203 if ff.match(x):
1187 wanted.discard(x)
1204 wanted.discard(x)
1188
1205
1189 # Now that wanted is correctly initialized, we can iterate over the
1206 # Now that wanted is correctly initialized, we can iterate over the
1190 # revision range, yielding only revisions in wanted.
1207 # revision range, yielding only revisions in wanted.
1191 def iterate():
1208 def iterate():
1192 if follow and not match.files():
1209 if follow and not match.files():
1193 ff = followfilter(onlyfirst=opts.get('follow_first'))
1210 ff = followfilter(onlyfirst=opts.get('follow_first'))
1194 def want(rev):
1211 def want(rev):
1195 return ff.match(rev) and rev in wanted
1212 return ff.match(rev) and rev in wanted
1196 else:
1213 else:
1197 def want(rev):
1214 def want(rev):
1198 return rev in wanted
1215 return rev in wanted
1199
1216
1200 for i, window in increasingwindows(0, len(revs)):
1217 for i, window in increasingwindows(0, len(revs)):
1201 nrevs = [rev for rev in revs[i:i + window] if want(rev)]
1218 nrevs = [rev for rev in revs[i:i + window] if want(rev)]
1202 for rev in sorted(nrevs):
1219 for rev in sorted(nrevs):
1203 fns = fncache.get(rev)
1220 fns = fncache.get(rev)
1204 ctx = change(rev)
1221 ctx = change(rev)
1205 if not fns:
1222 if not fns:
1206 def fns_generator():
1223 def fns_generator():
1207 for f in ctx.files():
1224 for f in ctx.files():
1208 if match(f):
1225 if match(f):
1209 yield f
1226 yield f
1210 fns = fns_generator()
1227 fns = fns_generator()
1211 prepare(ctx, fns)
1228 prepare(ctx, fns)
1212 for rev in nrevs:
1229 for rev in nrevs:
1213 yield change(rev)
1230 yield change(rev)
1214 return iterate()
1231 return iterate()
1215
1232
1216 def _makegraphfilematcher(repo, pats, followfirst):
1233 def _makegraphfilematcher(repo, pats, followfirst):
1217 # When displaying a revision with --patch --follow FILE, we have
1234 # When displaying a revision with --patch --follow FILE, we have
1218 # to know which file of the revision must be diffed. With
1235 # to know which file of the revision must be diffed. With
1219 # --follow, we want the names of the ancestors of FILE in the
1236 # --follow, we want the names of the ancestors of FILE in the
1220 # revision, stored in "fcache". "fcache" is populated by
1237 # revision, stored in "fcache". "fcache" is populated by
1221 # reproducing the graph traversal already done by --follow revset
1238 # reproducing the graph traversal already done by --follow revset
1222 # and relating linkrevs to file names (which is not "correct" but
1239 # and relating linkrevs to file names (which is not "correct" but
1223 # good enough).
1240 # good enough).
1224 fcache = {}
1241 fcache = {}
1225 fcacheready = [False]
1242 fcacheready = [False]
1226 pctx = repo['.']
1243 pctx = repo['.']
1227 wctx = repo[None]
1244 wctx = repo[None]
1228
1245
1229 def populate():
1246 def populate():
1230 for fn in pats:
1247 for fn in pats:
1231 for i in ((pctx[fn],), pctx[fn].ancestors(followfirst=followfirst)):
1248 for i in ((pctx[fn],), pctx[fn].ancestors(followfirst=followfirst)):
1232 for c in i:
1249 for c in i:
1233 fcache.setdefault(c.linkrev(), set()).add(c.path())
1250 fcache.setdefault(c.linkrev(), set()).add(c.path())
1234
1251
1235 def filematcher(rev):
1252 def filematcher(rev):
1236 if not fcacheready[0]:
1253 if not fcacheready[0]:
1237 # Lazy initialization
1254 # Lazy initialization
1238 fcacheready[0] = True
1255 fcacheready[0] = True
1239 populate()
1256 populate()
1240 return scmutil.match(wctx, fcache.get(rev, []), default='path')
1257 return scmutil.match(wctx, fcache.get(rev, []), default='path')
1241
1258
1242 return filematcher
1259 return filematcher
1243
1260
1244 def _makegraphlogrevset(repo, pats, opts, revs):
1261 def _makegraphlogrevset(repo, pats, opts, revs):
1245 """Return (expr, filematcher) where expr is a revset string built
1262 """Return (expr, filematcher) where expr is a revset string built
1246 from log options and file patterns or None. If --stat or --patch
1263 from log options and file patterns or None. If --stat or --patch
1247 are not passed filematcher is None. Otherwise it is a callable
1264 are not passed filematcher is None. Otherwise it is a callable
1248 taking a revision number and returning a match objects filtering
1265 taking a revision number and returning a match objects filtering
1249 the files to be detailed when displaying the revision.
1266 the files to be detailed when displaying the revision.
1250 """
1267 """
1251 opt2revset = {
1268 opt2revset = {
1252 'no_merges': ('not merge()', None),
1269 'no_merges': ('not merge()', None),
1253 'only_merges': ('merge()', None),
1270 'only_merges': ('merge()', None),
1254 '_ancestors': ('ancestors(%(val)s)', None),
1271 '_ancestors': ('ancestors(%(val)s)', None),
1255 '_fancestors': ('_firstancestors(%(val)s)', None),
1272 '_fancestors': ('_firstancestors(%(val)s)', None),
1256 '_descendants': ('descendants(%(val)s)', None),
1273 '_descendants': ('descendants(%(val)s)', None),
1257 '_fdescendants': ('_firstdescendants(%(val)s)', None),
1274 '_fdescendants': ('_firstdescendants(%(val)s)', None),
1258 '_matchfiles': ('_matchfiles(%(val)s)', None),
1275 '_matchfiles': ('_matchfiles(%(val)s)', None),
1259 'date': ('date(%(val)r)', None),
1276 'date': ('date(%(val)r)', None),
1260 'branch': ('branch(%(val)r)', ' or '),
1277 'branch': ('branch(%(val)r)', ' or '),
1261 '_patslog': ('filelog(%(val)r)', ' or '),
1278 '_patslog': ('filelog(%(val)r)', ' or '),
1262 '_patsfollow': ('follow(%(val)r)', ' or '),
1279 '_patsfollow': ('follow(%(val)r)', ' or '),
1263 '_patsfollowfirst': ('_followfirst(%(val)r)', ' or '),
1280 '_patsfollowfirst': ('_followfirst(%(val)r)', ' or '),
1264 'keyword': ('keyword(%(val)r)', ' or '),
1281 'keyword': ('keyword(%(val)r)', ' or '),
1265 'prune': ('not (%(val)r or ancestors(%(val)r))', ' and '),
1282 'prune': ('not (%(val)r or ancestors(%(val)r))', ' and '),
1266 'user': ('user(%(val)r)', ' or '),
1283 'user': ('user(%(val)r)', ' or '),
1267 }
1284 }
1268
1285
1269 opts = dict(opts)
1286 opts = dict(opts)
1270 # follow or not follow?
1287 # follow or not follow?
1271 follow = opts.get('follow') or opts.get('follow_first')
1288 follow = opts.get('follow') or opts.get('follow_first')
1272 followfirst = opts.get('follow_first') and 1 or 0
1289 followfirst = opts.get('follow_first') and 1 or 0
1273 # --follow with FILE behaviour depends on revs...
1290 # --follow with FILE behaviour depends on revs...
1274 startrev = revs[0]
1291 startrev = revs[0]
1275 followdescendants = (len(revs) > 1 and revs[0] < revs[1]) and 1 or 0
1292 followdescendants = (len(revs) > 1 and revs[0] < revs[1]) and 1 or 0
1276
1293
1277 # branch and only_branch are really aliases and must be handled at
1294 # branch and only_branch are really aliases and must be handled at
1278 # the same time
1295 # the same time
1279 opts['branch'] = opts.get('branch', []) + opts.get('only_branch', [])
1296 opts['branch'] = opts.get('branch', []) + opts.get('only_branch', [])
1280 opts['branch'] = [repo.lookupbranch(b) for b in opts['branch']]
1297 opts['branch'] = [repo.lookupbranch(b) for b in opts['branch']]
1281 # pats/include/exclude are passed to match.match() directly in
1298 # pats/include/exclude are passed to match.match() directly in
1282 # _matchfiles() revset but walkchangerevs() builds its matcher with
1299 # _matchfiles() revset but walkchangerevs() builds its matcher with
1283 # scmutil.match(). The difference is input pats are globbed on
1300 # scmutil.match(). The difference is input pats are globbed on
1284 # platforms without shell expansion (windows).
1301 # platforms without shell expansion (windows).
1285 pctx = repo[None]
1302 pctx = repo[None]
1286 match, pats = scmutil.matchandpats(pctx, pats, opts)
1303 match, pats = scmutil.matchandpats(pctx, pats, opts)
1287 slowpath = match.anypats() or (match.files() and opts.get('removed'))
1304 slowpath = match.anypats() or (match.files() and opts.get('removed'))
1288 if not slowpath:
1305 if not slowpath:
1289 for f in match.files():
1306 for f in match.files():
1290 if follow and f not in pctx:
1307 if follow and f not in pctx:
1291 raise util.Abort(_('cannot follow file not in parent '
1308 raise util.Abort(_('cannot follow file not in parent '
1292 'revision: "%s"') % f)
1309 'revision: "%s"') % f)
1293 filelog = repo.file(f)
1310 filelog = repo.file(f)
1294 if not len(filelog):
1311 if not len(filelog):
1295 # A zero count may be a directory or deleted file, so
1312 # A zero count may be a directory or deleted file, so
1296 # try to find matching entries on the slow path.
1313 # try to find matching entries on the slow path.
1297 if follow:
1314 if follow:
1298 raise util.Abort(
1315 raise util.Abort(
1299 _('cannot follow nonexistent file: "%s"') % f)
1316 _('cannot follow nonexistent file: "%s"') % f)
1300 slowpath = True
1317 slowpath = True
1301
1318
1302 # We decided to fall back to the slowpath because at least one
1319 # We decided to fall back to the slowpath because at least one
1303 # of the paths was not a file. Check to see if at least one of them
1320 # of the paths was not a file. Check to see if at least one of them
1304 # existed in history - in that case, we'll continue down the
1321 # existed in history - in that case, we'll continue down the
1305 # slowpath; otherwise, we can turn off the slowpath
1322 # slowpath; otherwise, we can turn off the slowpath
1306 if slowpath:
1323 if slowpath:
1307 for path in match.files():
1324 for path in match.files():
1308 if path == '.' or path in repo.store:
1325 if path == '.' or path in repo.store:
1309 break
1326 break
1310 else:
1327 else:
1311 slowpath = False
1328 slowpath = False
1312
1329
1313 if slowpath:
1330 if slowpath:
1314 # See walkchangerevs() slow path.
1331 # See walkchangerevs() slow path.
1315 #
1332 #
1316 if follow:
1333 if follow:
1317 raise util.Abort(_('can only follow copies/renames for explicit '
1334 raise util.Abort(_('can only follow copies/renames for explicit '
1318 'filenames'))
1335 'filenames'))
1319 # pats/include/exclude cannot be represented as separate
1336 # pats/include/exclude cannot be represented as separate
1320 # revset expressions as their filtering logic applies at file
1337 # revset expressions as their filtering logic applies at file
1321 # level. For instance "-I a -X a" matches a revision touching
1338 # level. For instance "-I a -X a" matches a revision touching
1322 # "a" and "b" while "file(a) and not file(b)" does
1339 # "a" and "b" while "file(a) and not file(b)" does
1323 # not. Besides, filesets are evaluated against the working
1340 # not. Besides, filesets are evaluated against the working
1324 # directory.
1341 # directory.
1325 matchargs = ['r:', 'd:relpath']
1342 matchargs = ['r:', 'd:relpath']
1326 for p in pats:
1343 for p in pats:
1327 matchargs.append('p:' + p)
1344 matchargs.append('p:' + p)
1328 for p in opts.get('include', []):
1345 for p in opts.get('include', []):
1329 matchargs.append('i:' + p)
1346 matchargs.append('i:' + p)
1330 for p in opts.get('exclude', []):
1347 for p in opts.get('exclude', []):
1331 matchargs.append('x:' + p)
1348 matchargs.append('x:' + p)
1332 matchargs = ','.join(('%r' % p) for p in matchargs)
1349 matchargs = ','.join(('%r' % p) for p in matchargs)
1333 opts['_matchfiles'] = matchargs
1350 opts['_matchfiles'] = matchargs
1334 else:
1351 else:
1335 if follow:
1352 if follow:
1336 fpats = ('_patsfollow', '_patsfollowfirst')
1353 fpats = ('_patsfollow', '_patsfollowfirst')
1337 fnopats = (('_ancestors', '_fancestors'),
1354 fnopats = (('_ancestors', '_fancestors'),
1338 ('_descendants', '_fdescendants'))
1355 ('_descendants', '_fdescendants'))
1339 if pats:
1356 if pats:
1340 # follow() revset interprets its file argument as a
1357 # follow() revset interprets its file argument as a
1341 # manifest entry, so use match.files(), not pats.
1358 # manifest entry, so use match.files(), not pats.
1342 opts[fpats[followfirst]] = list(match.files())
1359 opts[fpats[followfirst]] = list(match.files())
1343 else:
1360 else:
1344 opts[fnopats[followdescendants][followfirst]] = str(startrev)
1361 opts[fnopats[followdescendants][followfirst]] = str(startrev)
1345 else:
1362 else:
1346 opts['_patslog'] = list(pats)
1363 opts['_patslog'] = list(pats)
1347
1364
1348 filematcher = None
1365 filematcher = None
1349 if opts.get('patch') or opts.get('stat'):
1366 if opts.get('patch') or opts.get('stat'):
1350 if follow:
1367 if follow:
1351 filematcher = _makegraphfilematcher(repo, pats, followfirst)
1368 filematcher = _makegraphfilematcher(repo, pats, followfirst)
1352 else:
1369 else:
1353 filematcher = lambda rev: match
1370 filematcher = lambda rev: match
1354
1371
1355 expr = []
1372 expr = []
1356 for op, val in opts.iteritems():
1373 for op, val in opts.iteritems():
1357 if not val:
1374 if not val:
1358 continue
1375 continue
1359 if op not in opt2revset:
1376 if op not in opt2revset:
1360 continue
1377 continue
1361 revop, andor = opt2revset[op]
1378 revop, andor = opt2revset[op]
1362 if '%(val)' not in revop:
1379 if '%(val)' not in revop:
1363 expr.append(revop)
1380 expr.append(revop)
1364 else:
1381 else:
1365 if not isinstance(val, list):
1382 if not isinstance(val, list):
1366 e = revop % {'val': val}
1383 e = revop % {'val': val}
1367 else:
1384 else:
1368 e = '(' + andor.join((revop % {'val': v}) for v in val) + ')'
1385 e = '(' + andor.join((revop % {'val': v}) for v in val) + ')'
1369 expr.append(e)
1386 expr.append(e)
1370
1387
1371 if expr:
1388 if expr:
1372 expr = '(' + ' and '.join(expr) + ')'
1389 expr = '(' + ' and '.join(expr) + ')'
1373 else:
1390 else:
1374 expr = None
1391 expr = None
1375 return expr, filematcher
1392 return expr, filematcher
1376
1393
1377 def getgraphlogrevs(repo, pats, opts):
1394 def getgraphlogrevs(repo, pats, opts):
1378 """Return (revs, expr, filematcher) where revs is an iterable of
1395 """Return (revs, expr, filematcher) where revs is an iterable of
1379 revision numbers, expr is a revset string built from log options
1396 revision numbers, expr is a revset string built from log options
1380 and file patterns or None, and used to filter 'revs'. If --stat or
1397 and file patterns or None, and used to filter 'revs'. If --stat or
1381 --patch are not passed filematcher is None. Otherwise it is a
1398 --patch are not passed filematcher is None. Otherwise it is a
1382 callable taking a revision number and returning a match objects
1399 callable taking a revision number and returning a match objects
1383 filtering the files to be detailed when displaying the revision.
1400 filtering the files to be detailed when displaying the revision.
1384 """
1401 """
1385 def increasingrevs(repo, revs, matcher):
1402 def increasingrevs(repo, revs, matcher):
1386 # The sorted input rev sequence is chopped in sub-sequences
1403 # The sorted input rev sequence is chopped in sub-sequences
1387 # which are sorted in ascending order and passed to the
1404 # which are sorted in ascending order and passed to the
1388 # matcher. The filtered revs are sorted again as they were in
1405 # matcher. The filtered revs are sorted again as they were in
1389 # the original sub-sequence. This achieve several things:
1406 # the original sub-sequence. This achieve several things:
1390 #
1407 #
1391 # - getlogrevs() now returns a generator which behaviour is
1408 # - getlogrevs() now returns a generator which behaviour is
1392 # adapted to log need. First results come fast, last ones
1409 # adapted to log need. First results come fast, last ones
1393 # are batched for performances.
1410 # are batched for performances.
1394 #
1411 #
1395 # - revset matchers often operate faster on revision in
1412 # - revset matchers often operate faster on revision in
1396 # changelog order, because most filters deal with the
1413 # changelog order, because most filters deal with the
1397 # changelog.
1414 # changelog.
1398 #
1415 #
1399 # - revset matchers can reorder revisions. "A or B" typically
1416 # - revset matchers can reorder revisions. "A or B" typically
1400 # returns returns the revision matching A then the revision
1417 # returns returns the revision matching A then the revision
1401 # matching B. We want to hide this internal implementation
1418 # matching B. We want to hide this internal implementation
1402 # detail from the caller, and sorting the filtered revision
1419 # detail from the caller, and sorting the filtered revision
1403 # again achieves this.
1420 # again achieves this.
1404 for i, window in increasingwindows(0, len(revs), windowsize=1):
1421 for i, window in increasingwindows(0, len(revs), windowsize=1):
1405 orevs = revs[i:i + window]
1422 orevs = revs[i:i + window]
1406 nrevs = set(matcher(repo, sorted(orevs)))
1423 nrevs = set(matcher(repo, sorted(orevs)))
1407 for rev in orevs:
1424 for rev in orevs:
1408 if rev in nrevs:
1425 if rev in nrevs:
1409 yield rev
1426 yield rev
1410
1427
1411 if not len(repo):
1428 if not len(repo):
1412 return iter([]), None, None
1429 return iter([]), None, None
1413 # Default --rev value depends on --follow but --follow behaviour
1430 # Default --rev value depends on --follow but --follow behaviour
1414 # depends on revisions resolved from --rev...
1431 # depends on revisions resolved from --rev...
1415 follow = opts.get('follow') or opts.get('follow_first')
1432 follow = opts.get('follow') or opts.get('follow_first')
1416 if opts.get('rev'):
1433 if opts.get('rev'):
1417 revs = scmutil.revrange(repo, opts['rev'])
1434 revs = scmutil.revrange(repo, opts['rev'])
1418 else:
1435 else:
1419 if follow and len(repo) > 0:
1436 if follow and len(repo) > 0:
1420 revs = repo.revs('reverse(:.)')
1437 revs = repo.revs('reverse(:.)')
1421 else:
1438 else:
1422 revs = list(repo.changelog)
1439 revs = list(repo.changelog)
1423 revs.reverse()
1440 revs.reverse()
1424 if not revs:
1441 if not revs:
1425 return iter([]), None, None
1442 return iter([]), None, None
1426 expr, filematcher = _makegraphlogrevset(repo, pats, opts, revs)
1443 expr, filematcher = _makegraphlogrevset(repo, pats, opts, revs)
1427 if expr:
1444 if expr:
1428 matcher = revset.match(repo.ui, expr)
1445 matcher = revset.match(repo.ui, expr)
1429 revs = increasingrevs(repo, revs, matcher)
1446 revs = increasingrevs(repo, revs, matcher)
1430 if not opts.get('hidden'):
1447 if not opts.get('hidden'):
1431 # --hidden is still experimental and not worth a dedicated revset
1448 # --hidden is still experimental and not worth a dedicated revset
1432 # yet. Fortunately, filtering revision number is fast.
1449 # yet. Fortunately, filtering revision number is fast.
1433 revs = (r for r in revs if r not in repo.hiddenrevs)
1450 revs = (r for r in revs if r not in repo.hiddenrevs)
1434 else:
1451 else:
1435 revs = iter(revs)
1452 revs = iter(revs)
1436 return revs, expr, filematcher
1453 return revs, expr, filematcher
1437
1454
1438 def displaygraph(ui, dag, displayer, showparents, edgefn, getrenamed=None,
1455 def displaygraph(ui, dag, displayer, showparents, edgefn, getrenamed=None,
1439 filematcher=None):
1456 filematcher=None):
1440 seen, state = [], graphmod.asciistate()
1457 seen, state = [], graphmod.asciistate()
1441 for rev, type, ctx, parents in dag:
1458 for rev, type, ctx, parents in dag:
1442 char = 'o'
1459 char = 'o'
1443 if ctx.node() in showparents:
1460 if ctx.node() in showparents:
1444 char = '@'
1461 char = '@'
1445 elif ctx.obsolete():
1462 elif ctx.obsolete():
1446 char = 'x'
1463 char = 'x'
1447 copies = None
1464 copies = None
1448 if getrenamed and ctx.rev():
1465 if getrenamed and ctx.rev():
1449 copies = []
1466 copies = []
1450 for fn in ctx.files():
1467 for fn in ctx.files():
1451 rename = getrenamed(fn, ctx.rev())
1468 rename = getrenamed(fn, ctx.rev())
1452 if rename:
1469 if rename:
1453 copies.append((fn, rename[0]))
1470 copies.append((fn, rename[0]))
1454 revmatchfn = None
1471 revmatchfn = None
1455 if filematcher is not None:
1472 if filematcher is not None:
1456 revmatchfn = filematcher(ctx.rev())
1473 revmatchfn = filematcher(ctx.rev())
1457 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
1474 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
1458 lines = displayer.hunk.pop(rev).split('\n')
1475 lines = displayer.hunk.pop(rev).split('\n')
1459 if not lines[-1]:
1476 if not lines[-1]:
1460 del lines[-1]
1477 del lines[-1]
1461 displayer.flush(rev)
1478 displayer.flush(rev)
1462 edges = edgefn(type, char, lines, seen, rev, parents)
1479 edges = edgefn(type, char, lines, seen, rev, parents)
1463 for type, char, lines, coldata in edges:
1480 for type, char, lines, coldata in edges:
1464 graphmod.ascii(ui, state, type, char, lines, coldata)
1481 graphmod.ascii(ui, state, type, char, lines, coldata)
1465 displayer.close()
1482 displayer.close()
1466
1483
1467 def graphlog(ui, repo, *pats, **opts):
1484 def graphlog(ui, repo, *pats, **opts):
1468 # Parameters are identical to log command ones
1485 # Parameters are identical to log command ones
1469 revs, expr, filematcher = getgraphlogrevs(repo, pats, opts)
1486 revs, expr, filematcher = getgraphlogrevs(repo, pats, opts)
1470 revs = sorted(revs, reverse=1)
1487 revs = sorted(revs, reverse=1)
1471 limit = loglimit(opts)
1488 limit = loglimit(opts)
1472 if limit is not None:
1489 if limit is not None:
1473 revs = revs[:limit]
1490 revs = revs[:limit]
1474 revdag = graphmod.dagwalker(repo, revs)
1491 revdag = graphmod.dagwalker(repo, revs)
1475
1492
1476 getrenamed = None
1493 getrenamed = None
1477 if opts.get('copies'):
1494 if opts.get('copies'):
1478 endrev = None
1495 endrev = None
1479 if opts.get('rev'):
1496 if opts.get('rev'):
1480 endrev = max(scmutil.revrange(repo, opts.get('rev'))) + 1
1497 endrev = max(scmutil.revrange(repo, opts.get('rev'))) + 1
1481 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
1498 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
1482 displayer = show_changeset(ui, repo, opts, buffered=True)
1499 displayer = show_changeset(ui, repo, opts, buffered=True)
1483 showparents = [ctx.node() for ctx in repo[None].parents()]
1500 showparents = [ctx.node() for ctx in repo[None].parents()]
1484 displaygraph(ui, revdag, displayer, showparents,
1501 displaygraph(ui, revdag, displayer, showparents,
1485 graphmod.asciiedges, getrenamed, filematcher)
1502 graphmod.asciiedges, getrenamed, filematcher)
1486
1503
1487 def checkunsupportedgraphflags(pats, opts):
1504 def checkunsupportedgraphflags(pats, opts):
1488 for op in ["newest_first"]:
1505 for op in ["newest_first"]:
1489 if op in opts and opts[op]:
1506 if op in opts and opts[op]:
1490 raise util.Abort(_("-G/--graph option is incompatible with --%s")
1507 raise util.Abort(_("-G/--graph option is incompatible with --%s")
1491 % op.replace("_", "-"))
1508 % op.replace("_", "-"))
1492
1509
1493 def graphrevs(repo, nodes, opts):
1510 def graphrevs(repo, nodes, opts):
1494 limit = loglimit(opts)
1511 limit = loglimit(opts)
1495 nodes.reverse()
1512 nodes.reverse()
1496 if limit is not None:
1513 if limit is not None:
1497 nodes = nodes[:limit]
1514 nodes = nodes[:limit]
1498 return graphmod.nodes(repo, nodes)
1515 return graphmod.nodes(repo, nodes)
1499
1516
1500 def add(ui, repo, match, dryrun, listsubrepos, prefix, explicitonly):
1517 def add(ui, repo, match, dryrun, listsubrepos, prefix, explicitonly):
1501 join = lambda f: os.path.join(prefix, f)
1518 join = lambda f: os.path.join(prefix, f)
1502 bad = []
1519 bad = []
1503 oldbad = match.bad
1520 oldbad = match.bad
1504 match.bad = lambda x, y: bad.append(x) or oldbad(x, y)
1521 match.bad = lambda x, y: bad.append(x) or oldbad(x, y)
1505 names = []
1522 names = []
1506 wctx = repo[None]
1523 wctx = repo[None]
1507 cca = None
1524 cca = None
1508 abort, warn = scmutil.checkportabilityalert(ui)
1525 abort, warn = scmutil.checkportabilityalert(ui)
1509 if abort or warn:
1526 if abort or warn:
1510 cca = scmutil.casecollisionauditor(ui, abort, repo.dirstate)
1527 cca = scmutil.casecollisionauditor(ui, abort, repo.dirstate)
1511 for f in repo.walk(match):
1528 for f in repo.walk(match):
1512 exact = match.exact(f)
1529 exact = match.exact(f)
1513 if exact or not explicitonly and f not in repo.dirstate:
1530 if exact or not explicitonly and f not in repo.dirstate:
1514 if cca:
1531 if cca:
1515 cca(f)
1532 cca(f)
1516 names.append(f)
1533 names.append(f)
1517 if ui.verbose or not exact:
1534 if ui.verbose or not exact:
1518 ui.status(_('adding %s\n') % match.rel(join(f)))
1535 ui.status(_('adding %s\n') % match.rel(join(f)))
1519
1536
1520 for subpath in wctx.substate:
1537 for subpath in wctx.substate:
1521 sub = wctx.sub(subpath)
1538 sub = wctx.sub(subpath)
1522 try:
1539 try:
1523 submatch = matchmod.narrowmatcher(subpath, match)
1540 submatch = matchmod.narrowmatcher(subpath, match)
1524 if listsubrepos:
1541 if listsubrepos:
1525 bad.extend(sub.add(ui, submatch, dryrun, listsubrepos, prefix,
1542 bad.extend(sub.add(ui, submatch, dryrun, listsubrepos, prefix,
1526 False))
1543 False))
1527 else:
1544 else:
1528 bad.extend(sub.add(ui, submatch, dryrun, listsubrepos, prefix,
1545 bad.extend(sub.add(ui, submatch, dryrun, listsubrepos, prefix,
1529 True))
1546 True))
1530 except error.LookupError:
1547 except error.LookupError:
1531 ui.status(_("skipping missing subrepository: %s\n")
1548 ui.status(_("skipping missing subrepository: %s\n")
1532 % join(subpath))
1549 % join(subpath))
1533
1550
1534 if not dryrun:
1551 if not dryrun:
1535 rejected = wctx.add(names, prefix)
1552 rejected = wctx.add(names, prefix)
1536 bad.extend(f for f in rejected if f in match.files())
1553 bad.extend(f for f in rejected if f in match.files())
1537 return bad
1554 return bad
1538
1555
1539 def forget(ui, repo, match, prefix, explicitonly):
1556 def forget(ui, repo, match, prefix, explicitonly):
1540 join = lambda f: os.path.join(prefix, f)
1557 join = lambda f: os.path.join(prefix, f)
1541 bad = []
1558 bad = []
1542 oldbad = match.bad
1559 oldbad = match.bad
1543 match.bad = lambda x, y: bad.append(x) or oldbad(x, y)
1560 match.bad = lambda x, y: bad.append(x) or oldbad(x, y)
1544 wctx = repo[None]
1561 wctx = repo[None]
1545 forgot = []
1562 forgot = []
1546 s = repo.status(match=match, clean=True)
1563 s = repo.status(match=match, clean=True)
1547 forget = sorted(s[0] + s[1] + s[3] + s[6])
1564 forget = sorted(s[0] + s[1] + s[3] + s[6])
1548 if explicitonly:
1565 if explicitonly:
1549 forget = [f for f in forget if match.exact(f)]
1566 forget = [f for f in forget if match.exact(f)]
1550
1567
1551 for subpath in wctx.substate:
1568 for subpath in wctx.substate:
1552 sub = wctx.sub(subpath)
1569 sub = wctx.sub(subpath)
1553 try:
1570 try:
1554 submatch = matchmod.narrowmatcher(subpath, match)
1571 submatch = matchmod.narrowmatcher(subpath, match)
1555 subbad, subforgot = sub.forget(ui, submatch, prefix)
1572 subbad, subforgot = sub.forget(ui, submatch, prefix)
1556 bad.extend([subpath + '/' + f for f in subbad])
1573 bad.extend([subpath + '/' + f for f in subbad])
1557 forgot.extend([subpath + '/' + f for f in subforgot])
1574 forgot.extend([subpath + '/' + f for f in subforgot])
1558 except error.LookupError:
1575 except error.LookupError:
1559 ui.status(_("skipping missing subrepository: %s\n")
1576 ui.status(_("skipping missing subrepository: %s\n")
1560 % join(subpath))
1577 % join(subpath))
1561
1578
1562 if not explicitonly:
1579 if not explicitonly:
1563 for f in match.files():
1580 for f in match.files():
1564 if f not in repo.dirstate and not os.path.isdir(match.rel(join(f))):
1581 if f not in repo.dirstate and not os.path.isdir(match.rel(join(f))):
1565 if f not in forgot:
1582 if f not in forgot:
1566 if os.path.exists(match.rel(join(f))):
1583 if os.path.exists(match.rel(join(f))):
1567 ui.warn(_('not removing %s: '
1584 ui.warn(_('not removing %s: '
1568 'file is already untracked\n')
1585 'file is already untracked\n')
1569 % match.rel(join(f)))
1586 % match.rel(join(f)))
1570 bad.append(f)
1587 bad.append(f)
1571
1588
1572 for f in forget:
1589 for f in forget:
1573 if ui.verbose or not match.exact(f):
1590 if ui.verbose or not match.exact(f):
1574 ui.status(_('removing %s\n') % match.rel(join(f)))
1591 ui.status(_('removing %s\n') % match.rel(join(f)))
1575
1592
1576 rejected = wctx.forget(forget, prefix)
1593 rejected = wctx.forget(forget, prefix)
1577 bad.extend(f for f in rejected if f in match.files())
1594 bad.extend(f for f in rejected if f in match.files())
1578 forgot.extend(forget)
1595 forgot.extend(forget)
1579 return bad, forgot
1596 return bad, forgot
1580
1597
1581 def duplicatecopies(repo, rev, p1):
1598 def duplicatecopies(repo, rev, p1):
1582 "Reproduce copies found in the source revision in the dirstate for grafts"
1599 "Reproduce copies found in the source revision in the dirstate for grafts"
1583 for dst, src in copies.pathcopies(repo[p1], repo[rev]).iteritems():
1600 for dst, src in copies.pathcopies(repo[p1], repo[rev]).iteritems():
1584 repo.dirstate.copy(src, dst)
1601 repo.dirstate.copy(src, dst)
1585
1602
1586 def commit(ui, repo, commitfunc, pats, opts):
1603 def commit(ui, repo, commitfunc, pats, opts):
1587 '''commit the specified files or all outstanding changes'''
1604 '''commit the specified files or all outstanding changes'''
1588 date = opts.get('date')
1605 date = opts.get('date')
1589 if date:
1606 if date:
1590 opts['date'] = util.parsedate(date)
1607 opts['date'] = util.parsedate(date)
1591 message = logmessage(ui, opts)
1608 message = logmessage(ui, opts)
1592
1609
1593 # extract addremove carefully -- this function can be called from a command
1610 # extract addremove carefully -- this function can be called from a command
1594 # that doesn't support addremove
1611 # that doesn't support addremove
1595 if opts.get('addremove'):
1612 if opts.get('addremove'):
1596 scmutil.addremove(repo, pats, opts)
1613 scmutil.addremove(repo, pats, opts)
1597
1614
1598 return commitfunc(ui, repo, message,
1615 return commitfunc(ui, repo, message,
1599 scmutil.match(repo[None], pats, opts), opts)
1616 scmutil.match(repo[None], pats, opts), opts)
1600
1617
1601 def amend(ui, repo, commitfunc, old, extra, pats, opts):
1618 def amend(ui, repo, commitfunc, old, extra, pats, opts):
1602 ui.note(_('amending changeset %s\n') % old)
1619 ui.note(_('amending changeset %s\n') % old)
1603 base = old.p1()
1620 base = old.p1()
1604
1621
1605 wlock = lock = None
1622 wlock = lock = None
1606 try:
1623 try:
1607 wlock = repo.wlock()
1624 wlock = repo.wlock()
1608 lock = repo.lock()
1625 lock = repo.lock()
1609 tr = repo.transaction('amend')
1626 tr = repo.transaction('amend')
1610 try:
1627 try:
1611 # See if we got a message from -m or -l, if not, open the editor
1628 # See if we got a message from -m or -l, if not, open the editor
1612 # with the message of the changeset to amend
1629 # with the message of the changeset to amend
1613 message = logmessage(ui, opts)
1630 message = logmessage(ui, opts)
1614 # ensure logfile does not conflict with later enforcement of the
1631 # ensure logfile does not conflict with later enforcement of the
1615 # message. potential logfile content has been processed by
1632 # message. potential logfile content has been processed by
1616 # `logmessage` anyway.
1633 # `logmessage` anyway.
1617 opts.pop('logfile')
1634 opts.pop('logfile')
1618 # First, do a regular commit to record all changes in the working
1635 # First, do a regular commit to record all changes in the working
1619 # directory (if there are any)
1636 # directory (if there are any)
1620 ui.callhooks = False
1637 ui.callhooks = False
1621 try:
1638 try:
1622 opts['message'] = 'temporary amend commit for %s' % old
1639 opts['message'] = 'temporary amend commit for %s' % old
1623 node = commit(ui, repo, commitfunc, pats, opts)
1640 node = commit(ui, repo, commitfunc, pats, opts)
1624 finally:
1641 finally:
1625 ui.callhooks = True
1642 ui.callhooks = True
1626 ctx = repo[node]
1643 ctx = repo[node]
1627
1644
1628 # Participating changesets:
1645 # Participating changesets:
1629 #
1646 #
1630 # node/ctx o - new (intermediate) commit that contains changes
1647 # node/ctx o - new (intermediate) commit that contains changes
1631 # | from working dir to go into amending commit
1648 # | from working dir to go into amending commit
1632 # | (or a workingctx if there were no changes)
1649 # | (or a workingctx if there were no changes)
1633 # |
1650 # |
1634 # old o - changeset to amend
1651 # old o - changeset to amend
1635 # |
1652 # |
1636 # base o - parent of amending changeset
1653 # base o - parent of amending changeset
1637
1654
1638 # Update extra dict from amended commit (e.g. to preserve graft
1655 # Update extra dict from amended commit (e.g. to preserve graft
1639 # source)
1656 # source)
1640 extra.update(old.extra())
1657 extra.update(old.extra())
1641
1658
1642 # Also update it from the intermediate commit or from the wctx
1659 # Also update it from the intermediate commit or from the wctx
1643 extra.update(ctx.extra())
1660 extra.update(ctx.extra())
1644
1661
1645 files = set(old.files())
1662 files = set(old.files())
1646
1663
1647 # Second, we use either the commit we just did, or if there were no
1664 # Second, we use either the commit we just did, or if there were no
1648 # changes the parent of the working directory as the version of the
1665 # changes the parent of the working directory as the version of the
1649 # files in the final amend commit
1666 # files in the final amend commit
1650 if node:
1667 if node:
1651 ui.note(_('copying changeset %s to %s\n') % (ctx, base))
1668 ui.note(_('copying changeset %s to %s\n') % (ctx, base))
1652
1669
1653 user = ctx.user()
1670 user = ctx.user()
1654 date = ctx.date()
1671 date = ctx.date()
1655 # Recompute copies (avoid recording a -> b -> a)
1672 # Recompute copies (avoid recording a -> b -> a)
1656 copied = copies.pathcopies(base, ctx)
1673 copied = copies.pathcopies(base, ctx)
1657
1674
1658 # Prune files which were reverted by the updates: if old
1675 # Prune files which were reverted by the updates: if old
1659 # introduced file X and our intermediate commit, node,
1676 # introduced file X and our intermediate commit, node,
1660 # renamed that file, then those two files are the same and
1677 # renamed that file, then those two files are the same and
1661 # we can discard X from our list of files. Likewise if X
1678 # we can discard X from our list of files. Likewise if X
1662 # was deleted, it's no longer relevant
1679 # was deleted, it's no longer relevant
1663 files.update(ctx.files())
1680 files.update(ctx.files())
1664
1681
1665 def samefile(f):
1682 def samefile(f):
1666 if f in ctx.manifest():
1683 if f in ctx.manifest():
1667 a = ctx.filectx(f)
1684 a = ctx.filectx(f)
1668 if f in base.manifest():
1685 if f in base.manifest():
1669 b = base.filectx(f)
1686 b = base.filectx(f)
1670 return (not a.cmp(b)
1687 return (not a.cmp(b)
1671 and a.flags() == b.flags())
1688 and a.flags() == b.flags())
1672 else:
1689 else:
1673 return False
1690 return False
1674 else:
1691 else:
1675 return f not in base.manifest()
1692 return f not in base.manifest()
1676 files = [f for f in files if not samefile(f)]
1693 files = [f for f in files if not samefile(f)]
1677
1694
1678 def filectxfn(repo, ctx_, path):
1695 def filectxfn(repo, ctx_, path):
1679 try:
1696 try:
1680 fctx = ctx[path]
1697 fctx = ctx[path]
1681 flags = fctx.flags()
1698 flags = fctx.flags()
1682 mctx = context.memfilectx(fctx.path(), fctx.data(),
1699 mctx = context.memfilectx(fctx.path(), fctx.data(),
1683 islink='l' in flags,
1700 islink='l' in flags,
1684 isexec='x' in flags,
1701 isexec='x' in flags,
1685 copied=copied.get(path))
1702 copied=copied.get(path))
1686 return mctx
1703 return mctx
1687 except KeyError:
1704 except KeyError:
1688 raise IOError
1705 raise IOError
1689 else:
1706 else:
1690 ui.note(_('copying changeset %s to %s\n') % (old, base))
1707 ui.note(_('copying changeset %s to %s\n') % (old, base))
1691
1708
1692 # Use version of files as in the old cset
1709 # Use version of files as in the old cset
1693 def filectxfn(repo, ctx_, path):
1710 def filectxfn(repo, ctx_, path):
1694 try:
1711 try:
1695 return old.filectx(path)
1712 return old.filectx(path)
1696 except KeyError:
1713 except KeyError:
1697 raise IOError
1714 raise IOError
1698
1715
1699 user = opts.get('user') or old.user()
1716 user = opts.get('user') or old.user()
1700 date = opts.get('date') or old.date()
1717 date = opts.get('date') or old.date()
1701 if not message:
1718 if not message:
1702 message = old.description()
1719 message = old.description()
1703
1720
1704 pureextra = extra.copy()
1721 pureextra = extra.copy()
1705 extra['amend_source'] = old.hex()
1722 extra['amend_source'] = old.hex()
1706
1723
1707 new = context.memctx(repo,
1724 new = context.memctx(repo,
1708 parents=[base.node(), nullid],
1725 parents=[base.node(), nullid],
1709 text=message,
1726 text=message,
1710 files=files,
1727 files=files,
1711 filectxfn=filectxfn,
1728 filectxfn=filectxfn,
1712 user=user,
1729 user=user,
1713 date=date,
1730 date=date,
1714 extra=extra)
1731 extra=extra)
1715 new._text = commitforceeditor(repo, new, [])
1732 new._text = commitforceeditor(repo, new, [])
1716
1733
1717 newdesc = changelog.stripdesc(new.description())
1734 newdesc = changelog.stripdesc(new.description())
1718 if ((not node)
1735 if ((not node)
1719 and newdesc == old.description()
1736 and newdesc == old.description()
1720 and user == old.user()
1737 and user == old.user()
1721 and date == old.date()
1738 and date == old.date()
1722 and pureextra == old.extra()):
1739 and pureextra == old.extra()):
1723 # nothing changed. continuing here would create a new node
1740 # nothing changed. continuing here would create a new node
1724 # anyway because of the amend_source noise.
1741 # anyway because of the amend_source noise.
1725 #
1742 #
1726 # This not what we expect from amend.
1743 # This not what we expect from amend.
1727 return old.node()
1744 return old.node()
1728
1745
1729 ph = repo.ui.config('phases', 'new-commit', phases.draft)
1746 ph = repo.ui.config('phases', 'new-commit', phases.draft)
1730 try:
1747 try:
1731 repo.ui.setconfig('phases', 'new-commit', old.phase())
1748 repo.ui.setconfig('phases', 'new-commit', old.phase())
1732 newid = repo.commitctx(new)
1749 newid = repo.commitctx(new)
1733 finally:
1750 finally:
1734 repo.ui.setconfig('phases', 'new-commit', ph)
1751 repo.ui.setconfig('phases', 'new-commit', ph)
1735 if newid != old.node():
1752 if newid != old.node():
1736 # Reroute the working copy parent to the new changeset
1753 # Reroute the working copy parent to the new changeset
1737 repo.setparents(newid, nullid)
1754 repo.setparents(newid, nullid)
1738
1755
1739 # Move bookmarks from old parent to amend commit
1756 # Move bookmarks from old parent to amend commit
1740 bms = repo.nodebookmarks(old.node())
1757 bms = repo.nodebookmarks(old.node())
1741 if bms:
1758 if bms:
1742 for bm in bms:
1759 for bm in bms:
1743 repo._bookmarks[bm] = newid
1760 repo._bookmarks[bm] = newid
1744 bookmarks.write(repo)
1761 bookmarks.write(repo)
1745 #commit the whole amend process
1762 #commit the whole amend process
1746 if obsolete._enabled and newid != old.node():
1763 if obsolete._enabled and newid != old.node():
1747 # mark the new changeset as successor of the rewritten one
1764 # mark the new changeset as successor of the rewritten one
1748 new = repo[newid]
1765 new = repo[newid]
1749 obs = [(old, (new,))]
1766 obs = [(old, (new,))]
1750 if node:
1767 if node:
1751 obs.append((ctx, ()))
1768 obs.append((ctx, ()))
1752
1769
1753 obsolete.createmarkers(repo, obs)
1770 obsolete.createmarkers(repo, obs)
1754 tr.close()
1771 tr.close()
1755 finally:
1772 finally:
1756 tr.release()
1773 tr.release()
1757 if (not obsolete._enabled) and newid != old.node():
1774 if (not obsolete._enabled) and newid != old.node():
1758 # Strip the intermediate commit (if there was one) and the amended
1775 # Strip the intermediate commit (if there was one) and the amended
1759 # commit
1776 # commit
1760 if node:
1777 if node:
1761 ui.note(_('stripping intermediate changeset %s\n') % ctx)
1778 ui.note(_('stripping intermediate changeset %s\n') % ctx)
1762 ui.note(_('stripping amended changeset %s\n') % old)
1779 ui.note(_('stripping amended changeset %s\n') % old)
1763 repair.strip(ui, repo, old.node(), topic='amend-backup')
1780 repair.strip(ui, repo, old.node(), topic='amend-backup')
1764 finally:
1781 finally:
1765 lockmod.release(wlock, lock)
1782 lockmod.release(wlock, lock)
1766 return newid
1783 return newid
1767
1784
1768 def commiteditor(repo, ctx, subs):
1785 def commiteditor(repo, ctx, subs):
1769 if ctx.description():
1786 if ctx.description():
1770 return ctx.description()
1787 return ctx.description()
1771 return commitforceeditor(repo, ctx, subs)
1788 return commitforceeditor(repo, ctx, subs)
1772
1789
1773 def commitforceeditor(repo, ctx, subs):
1790 def commitforceeditor(repo, ctx, subs):
1774 edittext = []
1791 edittext = []
1775 modified, added, removed = ctx.modified(), ctx.added(), ctx.removed()
1792 modified, added, removed = ctx.modified(), ctx.added(), ctx.removed()
1776 if ctx.description():
1793 if ctx.description():
1777 edittext.append(ctx.description())
1794 edittext.append(ctx.description())
1778 edittext.append("")
1795 edittext.append("")
1779 edittext.append("") # Empty line between message and comments.
1796 edittext.append("") # Empty line between message and comments.
1780 edittext.append(_("HG: Enter commit message."
1797 edittext.append(_("HG: Enter commit message."
1781 " Lines beginning with 'HG:' are removed."))
1798 " Lines beginning with 'HG:' are removed."))
1782 edittext.append(_("HG: Leave message empty to abort commit."))
1799 edittext.append(_("HG: Leave message empty to abort commit."))
1783 edittext.append("HG: --")
1800 edittext.append("HG: --")
1784 edittext.append(_("HG: user: %s") % ctx.user())
1801 edittext.append(_("HG: user: %s") % ctx.user())
1785 if ctx.p2():
1802 if ctx.p2():
1786 edittext.append(_("HG: branch merge"))
1803 edittext.append(_("HG: branch merge"))
1787 if ctx.branch():
1804 if ctx.branch():
1788 edittext.append(_("HG: branch '%s'") % ctx.branch())
1805 edittext.append(_("HG: branch '%s'") % ctx.branch())
1789 edittext.extend([_("HG: subrepo %s") % s for s in subs])
1806 edittext.extend([_("HG: subrepo %s") % s for s in subs])
1790 edittext.extend([_("HG: added %s") % f for f in added])
1807 edittext.extend([_("HG: added %s") % f for f in added])
1791 edittext.extend([_("HG: changed %s") % f for f in modified])
1808 edittext.extend([_("HG: changed %s") % f for f in modified])
1792 edittext.extend([_("HG: removed %s") % f for f in removed])
1809 edittext.extend([_("HG: removed %s") % f for f in removed])
1793 if not added and not modified and not removed:
1810 if not added and not modified and not removed:
1794 edittext.append(_("HG: no files changed"))
1811 edittext.append(_("HG: no files changed"))
1795 edittext.append("")
1812 edittext.append("")
1796 # run editor in the repository root
1813 # run editor in the repository root
1797 olddir = os.getcwd()
1814 olddir = os.getcwd()
1798 os.chdir(repo.root)
1815 os.chdir(repo.root)
1799 text = repo.ui.edit("\n".join(edittext), ctx.user())
1816 text = repo.ui.edit("\n".join(edittext), ctx.user())
1800 text = re.sub("(?m)^HG:.*(\n|$)", "", text)
1817 text = re.sub("(?m)^HG:.*(\n|$)", "", text)
1801 os.chdir(olddir)
1818 os.chdir(olddir)
1802
1819
1803 if not text.strip():
1820 if not text.strip():
1804 raise util.Abort(_("empty commit message"))
1821 raise util.Abort(_("empty commit message"))
1805
1822
1806 return text
1823 return text
1807
1824
1808 def revert(ui, repo, ctx, parents, *pats, **opts):
1825 def revert(ui, repo, ctx, parents, *pats, **opts):
1809 parent, p2 = parents
1826 parent, p2 = parents
1810 node = ctx.node()
1827 node = ctx.node()
1811
1828
1812 mf = ctx.manifest()
1829 mf = ctx.manifest()
1813 if node == parent:
1830 if node == parent:
1814 pmf = mf
1831 pmf = mf
1815 else:
1832 else:
1816 pmf = None
1833 pmf = None
1817
1834
1818 # need all matching names in dirstate and manifest of target rev,
1835 # need all matching names in dirstate and manifest of target rev,
1819 # so have to walk both. do not print errors if files exist in one
1836 # so have to walk both. do not print errors if files exist in one
1820 # but not other.
1837 # but not other.
1821
1838
1822 names = {}
1839 names = {}
1823
1840
1824 wlock = repo.wlock()
1841 wlock = repo.wlock()
1825 try:
1842 try:
1826 # walk dirstate.
1843 # walk dirstate.
1827
1844
1828 m = scmutil.match(repo[None], pats, opts)
1845 m = scmutil.match(repo[None], pats, opts)
1829 m.bad = lambda x, y: False
1846 m.bad = lambda x, y: False
1830 for abs in repo.walk(m):
1847 for abs in repo.walk(m):
1831 names[abs] = m.rel(abs), m.exact(abs)
1848 names[abs] = m.rel(abs), m.exact(abs)
1832
1849
1833 # walk target manifest.
1850 # walk target manifest.
1834
1851
1835 def badfn(path, msg):
1852 def badfn(path, msg):
1836 if path in names:
1853 if path in names:
1837 return
1854 return
1838 if path in ctx.substate:
1855 if path in ctx.substate:
1839 return
1856 return
1840 path_ = path + '/'
1857 path_ = path + '/'
1841 for f in names:
1858 for f in names:
1842 if f.startswith(path_):
1859 if f.startswith(path_):
1843 return
1860 return
1844 ui.warn("%s: %s\n" % (m.rel(path), msg))
1861 ui.warn("%s: %s\n" % (m.rel(path), msg))
1845
1862
1846 m = scmutil.match(ctx, pats, opts)
1863 m = scmutil.match(ctx, pats, opts)
1847 m.bad = badfn
1864 m.bad = badfn
1848 for abs in ctx.walk(m):
1865 for abs in ctx.walk(m):
1849 if abs not in names:
1866 if abs not in names:
1850 names[abs] = m.rel(abs), m.exact(abs)
1867 names[abs] = m.rel(abs), m.exact(abs)
1851
1868
1852 # get the list of subrepos that must be reverted
1869 # get the list of subrepos that must be reverted
1853 targetsubs = [s for s in ctx.substate if m(s)]
1870 targetsubs = [s for s in ctx.substate if m(s)]
1854 m = scmutil.matchfiles(repo, names)
1871 m = scmutil.matchfiles(repo, names)
1855 changes = repo.status(match=m)[:4]
1872 changes = repo.status(match=m)[:4]
1856 modified, added, removed, deleted = map(set, changes)
1873 modified, added, removed, deleted = map(set, changes)
1857
1874
1858 # if f is a rename, also revert the source
1875 # if f is a rename, also revert the source
1859 cwd = repo.getcwd()
1876 cwd = repo.getcwd()
1860 for f in added:
1877 for f in added:
1861 src = repo.dirstate.copied(f)
1878 src = repo.dirstate.copied(f)
1862 if src and src not in names and repo.dirstate[src] == 'r':
1879 if src and src not in names and repo.dirstate[src] == 'r':
1863 removed.add(src)
1880 removed.add(src)
1864 names[src] = (repo.pathto(src, cwd), True)
1881 names[src] = (repo.pathto(src, cwd), True)
1865
1882
1866 def removeforget(abs):
1883 def removeforget(abs):
1867 if repo.dirstate[abs] == 'a':
1884 if repo.dirstate[abs] == 'a':
1868 return _('forgetting %s\n')
1885 return _('forgetting %s\n')
1869 return _('removing %s\n')
1886 return _('removing %s\n')
1870
1887
1871 revert = ([], _('reverting %s\n'))
1888 revert = ([], _('reverting %s\n'))
1872 add = ([], _('adding %s\n'))
1889 add = ([], _('adding %s\n'))
1873 remove = ([], removeforget)
1890 remove = ([], removeforget)
1874 undelete = ([], _('undeleting %s\n'))
1891 undelete = ([], _('undeleting %s\n'))
1875
1892
1876 disptable = (
1893 disptable = (
1877 # dispatch table:
1894 # dispatch table:
1878 # file state
1895 # file state
1879 # action if in target manifest
1896 # action if in target manifest
1880 # action if not in target manifest
1897 # action if not in target manifest
1881 # make backup if in target manifest
1898 # make backup if in target manifest
1882 # make backup if not in target manifest
1899 # make backup if not in target manifest
1883 (modified, revert, remove, True, True),
1900 (modified, revert, remove, True, True),
1884 (added, revert, remove, True, False),
1901 (added, revert, remove, True, False),
1885 (removed, undelete, None, False, False),
1902 (removed, undelete, None, False, False),
1886 (deleted, revert, remove, False, False),
1903 (deleted, revert, remove, False, False),
1887 )
1904 )
1888
1905
1889 for abs, (rel, exact) in sorted(names.items()):
1906 for abs, (rel, exact) in sorted(names.items()):
1890 mfentry = mf.get(abs)
1907 mfentry = mf.get(abs)
1891 target = repo.wjoin(abs)
1908 target = repo.wjoin(abs)
1892 def handle(xlist, dobackup):
1909 def handle(xlist, dobackup):
1893 xlist[0].append(abs)
1910 xlist[0].append(abs)
1894 if (dobackup and not opts.get('no_backup') and
1911 if (dobackup and not opts.get('no_backup') and
1895 os.path.lexists(target)):
1912 os.path.lexists(target)):
1896 bakname = "%s.orig" % rel
1913 bakname = "%s.orig" % rel
1897 ui.note(_('saving current version of %s as %s\n') %
1914 ui.note(_('saving current version of %s as %s\n') %
1898 (rel, bakname))
1915 (rel, bakname))
1899 if not opts.get('dry_run'):
1916 if not opts.get('dry_run'):
1900 util.rename(target, bakname)
1917 util.rename(target, bakname)
1901 if ui.verbose or not exact:
1918 if ui.verbose or not exact:
1902 msg = xlist[1]
1919 msg = xlist[1]
1903 if not isinstance(msg, basestring):
1920 if not isinstance(msg, basestring):
1904 msg = msg(abs)
1921 msg = msg(abs)
1905 ui.status(msg % rel)
1922 ui.status(msg % rel)
1906 for table, hitlist, misslist, backuphit, backupmiss in disptable:
1923 for table, hitlist, misslist, backuphit, backupmiss in disptable:
1907 if abs not in table:
1924 if abs not in table:
1908 continue
1925 continue
1909 # file has changed in dirstate
1926 # file has changed in dirstate
1910 if mfentry:
1927 if mfentry:
1911 handle(hitlist, backuphit)
1928 handle(hitlist, backuphit)
1912 elif misslist is not None:
1929 elif misslist is not None:
1913 handle(misslist, backupmiss)
1930 handle(misslist, backupmiss)
1914 break
1931 break
1915 else:
1932 else:
1916 if abs not in repo.dirstate:
1933 if abs not in repo.dirstate:
1917 if mfentry:
1934 if mfentry:
1918 handle(add, True)
1935 handle(add, True)
1919 elif exact:
1936 elif exact:
1920 ui.warn(_('file not managed: %s\n') % rel)
1937 ui.warn(_('file not managed: %s\n') % rel)
1921 continue
1938 continue
1922 # file has not changed in dirstate
1939 # file has not changed in dirstate
1923 if node == parent:
1940 if node == parent:
1924 if exact:
1941 if exact:
1925 ui.warn(_('no changes needed to %s\n') % rel)
1942 ui.warn(_('no changes needed to %s\n') % rel)
1926 continue
1943 continue
1927 if pmf is None:
1944 if pmf is None:
1928 # only need parent manifest in this unlikely case,
1945 # only need parent manifest in this unlikely case,
1929 # so do not read by default
1946 # so do not read by default
1930 pmf = repo[parent].manifest()
1947 pmf = repo[parent].manifest()
1931 if abs in pmf and mfentry:
1948 if abs in pmf and mfentry:
1932 # if version of file is same in parent and target
1949 # if version of file is same in parent and target
1933 # manifests, do nothing
1950 # manifests, do nothing
1934 if (pmf[abs] != mfentry or
1951 if (pmf[abs] != mfentry or
1935 pmf.flags(abs) != mf.flags(abs)):
1952 pmf.flags(abs) != mf.flags(abs)):
1936 handle(revert, False)
1953 handle(revert, False)
1937 else:
1954 else:
1938 handle(remove, False)
1955 handle(remove, False)
1939
1956
1940 if not opts.get('dry_run'):
1957 if not opts.get('dry_run'):
1941 def checkout(f):
1958 def checkout(f):
1942 fc = ctx[f]
1959 fc = ctx[f]
1943 repo.wwrite(f, fc.data(), fc.flags())
1960 repo.wwrite(f, fc.data(), fc.flags())
1944
1961
1945 audit_path = scmutil.pathauditor(repo.root)
1962 audit_path = scmutil.pathauditor(repo.root)
1946 for f in remove[0]:
1963 for f in remove[0]:
1947 if repo.dirstate[f] == 'a':
1964 if repo.dirstate[f] == 'a':
1948 repo.dirstate.drop(f)
1965 repo.dirstate.drop(f)
1949 continue
1966 continue
1950 audit_path(f)
1967 audit_path(f)
1951 try:
1968 try:
1952 util.unlinkpath(repo.wjoin(f))
1969 util.unlinkpath(repo.wjoin(f))
1953 except OSError:
1970 except OSError:
1954 pass
1971 pass
1955 repo.dirstate.remove(f)
1972 repo.dirstate.remove(f)
1956
1973
1957 normal = None
1974 normal = None
1958 if node == parent:
1975 if node == parent:
1959 # We're reverting to our parent. If possible, we'd like status
1976 # We're reverting to our parent. If possible, we'd like status
1960 # to report the file as clean. We have to use normallookup for
1977 # to report the file as clean. We have to use normallookup for
1961 # merges to avoid losing information about merged/dirty files.
1978 # merges to avoid losing information about merged/dirty files.
1962 if p2 != nullid:
1979 if p2 != nullid:
1963 normal = repo.dirstate.normallookup
1980 normal = repo.dirstate.normallookup
1964 else:
1981 else:
1965 normal = repo.dirstate.normal
1982 normal = repo.dirstate.normal
1966 for f in revert[0]:
1983 for f in revert[0]:
1967 checkout(f)
1984 checkout(f)
1968 if normal:
1985 if normal:
1969 normal(f)
1986 normal(f)
1970
1987
1971 for f in add[0]:
1988 for f in add[0]:
1972 checkout(f)
1989 checkout(f)
1973 repo.dirstate.add(f)
1990 repo.dirstate.add(f)
1974
1991
1975 normal = repo.dirstate.normallookup
1992 normal = repo.dirstate.normallookup
1976 if node == parent and p2 == nullid:
1993 if node == parent and p2 == nullid:
1977 normal = repo.dirstate.normal
1994 normal = repo.dirstate.normal
1978 for f in undelete[0]:
1995 for f in undelete[0]:
1979 checkout(f)
1996 checkout(f)
1980 normal(f)
1997 normal(f)
1981
1998
1982 if targetsubs:
1999 if targetsubs:
1983 # Revert the subrepos on the revert list
2000 # Revert the subrepos on the revert list
1984 for sub in targetsubs:
2001 for sub in targetsubs:
1985 ctx.sub(sub).revert(ui, ctx.substate[sub], *pats, **opts)
2002 ctx.sub(sub).revert(ui, ctx.substate[sub], *pats, **opts)
1986 finally:
2003 finally:
1987 wlock.release()
2004 wlock.release()
1988
2005
1989 def command(table):
2006 def command(table):
1990 '''returns a function object bound to table which can be used as
2007 '''returns a function object bound to table which can be used as
1991 a decorator for populating table as a command table'''
2008 a decorator for populating table as a command table'''
1992
2009
1993 def cmd(name, options, synopsis=None):
2010 def cmd(name, options, synopsis=None):
1994 def decorator(func):
2011 def decorator(func):
1995 if synopsis:
2012 if synopsis:
1996 table[name] = func, options[:], synopsis
2013 table[name] = func, options[:], synopsis
1997 else:
2014 else:
1998 table[name] = func, options[:]
2015 table[name] = func, options[:]
1999 return func
2016 return func
2000 return decorator
2017 return decorator
2001
2018
2002 return cmd
2019 return cmd
General Comments 0
You need to be logged in to leave comments. Login now