##// END OF EJS Templates
addremove: normalize some variable names
Matt Mackall -
r8988:1247751d default
parent child Browse files
Show More
@@ -1,1242 +1,1242
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, incorporated herein by reference.
6 # GNU General Public License version 2, incorporated herein by reference.
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, glob
10 import os, sys, errno, re, glob
11 import mdiff, bdiff, util, templater, patch, error, encoding
11 import mdiff, bdiff, util, templater, patch, error, encoding
12 import match as _match
12 import match as _match
13
13
14 revrangesep = ':'
14 revrangesep = ':'
15
15
16 def findpossible(cmd, table, strict=False):
16 def findpossible(cmd, table, strict=False):
17 """
17 """
18 Return cmd -> (aliases, command table entry)
18 Return cmd -> (aliases, command table entry)
19 for each matching command.
19 for each matching command.
20 Return debug commands (or their aliases) only if no normal command matches.
20 Return debug commands (or their aliases) only if no normal command matches.
21 """
21 """
22 choice = {}
22 choice = {}
23 debugchoice = {}
23 debugchoice = {}
24 for e in table.keys():
24 for e in table.keys():
25 aliases = e.lstrip("^").split("|")
25 aliases = e.lstrip("^").split("|")
26 found = None
26 found = None
27 if cmd in aliases:
27 if cmd in aliases:
28 found = cmd
28 found = cmd
29 elif not strict:
29 elif not strict:
30 for a in aliases:
30 for a in aliases:
31 if a.startswith(cmd):
31 if a.startswith(cmd):
32 found = a
32 found = a
33 break
33 break
34 if found is not None:
34 if found is not None:
35 if aliases[0].startswith("debug") or found.startswith("debug"):
35 if aliases[0].startswith("debug") or found.startswith("debug"):
36 debugchoice[found] = (aliases, table[e])
36 debugchoice[found] = (aliases, table[e])
37 else:
37 else:
38 choice[found] = (aliases, table[e])
38 choice[found] = (aliases, table[e])
39
39
40 if not choice and debugchoice:
40 if not choice and debugchoice:
41 choice = debugchoice
41 choice = debugchoice
42
42
43 return choice
43 return choice
44
44
45 def findcmd(cmd, table, strict=True):
45 def findcmd(cmd, table, strict=True):
46 """Return (aliases, command table entry) for command string."""
46 """Return (aliases, command table entry) for command string."""
47 choice = findpossible(cmd, table, strict)
47 choice = findpossible(cmd, table, strict)
48
48
49 if cmd in choice:
49 if cmd in choice:
50 return choice[cmd]
50 return choice[cmd]
51
51
52 if len(choice) > 1:
52 if len(choice) > 1:
53 clist = choice.keys()
53 clist = choice.keys()
54 clist.sort()
54 clist.sort()
55 raise error.AmbiguousCommand(cmd, clist)
55 raise error.AmbiguousCommand(cmd, clist)
56
56
57 if choice:
57 if choice:
58 return choice.values()[0]
58 return choice.values()[0]
59
59
60 raise error.UnknownCommand(cmd)
60 raise error.UnknownCommand(cmd)
61
61
62 def bail_if_changed(repo):
62 def bail_if_changed(repo):
63 if repo.dirstate.parents()[1] != nullid:
63 if repo.dirstate.parents()[1] != nullid:
64 raise util.Abort(_('outstanding uncommitted merge'))
64 raise util.Abort(_('outstanding uncommitted merge'))
65 modified, added, removed, deleted = repo.status()[:4]
65 modified, added, removed, deleted = repo.status()[:4]
66 if modified or added or removed or deleted:
66 if modified or added or removed or deleted:
67 raise util.Abort(_("outstanding uncommitted changes"))
67 raise util.Abort(_("outstanding uncommitted changes"))
68
68
69 def logmessage(opts):
69 def logmessage(opts):
70 """ get the log message according to -m and -l option """
70 """ get the log message according to -m and -l option """
71 message = opts.get('message')
71 message = opts.get('message')
72 logfile = opts.get('logfile')
72 logfile = opts.get('logfile')
73
73
74 if message and logfile:
74 if message and logfile:
75 raise util.Abort(_('options --message and --logfile are mutually '
75 raise util.Abort(_('options --message and --logfile are mutually '
76 'exclusive'))
76 'exclusive'))
77 if not message and logfile:
77 if not message and logfile:
78 try:
78 try:
79 if logfile == '-':
79 if logfile == '-':
80 message = sys.stdin.read()
80 message = sys.stdin.read()
81 else:
81 else:
82 message = open(logfile).read()
82 message = open(logfile).read()
83 except IOError, inst:
83 except IOError, inst:
84 raise util.Abort(_("can't read commit message '%s': %s") %
84 raise util.Abort(_("can't read commit message '%s': %s") %
85 (logfile, inst.strerror))
85 (logfile, inst.strerror))
86 return message
86 return message
87
87
88 def loglimit(opts):
88 def loglimit(opts):
89 """get the log limit according to option -l/--limit"""
89 """get the log limit according to option -l/--limit"""
90 limit = opts.get('limit')
90 limit = opts.get('limit')
91 if limit:
91 if limit:
92 try:
92 try:
93 limit = int(limit)
93 limit = int(limit)
94 except ValueError:
94 except ValueError:
95 raise util.Abort(_('limit must be a positive integer'))
95 raise util.Abort(_('limit must be a positive integer'))
96 if limit <= 0: raise util.Abort(_('limit must be positive'))
96 if limit <= 0: raise util.Abort(_('limit must be positive'))
97 else:
97 else:
98 limit = sys.maxint
98 limit = sys.maxint
99 return limit
99 return limit
100
100
101 def remoteui(src, opts):
101 def remoteui(src, opts):
102 'build a remote ui from ui or repo and opts'
102 'build a remote ui from ui or repo and opts'
103 if hasattr(src, 'baseui'): # looks like a repository
103 if hasattr(src, 'baseui'): # looks like a repository
104 dst = src.baseui.copy() # drop repo-specific config
104 dst = src.baseui.copy() # drop repo-specific config
105 src = src.ui # copy target options from repo
105 src = src.ui # copy target options from repo
106 else: # assume it's a global ui object
106 else: # assume it's a global ui object
107 dst = src.copy() # keep all global options
107 dst = src.copy() # keep all global options
108
108
109 # copy ssh-specific options
109 # copy ssh-specific options
110 for o in 'ssh', 'remotecmd':
110 for o in 'ssh', 'remotecmd':
111 v = opts.get(o) or src.config('ui', o)
111 v = opts.get(o) or src.config('ui', o)
112 if v:
112 if v:
113 dst.setconfig("ui", o, v)
113 dst.setconfig("ui", o, v)
114 # copy bundle-specific options
114 # copy bundle-specific options
115 r = src.config('bundle', 'mainreporoot')
115 r = src.config('bundle', 'mainreporoot')
116 if r:
116 if r:
117 dst.setconfig('bundle', 'mainreporoot', r)
117 dst.setconfig('bundle', 'mainreporoot', r)
118
118
119 return dst
119 return dst
120
120
121 def revpair(repo, revs):
121 def revpair(repo, revs):
122 '''return pair of nodes, given list of revisions. second item can
122 '''return pair of nodes, given list of revisions. second item can
123 be None, meaning use working dir.'''
123 be None, meaning use working dir.'''
124
124
125 def revfix(repo, val, defval):
125 def revfix(repo, val, defval):
126 if not val and val != 0 and defval is not None:
126 if not val and val != 0 and defval is not None:
127 val = defval
127 val = defval
128 return repo.lookup(val)
128 return repo.lookup(val)
129
129
130 if not revs:
130 if not revs:
131 return repo.dirstate.parents()[0], None
131 return repo.dirstate.parents()[0], None
132 end = None
132 end = None
133 if len(revs) == 1:
133 if len(revs) == 1:
134 if revrangesep in revs[0]:
134 if revrangesep in revs[0]:
135 start, end = revs[0].split(revrangesep, 1)
135 start, end = revs[0].split(revrangesep, 1)
136 start = revfix(repo, start, 0)
136 start = revfix(repo, start, 0)
137 end = revfix(repo, end, len(repo) - 1)
137 end = revfix(repo, end, len(repo) - 1)
138 else:
138 else:
139 start = revfix(repo, revs[0], None)
139 start = revfix(repo, revs[0], None)
140 elif len(revs) == 2:
140 elif len(revs) == 2:
141 if revrangesep in revs[0] or revrangesep in revs[1]:
141 if revrangesep in revs[0] or revrangesep in revs[1]:
142 raise util.Abort(_('too many revisions specified'))
142 raise util.Abort(_('too many revisions specified'))
143 start = revfix(repo, revs[0], None)
143 start = revfix(repo, revs[0], None)
144 end = revfix(repo, revs[1], None)
144 end = revfix(repo, revs[1], None)
145 else:
145 else:
146 raise util.Abort(_('too many revisions specified'))
146 raise util.Abort(_('too many revisions specified'))
147 return start, end
147 return start, end
148
148
149 def revrange(repo, revs):
149 def revrange(repo, revs):
150 """Yield revision as strings from a list of revision specifications."""
150 """Yield revision as strings from a list of revision specifications."""
151
151
152 def revfix(repo, val, defval):
152 def revfix(repo, val, defval):
153 if not val and val != 0 and defval is not None:
153 if not val and val != 0 and defval is not None:
154 return defval
154 return defval
155 return repo.changelog.rev(repo.lookup(val))
155 return repo.changelog.rev(repo.lookup(val))
156
156
157 seen, l = set(), []
157 seen, l = set(), []
158 for spec in revs:
158 for spec in revs:
159 if revrangesep in spec:
159 if revrangesep in spec:
160 start, end = spec.split(revrangesep, 1)
160 start, end = spec.split(revrangesep, 1)
161 start = revfix(repo, start, 0)
161 start = revfix(repo, start, 0)
162 end = revfix(repo, end, len(repo) - 1)
162 end = revfix(repo, end, len(repo) - 1)
163 step = start > end and -1 or 1
163 step = start > end and -1 or 1
164 for rev in xrange(start, end+step, step):
164 for rev in xrange(start, end+step, step):
165 if rev in seen:
165 if rev in seen:
166 continue
166 continue
167 seen.add(rev)
167 seen.add(rev)
168 l.append(rev)
168 l.append(rev)
169 else:
169 else:
170 rev = revfix(repo, spec, None)
170 rev = revfix(repo, spec, None)
171 if rev in seen:
171 if rev in seen:
172 continue
172 continue
173 seen.add(rev)
173 seen.add(rev)
174 l.append(rev)
174 l.append(rev)
175
175
176 return l
176 return l
177
177
178 def make_filename(repo, pat, node,
178 def make_filename(repo, pat, node,
179 total=None, seqno=None, revwidth=None, pathname=None):
179 total=None, seqno=None, revwidth=None, pathname=None):
180 node_expander = {
180 node_expander = {
181 'H': lambda: hex(node),
181 'H': lambda: hex(node),
182 'R': lambda: str(repo.changelog.rev(node)),
182 'R': lambda: str(repo.changelog.rev(node)),
183 'h': lambda: short(node),
183 'h': lambda: short(node),
184 }
184 }
185 expander = {
185 expander = {
186 '%': lambda: '%',
186 '%': lambda: '%',
187 'b': lambda: os.path.basename(repo.root),
187 'b': lambda: os.path.basename(repo.root),
188 }
188 }
189
189
190 try:
190 try:
191 if node:
191 if node:
192 expander.update(node_expander)
192 expander.update(node_expander)
193 if node:
193 if node:
194 expander['r'] = (lambda:
194 expander['r'] = (lambda:
195 str(repo.changelog.rev(node)).zfill(revwidth or 0))
195 str(repo.changelog.rev(node)).zfill(revwidth or 0))
196 if total is not None:
196 if total is not None:
197 expander['N'] = lambda: str(total)
197 expander['N'] = lambda: str(total)
198 if seqno is not None:
198 if seqno is not None:
199 expander['n'] = lambda: str(seqno)
199 expander['n'] = lambda: str(seqno)
200 if total is not None and seqno is not None:
200 if total is not None and seqno is not None:
201 expander['n'] = lambda: str(seqno).zfill(len(str(total)))
201 expander['n'] = lambda: str(seqno).zfill(len(str(total)))
202 if pathname is not None:
202 if pathname is not None:
203 expander['s'] = lambda: os.path.basename(pathname)
203 expander['s'] = lambda: os.path.basename(pathname)
204 expander['d'] = lambda: os.path.dirname(pathname) or '.'
204 expander['d'] = lambda: os.path.dirname(pathname) or '.'
205 expander['p'] = lambda: pathname
205 expander['p'] = lambda: pathname
206
206
207 newname = []
207 newname = []
208 patlen = len(pat)
208 patlen = len(pat)
209 i = 0
209 i = 0
210 while i < patlen:
210 while i < patlen:
211 c = pat[i]
211 c = pat[i]
212 if c == '%':
212 if c == '%':
213 i += 1
213 i += 1
214 c = pat[i]
214 c = pat[i]
215 c = expander[c]()
215 c = expander[c]()
216 newname.append(c)
216 newname.append(c)
217 i += 1
217 i += 1
218 return ''.join(newname)
218 return ''.join(newname)
219 except KeyError, inst:
219 except KeyError, inst:
220 raise util.Abort(_("invalid format spec '%%%s' in output filename") %
220 raise util.Abort(_("invalid format spec '%%%s' in output filename") %
221 inst.args[0])
221 inst.args[0])
222
222
223 def make_file(repo, pat, node=None,
223 def make_file(repo, pat, node=None,
224 total=None, seqno=None, revwidth=None, mode='wb', pathname=None):
224 total=None, seqno=None, revwidth=None, mode='wb', pathname=None):
225
225
226 writable = 'w' in mode or 'a' in mode
226 writable = 'w' in mode or 'a' in mode
227
227
228 if not pat or pat == '-':
228 if not pat or pat == '-':
229 return writable and sys.stdout or sys.stdin
229 return writable and sys.stdout or sys.stdin
230 if hasattr(pat, 'write') and writable:
230 if hasattr(pat, 'write') and writable:
231 return pat
231 return pat
232 if hasattr(pat, 'read') and 'r' in mode:
232 if hasattr(pat, 'read') and 'r' in mode:
233 return pat
233 return pat
234 return open(make_filename(repo, pat, node, total, seqno, revwidth,
234 return open(make_filename(repo, pat, node, total, seqno, revwidth,
235 pathname),
235 pathname),
236 mode)
236 mode)
237
237
238 def expandpats(pats):
238 def expandpats(pats):
239 if not util.expandglobs:
239 if not util.expandglobs:
240 return list(pats)
240 return list(pats)
241 ret = []
241 ret = []
242 for p in pats:
242 for p in pats:
243 kind, name = _match._patsplit(p, None)
243 kind, name = _match._patsplit(p, None)
244 if kind is None:
244 if kind is None:
245 globbed = glob.glob(name)
245 globbed = glob.glob(name)
246 if globbed:
246 if globbed:
247 ret.extend(globbed)
247 ret.extend(globbed)
248 continue
248 continue
249 ret.append(p)
249 ret.append(p)
250 return ret
250 return ret
251
251
252 def match(repo, pats=[], opts={}, globbed=False, default='relpath'):
252 def match(repo, pats=[], opts={}, globbed=False, default='relpath'):
253 if not globbed and default == 'relpath':
253 if not globbed and default == 'relpath':
254 pats = expandpats(pats or [])
254 pats = expandpats(pats or [])
255 m = _match.match(repo.root, repo.getcwd(), pats,
255 m = _match.match(repo.root, repo.getcwd(), pats,
256 opts.get('include'), opts.get('exclude'), default)
256 opts.get('include'), opts.get('exclude'), default)
257 def badfn(f, msg):
257 def badfn(f, msg):
258 repo.ui.warn("%s: %s\n" % (m.rel(f), msg))
258 repo.ui.warn("%s: %s\n" % (m.rel(f), msg))
259 m.bad = badfn
259 m.bad = badfn
260 return m
260 return m
261
261
262 def matchall(repo):
262 def matchall(repo):
263 return _match.always(repo.root, repo.getcwd())
263 return _match.always(repo.root, repo.getcwd())
264
264
265 def matchfiles(repo, files):
265 def matchfiles(repo, files):
266 return _match.exact(repo.root, repo.getcwd(), files)
266 return _match.exact(repo.root, repo.getcwd(), files)
267
267
268 def findrenames(repo, match, threshold):
268 def findrenames(repo, match, threshold):
269 '''find renamed files -- yields (before, after, score) tuples'''
269 '''find renamed files -- yields (before, after, score) tuples'''
270 added, removed = repo.status(match=match)[1:3]
270 added, removed = repo.status(match=match)[1:3]
271 ctx = repo['.']
271 ctx = repo['.']
272 for a in added:
272 for a in added:
273 aa = repo.wread(a)
273 aa = repo.wread(a)
274 bestname, bestscore = None, threshold
274 bestname, bestscore = None, threshold
275 for r in removed:
275 for r in removed:
276 rr = ctx.filectx(r).data()
276 rr = ctx.filectx(r).data()
277
277
278 # bdiff.blocks() returns blocks of matching lines
278 # bdiff.blocks() returns blocks of matching lines
279 # count the number of bytes in each
279 # count the number of bytes in each
280 equal = 0
280 equal = 0
281 alines = mdiff.splitnewlines(aa)
281 alines = mdiff.splitnewlines(aa)
282 matches = bdiff.blocks(aa, rr)
282 matches = bdiff.blocks(aa, rr)
283 for x1,x2,y1,y2 in matches:
283 for x1,x2,y1,y2 in matches:
284 for line in alines[x1:x2]:
284 for line in alines[x1:x2]:
285 equal += len(line)
285 equal += len(line)
286
286
287 lengths = len(aa) + len(rr)
287 lengths = len(aa) + len(rr)
288 if lengths:
288 if lengths:
289 myscore = equal*2.0 / lengths
289 myscore = equal*2.0 / lengths
290 if myscore >= bestscore:
290 if myscore >= bestscore:
291 bestname, bestscore = r, myscore
291 bestname, bestscore = r, myscore
292 if bestname:
292 if bestname:
293 yield bestname, a, bestscore
293 yield bestname, a, bestscore
294
294
295 def addremove(repo, pats=[], opts={}, dry_run=None, similarity=None):
295 def addremove(repo, pats=[], opts={}, dry_run=None, similarity=None):
296 if dry_run is None:
296 if dry_run is None:
297 dry_run = opts.get('dry_run')
297 dry_run = opts.get('dry_run')
298 if similarity is None:
298 if similarity is None:
299 similarity = float(opts.get('similarity') or 0)
299 similarity = float(opts.get('similarity') or 0)
300 add, remove = [], []
300 unknown, deleted = [], []
301 audit_path = util.path_auditor(repo.root)
301 audit_path = util.path_auditor(repo.root)
302 m = match(repo, pats, opts)
302 m = match(repo, pats, opts)
303 for abs in repo.walk(m):
303 for abs in repo.walk(m):
304 target = repo.wjoin(abs)
304 target = repo.wjoin(abs)
305 good = True
305 good = True
306 try:
306 try:
307 audit_path(abs)
307 audit_path(abs)
308 except:
308 except:
309 good = False
309 good = False
310 rel = m.rel(abs)
310 rel = m.rel(abs)
311 exact = m.exact(abs)
311 exact = m.exact(abs)
312 if good and abs not in repo.dirstate:
312 if good and abs not in repo.dirstate:
313 add.append(abs)
313 unknown.append(abs)
314 if repo.ui.verbose or not exact:
314 if repo.ui.verbose or not exact:
315 repo.ui.status(_('adding %s\n') % ((pats and rel) or abs))
315 repo.ui.status(_('adding %s\n') % ((pats and rel) or abs))
316 if repo.dirstate[abs] != 'r' and (not good or not util.lexists(target)
316 if repo.dirstate[abs] != 'r' and (not good or not util.lexists(target)
317 or (os.path.isdir(target) and not os.path.islink(target))):
317 or (os.path.isdir(target) and not os.path.islink(target))):
318 remove.append(abs)
318 deleted.append(abs)
319 if repo.ui.verbose or not exact:
319 if repo.ui.verbose or not exact:
320 repo.ui.status(_('removing %s\n') % ((pats and rel) or abs))
320 repo.ui.status(_('removing %s\n') % ((pats and rel) or abs))
321 if not dry_run:
321 if not dry_run:
322 repo.remove(remove)
322 repo.remove(deleted)
323 repo.add(add)
323 repo.add(unknown)
324 if similarity > 0:
324 if similarity > 0:
325 for old, new, score in findrenames(repo, m, similarity):
325 for old, new, score in findrenames(repo, m, similarity):
326 if repo.ui.verbose or not m.exact(old) or not m.exact(new):
326 if repo.ui.verbose or not m.exact(old) or not m.exact(new):
327 repo.ui.status(_('recording removal of %s as rename to %s '
327 repo.ui.status(_('recording removal of %s as rename to %s '
328 '(%d%% similar)\n') %
328 '(%d%% similar)\n') %
329 (m.rel(old), m.rel(new), score * 100))
329 (m.rel(old), m.rel(new), score * 100))
330 if not dry_run:
330 if not dry_run:
331 repo.copy(old, new)
331 repo.copy(old, new)
332
332
333 def copy(ui, repo, pats, opts, rename=False):
333 def copy(ui, repo, pats, opts, rename=False):
334 # called with the repo lock held
334 # called with the repo lock held
335 #
335 #
336 # hgsep => pathname that uses "/" to separate directories
336 # hgsep => pathname that uses "/" to separate directories
337 # ossep => pathname that uses os.sep to separate directories
337 # ossep => pathname that uses os.sep to separate directories
338 cwd = repo.getcwd()
338 cwd = repo.getcwd()
339 targets = {}
339 targets = {}
340 after = opts.get("after")
340 after = opts.get("after")
341 dryrun = opts.get("dry_run")
341 dryrun = opts.get("dry_run")
342
342
343 def walkpat(pat):
343 def walkpat(pat):
344 srcs = []
344 srcs = []
345 m = match(repo, [pat], opts, globbed=True)
345 m = match(repo, [pat], opts, globbed=True)
346 for abs in repo.walk(m):
346 for abs in repo.walk(m):
347 state = repo.dirstate[abs]
347 state = repo.dirstate[abs]
348 rel = m.rel(abs)
348 rel = m.rel(abs)
349 exact = m.exact(abs)
349 exact = m.exact(abs)
350 if state in '?r':
350 if state in '?r':
351 if exact and state == '?':
351 if exact and state == '?':
352 ui.warn(_('%s: not copying - file is not managed\n') % rel)
352 ui.warn(_('%s: not copying - file is not managed\n') % rel)
353 if exact and state == 'r':
353 if exact and state == 'r':
354 ui.warn(_('%s: not copying - file has been marked for'
354 ui.warn(_('%s: not copying - file has been marked for'
355 ' remove\n') % rel)
355 ' remove\n') % rel)
356 continue
356 continue
357 # abs: hgsep
357 # abs: hgsep
358 # rel: ossep
358 # rel: ossep
359 srcs.append((abs, rel, exact))
359 srcs.append((abs, rel, exact))
360 return srcs
360 return srcs
361
361
362 # abssrc: hgsep
362 # abssrc: hgsep
363 # relsrc: ossep
363 # relsrc: ossep
364 # otarget: ossep
364 # otarget: ossep
365 def copyfile(abssrc, relsrc, otarget, exact):
365 def copyfile(abssrc, relsrc, otarget, exact):
366 abstarget = util.canonpath(repo.root, cwd, otarget)
366 abstarget = util.canonpath(repo.root, cwd, otarget)
367 reltarget = repo.pathto(abstarget, cwd)
367 reltarget = repo.pathto(abstarget, cwd)
368 target = repo.wjoin(abstarget)
368 target = repo.wjoin(abstarget)
369 src = repo.wjoin(abssrc)
369 src = repo.wjoin(abssrc)
370 state = repo.dirstate[abstarget]
370 state = repo.dirstate[abstarget]
371
371
372 # check for collisions
372 # check for collisions
373 prevsrc = targets.get(abstarget)
373 prevsrc = targets.get(abstarget)
374 if prevsrc is not None:
374 if prevsrc is not None:
375 ui.warn(_('%s: not overwriting - %s collides with %s\n') %
375 ui.warn(_('%s: not overwriting - %s collides with %s\n') %
376 (reltarget, repo.pathto(abssrc, cwd),
376 (reltarget, repo.pathto(abssrc, cwd),
377 repo.pathto(prevsrc, cwd)))
377 repo.pathto(prevsrc, cwd)))
378 return
378 return
379
379
380 # check for overwrites
380 # check for overwrites
381 exists = os.path.exists(target)
381 exists = os.path.exists(target)
382 if not after and exists or after and state in 'mn':
382 if not after and exists or after and state in 'mn':
383 if not opts['force']:
383 if not opts['force']:
384 ui.warn(_('%s: not overwriting - file exists\n') %
384 ui.warn(_('%s: not overwriting - file exists\n') %
385 reltarget)
385 reltarget)
386 return
386 return
387
387
388 if after:
388 if after:
389 if not exists:
389 if not exists:
390 return
390 return
391 elif not dryrun:
391 elif not dryrun:
392 try:
392 try:
393 if exists:
393 if exists:
394 os.unlink(target)
394 os.unlink(target)
395 targetdir = os.path.dirname(target) or '.'
395 targetdir = os.path.dirname(target) or '.'
396 if not os.path.isdir(targetdir):
396 if not os.path.isdir(targetdir):
397 os.makedirs(targetdir)
397 os.makedirs(targetdir)
398 util.copyfile(src, target)
398 util.copyfile(src, target)
399 except IOError, inst:
399 except IOError, inst:
400 if inst.errno == errno.ENOENT:
400 if inst.errno == errno.ENOENT:
401 ui.warn(_('%s: deleted in working copy\n') % relsrc)
401 ui.warn(_('%s: deleted in working copy\n') % relsrc)
402 else:
402 else:
403 ui.warn(_('%s: cannot copy - %s\n') %
403 ui.warn(_('%s: cannot copy - %s\n') %
404 (relsrc, inst.strerror))
404 (relsrc, inst.strerror))
405 return True # report a failure
405 return True # report a failure
406
406
407 if ui.verbose or not exact:
407 if ui.verbose or not exact:
408 if rename:
408 if rename:
409 ui.status(_('moving %s to %s\n') % (relsrc, reltarget))
409 ui.status(_('moving %s to %s\n') % (relsrc, reltarget))
410 else:
410 else:
411 ui.status(_('copying %s to %s\n') % (relsrc, reltarget))
411 ui.status(_('copying %s to %s\n') % (relsrc, reltarget))
412
412
413 targets[abstarget] = abssrc
413 targets[abstarget] = abssrc
414
414
415 # fix up dirstate
415 # fix up dirstate
416 origsrc = repo.dirstate.copied(abssrc) or abssrc
416 origsrc = repo.dirstate.copied(abssrc) or abssrc
417 if abstarget == origsrc: # copying back a copy?
417 if abstarget == origsrc: # copying back a copy?
418 if state not in 'mn' and not dryrun:
418 if state not in 'mn' and not dryrun:
419 repo.dirstate.normallookup(abstarget)
419 repo.dirstate.normallookup(abstarget)
420 else:
420 else:
421 if repo.dirstate[origsrc] == 'a' and origsrc == abssrc:
421 if repo.dirstate[origsrc] == 'a' and origsrc == abssrc:
422 if not ui.quiet:
422 if not ui.quiet:
423 ui.warn(_("%s has not been committed yet, so no copy "
423 ui.warn(_("%s has not been committed yet, so no copy "
424 "data will be stored for %s.\n")
424 "data will be stored for %s.\n")
425 % (repo.pathto(origsrc, cwd), reltarget))
425 % (repo.pathto(origsrc, cwd), reltarget))
426 if repo.dirstate[abstarget] in '?r' and not dryrun:
426 if repo.dirstate[abstarget] in '?r' and not dryrun:
427 repo.add([abstarget])
427 repo.add([abstarget])
428 elif not dryrun:
428 elif not dryrun:
429 repo.copy(origsrc, abstarget)
429 repo.copy(origsrc, abstarget)
430
430
431 if rename and not dryrun:
431 if rename and not dryrun:
432 repo.remove([abssrc], not after)
432 repo.remove([abssrc], not after)
433
433
434 # pat: ossep
434 # pat: ossep
435 # dest ossep
435 # dest ossep
436 # srcs: list of (hgsep, hgsep, ossep, bool)
436 # srcs: list of (hgsep, hgsep, ossep, bool)
437 # return: function that takes hgsep and returns ossep
437 # return: function that takes hgsep and returns ossep
438 def targetpathfn(pat, dest, srcs):
438 def targetpathfn(pat, dest, srcs):
439 if os.path.isdir(pat):
439 if os.path.isdir(pat):
440 abspfx = util.canonpath(repo.root, cwd, pat)
440 abspfx = util.canonpath(repo.root, cwd, pat)
441 abspfx = util.localpath(abspfx)
441 abspfx = util.localpath(abspfx)
442 if destdirexists:
442 if destdirexists:
443 striplen = len(os.path.split(abspfx)[0])
443 striplen = len(os.path.split(abspfx)[0])
444 else:
444 else:
445 striplen = len(abspfx)
445 striplen = len(abspfx)
446 if striplen:
446 if striplen:
447 striplen += len(os.sep)
447 striplen += len(os.sep)
448 res = lambda p: os.path.join(dest, util.localpath(p)[striplen:])
448 res = lambda p: os.path.join(dest, util.localpath(p)[striplen:])
449 elif destdirexists:
449 elif destdirexists:
450 res = lambda p: os.path.join(dest,
450 res = lambda p: os.path.join(dest,
451 os.path.basename(util.localpath(p)))
451 os.path.basename(util.localpath(p)))
452 else:
452 else:
453 res = lambda p: dest
453 res = lambda p: dest
454 return res
454 return res
455
455
456 # pat: ossep
456 # pat: ossep
457 # dest ossep
457 # dest ossep
458 # srcs: list of (hgsep, hgsep, ossep, bool)
458 # srcs: list of (hgsep, hgsep, ossep, bool)
459 # return: function that takes hgsep and returns ossep
459 # return: function that takes hgsep and returns ossep
460 def targetpathafterfn(pat, dest, srcs):
460 def targetpathafterfn(pat, dest, srcs):
461 if _match.patkind(pat):
461 if _match.patkind(pat):
462 # a mercurial pattern
462 # a mercurial pattern
463 res = lambda p: os.path.join(dest,
463 res = lambda p: os.path.join(dest,
464 os.path.basename(util.localpath(p)))
464 os.path.basename(util.localpath(p)))
465 else:
465 else:
466 abspfx = util.canonpath(repo.root, cwd, pat)
466 abspfx = util.canonpath(repo.root, cwd, pat)
467 if len(abspfx) < len(srcs[0][0]):
467 if len(abspfx) < len(srcs[0][0]):
468 # A directory. Either the target path contains the last
468 # A directory. Either the target path contains the last
469 # component of the source path or it does not.
469 # component of the source path or it does not.
470 def evalpath(striplen):
470 def evalpath(striplen):
471 score = 0
471 score = 0
472 for s in srcs:
472 for s in srcs:
473 t = os.path.join(dest, util.localpath(s[0])[striplen:])
473 t = os.path.join(dest, util.localpath(s[0])[striplen:])
474 if os.path.exists(t):
474 if os.path.exists(t):
475 score += 1
475 score += 1
476 return score
476 return score
477
477
478 abspfx = util.localpath(abspfx)
478 abspfx = util.localpath(abspfx)
479 striplen = len(abspfx)
479 striplen = len(abspfx)
480 if striplen:
480 if striplen:
481 striplen += len(os.sep)
481 striplen += len(os.sep)
482 if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])):
482 if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])):
483 score = evalpath(striplen)
483 score = evalpath(striplen)
484 striplen1 = len(os.path.split(abspfx)[0])
484 striplen1 = len(os.path.split(abspfx)[0])
485 if striplen1:
485 if striplen1:
486 striplen1 += len(os.sep)
486 striplen1 += len(os.sep)
487 if evalpath(striplen1) > score:
487 if evalpath(striplen1) > score:
488 striplen = striplen1
488 striplen = striplen1
489 res = lambda p: os.path.join(dest,
489 res = lambda p: os.path.join(dest,
490 util.localpath(p)[striplen:])
490 util.localpath(p)[striplen:])
491 else:
491 else:
492 # a file
492 # a file
493 if destdirexists:
493 if destdirexists:
494 res = lambda p: os.path.join(dest,
494 res = lambda p: os.path.join(dest,
495 os.path.basename(util.localpath(p)))
495 os.path.basename(util.localpath(p)))
496 else:
496 else:
497 res = lambda p: dest
497 res = lambda p: dest
498 return res
498 return res
499
499
500
500
501 pats = expandpats(pats)
501 pats = expandpats(pats)
502 if not pats:
502 if not pats:
503 raise util.Abort(_('no source or destination specified'))
503 raise util.Abort(_('no source or destination specified'))
504 if len(pats) == 1:
504 if len(pats) == 1:
505 raise util.Abort(_('no destination specified'))
505 raise util.Abort(_('no destination specified'))
506 dest = pats.pop()
506 dest = pats.pop()
507 destdirexists = os.path.isdir(dest) and not os.path.islink(dest)
507 destdirexists = os.path.isdir(dest) and not os.path.islink(dest)
508 if not destdirexists:
508 if not destdirexists:
509 if len(pats) > 1 or _match.patkind(pats[0]):
509 if len(pats) > 1 or _match.patkind(pats[0]):
510 raise util.Abort(_('with multiple sources, destination must be an '
510 raise util.Abort(_('with multiple sources, destination must be an '
511 'existing directory'))
511 'existing directory'))
512 if util.endswithsep(dest):
512 if util.endswithsep(dest):
513 raise util.Abort(_('destination %s is not a directory') % dest)
513 raise util.Abort(_('destination %s is not a directory') % dest)
514
514
515 tfn = targetpathfn
515 tfn = targetpathfn
516 if after:
516 if after:
517 tfn = targetpathafterfn
517 tfn = targetpathafterfn
518 copylist = []
518 copylist = []
519 for pat in pats:
519 for pat in pats:
520 srcs = walkpat(pat)
520 srcs = walkpat(pat)
521 if not srcs:
521 if not srcs:
522 continue
522 continue
523 copylist.append((tfn(pat, dest, srcs), srcs))
523 copylist.append((tfn(pat, dest, srcs), srcs))
524 if not copylist:
524 if not copylist:
525 raise util.Abort(_('no files to copy'))
525 raise util.Abort(_('no files to copy'))
526
526
527 errors = 0
527 errors = 0
528 for targetpath, srcs in copylist:
528 for targetpath, srcs in copylist:
529 for abssrc, relsrc, exact in srcs:
529 for abssrc, relsrc, exact in srcs:
530 if copyfile(abssrc, relsrc, targetpath(abssrc), exact):
530 if copyfile(abssrc, relsrc, targetpath(abssrc), exact):
531 errors += 1
531 errors += 1
532
532
533 if errors:
533 if errors:
534 ui.warn(_('(consider using --after)\n'))
534 ui.warn(_('(consider using --after)\n'))
535
535
536 return errors
536 return errors
537
537
538 def service(opts, parentfn=None, initfn=None, runfn=None, logfile=None):
538 def service(opts, parentfn=None, initfn=None, runfn=None, logfile=None):
539 '''Run a command as a service.'''
539 '''Run a command as a service.'''
540
540
541 if opts['daemon'] and not opts['daemon_pipefds']:
541 if opts['daemon'] and not opts['daemon_pipefds']:
542 rfd, wfd = os.pipe()
542 rfd, wfd = os.pipe()
543 args = sys.argv[:]
543 args = sys.argv[:]
544 args.append('--daemon-pipefds=%d,%d' % (rfd, wfd))
544 args.append('--daemon-pipefds=%d,%d' % (rfd, wfd))
545 # Don't pass --cwd to the child process, because we've already
545 # Don't pass --cwd to the child process, because we've already
546 # changed directory.
546 # changed directory.
547 for i in xrange(1,len(args)):
547 for i in xrange(1,len(args)):
548 if args[i].startswith('--cwd='):
548 if args[i].startswith('--cwd='):
549 del args[i]
549 del args[i]
550 break
550 break
551 elif args[i].startswith('--cwd'):
551 elif args[i].startswith('--cwd'):
552 del args[i:i+2]
552 del args[i:i+2]
553 break
553 break
554 pid = os.spawnvp(os.P_NOWAIT | getattr(os, 'P_DETACH', 0),
554 pid = os.spawnvp(os.P_NOWAIT | getattr(os, 'P_DETACH', 0),
555 args[0], args)
555 args[0], args)
556 os.close(wfd)
556 os.close(wfd)
557 os.read(rfd, 1)
557 os.read(rfd, 1)
558 if parentfn:
558 if parentfn:
559 return parentfn(pid)
559 return parentfn(pid)
560 else:
560 else:
561 os._exit(0)
561 os._exit(0)
562
562
563 if initfn:
563 if initfn:
564 initfn()
564 initfn()
565
565
566 if opts['pid_file']:
566 if opts['pid_file']:
567 fp = open(opts['pid_file'], 'w')
567 fp = open(opts['pid_file'], 'w')
568 fp.write(str(os.getpid()) + '\n')
568 fp.write(str(os.getpid()) + '\n')
569 fp.close()
569 fp.close()
570
570
571 if opts['daemon_pipefds']:
571 if opts['daemon_pipefds']:
572 rfd, wfd = [int(x) for x in opts['daemon_pipefds'].split(',')]
572 rfd, wfd = [int(x) for x in opts['daemon_pipefds'].split(',')]
573 os.close(rfd)
573 os.close(rfd)
574 try:
574 try:
575 os.setsid()
575 os.setsid()
576 except AttributeError:
576 except AttributeError:
577 pass
577 pass
578 os.write(wfd, 'y')
578 os.write(wfd, 'y')
579 os.close(wfd)
579 os.close(wfd)
580 sys.stdout.flush()
580 sys.stdout.flush()
581 sys.stderr.flush()
581 sys.stderr.flush()
582
582
583 nullfd = os.open(util.nulldev, os.O_RDWR)
583 nullfd = os.open(util.nulldev, os.O_RDWR)
584 logfilefd = nullfd
584 logfilefd = nullfd
585 if logfile:
585 if logfile:
586 logfilefd = os.open(logfile, os.O_RDWR | os.O_CREAT | os.O_APPEND)
586 logfilefd = os.open(logfile, os.O_RDWR | os.O_CREAT | os.O_APPEND)
587 os.dup2(nullfd, 0)
587 os.dup2(nullfd, 0)
588 os.dup2(logfilefd, 1)
588 os.dup2(logfilefd, 1)
589 os.dup2(logfilefd, 2)
589 os.dup2(logfilefd, 2)
590 if nullfd not in (0, 1, 2):
590 if nullfd not in (0, 1, 2):
591 os.close(nullfd)
591 os.close(nullfd)
592 if logfile and logfilefd not in (0, 1, 2):
592 if logfile and logfilefd not in (0, 1, 2):
593 os.close(logfilefd)
593 os.close(logfilefd)
594
594
595 if runfn:
595 if runfn:
596 return runfn()
596 return runfn()
597
597
598 class changeset_printer(object):
598 class changeset_printer(object):
599 '''show changeset information when templating not requested.'''
599 '''show changeset information when templating not requested.'''
600
600
601 def __init__(self, ui, repo, patch, diffopts, buffered):
601 def __init__(self, ui, repo, patch, diffopts, buffered):
602 self.ui = ui
602 self.ui = ui
603 self.repo = repo
603 self.repo = repo
604 self.buffered = buffered
604 self.buffered = buffered
605 self.patch = patch
605 self.patch = patch
606 self.diffopts = diffopts
606 self.diffopts = diffopts
607 self.header = {}
607 self.header = {}
608 self.hunk = {}
608 self.hunk = {}
609 self.lastheader = None
609 self.lastheader = None
610
610
611 def flush(self, rev):
611 def flush(self, rev):
612 if rev in self.header:
612 if rev in self.header:
613 h = self.header[rev]
613 h = self.header[rev]
614 if h != self.lastheader:
614 if h != self.lastheader:
615 self.lastheader = h
615 self.lastheader = h
616 self.ui.write(h)
616 self.ui.write(h)
617 del self.header[rev]
617 del self.header[rev]
618 if rev in self.hunk:
618 if rev in self.hunk:
619 self.ui.write(self.hunk[rev])
619 self.ui.write(self.hunk[rev])
620 del self.hunk[rev]
620 del self.hunk[rev]
621 return 1
621 return 1
622 return 0
622 return 0
623
623
624 def show(self, ctx, copies=(), **props):
624 def show(self, ctx, copies=(), **props):
625 if self.buffered:
625 if self.buffered:
626 self.ui.pushbuffer()
626 self.ui.pushbuffer()
627 self._show(ctx, copies, props)
627 self._show(ctx, copies, props)
628 self.hunk[ctx.rev()] = self.ui.popbuffer()
628 self.hunk[ctx.rev()] = self.ui.popbuffer()
629 else:
629 else:
630 self._show(ctx, copies, props)
630 self._show(ctx, copies, props)
631
631
632 def _show(self, ctx, copies, props):
632 def _show(self, ctx, copies, props):
633 '''show a single changeset or file revision'''
633 '''show a single changeset or file revision'''
634 changenode = ctx.node()
634 changenode = ctx.node()
635 rev = ctx.rev()
635 rev = ctx.rev()
636
636
637 if self.ui.quiet:
637 if self.ui.quiet:
638 self.ui.write("%d:%s\n" % (rev, short(changenode)))
638 self.ui.write("%d:%s\n" % (rev, short(changenode)))
639 return
639 return
640
640
641 log = self.repo.changelog
641 log = self.repo.changelog
642 changes = log.read(changenode)
642 changes = log.read(changenode)
643 date = util.datestr(changes[2])
643 date = util.datestr(changes[2])
644 extra = changes[5]
644 extra = changes[5]
645 branch = extra.get("branch")
645 branch = extra.get("branch")
646
646
647 hexfunc = self.ui.debugflag and hex or short
647 hexfunc = self.ui.debugflag and hex or short
648
648
649 parents = [(p, hexfunc(log.node(p)))
649 parents = [(p, hexfunc(log.node(p)))
650 for p in self._meaningful_parentrevs(log, rev)]
650 for p in self._meaningful_parentrevs(log, rev)]
651
651
652 self.ui.write(_("changeset: %d:%s\n") % (rev, hexfunc(changenode)))
652 self.ui.write(_("changeset: %d:%s\n") % (rev, hexfunc(changenode)))
653
653
654 # don't show the default branch name
654 # don't show the default branch name
655 if branch != 'default':
655 if branch != 'default':
656 branch = encoding.tolocal(branch)
656 branch = encoding.tolocal(branch)
657 self.ui.write(_("branch: %s\n") % branch)
657 self.ui.write(_("branch: %s\n") % branch)
658 for tag in self.repo.nodetags(changenode):
658 for tag in self.repo.nodetags(changenode):
659 self.ui.write(_("tag: %s\n") % tag)
659 self.ui.write(_("tag: %s\n") % tag)
660 for parent in parents:
660 for parent in parents:
661 self.ui.write(_("parent: %d:%s\n") % parent)
661 self.ui.write(_("parent: %d:%s\n") % parent)
662
662
663 if self.ui.debugflag:
663 if self.ui.debugflag:
664 self.ui.write(_("manifest: %d:%s\n") %
664 self.ui.write(_("manifest: %d:%s\n") %
665 (self.repo.manifest.rev(changes[0]), hex(changes[0])))
665 (self.repo.manifest.rev(changes[0]), hex(changes[0])))
666 self.ui.write(_("user: %s\n") % changes[1])
666 self.ui.write(_("user: %s\n") % changes[1])
667 self.ui.write(_("date: %s\n") % date)
667 self.ui.write(_("date: %s\n") % date)
668
668
669 if self.ui.debugflag:
669 if self.ui.debugflag:
670 files = self.repo.status(log.parents(changenode)[0], changenode)[:3]
670 files = self.repo.status(log.parents(changenode)[0], changenode)[:3]
671 for key, value in zip([_("files:"), _("files+:"), _("files-:")],
671 for key, value in zip([_("files:"), _("files+:"), _("files-:")],
672 files):
672 files):
673 if value:
673 if value:
674 self.ui.write("%-12s %s\n" % (key, " ".join(value)))
674 self.ui.write("%-12s %s\n" % (key, " ".join(value)))
675 elif changes[3] and self.ui.verbose:
675 elif changes[3] and self.ui.verbose:
676 self.ui.write(_("files: %s\n") % " ".join(changes[3]))
676 self.ui.write(_("files: %s\n") % " ".join(changes[3]))
677 if copies and self.ui.verbose:
677 if copies and self.ui.verbose:
678 copies = ['%s (%s)' % c for c in copies]
678 copies = ['%s (%s)' % c for c in copies]
679 self.ui.write(_("copies: %s\n") % ' '.join(copies))
679 self.ui.write(_("copies: %s\n") % ' '.join(copies))
680
680
681 if extra and self.ui.debugflag:
681 if extra and self.ui.debugflag:
682 for key, value in sorted(extra.items()):
682 for key, value in sorted(extra.items()):
683 self.ui.write(_("extra: %s=%s\n")
683 self.ui.write(_("extra: %s=%s\n")
684 % (key, value.encode('string_escape')))
684 % (key, value.encode('string_escape')))
685
685
686 description = changes[4].strip()
686 description = changes[4].strip()
687 if description:
687 if description:
688 if self.ui.verbose:
688 if self.ui.verbose:
689 self.ui.write(_("description:\n"))
689 self.ui.write(_("description:\n"))
690 self.ui.write(description)
690 self.ui.write(description)
691 self.ui.write("\n\n")
691 self.ui.write("\n\n")
692 else:
692 else:
693 self.ui.write(_("summary: %s\n") %
693 self.ui.write(_("summary: %s\n") %
694 description.splitlines()[0])
694 description.splitlines()[0])
695 self.ui.write("\n")
695 self.ui.write("\n")
696
696
697 self.showpatch(changenode)
697 self.showpatch(changenode)
698
698
699 def showpatch(self, node):
699 def showpatch(self, node):
700 if self.patch:
700 if self.patch:
701 prev = self.repo.changelog.parents(node)[0]
701 prev = self.repo.changelog.parents(node)[0]
702 chunks = patch.diff(self.repo, prev, node, match=self.patch,
702 chunks = patch.diff(self.repo, prev, node, match=self.patch,
703 opts=patch.diffopts(self.ui, self.diffopts))
703 opts=patch.diffopts(self.ui, self.diffopts))
704 for chunk in chunks:
704 for chunk in chunks:
705 self.ui.write(chunk)
705 self.ui.write(chunk)
706 self.ui.write("\n")
706 self.ui.write("\n")
707
707
708 def _meaningful_parentrevs(self, log, rev):
708 def _meaningful_parentrevs(self, log, rev):
709 """Return list of meaningful (or all if debug) parentrevs for rev.
709 """Return list of meaningful (or all if debug) parentrevs for rev.
710
710
711 For merges (two non-nullrev revisions) both parents are meaningful.
711 For merges (two non-nullrev revisions) both parents are meaningful.
712 Otherwise the first parent revision is considered meaningful if it
712 Otherwise the first parent revision is considered meaningful if it
713 is not the preceding revision.
713 is not the preceding revision.
714 """
714 """
715 parents = log.parentrevs(rev)
715 parents = log.parentrevs(rev)
716 if not self.ui.debugflag and parents[1] == nullrev:
716 if not self.ui.debugflag and parents[1] == nullrev:
717 if parents[0] >= rev - 1:
717 if parents[0] >= rev - 1:
718 parents = []
718 parents = []
719 else:
719 else:
720 parents = [parents[0]]
720 parents = [parents[0]]
721 return parents
721 return parents
722
722
723
723
724 class changeset_templater(changeset_printer):
724 class changeset_templater(changeset_printer):
725 '''format changeset information.'''
725 '''format changeset information.'''
726
726
727 def __init__(self, ui, repo, patch, diffopts, mapfile, buffered):
727 def __init__(self, ui, repo, patch, diffopts, mapfile, buffered):
728 changeset_printer.__init__(self, ui, repo, patch, diffopts, buffered)
728 changeset_printer.__init__(self, ui, repo, patch, diffopts, buffered)
729 formatnode = ui.debugflag and (lambda x: x) or (lambda x: x[:12])
729 formatnode = ui.debugflag and (lambda x: x) or (lambda x: x[:12])
730 self.t = templater.templater(mapfile, {'formatnode': formatnode},
730 self.t = templater.templater(mapfile, {'formatnode': formatnode},
731 cache={
731 cache={
732 'parent': '{rev}:{node|formatnode} ',
732 'parent': '{rev}:{node|formatnode} ',
733 'manifest': '{rev}:{node|formatnode}',
733 'manifest': '{rev}:{node|formatnode}',
734 'filecopy': '{name} ({source})'})
734 'filecopy': '{name} ({source})'})
735
735
736 def use_template(self, t):
736 def use_template(self, t):
737 '''set template string to use'''
737 '''set template string to use'''
738 self.t.cache['changeset'] = t
738 self.t.cache['changeset'] = t
739
739
740 def _meaningful_parentrevs(self, ctx):
740 def _meaningful_parentrevs(self, ctx):
741 """Return list of meaningful (or all if debug) parentrevs for rev.
741 """Return list of meaningful (or all if debug) parentrevs for rev.
742 """
742 """
743 parents = ctx.parents()
743 parents = ctx.parents()
744 if len(parents) > 1:
744 if len(parents) > 1:
745 return parents
745 return parents
746 if self.ui.debugflag:
746 if self.ui.debugflag:
747 return [parents[0], self.repo['null']]
747 return [parents[0], self.repo['null']]
748 if parents[0].rev() >= ctx.rev() - 1:
748 if parents[0].rev() >= ctx.rev() - 1:
749 return []
749 return []
750 return parents
750 return parents
751
751
752 def _show(self, ctx, copies, props):
752 def _show(self, ctx, copies, props):
753 '''show a single changeset or file revision'''
753 '''show a single changeset or file revision'''
754
754
755 def showlist(name, values, plural=None, **args):
755 def showlist(name, values, plural=None, **args):
756 '''expand set of values.
756 '''expand set of values.
757 name is name of key in template map.
757 name is name of key in template map.
758 values is list of strings or dicts.
758 values is list of strings or dicts.
759 plural is plural of name, if not simply name + 's'.
759 plural is plural of name, if not simply name + 's'.
760
760
761 expansion works like this, given name 'foo'.
761 expansion works like this, given name 'foo'.
762
762
763 if values is empty, expand 'no_foos'.
763 if values is empty, expand 'no_foos'.
764
764
765 if 'foo' not in template map, return values as a string,
765 if 'foo' not in template map, return values as a string,
766 joined by space.
766 joined by space.
767
767
768 expand 'start_foos'.
768 expand 'start_foos'.
769
769
770 for each value, expand 'foo'. if 'last_foo' in template
770 for each value, expand 'foo'. if 'last_foo' in template
771 map, expand it instead of 'foo' for last key.
771 map, expand it instead of 'foo' for last key.
772
772
773 expand 'end_foos'.
773 expand 'end_foos'.
774 '''
774 '''
775 if plural: names = plural
775 if plural: names = plural
776 else: names = name + 's'
776 else: names = name + 's'
777 if not values:
777 if not values:
778 noname = 'no_' + names
778 noname = 'no_' + names
779 if noname in self.t:
779 if noname in self.t:
780 yield self.t(noname, **args)
780 yield self.t(noname, **args)
781 return
781 return
782 if name not in self.t:
782 if name not in self.t:
783 if isinstance(values[0], str):
783 if isinstance(values[0], str):
784 yield ' '.join(values)
784 yield ' '.join(values)
785 else:
785 else:
786 for v in values:
786 for v in values:
787 yield dict(v, **args)
787 yield dict(v, **args)
788 return
788 return
789 startname = 'start_' + names
789 startname = 'start_' + names
790 if startname in self.t:
790 if startname in self.t:
791 yield self.t(startname, **args)
791 yield self.t(startname, **args)
792 vargs = args.copy()
792 vargs = args.copy()
793 def one(v, tag=name):
793 def one(v, tag=name):
794 try:
794 try:
795 vargs.update(v)
795 vargs.update(v)
796 except (AttributeError, ValueError):
796 except (AttributeError, ValueError):
797 try:
797 try:
798 for a, b in v:
798 for a, b in v:
799 vargs[a] = b
799 vargs[a] = b
800 except ValueError:
800 except ValueError:
801 vargs[name] = v
801 vargs[name] = v
802 return self.t(tag, **vargs)
802 return self.t(tag, **vargs)
803 lastname = 'last_' + name
803 lastname = 'last_' + name
804 if lastname in self.t:
804 if lastname in self.t:
805 last = values.pop()
805 last = values.pop()
806 else:
806 else:
807 last = None
807 last = None
808 for v in values:
808 for v in values:
809 yield one(v)
809 yield one(v)
810 if last is not None:
810 if last is not None:
811 yield one(last, tag=lastname)
811 yield one(last, tag=lastname)
812 endname = 'end_' + names
812 endname = 'end_' + names
813 if endname in self.t:
813 if endname in self.t:
814 yield self.t(endname, **args)
814 yield self.t(endname, **args)
815
815
816 def showbranches(**args):
816 def showbranches(**args):
817 branch = ctx.branch()
817 branch = ctx.branch()
818 if branch != 'default':
818 if branch != 'default':
819 branch = encoding.tolocal(branch)
819 branch = encoding.tolocal(branch)
820 return showlist('branch', [branch], plural='branches', **args)
820 return showlist('branch', [branch], plural='branches', **args)
821
821
822 def showparents(**args):
822 def showparents(**args):
823 parents = [[('rev', p.rev()), ('node', p.hex())]
823 parents = [[('rev', p.rev()), ('node', p.hex())]
824 for p in self._meaningful_parentrevs(ctx)]
824 for p in self._meaningful_parentrevs(ctx)]
825 return showlist('parent', parents, **args)
825 return showlist('parent', parents, **args)
826
826
827 def showtags(**args):
827 def showtags(**args):
828 return showlist('tag', ctx.tags(), **args)
828 return showlist('tag', ctx.tags(), **args)
829
829
830 def showextras(**args):
830 def showextras(**args):
831 for key, value in sorted(ctx.extra().items()):
831 for key, value in sorted(ctx.extra().items()):
832 args = args.copy()
832 args = args.copy()
833 args.update(dict(key=key, value=value))
833 args.update(dict(key=key, value=value))
834 yield self.t('extra', **args)
834 yield self.t('extra', **args)
835
835
836 def showcopies(**args):
836 def showcopies(**args):
837 c = [{'name': x[0], 'source': x[1]} for x in copies]
837 c = [{'name': x[0], 'source': x[1]} for x in copies]
838 return showlist('file_copy', c, plural='file_copies', **args)
838 return showlist('file_copy', c, plural='file_copies', **args)
839
839
840 files = []
840 files = []
841 def getfiles():
841 def getfiles():
842 if not files:
842 if not files:
843 files[:] = self.repo.status(ctx.parents()[0].node(),
843 files[:] = self.repo.status(ctx.parents()[0].node(),
844 ctx.node())[:3]
844 ctx.node())[:3]
845 return files
845 return files
846 def showfiles(**args):
846 def showfiles(**args):
847 return showlist('file', ctx.files(), **args)
847 return showlist('file', ctx.files(), **args)
848 def showmods(**args):
848 def showmods(**args):
849 return showlist('file_mod', getfiles()[0], **args)
849 return showlist('file_mod', getfiles()[0], **args)
850 def showadds(**args):
850 def showadds(**args):
851 return showlist('file_add', getfiles()[1], **args)
851 return showlist('file_add', getfiles()[1], **args)
852 def showdels(**args):
852 def showdels(**args):
853 return showlist('file_del', getfiles()[2], **args)
853 return showlist('file_del', getfiles()[2], **args)
854 def showmanifest(**args):
854 def showmanifest(**args):
855 args = args.copy()
855 args = args.copy()
856 args.update(dict(rev=self.repo.manifest.rev(ctx.changeset()[0]),
856 args.update(dict(rev=self.repo.manifest.rev(ctx.changeset()[0]),
857 node=hex(ctx.changeset()[0])))
857 node=hex(ctx.changeset()[0])))
858 return self.t('manifest', **args)
858 return self.t('manifest', **args)
859
859
860 def showdiffstat(**args):
860 def showdiffstat(**args):
861 diff = patch.diff(self.repo, ctx.parents()[0].node(), ctx.node())
861 diff = patch.diff(self.repo, ctx.parents()[0].node(), ctx.node())
862 files, adds, removes = 0, 0, 0
862 files, adds, removes = 0, 0, 0
863 for i in patch.diffstatdata(util.iterlines(diff)):
863 for i in patch.diffstatdata(util.iterlines(diff)):
864 files += 1
864 files += 1
865 adds += i[1]
865 adds += i[1]
866 removes += i[2]
866 removes += i[2]
867 return '%s: +%s/-%s' % (files, adds, removes)
867 return '%s: +%s/-%s' % (files, adds, removes)
868
868
869 defprops = {
869 defprops = {
870 'author': ctx.user(),
870 'author': ctx.user(),
871 'branches': showbranches,
871 'branches': showbranches,
872 'date': ctx.date(),
872 'date': ctx.date(),
873 'desc': ctx.description().strip(),
873 'desc': ctx.description().strip(),
874 'file_adds': showadds,
874 'file_adds': showadds,
875 'file_dels': showdels,
875 'file_dels': showdels,
876 'file_mods': showmods,
876 'file_mods': showmods,
877 'files': showfiles,
877 'files': showfiles,
878 'file_copies': showcopies,
878 'file_copies': showcopies,
879 'manifest': showmanifest,
879 'manifest': showmanifest,
880 'node': ctx.hex(),
880 'node': ctx.hex(),
881 'parents': showparents,
881 'parents': showparents,
882 'rev': ctx.rev(),
882 'rev': ctx.rev(),
883 'tags': showtags,
883 'tags': showtags,
884 'extras': showextras,
884 'extras': showextras,
885 'diffstat': showdiffstat,
885 'diffstat': showdiffstat,
886 }
886 }
887 props = props.copy()
887 props = props.copy()
888 props.update(defprops)
888 props.update(defprops)
889
889
890 # find correct templates for current mode
890 # find correct templates for current mode
891
891
892 tmplmodes = [
892 tmplmodes = [
893 (True, None),
893 (True, None),
894 (self.ui.verbose, 'verbose'),
894 (self.ui.verbose, 'verbose'),
895 (self.ui.quiet, 'quiet'),
895 (self.ui.quiet, 'quiet'),
896 (self.ui.debugflag, 'debug'),
896 (self.ui.debugflag, 'debug'),
897 ]
897 ]
898
898
899 types = {'header': '', 'changeset': 'changeset'}
899 types = {'header': '', 'changeset': 'changeset'}
900 for mode, postfix in tmplmodes:
900 for mode, postfix in tmplmodes:
901 for type in types:
901 for type in types:
902 cur = postfix and ('%s_%s' % (type, postfix)) or type
902 cur = postfix and ('%s_%s' % (type, postfix)) or type
903 if mode and cur in self.t:
903 if mode and cur in self.t:
904 types[type] = cur
904 types[type] = cur
905
905
906 try:
906 try:
907
907
908 # write header
908 # write header
909 if types['header']:
909 if types['header']:
910 h = templater.stringify(self.t(types['header'], **props))
910 h = templater.stringify(self.t(types['header'], **props))
911 if self.buffered:
911 if self.buffered:
912 self.header[ctx.rev()] = h
912 self.header[ctx.rev()] = h
913 else:
913 else:
914 self.ui.write(h)
914 self.ui.write(h)
915
915
916 # write changeset metadata, then patch if requested
916 # write changeset metadata, then patch if requested
917 key = types['changeset']
917 key = types['changeset']
918 self.ui.write(templater.stringify(self.t(key, **props)))
918 self.ui.write(templater.stringify(self.t(key, **props)))
919 self.showpatch(ctx.node())
919 self.showpatch(ctx.node())
920
920
921 except KeyError, inst:
921 except KeyError, inst:
922 msg = _("%s: no key named '%s'")
922 msg = _("%s: no key named '%s'")
923 raise util.Abort(msg % (self.t.mapfile, inst.args[0]))
923 raise util.Abort(msg % (self.t.mapfile, inst.args[0]))
924 except SyntaxError, inst:
924 except SyntaxError, inst:
925 raise util.Abort(_('%s: %s') % (self.t.mapfile, inst.args[0]))
925 raise util.Abort(_('%s: %s') % (self.t.mapfile, inst.args[0]))
926
926
927 def show_changeset(ui, repo, opts, buffered=False, matchfn=False):
927 def show_changeset(ui, repo, opts, buffered=False, matchfn=False):
928 """show one changeset using template or regular display.
928 """show one changeset using template or regular display.
929
929
930 Display format will be the first non-empty hit of:
930 Display format will be the first non-empty hit of:
931 1. option 'template'
931 1. option 'template'
932 2. option 'style'
932 2. option 'style'
933 3. [ui] setting 'logtemplate'
933 3. [ui] setting 'logtemplate'
934 4. [ui] setting 'style'
934 4. [ui] setting 'style'
935 If all of these values are either the unset or the empty string,
935 If all of these values are either the unset or the empty string,
936 regular display via changeset_printer() is done.
936 regular display via changeset_printer() is done.
937 """
937 """
938 # options
938 # options
939 patch = False
939 patch = False
940 if opts.get('patch'):
940 if opts.get('patch'):
941 patch = matchfn or matchall(repo)
941 patch = matchfn or matchall(repo)
942
942
943 tmpl = opts.get('template')
943 tmpl = opts.get('template')
944 style = None
944 style = None
945 if tmpl:
945 if tmpl:
946 tmpl = templater.parsestring(tmpl, quoted=False)
946 tmpl = templater.parsestring(tmpl, quoted=False)
947 else:
947 else:
948 style = opts.get('style')
948 style = opts.get('style')
949
949
950 # ui settings
950 # ui settings
951 if not (tmpl or style):
951 if not (tmpl or style):
952 tmpl = ui.config('ui', 'logtemplate')
952 tmpl = ui.config('ui', 'logtemplate')
953 if tmpl:
953 if tmpl:
954 tmpl = templater.parsestring(tmpl)
954 tmpl = templater.parsestring(tmpl)
955 else:
955 else:
956 style = ui.config('ui', 'style')
956 style = ui.config('ui', 'style')
957
957
958 if not (tmpl or style):
958 if not (tmpl or style):
959 return changeset_printer(ui, repo, patch, opts, buffered)
959 return changeset_printer(ui, repo, patch, opts, buffered)
960
960
961 mapfile = None
961 mapfile = None
962 if style and not tmpl:
962 if style and not tmpl:
963 mapfile = style
963 mapfile = style
964 if not os.path.split(mapfile)[0]:
964 if not os.path.split(mapfile)[0]:
965 mapname = (templater.templatepath('map-cmdline.' + mapfile)
965 mapname = (templater.templatepath('map-cmdline.' + mapfile)
966 or templater.templatepath(mapfile))
966 or templater.templatepath(mapfile))
967 if mapname: mapfile = mapname
967 if mapname: mapfile = mapname
968
968
969 try:
969 try:
970 t = changeset_templater(ui, repo, patch, opts, mapfile, buffered)
970 t = changeset_templater(ui, repo, patch, opts, mapfile, buffered)
971 except SyntaxError, inst:
971 except SyntaxError, inst:
972 raise util.Abort(inst.args[0])
972 raise util.Abort(inst.args[0])
973 if tmpl: t.use_template(tmpl)
973 if tmpl: t.use_template(tmpl)
974 return t
974 return t
975
975
976 def finddate(ui, repo, date):
976 def finddate(ui, repo, date):
977 """Find the tipmost changeset that matches the given date spec"""
977 """Find the tipmost changeset that matches the given date spec"""
978 df = util.matchdate(date)
978 df = util.matchdate(date)
979 get = util.cachefunc(lambda r: repo[r].changeset())
979 get = util.cachefunc(lambda r: repo[r].changeset())
980 changeiter, matchfn = walkchangerevs(ui, repo, [], get, {'rev':None})
980 changeiter, matchfn = walkchangerevs(ui, repo, [], get, {'rev':None})
981 results = {}
981 results = {}
982 for st, rev, fns in changeiter:
982 for st, rev, fns in changeiter:
983 if st == 'add':
983 if st == 'add':
984 d = get(rev)[2]
984 d = get(rev)[2]
985 if df(d[0]):
985 if df(d[0]):
986 results[rev] = d
986 results[rev] = d
987 elif st == 'iter':
987 elif st == 'iter':
988 if rev in results:
988 if rev in results:
989 ui.status(_("Found revision %s from %s\n") %
989 ui.status(_("Found revision %s from %s\n") %
990 (rev, util.datestr(results[rev])))
990 (rev, util.datestr(results[rev])))
991 return str(rev)
991 return str(rev)
992
992
993 raise util.Abort(_("revision matching date not found"))
993 raise util.Abort(_("revision matching date not found"))
994
994
995 def walkchangerevs(ui, repo, pats, change, opts):
995 def walkchangerevs(ui, repo, pats, change, opts):
996 '''Iterate over files and the revs in which they changed.
996 '''Iterate over files and the revs in which they changed.
997
997
998 Callers most commonly need to iterate backwards over the history
998 Callers most commonly need to iterate backwards over the history
999 in which they are interested. Doing so has awful (quadratic-looking)
999 in which they are interested. Doing so has awful (quadratic-looking)
1000 performance, so we use iterators in a "windowed" way.
1000 performance, so we use iterators in a "windowed" way.
1001
1001
1002 We walk a window of revisions in the desired order. Within the
1002 We walk a window of revisions in the desired order. Within the
1003 window, we first walk forwards to gather data, then in the desired
1003 window, we first walk forwards to gather data, then in the desired
1004 order (usually backwards) to display it.
1004 order (usually backwards) to display it.
1005
1005
1006 This function returns an (iterator, matchfn) tuple. The iterator
1006 This function returns an (iterator, matchfn) tuple. The iterator
1007 yields 3-tuples. They will be of one of the following forms:
1007 yields 3-tuples. They will be of one of the following forms:
1008
1008
1009 "window", incrementing, lastrev: stepping through a window,
1009 "window", incrementing, lastrev: stepping through a window,
1010 positive if walking forwards through revs, last rev in the
1010 positive if walking forwards through revs, last rev in the
1011 sequence iterated over - use to reset state for the current window
1011 sequence iterated over - use to reset state for the current window
1012
1012
1013 "add", rev, fns: out-of-order traversal of the given filenames
1013 "add", rev, fns: out-of-order traversal of the given filenames
1014 fns, which changed during revision rev - use to gather data for
1014 fns, which changed during revision rev - use to gather data for
1015 possible display
1015 possible display
1016
1016
1017 "iter", rev, None: in-order traversal of the revs earlier iterated
1017 "iter", rev, None: in-order traversal of the revs earlier iterated
1018 over with "add" - use to display data'''
1018 over with "add" - use to display data'''
1019
1019
1020 def increasing_windows(start, end, windowsize=8, sizelimit=512):
1020 def increasing_windows(start, end, windowsize=8, sizelimit=512):
1021 if start < end:
1021 if start < end:
1022 while start < end:
1022 while start < end:
1023 yield start, min(windowsize, end-start)
1023 yield start, min(windowsize, end-start)
1024 start += windowsize
1024 start += windowsize
1025 if windowsize < sizelimit:
1025 if windowsize < sizelimit:
1026 windowsize *= 2
1026 windowsize *= 2
1027 else:
1027 else:
1028 while start > end:
1028 while start > end:
1029 yield start, min(windowsize, start-end-1)
1029 yield start, min(windowsize, start-end-1)
1030 start -= windowsize
1030 start -= windowsize
1031 if windowsize < sizelimit:
1031 if windowsize < sizelimit:
1032 windowsize *= 2
1032 windowsize *= 2
1033
1033
1034 m = match(repo, pats, opts)
1034 m = match(repo, pats, opts)
1035 follow = opts.get('follow') or opts.get('follow_first')
1035 follow = opts.get('follow') or opts.get('follow_first')
1036
1036
1037 if not len(repo):
1037 if not len(repo):
1038 return [], m
1038 return [], m
1039
1039
1040 if follow:
1040 if follow:
1041 defrange = '%s:0' % repo['.'].rev()
1041 defrange = '%s:0' % repo['.'].rev()
1042 else:
1042 else:
1043 defrange = '-1:0'
1043 defrange = '-1:0'
1044 revs = revrange(repo, opts['rev'] or [defrange])
1044 revs = revrange(repo, opts['rev'] or [defrange])
1045 wanted = set()
1045 wanted = set()
1046 slowpath = m.anypats() or (m.files() and opts.get('removed'))
1046 slowpath = m.anypats() or (m.files() and opts.get('removed'))
1047 fncache = {}
1047 fncache = {}
1048
1048
1049 if not slowpath and not m.files():
1049 if not slowpath and not m.files():
1050 # No files, no patterns. Display all revs.
1050 # No files, no patterns. Display all revs.
1051 wanted = set(revs)
1051 wanted = set(revs)
1052 copies = []
1052 copies = []
1053 if not slowpath:
1053 if not slowpath:
1054 # Only files, no patterns. Check the history of each file.
1054 # Only files, no patterns. Check the history of each file.
1055 def filerevgen(filelog, node):
1055 def filerevgen(filelog, node):
1056 cl_count = len(repo)
1056 cl_count = len(repo)
1057 if node is None:
1057 if node is None:
1058 last = len(filelog) - 1
1058 last = len(filelog) - 1
1059 else:
1059 else:
1060 last = filelog.rev(node)
1060 last = filelog.rev(node)
1061 for i, window in increasing_windows(last, nullrev):
1061 for i, window in increasing_windows(last, nullrev):
1062 revs = []
1062 revs = []
1063 for j in xrange(i - window, i + 1):
1063 for j in xrange(i - window, i + 1):
1064 n = filelog.node(j)
1064 n = filelog.node(j)
1065 revs.append((filelog.linkrev(j),
1065 revs.append((filelog.linkrev(j),
1066 follow and filelog.renamed(n)))
1066 follow and filelog.renamed(n)))
1067 for rev in reversed(revs):
1067 for rev in reversed(revs):
1068 # only yield rev for which we have the changelog, it can
1068 # only yield rev for which we have the changelog, it can
1069 # happen while doing "hg log" during a pull or commit
1069 # happen while doing "hg log" during a pull or commit
1070 if rev[0] < cl_count:
1070 if rev[0] < cl_count:
1071 yield rev
1071 yield rev
1072 def iterfiles():
1072 def iterfiles():
1073 for filename in m.files():
1073 for filename in m.files():
1074 yield filename, None
1074 yield filename, None
1075 for filename_node in copies:
1075 for filename_node in copies:
1076 yield filename_node
1076 yield filename_node
1077 minrev, maxrev = min(revs), max(revs)
1077 minrev, maxrev = min(revs), max(revs)
1078 for file_, node in iterfiles():
1078 for file_, node in iterfiles():
1079 filelog = repo.file(file_)
1079 filelog = repo.file(file_)
1080 if not len(filelog):
1080 if not len(filelog):
1081 if node is None:
1081 if node is None:
1082 # A zero count may be a directory or deleted file, so
1082 # A zero count may be a directory or deleted file, so
1083 # try to find matching entries on the slow path.
1083 # try to find matching entries on the slow path.
1084 if follow:
1084 if follow:
1085 raise util.Abort(_('cannot follow nonexistent file: "%s"') % file_)
1085 raise util.Abort(_('cannot follow nonexistent file: "%s"') % file_)
1086 slowpath = True
1086 slowpath = True
1087 break
1087 break
1088 else:
1088 else:
1089 ui.warn(_('%s:%s copy source revision cannot be found!\n')
1089 ui.warn(_('%s:%s copy source revision cannot be found!\n')
1090 % (file_, short(node)))
1090 % (file_, short(node)))
1091 continue
1091 continue
1092 for rev, copied in filerevgen(filelog, node):
1092 for rev, copied in filerevgen(filelog, node):
1093 if rev <= maxrev:
1093 if rev <= maxrev:
1094 if rev < minrev:
1094 if rev < minrev:
1095 break
1095 break
1096 fncache.setdefault(rev, [])
1096 fncache.setdefault(rev, [])
1097 fncache[rev].append(file_)
1097 fncache[rev].append(file_)
1098 wanted.add(rev)
1098 wanted.add(rev)
1099 if follow and copied:
1099 if follow and copied:
1100 copies.append(copied)
1100 copies.append(copied)
1101 if slowpath:
1101 if slowpath:
1102 if follow:
1102 if follow:
1103 raise util.Abort(_('can only follow copies/renames for explicit '
1103 raise util.Abort(_('can only follow copies/renames for explicit '
1104 'filenames'))
1104 'filenames'))
1105
1105
1106 # The slow path checks files modified in every changeset.
1106 # The slow path checks files modified in every changeset.
1107 def changerevgen():
1107 def changerevgen():
1108 for i, window in increasing_windows(len(repo) - 1, nullrev):
1108 for i, window in increasing_windows(len(repo) - 1, nullrev):
1109 for j in xrange(i - window, i + 1):
1109 for j in xrange(i - window, i + 1):
1110 yield j, change(j)[3]
1110 yield j, change(j)[3]
1111
1111
1112 for rev, changefiles in changerevgen():
1112 for rev, changefiles in changerevgen():
1113 matches = filter(m, changefiles)
1113 matches = filter(m, changefiles)
1114 if matches:
1114 if matches:
1115 fncache[rev] = matches
1115 fncache[rev] = matches
1116 wanted.add(rev)
1116 wanted.add(rev)
1117
1117
1118 class followfilter(object):
1118 class followfilter(object):
1119 def __init__(self, onlyfirst=False):
1119 def __init__(self, onlyfirst=False):
1120 self.startrev = nullrev
1120 self.startrev = nullrev
1121 self.roots = []
1121 self.roots = []
1122 self.onlyfirst = onlyfirst
1122 self.onlyfirst = onlyfirst
1123
1123
1124 def match(self, rev):
1124 def match(self, rev):
1125 def realparents(rev):
1125 def realparents(rev):
1126 if self.onlyfirst:
1126 if self.onlyfirst:
1127 return repo.changelog.parentrevs(rev)[0:1]
1127 return repo.changelog.parentrevs(rev)[0:1]
1128 else:
1128 else:
1129 return filter(lambda x: x != nullrev,
1129 return filter(lambda x: x != nullrev,
1130 repo.changelog.parentrevs(rev))
1130 repo.changelog.parentrevs(rev))
1131
1131
1132 if self.startrev == nullrev:
1132 if self.startrev == nullrev:
1133 self.startrev = rev
1133 self.startrev = rev
1134 return True
1134 return True
1135
1135
1136 if rev > self.startrev:
1136 if rev > self.startrev:
1137 # forward: all descendants
1137 # forward: all descendants
1138 if not self.roots:
1138 if not self.roots:
1139 self.roots.append(self.startrev)
1139 self.roots.append(self.startrev)
1140 for parent in realparents(rev):
1140 for parent in realparents(rev):
1141 if parent in self.roots:
1141 if parent in self.roots:
1142 self.roots.append(rev)
1142 self.roots.append(rev)
1143 return True
1143 return True
1144 else:
1144 else:
1145 # backwards: all parents
1145 # backwards: all parents
1146 if not self.roots:
1146 if not self.roots:
1147 self.roots.extend(realparents(self.startrev))
1147 self.roots.extend(realparents(self.startrev))
1148 if rev in self.roots:
1148 if rev in self.roots:
1149 self.roots.remove(rev)
1149 self.roots.remove(rev)
1150 self.roots.extend(realparents(rev))
1150 self.roots.extend(realparents(rev))
1151 return True
1151 return True
1152
1152
1153 return False
1153 return False
1154
1154
1155 # it might be worthwhile to do this in the iterator if the rev range
1155 # it might be worthwhile to do this in the iterator if the rev range
1156 # is descending and the prune args are all within that range
1156 # is descending and the prune args are all within that range
1157 for rev in opts.get('prune', ()):
1157 for rev in opts.get('prune', ()):
1158 rev = repo.changelog.rev(repo.lookup(rev))
1158 rev = repo.changelog.rev(repo.lookup(rev))
1159 ff = followfilter()
1159 ff = followfilter()
1160 stop = min(revs[0], revs[-1])
1160 stop = min(revs[0], revs[-1])
1161 for x in xrange(rev, stop-1, -1):
1161 for x in xrange(rev, stop-1, -1):
1162 if ff.match(x):
1162 if ff.match(x):
1163 wanted.discard(x)
1163 wanted.discard(x)
1164
1164
1165 def iterate():
1165 def iterate():
1166 if follow and not m.files():
1166 if follow and not m.files():
1167 ff = followfilter(onlyfirst=opts.get('follow_first'))
1167 ff = followfilter(onlyfirst=opts.get('follow_first'))
1168 def want(rev):
1168 def want(rev):
1169 return ff.match(rev) and rev in wanted
1169 return ff.match(rev) and rev in wanted
1170 else:
1170 else:
1171 def want(rev):
1171 def want(rev):
1172 return rev in wanted
1172 return rev in wanted
1173
1173
1174 for i, window in increasing_windows(0, len(revs)):
1174 for i, window in increasing_windows(0, len(revs)):
1175 yield 'window', revs[0] < revs[-1], revs[-1]
1175 yield 'window', revs[0] < revs[-1], revs[-1]
1176 nrevs = [rev for rev in revs[i:i+window] if want(rev)]
1176 nrevs = [rev for rev in revs[i:i+window] if want(rev)]
1177 for rev in sorted(nrevs):
1177 for rev in sorted(nrevs):
1178 fns = fncache.get(rev)
1178 fns = fncache.get(rev)
1179 if not fns:
1179 if not fns:
1180 def fns_generator():
1180 def fns_generator():
1181 for f in change(rev)[3]:
1181 for f in change(rev)[3]:
1182 if m(f):
1182 if m(f):
1183 yield f
1183 yield f
1184 fns = fns_generator()
1184 fns = fns_generator()
1185 yield 'add', rev, fns
1185 yield 'add', rev, fns
1186 for rev in nrevs:
1186 for rev in nrevs:
1187 yield 'iter', rev, None
1187 yield 'iter', rev, None
1188 return iterate(), m
1188 return iterate(), m
1189
1189
1190 def commit(ui, repo, commitfunc, pats, opts):
1190 def commit(ui, repo, commitfunc, pats, opts):
1191 '''commit the specified files or all outstanding changes'''
1191 '''commit the specified files or all outstanding changes'''
1192 date = opts.get('date')
1192 date = opts.get('date')
1193 if date:
1193 if date:
1194 opts['date'] = util.parsedate(date)
1194 opts['date'] = util.parsedate(date)
1195 message = logmessage(opts)
1195 message = logmessage(opts)
1196
1196
1197 # extract addremove carefully -- this function can be called from a command
1197 # extract addremove carefully -- this function can be called from a command
1198 # that doesn't support addremove
1198 # that doesn't support addremove
1199 if opts.get('addremove'):
1199 if opts.get('addremove'):
1200 addremove(repo, pats, opts)
1200 addremove(repo, pats, opts)
1201
1201
1202 return commitfunc(ui, repo, message, match(repo, pats, opts), opts)
1202 return commitfunc(ui, repo, message, match(repo, pats, opts), opts)
1203
1203
1204 def commiteditor(repo, ctx):
1204 def commiteditor(repo, ctx):
1205 if ctx.description():
1205 if ctx.description():
1206 return ctx.description()
1206 return ctx.description()
1207 return commitforceeditor(repo, ctx)
1207 return commitforceeditor(repo, ctx)
1208
1208
1209 def commitforceeditor(repo, ctx):
1209 def commitforceeditor(repo, ctx):
1210 edittext = []
1210 edittext = []
1211 modified, added, removed = ctx.modified(), ctx.added(), ctx.removed()
1211 modified, added, removed = ctx.modified(), ctx.added(), ctx.removed()
1212 if ctx.description():
1212 if ctx.description():
1213 edittext.append(ctx.description())
1213 edittext.append(ctx.description())
1214 edittext.append("")
1214 edittext.append("")
1215 edittext.append("") # Empty line between message and comments.
1215 edittext.append("") # Empty line between message and comments.
1216 edittext.append(_("HG: Enter commit message."
1216 edittext.append(_("HG: Enter commit message."
1217 " Lines beginning with 'HG:' are removed."))
1217 " Lines beginning with 'HG:' are removed."))
1218 edittext.append(_("HG: Leave message empty to abort commit."))
1218 edittext.append(_("HG: Leave message empty to abort commit."))
1219 edittext.append("HG: --")
1219 edittext.append("HG: --")
1220 edittext.append(_("HG: user: %s") % ctx.user())
1220 edittext.append(_("HG: user: %s") % ctx.user())
1221 if ctx.p2():
1221 if ctx.p2():
1222 edittext.append(_("HG: branch merge"))
1222 edittext.append(_("HG: branch merge"))
1223 if ctx.branch():
1223 if ctx.branch():
1224 edittext.append(_("HG: branch '%s'")
1224 edittext.append(_("HG: branch '%s'")
1225 % encoding.tolocal(ctx.branch()))
1225 % encoding.tolocal(ctx.branch()))
1226 edittext.extend([_("HG: added %s") % f for f in added])
1226 edittext.extend([_("HG: added %s") % f for f in added])
1227 edittext.extend([_("HG: changed %s") % f for f in modified])
1227 edittext.extend([_("HG: changed %s") % f for f in modified])
1228 edittext.extend([_("HG: removed %s") % f for f in removed])
1228 edittext.extend([_("HG: removed %s") % f for f in removed])
1229 if not added and not modified and not removed:
1229 if not added and not modified and not removed:
1230 edittext.append(_("HG: no files changed"))
1230 edittext.append(_("HG: no files changed"))
1231 edittext.append("")
1231 edittext.append("")
1232 # run editor in the repository root
1232 # run editor in the repository root
1233 olddir = os.getcwd()
1233 olddir = os.getcwd()
1234 os.chdir(repo.root)
1234 os.chdir(repo.root)
1235 text = repo.ui.edit("\n".join(edittext), ctx.user())
1235 text = repo.ui.edit("\n".join(edittext), ctx.user())
1236 text = re.sub("(?m)^HG:.*\n", "", text)
1236 text = re.sub("(?m)^HG:.*\n", "", text)
1237 os.chdir(olddir)
1237 os.chdir(olddir)
1238
1238
1239 if not text.strip():
1239 if not text.strip():
1240 raise util.Abort(_("empty commit message"))
1240 raise util.Abort(_("empty commit message"))
1241
1241
1242 return text
1242 return text
General Comments 0
You need to be logged in to leave comments. Login now