##// END OF EJS Templates
log speedup: use only ui.write in changeset_printer.show...
Alexis S. L. Carvalho -
r3572:fe03c9a4 default
parent child Browse files
Show More
@@ -1,3540 +1,3541 b''
1 # commands.py - command processing for mercurial
1 # commands.py - command processing for mercurial
2 #
2 #
3 # Copyright 2005, 2006 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005, 2006 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms
5 # This software may be used and distributed according to the terms
6 # of the GNU General Public License, incorporated herein by reference.
6 # of the GNU General Public License, incorporated herein by reference.
7
7
8 from demandload import demandload
8 from demandload import demandload
9 from node import *
9 from node import *
10 from i18n import gettext as _
10 from i18n import gettext as _
11 demandload(globals(), "os re sys signal shutil imp urllib pdb shlex")
11 demandload(globals(), "os re sys signal shutil imp urllib pdb shlex")
12 demandload(globals(), "fancyopts ui hg util lock revlog templater bundlerepo")
12 demandload(globals(), "fancyopts ui hg util lock revlog templater bundlerepo")
13 demandload(globals(), "fnmatch difflib patch random signal tempfile time")
13 demandload(globals(), "fnmatch difflib patch random signal tempfile time")
14 demandload(globals(), "traceback errno socket version struct atexit sets bz2")
14 demandload(globals(), "traceback errno socket version struct atexit sets bz2")
15 demandload(globals(), "archival cStringIO changegroup")
15 demandload(globals(), "archival cStringIO changegroup")
16 demandload(globals(), "cmdutil hgweb.server sshserver")
16 demandload(globals(), "cmdutil hgweb.server sshserver")
17
17
18 class UnknownCommand(Exception):
18 class UnknownCommand(Exception):
19 """Exception raised if command is not in the command table."""
19 """Exception raised if command is not in the command table."""
20 class AmbiguousCommand(Exception):
20 class AmbiguousCommand(Exception):
21 """Exception raised if command shortcut matches more than one command."""
21 """Exception raised if command shortcut matches more than one command."""
22
22
23 def bail_if_changed(repo):
23 def bail_if_changed(repo):
24 modified, added, removed, deleted = repo.status()[:4]
24 modified, added, removed, deleted = repo.status()[:4]
25 if modified or added or removed or deleted:
25 if modified or added or removed or deleted:
26 raise util.Abort(_("outstanding uncommitted changes"))
26 raise util.Abort(_("outstanding uncommitted changes"))
27
27
28 def relpath(repo, args):
28 def relpath(repo, args):
29 cwd = repo.getcwd()
29 cwd = repo.getcwd()
30 if cwd:
30 if cwd:
31 return [util.normpath(os.path.join(cwd, x)) for x in args]
31 return [util.normpath(os.path.join(cwd, x)) for x in args]
32 return args
32 return args
33
33
34 def logmessage(opts):
34 def logmessage(opts):
35 """ get the log message according to -m and -l option """
35 """ get the log message according to -m and -l option """
36 message = opts['message']
36 message = opts['message']
37 logfile = opts['logfile']
37 logfile = opts['logfile']
38
38
39 if message and logfile:
39 if message and logfile:
40 raise util.Abort(_('options --message and --logfile are mutually '
40 raise util.Abort(_('options --message and --logfile are mutually '
41 'exclusive'))
41 'exclusive'))
42 if not message and logfile:
42 if not message and logfile:
43 try:
43 try:
44 if logfile == '-':
44 if logfile == '-':
45 message = sys.stdin.read()
45 message = sys.stdin.read()
46 else:
46 else:
47 message = open(logfile).read()
47 message = open(logfile).read()
48 except IOError, inst:
48 except IOError, inst:
49 raise util.Abort(_("can't read commit message '%s': %s") %
49 raise util.Abort(_("can't read commit message '%s': %s") %
50 (logfile, inst.strerror))
50 (logfile, inst.strerror))
51 return message
51 return message
52
52
53 def walkchangerevs(ui, repo, pats, change, opts):
53 def walkchangerevs(ui, repo, pats, change, opts):
54 '''Iterate over files and the revs they changed in.
54 '''Iterate over files and the revs they changed in.
55
55
56 Callers most commonly need to iterate backwards over the history
56 Callers most commonly need to iterate backwards over the history
57 it is interested in. Doing so has awful (quadratic-looking)
57 it is interested in. Doing so has awful (quadratic-looking)
58 performance, so we use iterators in a "windowed" way.
58 performance, so we use iterators in a "windowed" way.
59
59
60 We walk a window of revisions in the desired order. Within the
60 We walk a window of revisions in the desired order. Within the
61 window, we first walk forwards to gather data, then in the desired
61 window, we first walk forwards to gather data, then in the desired
62 order (usually backwards) to display it.
62 order (usually backwards) to display it.
63
63
64 This function returns an (iterator, matchfn) tuple. The iterator
64 This function returns an (iterator, matchfn) tuple. The iterator
65 yields 3-tuples. They will be of one of the following forms:
65 yields 3-tuples. They will be of one of the following forms:
66
66
67 "window", incrementing, lastrev: stepping through a window,
67 "window", incrementing, lastrev: stepping through a window,
68 positive if walking forwards through revs, last rev in the
68 positive if walking forwards through revs, last rev in the
69 sequence iterated over - use to reset state for the current window
69 sequence iterated over - use to reset state for the current window
70
70
71 "add", rev, fns: out-of-order traversal of the given file names
71 "add", rev, fns: out-of-order traversal of the given file names
72 fns, which changed during revision rev - use to gather data for
72 fns, which changed during revision rev - use to gather data for
73 possible display
73 possible display
74
74
75 "iter", rev, None: in-order traversal of the revs earlier iterated
75 "iter", rev, None: in-order traversal of the revs earlier iterated
76 over with "add" - use to display data'''
76 over with "add" - use to display data'''
77
77
78 def increasing_windows(start, end, windowsize=8, sizelimit=512):
78 def increasing_windows(start, end, windowsize=8, sizelimit=512):
79 if start < end:
79 if start < end:
80 while start < end:
80 while start < end:
81 yield start, min(windowsize, end-start)
81 yield start, min(windowsize, end-start)
82 start += windowsize
82 start += windowsize
83 if windowsize < sizelimit:
83 if windowsize < sizelimit:
84 windowsize *= 2
84 windowsize *= 2
85 else:
85 else:
86 while start > end:
86 while start > end:
87 yield start, min(windowsize, start-end-1)
87 yield start, min(windowsize, start-end-1)
88 start -= windowsize
88 start -= windowsize
89 if windowsize < sizelimit:
89 if windowsize < sizelimit:
90 windowsize *= 2
90 windowsize *= 2
91
91
92 files, matchfn, anypats = cmdutil.matchpats(repo, pats, opts)
92 files, matchfn, anypats = cmdutil.matchpats(repo, pats, opts)
93 follow = opts.get('follow') or opts.get('follow_first')
93 follow = opts.get('follow') or opts.get('follow_first')
94
94
95 if repo.changelog.count() == 0:
95 if repo.changelog.count() == 0:
96 return [], matchfn
96 return [], matchfn
97
97
98 if follow:
98 if follow:
99 defrange = '%s:0' % repo.changectx().rev()
99 defrange = '%s:0' % repo.changectx().rev()
100 else:
100 else:
101 defrange = 'tip:0'
101 defrange = 'tip:0'
102 revs = cmdutil.revrange(ui, repo, opts['rev'] or [defrange])
102 revs = cmdutil.revrange(ui, repo, opts['rev'] or [defrange])
103 wanted = {}
103 wanted = {}
104 slowpath = anypats
104 slowpath = anypats
105 fncache = {}
105 fncache = {}
106
106
107 if not slowpath and not files:
107 if not slowpath and not files:
108 # No files, no patterns. Display all revs.
108 # No files, no patterns. Display all revs.
109 wanted = dict.fromkeys(revs)
109 wanted = dict.fromkeys(revs)
110 copies = []
110 copies = []
111 if not slowpath:
111 if not slowpath:
112 # Only files, no patterns. Check the history of each file.
112 # Only files, no patterns. Check the history of each file.
113 def filerevgen(filelog, node):
113 def filerevgen(filelog, node):
114 cl_count = repo.changelog.count()
114 cl_count = repo.changelog.count()
115 if node is None:
115 if node is None:
116 last = filelog.count() - 1
116 last = filelog.count() - 1
117 else:
117 else:
118 last = filelog.rev(node)
118 last = filelog.rev(node)
119 for i, window in increasing_windows(last, -1):
119 for i, window in increasing_windows(last, -1):
120 revs = []
120 revs = []
121 for j in xrange(i - window, i + 1):
121 for j in xrange(i - window, i + 1):
122 n = filelog.node(j)
122 n = filelog.node(j)
123 revs.append((filelog.linkrev(n),
123 revs.append((filelog.linkrev(n),
124 follow and filelog.renamed(n)))
124 follow and filelog.renamed(n)))
125 revs.reverse()
125 revs.reverse()
126 for rev in revs:
126 for rev in revs:
127 # only yield rev for which we have the changelog, it can
127 # only yield rev for which we have the changelog, it can
128 # happen while doing "hg log" during a pull or commit
128 # happen while doing "hg log" during a pull or commit
129 if rev[0] < cl_count:
129 if rev[0] < cl_count:
130 yield rev
130 yield rev
131 def iterfiles():
131 def iterfiles():
132 for filename in files:
132 for filename in files:
133 yield filename, None
133 yield filename, None
134 for filename_node in copies:
134 for filename_node in copies:
135 yield filename_node
135 yield filename_node
136 minrev, maxrev = min(revs), max(revs)
136 minrev, maxrev = min(revs), max(revs)
137 for file_, node in iterfiles():
137 for file_, node in iterfiles():
138 filelog = repo.file(file_)
138 filelog = repo.file(file_)
139 # A zero count may be a directory or deleted file, so
139 # A zero count may be a directory or deleted file, so
140 # try to find matching entries on the slow path.
140 # try to find matching entries on the slow path.
141 if filelog.count() == 0:
141 if filelog.count() == 0:
142 slowpath = True
142 slowpath = True
143 break
143 break
144 for rev, copied in filerevgen(filelog, node):
144 for rev, copied in filerevgen(filelog, node):
145 if rev <= maxrev:
145 if rev <= maxrev:
146 if rev < minrev:
146 if rev < minrev:
147 break
147 break
148 fncache.setdefault(rev, [])
148 fncache.setdefault(rev, [])
149 fncache[rev].append(file_)
149 fncache[rev].append(file_)
150 wanted[rev] = 1
150 wanted[rev] = 1
151 if follow and copied:
151 if follow and copied:
152 copies.append(copied)
152 copies.append(copied)
153 if slowpath:
153 if slowpath:
154 if follow:
154 if follow:
155 raise util.Abort(_('can only follow copies/renames for explicit '
155 raise util.Abort(_('can only follow copies/renames for explicit '
156 'file names'))
156 'file names'))
157
157
158 # The slow path checks files modified in every changeset.
158 # The slow path checks files modified in every changeset.
159 def changerevgen():
159 def changerevgen():
160 for i, window in increasing_windows(repo.changelog.count()-1, -1):
160 for i, window in increasing_windows(repo.changelog.count()-1, -1):
161 for j in xrange(i - window, i + 1):
161 for j in xrange(i - window, i + 1):
162 yield j, change(j)[3]
162 yield j, change(j)[3]
163
163
164 for rev, changefiles in changerevgen():
164 for rev, changefiles in changerevgen():
165 matches = filter(matchfn, changefiles)
165 matches = filter(matchfn, changefiles)
166 if matches:
166 if matches:
167 fncache[rev] = matches
167 fncache[rev] = matches
168 wanted[rev] = 1
168 wanted[rev] = 1
169
169
170 class followfilter:
170 class followfilter:
171 def __init__(self, onlyfirst=False):
171 def __init__(self, onlyfirst=False):
172 self.startrev = -1
172 self.startrev = -1
173 self.roots = []
173 self.roots = []
174 self.onlyfirst = onlyfirst
174 self.onlyfirst = onlyfirst
175
175
176 def match(self, rev):
176 def match(self, rev):
177 def realparents(rev):
177 def realparents(rev):
178 if self.onlyfirst:
178 if self.onlyfirst:
179 return repo.changelog.parentrevs(rev)[0:1]
179 return repo.changelog.parentrevs(rev)[0:1]
180 else:
180 else:
181 return filter(lambda x: x != -1, repo.changelog.parentrevs(rev))
181 return filter(lambda x: x != -1, repo.changelog.parentrevs(rev))
182
182
183 if self.startrev == -1:
183 if self.startrev == -1:
184 self.startrev = rev
184 self.startrev = rev
185 return True
185 return True
186
186
187 if rev > self.startrev:
187 if rev > self.startrev:
188 # forward: all descendants
188 # forward: all descendants
189 if not self.roots:
189 if not self.roots:
190 self.roots.append(self.startrev)
190 self.roots.append(self.startrev)
191 for parent in realparents(rev):
191 for parent in realparents(rev):
192 if parent in self.roots:
192 if parent in self.roots:
193 self.roots.append(rev)
193 self.roots.append(rev)
194 return True
194 return True
195 else:
195 else:
196 # backwards: all parents
196 # backwards: all parents
197 if not self.roots:
197 if not self.roots:
198 self.roots.extend(realparents(self.startrev))
198 self.roots.extend(realparents(self.startrev))
199 if rev in self.roots:
199 if rev in self.roots:
200 self.roots.remove(rev)
200 self.roots.remove(rev)
201 self.roots.extend(realparents(rev))
201 self.roots.extend(realparents(rev))
202 return True
202 return True
203
203
204 return False
204 return False
205
205
206 # it might be worthwhile to do this in the iterator if the rev range
206 # it might be worthwhile to do this in the iterator if the rev range
207 # is descending and the prune args are all within that range
207 # is descending and the prune args are all within that range
208 for rev in opts.get('prune', ()):
208 for rev in opts.get('prune', ()):
209 rev = repo.changelog.rev(repo.lookup(rev))
209 rev = repo.changelog.rev(repo.lookup(rev))
210 ff = followfilter()
210 ff = followfilter()
211 stop = min(revs[0], revs[-1])
211 stop = min(revs[0], revs[-1])
212 for x in xrange(rev, stop-1, -1):
212 for x in xrange(rev, stop-1, -1):
213 if ff.match(x) and x in wanted:
213 if ff.match(x) and x in wanted:
214 del wanted[x]
214 del wanted[x]
215
215
216 def iterate():
216 def iterate():
217 if follow and not files:
217 if follow and not files:
218 ff = followfilter(onlyfirst=opts.get('follow_first'))
218 ff = followfilter(onlyfirst=opts.get('follow_first'))
219 def want(rev):
219 def want(rev):
220 if ff.match(rev) and rev in wanted:
220 if ff.match(rev) and rev in wanted:
221 return True
221 return True
222 return False
222 return False
223 else:
223 else:
224 def want(rev):
224 def want(rev):
225 return rev in wanted
225 return rev in wanted
226
226
227 for i, window in increasing_windows(0, len(revs)):
227 for i, window in increasing_windows(0, len(revs)):
228 yield 'window', revs[0] < revs[-1], revs[-1]
228 yield 'window', revs[0] < revs[-1], revs[-1]
229 nrevs = [rev for rev in revs[i:i+window] if want(rev)]
229 nrevs = [rev for rev in revs[i:i+window] if want(rev)]
230 srevs = list(nrevs)
230 srevs = list(nrevs)
231 srevs.sort()
231 srevs.sort()
232 for rev in srevs:
232 for rev in srevs:
233 fns = fncache.get(rev)
233 fns = fncache.get(rev)
234 if not fns:
234 if not fns:
235 def fns_generator():
235 def fns_generator():
236 for f in change(rev)[3]:
236 for f in change(rev)[3]:
237 if matchfn(f):
237 if matchfn(f):
238 yield f
238 yield f
239 fns = fns_generator()
239 fns = fns_generator()
240 yield 'add', rev, fns
240 yield 'add', rev, fns
241 for rev in nrevs:
241 for rev in nrevs:
242 yield 'iter', rev, None
242 yield 'iter', rev, None
243 return iterate(), matchfn
243 return iterate(), matchfn
244
244
245 def write_bundle(cg, filename=None, compress=True):
245 def write_bundle(cg, filename=None, compress=True):
246 """Write a bundle file and return its filename.
246 """Write a bundle file and return its filename.
247
247
248 Existing files will not be overwritten.
248 Existing files will not be overwritten.
249 If no filename is specified, a temporary file is created.
249 If no filename is specified, a temporary file is created.
250 bz2 compression can be turned off.
250 bz2 compression can be turned off.
251 The bundle file will be deleted in case of errors.
251 The bundle file will be deleted in case of errors.
252 """
252 """
253 class nocompress(object):
253 class nocompress(object):
254 def compress(self, x):
254 def compress(self, x):
255 return x
255 return x
256 def flush(self):
256 def flush(self):
257 return ""
257 return ""
258
258
259 fh = None
259 fh = None
260 cleanup = None
260 cleanup = None
261 try:
261 try:
262 if filename:
262 if filename:
263 if os.path.exists(filename):
263 if os.path.exists(filename):
264 raise util.Abort(_("file '%s' already exists") % filename)
264 raise util.Abort(_("file '%s' already exists") % filename)
265 fh = open(filename, "wb")
265 fh = open(filename, "wb")
266 else:
266 else:
267 fd, filename = tempfile.mkstemp(prefix="hg-bundle-", suffix=".hg")
267 fd, filename = tempfile.mkstemp(prefix="hg-bundle-", suffix=".hg")
268 fh = os.fdopen(fd, "wb")
268 fh = os.fdopen(fd, "wb")
269 cleanup = filename
269 cleanup = filename
270
270
271 if compress:
271 if compress:
272 fh.write("HG10")
272 fh.write("HG10")
273 z = bz2.BZ2Compressor(9)
273 z = bz2.BZ2Compressor(9)
274 else:
274 else:
275 fh.write("HG10UN")
275 fh.write("HG10UN")
276 z = nocompress()
276 z = nocompress()
277 # parse the changegroup data, otherwise we will block
277 # parse the changegroup data, otherwise we will block
278 # in case of sshrepo because we don't know the end of the stream
278 # in case of sshrepo because we don't know the end of the stream
279
279
280 # an empty chunkiter is the end of the changegroup
280 # an empty chunkiter is the end of the changegroup
281 empty = False
281 empty = False
282 while not empty:
282 while not empty:
283 empty = True
283 empty = True
284 for chunk in changegroup.chunkiter(cg):
284 for chunk in changegroup.chunkiter(cg):
285 empty = False
285 empty = False
286 fh.write(z.compress(changegroup.genchunk(chunk)))
286 fh.write(z.compress(changegroup.genchunk(chunk)))
287 fh.write(z.compress(changegroup.closechunk()))
287 fh.write(z.compress(changegroup.closechunk()))
288 fh.write(z.flush())
288 fh.write(z.flush())
289 cleanup = None
289 cleanup = None
290 return filename
290 return filename
291 finally:
291 finally:
292 if fh is not None:
292 if fh is not None:
293 fh.close()
293 fh.close()
294 if cleanup is not None:
294 if cleanup is not None:
295 os.unlink(cleanup)
295 os.unlink(cleanup)
296
296
297 class changeset_printer(object):
297 class changeset_printer(object):
298 '''show changeset information when templating not requested.'''
298 '''show changeset information when templating not requested.'''
299
299
300 def __init__(self, ui, repo):
300 def __init__(self, ui, repo):
301 self.ui = ui
301 self.ui = ui
302 self.repo = repo
302 self.repo = repo
303
303
304 def show(self, rev=0, changenode=None, brinfo=None, copies=None):
304 def show(self, rev=0, changenode=None, brinfo=None, copies=None):
305 '''show a single changeset or file revision'''
305 '''show a single changeset or file revision'''
306 log = self.repo.changelog
306 log = self.repo.changelog
307 if changenode is None:
307 if changenode is None:
308 changenode = log.node(rev)
308 changenode = log.node(rev)
309 elif not rev:
309 elif not rev:
310 rev = log.rev(changenode)
310 rev = log.rev(changenode)
311
311
312 if self.ui.quiet:
312 if self.ui.quiet:
313 self.ui.write("%d:%s\n" % (rev, short(changenode)))
313 self.ui.write("%d:%s\n" % (rev, short(changenode)))
314 return
314 return
315
315
316 changes = log.read(changenode)
316 changes = log.read(changenode)
317 date = util.datestr(changes[2])
317 date = util.datestr(changes[2])
318 extra = changes[5]
318 extra = changes[5]
319 branch = extra.get("branch")
319 branch = extra.get("branch")
320
320
321 hexfunc = self.ui.debugflag and hex or short
321 hexfunc = self.ui.debugflag and hex or short
322
322
323 parents = [(log.rev(p), hexfunc(p)) for p in log.parents(changenode)
323 parents = [(log.rev(p), hexfunc(p)) for p in log.parents(changenode)
324 if self.ui.debugflag or p != nullid]
324 if self.ui.debugflag or p != nullid]
325 if (not self.ui.debugflag and len(parents) == 1 and
325 if (not self.ui.debugflag and len(parents) == 1 and
326 parents[0][0] == rev-1):
326 parents[0][0] == rev-1):
327 parents = []
327 parents = []
328
328
329 self.ui.write(_("changeset: %d:%s\n") % (rev, hexfunc(changenode)))
329 self.ui.write(_("changeset: %d:%s\n") % (rev, hexfunc(changenode)))
330
330
331 if branch:
331 if branch:
332 self.ui.status(_("branch: %s\n") % branch)
332 self.ui.write(_("branch: %s\n") % branch)
333 for tag in self.repo.nodetags(changenode):
333 for tag in self.repo.nodetags(changenode):
334 self.ui.status(_("tag: %s\n") % tag)
334 self.ui.write(_("tag: %s\n") % tag)
335 for parent in parents:
335 for parent in parents:
336 self.ui.write(_("parent: %d:%s\n") % parent)
336 self.ui.write(_("parent: %d:%s\n") % parent)
337
337
338 if brinfo and changenode in brinfo:
338 if brinfo and changenode in brinfo:
339 br = brinfo[changenode]
339 br = brinfo[changenode]
340 self.ui.write(_("branch: %s\n") % " ".join(br))
340 self.ui.write(_("branch: %s\n") % " ".join(br))
341
341
342 self.ui.debug(_("manifest: %d:%s\n") %
342 if self.ui.debugflag:
343 (self.repo.manifest.rev(changes[0]), hex(changes[0])))
343 self.ui.write(_("manifest: %d:%s\n") %
344 self.ui.status(_("user: %s\n") % changes[1])
344 (self.repo.manifest.rev(changes[0]), hex(changes[0])))
345 self.ui.status(_("date: %s\n") % date)
345 self.ui.write(_("user: %s\n") % changes[1])
346 self.ui.write(_("date: %s\n") % date)
346
347
347 if self.ui.debugflag:
348 if self.ui.debugflag:
348 files = self.repo.status(log.parents(changenode)[0], changenode)[:3]
349 files = self.repo.status(log.parents(changenode)[0], changenode)[:3]
349 for key, value in zip([_("files:"), _("files+:"), _("files-:")],
350 for key, value in zip([_("files:"), _("files+:"), _("files-:")],
350 files):
351 files):
351 if value:
352 if value:
352 self.ui.note("%-12s %s\n" % (key, " ".join(value)))
353 self.ui.write("%-12s %s\n" % (key, " ".join(value)))
353 elif changes[3]:
354 elif changes[3] and self.ui.verbose:
354 self.ui.note(_("files: %s\n") % " ".join(changes[3]))
355 self.ui.write(_("files: %s\n") % " ".join(changes[3]))
355 if copies:
356 if copies and self.ui.verbose:
356 copies = ['%s (%s)' % c for c in copies]
357 copies = ['%s (%s)' % c for c in copies]
357 self.ui.note(_("copies: %s\n") % ' '.join(copies))
358 self.ui.write(_("copies: %s\n") % ' '.join(copies))
358
359
359 if extra and self.ui.debugflag:
360 if extra and self.ui.debugflag:
360 extraitems = extra.items()
361 extraitems = extra.items()
361 extraitems.sort()
362 extraitems.sort()
362 for key, value in extraitems:
363 for key, value in extraitems:
363 self.ui.debug(_("extra: %s=%s\n")
364 self.ui.write(_("extra: %s=%s\n")
364 % (key, value.encode('string_escape')))
365 % (key, value.encode('string_escape')))
365
366
366 description = changes[4].strip()
367 description = changes[4].strip()
367 if description:
368 if description:
368 if self.ui.verbose:
369 if self.ui.verbose:
369 self.ui.status(_("description:\n"))
370 self.ui.write(_("description:\n"))
370 self.ui.status(description)
371 self.ui.write(description)
371 self.ui.status("\n\n")
372 self.ui.write("\n\n")
372 else:
373 else:
373 self.ui.status(_("summary: %s\n") %
374 self.ui.write(_("summary: %s\n") %
374 description.splitlines()[0])
375 description.splitlines()[0])
375 self.ui.status("\n")
376 self.ui.write("\n")
376
377
377 def show_changeset(ui, repo, opts):
378 def show_changeset(ui, repo, opts):
378 """show one changeset using template or regular display.
379 """show one changeset using template or regular display.
379
380
380 Display format will be the first non-empty hit of:
381 Display format will be the first non-empty hit of:
381 1. option 'template'
382 1. option 'template'
382 2. option 'style'
383 2. option 'style'
383 3. [ui] setting 'logtemplate'
384 3. [ui] setting 'logtemplate'
384 4. [ui] setting 'style'
385 4. [ui] setting 'style'
385 If all of these values are either the unset or the empty string,
386 If all of these values are either the unset or the empty string,
386 regular display via changeset_printer() is done.
387 regular display via changeset_printer() is done.
387 """
388 """
388 # options
389 # options
389 tmpl = opts.get('template')
390 tmpl = opts.get('template')
390 mapfile = None
391 mapfile = None
391 if tmpl:
392 if tmpl:
392 tmpl = templater.parsestring(tmpl, quoted=False)
393 tmpl = templater.parsestring(tmpl, quoted=False)
393 else:
394 else:
394 mapfile = opts.get('style')
395 mapfile = opts.get('style')
395 # ui settings
396 # ui settings
396 if not mapfile:
397 if not mapfile:
397 tmpl = ui.config('ui', 'logtemplate')
398 tmpl = ui.config('ui', 'logtemplate')
398 if tmpl:
399 if tmpl:
399 tmpl = templater.parsestring(tmpl)
400 tmpl = templater.parsestring(tmpl)
400 else:
401 else:
401 mapfile = ui.config('ui', 'style')
402 mapfile = ui.config('ui', 'style')
402
403
403 if tmpl or mapfile:
404 if tmpl or mapfile:
404 if mapfile:
405 if mapfile:
405 if not os.path.split(mapfile)[0]:
406 if not os.path.split(mapfile)[0]:
406 mapname = (templater.templatepath('map-cmdline.' + mapfile)
407 mapname = (templater.templatepath('map-cmdline.' + mapfile)
407 or templater.templatepath(mapfile))
408 or templater.templatepath(mapfile))
408 if mapname: mapfile = mapname
409 if mapname: mapfile = mapname
409 try:
410 try:
410 t = templater.changeset_templater(ui, repo, mapfile)
411 t = templater.changeset_templater(ui, repo, mapfile)
411 except SyntaxError, inst:
412 except SyntaxError, inst:
412 raise util.Abort(inst.args[0])
413 raise util.Abort(inst.args[0])
413 if tmpl: t.use_template(tmpl)
414 if tmpl: t.use_template(tmpl)
414 return t
415 return t
415 return changeset_printer(ui, repo)
416 return changeset_printer(ui, repo)
416
417
417 def setremoteconfig(ui, opts):
418 def setremoteconfig(ui, opts):
418 "copy remote options to ui tree"
419 "copy remote options to ui tree"
419 if opts.get('ssh'):
420 if opts.get('ssh'):
420 ui.setconfig("ui", "ssh", opts['ssh'])
421 ui.setconfig("ui", "ssh", opts['ssh'])
421 if opts.get('remotecmd'):
422 if opts.get('remotecmd'):
422 ui.setconfig("ui", "remotecmd", opts['remotecmd'])
423 ui.setconfig("ui", "remotecmd", opts['remotecmd'])
423
424
424 def show_version(ui):
425 def show_version(ui):
425 """output version and copyright information"""
426 """output version and copyright information"""
426 ui.write(_("Mercurial Distributed SCM (version %s)\n")
427 ui.write(_("Mercurial Distributed SCM (version %s)\n")
427 % version.get_version())
428 % version.get_version())
428 ui.status(_(
429 ui.status(_(
429 "\nCopyright (C) 2005, 2006 Matt Mackall <mpm@selenic.com>\n"
430 "\nCopyright (C) 2005, 2006 Matt Mackall <mpm@selenic.com>\n"
430 "This is free software; see the source for copying conditions. "
431 "This is free software; see the source for copying conditions. "
431 "There is NO\nwarranty; "
432 "There is NO\nwarranty; "
432 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
433 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
433 ))
434 ))
434
435
435 def help_(ui, name=None, with_version=False):
436 def help_(ui, name=None, with_version=False):
436 """show help for a command, extension, or list of commands
437 """show help for a command, extension, or list of commands
437
438
438 With no arguments, print a list of commands and short help.
439 With no arguments, print a list of commands and short help.
439
440
440 Given a command name, print help for that command.
441 Given a command name, print help for that command.
441
442
442 Given an extension name, print help for that extension, and the
443 Given an extension name, print help for that extension, and the
443 commands it provides."""
444 commands it provides."""
444 option_lists = []
445 option_lists = []
445
446
446 def helpcmd(name):
447 def helpcmd(name):
447 if with_version:
448 if with_version:
448 show_version(ui)
449 show_version(ui)
449 ui.write('\n')
450 ui.write('\n')
450 aliases, i = findcmd(ui, name)
451 aliases, i = findcmd(ui, name)
451 # synopsis
452 # synopsis
452 ui.write("%s\n\n" % i[2])
453 ui.write("%s\n\n" % i[2])
453
454
454 # description
455 # description
455 doc = i[0].__doc__
456 doc = i[0].__doc__
456 if not doc:
457 if not doc:
457 doc = _("(No help text available)")
458 doc = _("(No help text available)")
458 if ui.quiet:
459 if ui.quiet:
459 doc = doc.splitlines(0)[0]
460 doc = doc.splitlines(0)[0]
460 ui.write("%s\n" % doc.rstrip())
461 ui.write("%s\n" % doc.rstrip())
461
462
462 if not ui.quiet:
463 if not ui.quiet:
463 # aliases
464 # aliases
464 if len(aliases) > 1:
465 if len(aliases) > 1:
465 ui.write(_("\naliases: %s\n") % ', '.join(aliases[1:]))
466 ui.write(_("\naliases: %s\n") % ', '.join(aliases[1:]))
466
467
467 # options
468 # options
468 if i[1]:
469 if i[1]:
469 option_lists.append(("options", i[1]))
470 option_lists.append(("options", i[1]))
470
471
471 def helplist(select=None):
472 def helplist(select=None):
472 h = {}
473 h = {}
473 cmds = {}
474 cmds = {}
474 for c, e in table.items():
475 for c, e in table.items():
475 f = c.split("|", 1)[0]
476 f = c.split("|", 1)[0]
476 if select and not select(f):
477 if select and not select(f):
477 continue
478 continue
478 if name == "shortlist" and not f.startswith("^"):
479 if name == "shortlist" and not f.startswith("^"):
479 continue
480 continue
480 f = f.lstrip("^")
481 f = f.lstrip("^")
481 if not ui.debugflag and f.startswith("debug"):
482 if not ui.debugflag and f.startswith("debug"):
482 continue
483 continue
483 doc = e[0].__doc__
484 doc = e[0].__doc__
484 if not doc:
485 if not doc:
485 doc = _("(No help text available)")
486 doc = _("(No help text available)")
486 h[f] = doc.splitlines(0)[0].rstrip()
487 h[f] = doc.splitlines(0)[0].rstrip()
487 cmds[f] = c.lstrip("^")
488 cmds[f] = c.lstrip("^")
488
489
489 fns = h.keys()
490 fns = h.keys()
490 fns.sort()
491 fns.sort()
491 m = max(map(len, fns))
492 m = max(map(len, fns))
492 for f in fns:
493 for f in fns:
493 if ui.verbose:
494 if ui.verbose:
494 commands = cmds[f].replace("|",", ")
495 commands = cmds[f].replace("|",", ")
495 ui.write(" %s:\n %s\n"%(commands, h[f]))
496 ui.write(" %s:\n %s\n"%(commands, h[f]))
496 else:
497 else:
497 ui.write(' %-*s %s\n' % (m, f, h[f]))
498 ui.write(' %-*s %s\n' % (m, f, h[f]))
498
499
499 def helpext(name):
500 def helpext(name):
500 try:
501 try:
501 mod = findext(name)
502 mod = findext(name)
502 except KeyError:
503 except KeyError:
503 raise UnknownCommand(name)
504 raise UnknownCommand(name)
504
505
505 doc = (mod.__doc__ or _('No help text available')).splitlines(0)
506 doc = (mod.__doc__ or _('No help text available')).splitlines(0)
506 ui.write(_('%s extension - %s\n') % (name.split('.')[-1], doc[0]))
507 ui.write(_('%s extension - %s\n') % (name.split('.')[-1], doc[0]))
507 for d in doc[1:]:
508 for d in doc[1:]:
508 ui.write(d, '\n')
509 ui.write(d, '\n')
509
510
510 ui.status('\n')
511 ui.status('\n')
511 if ui.verbose:
512 if ui.verbose:
512 ui.status(_('list of commands:\n\n'))
513 ui.status(_('list of commands:\n\n'))
513 else:
514 else:
514 ui.status(_('list of commands (use "hg help -v %s" '
515 ui.status(_('list of commands (use "hg help -v %s" '
515 'to show aliases and global options):\n\n') % name)
516 'to show aliases and global options):\n\n') % name)
516
517
517 modcmds = dict.fromkeys([c.split('|', 1)[0] for c in mod.cmdtable])
518 modcmds = dict.fromkeys([c.split('|', 1)[0] for c in mod.cmdtable])
518 helplist(modcmds.has_key)
519 helplist(modcmds.has_key)
519
520
520 if name and name != 'shortlist':
521 if name and name != 'shortlist':
521 try:
522 try:
522 helpcmd(name)
523 helpcmd(name)
523 except UnknownCommand:
524 except UnknownCommand:
524 helpext(name)
525 helpext(name)
525
526
526 else:
527 else:
527 # program name
528 # program name
528 if ui.verbose or with_version:
529 if ui.verbose or with_version:
529 show_version(ui)
530 show_version(ui)
530 else:
531 else:
531 ui.status(_("Mercurial Distributed SCM\n"))
532 ui.status(_("Mercurial Distributed SCM\n"))
532 ui.status('\n')
533 ui.status('\n')
533
534
534 # list of commands
535 # list of commands
535 if name == "shortlist":
536 if name == "shortlist":
536 ui.status(_('basic commands (use "hg help" '
537 ui.status(_('basic commands (use "hg help" '
537 'for the full list or option "-v" for details):\n\n'))
538 'for the full list or option "-v" for details):\n\n'))
538 elif ui.verbose:
539 elif ui.verbose:
539 ui.status(_('list of commands:\n\n'))
540 ui.status(_('list of commands:\n\n'))
540 else:
541 else:
541 ui.status(_('list of commands (use "hg help -v" '
542 ui.status(_('list of commands (use "hg help -v" '
542 'to show aliases and global options):\n\n'))
543 'to show aliases and global options):\n\n'))
543
544
544 helplist()
545 helplist()
545
546
546 # global options
547 # global options
547 if ui.verbose:
548 if ui.verbose:
548 option_lists.append(("global options", globalopts))
549 option_lists.append(("global options", globalopts))
549
550
550 # list all option lists
551 # list all option lists
551 opt_output = []
552 opt_output = []
552 for title, options in option_lists:
553 for title, options in option_lists:
553 opt_output.append(("\n%s:\n" % title, None))
554 opt_output.append(("\n%s:\n" % title, None))
554 for shortopt, longopt, default, desc in options:
555 for shortopt, longopt, default, desc in options:
555 if "DEPRECATED" in desc and not ui.verbose: continue
556 if "DEPRECATED" in desc and not ui.verbose: continue
556 opt_output.append(("%2s%s" % (shortopt and "-%s" % shortopt,
557 opt_output.append(("%2s%s" % (shortopt and "-%s" % shortopt,
557 longopt and " --%s" % longopt),
558 longopt and " --%s" % longopt),
558 "%s%s" % (desc,
559 "%s%s" % (desc,
559 default
560 default
560 and _(" (default: %s)") % default
561 and _(" (default: %s)") % default
561 or "")))
562 or "")))
562
563
563 if opt_output:
564 if opt_output:
564 opts_len = max([len(line[0]) for line in opt_output if line[1]])
565 opts_len = max([len(line[0]) for line in opt_output if line[1]])
565 for first, second in opt_output:
566 for first, second in opt_output:
566 if second:
567 if second:
567 ui.write(" %-*s %s\n" % (opts_len, first, second))
568 ui.write(" %-*s %s\n" % (opts_len, first, second))
568 else:
569 else:
569 ui.write("%s\n" % first)
570 ui.write("%s\n" % first)
570
571
571 # Commands start here, listed alphabetically
572 # Commands start here, listed alphabetically
572
573
573 def add(ui, repo, *pats, **opts):
574 def add(ui, repo, *pats, **opts):
574 """add the specified files on the next commit
575 """add the specified files on the next commit
575
576
576 Schedule files to be version controlled and added to the repository.
577 Schedule files to be version controlled and added to the repository.
577
578
578 The files will be added to the repository at the next commit.
579 The files will be added to the repository at the next commit.
579
580
580 If no names are given, add all files in the repository.
581 If no names are given, add all files in the repository.
581 """
582 """
582
583
583 names = []
584 names = []
584 for src, abs, rel, exact in cmdutil.walk(repo, pats, opts):
585 for src, abs, rel, exact in cmdutil.walk(repo, pats, opts):
585 if exact:
586 if exact:
586 if ui.verbose:
587 if ui.verbose:
587 ui.status(_('adding %s\n') % rel)
588 ui.status(_('adding %s\n') % rel)
588 names.append(abs)
589 names.append(abs)
589 elif repo.dirstate.state(abs) == '?':
590 elif repo.dirstate.state(abs) == '?':
590 ui.status(_('adding %s\n') % rel)
591 ui.status(_('adding %s\n') % rel)
591 names.append(abs)
592 names.append(abs)
592 if not opts.get('dry_run'):
593 if not opts.get('dry_run'):
593 repo.add(names)
594 repo.add(names)
594
595
595 def addremove(ui, repo, *pats, **opts):
596 def addremove(ui, repo, *pats, **opts):
596 """add all new files, delete all missing files
597 """add all new files, delete all missing files
597
598
598 Add all new files and remove all missing files from the repository.
599 Add all new files and remove all missing files from the repository.
599
600
600 New files are ignored if they match any of the patterns in .hgignore. As
601 New files are ignored if they match any of the patterns in .hgignore. As
601 with add, these changes take effect at the next commit.
602 with add, these changes take effect at the next commit.
602
603
603 Use the -s option to detect renamed files. With a parameter > 0,
604 Use the -s option to detect renamed files. With a parameter > 0,
604 this compares every removed file with every added file and records
605 this compares every removed file with every added file and records
605 those similar enough as renames. This option takes a percentage
606 those similar enough as renames. This option takes a percentage
606 between 0 (disabled) and 100 (files must be identical) as its
607 between 0 (disabled) and 100 (files must be identical) as its
607 parameter. Detecting renamed files this way can be expensive.
608 parameter. Detecting renamed files this way can be expensive.
608 """
609 """
609 sim = float(opts.get('similarity') or 0)
610 sim = float(opts.get('similarity') or 0)
610 if sim < 0 or sim > 100:
611 if sim < 0 or sim > 100:
611 raise util.Abort(_('similarity must be between 0 and 100'))
612 raise util.Abort(_('similarity must be between 0 and 100'))
612 return cmdutil.addremove(repo, pats, opts, similarity=sim/100.)
613 return cmdutil.addremove(repo, pats, opts, similarity=sim/100.)
613
614
614 def annotate(ui, repo, *pats, **opts):
615 def annotate(ui, repo, *pats, **opts):
615 """show changeset information per file line
616 """show changeset information per file line
616
617
617 List changes in files, showing the revision id responsible for each line
618 List changes in files, showing the revision id responsible for each line
618
619
619 This command is useful to discover who did a change or when a change took
620 This command is useful to discover who did a change or when a change took
620 place.
621 place.
621
622
622 Without the -a option, annotate will avoid processing files it
623 Without the -a option, annotate will avoid processing files it
623 detects as binary. With -a, annotate will generate an annotation
624 detects as binary. With -a, annotate will generate an annotation
624 anyway, probably with undesirable results.
625 anyway, probably with undesirable results.
625 """
626 """
626 getdate = util.cachefunc(lambda x: util.datestr(x.date()))
627 getdate = util.cachefunc(lambda x: util.datestr(x.date()))
627
628
628 if not pats:
629 if not pats:
629 raise util.Abort(_('at least one file name or pattern required'))
630 raise util.Abort(_('at least one file name or pattern required'))
630
631
631 opmap = [['user', lambda x: ui.shortuser(x.user())],
632 opmap = [['user', lambda x: ui.shortuser(x.user())],
632 ['number', lambda x: str(x.rev())],
633 ['number', lambda x: str(x.rev())],
633 ['changeset', lambda x: short(x.node())],
634 ['changeset', lambda x: short(x.node())],
634 ['date', getdate], ['follow', lambda x: x.path()]]
635 ['date', getdate], ['follow', lambda x: x.path()]]
635 if (not opts['user'] and not opts['changeset'] and not opts['date']
636 if (not opts['user'] and not opts['changeset'] and not opts['date']
636 and not opts['follow']):
637 and not opts['follow']):
637 opts['number'] = 1
638 opts['number'] = 1
638
639
639 ctx = repo.changectx(opts['rev'])
640 ctx = repo.changectx(opts['rev'])
640
641
641 for src, abs, rel, exact in cmdutil.walk(repo, pats, opts,
642 for src, abs, rel, exact in cmdutil.walk(repo, pats, opts,
642 node=ctx.node()):
643 node=ctx.node()):
643 fctx = ctx.filectx(abs)
644 fctx = ctx.filectx(abs)
644 if not opts['text'] and util.binary(fctx.data()):
645 if not opts['text'] and util.binary(fctx.data()):
645 ui.write(_("%s: binary file\n") % ((pats and rel) or abs))
646 ui.write(_("%s: binary file\n") % ((pats and rel) or abs))
646 continue
647 continue
647
648
648 lines = fctx.annotate(follow=opts.get('follow'))
649 lines = fctx.annotate(follow=opts.get('follow'))
649 pieces = []
650 pieces = []
650
651
651 for o, f in opmap:
652 for o, f in opmap:
652 if opts[o]:
653 if opts[o]:
653 l = [f(n) for n, dummy in lines]
654 l = [f(n) for n, dummy in lines]
654 if l:
655 if l:
655 m = max(map(len, l))
656 m = max(map(len, l))
656 pieces.append(["%*s" % (m, x) for x in l])
657 pieces.append(["%*s" % (m, x) for x in l])
657
658
658 if pieces:
659 if pieces:
659 for p, l in zip(zip(*pieces), lines):
660 for p, l in zip(zip(*pieces), lines):
660 ui.write("%s: %s" % (" ".join(p), l[1]))
661 ui.write("%s: %s" % (" ".join(p), l[1]))
661
662
662 def archive(ui, repo, dest, **opts):
663 def archive(ui, repo, dest, **opts):
663 '''create unversioned archive of a repository revision
664 '''create unversioned archive of a repository revision
664
665
665 By default, the revision used is the parent of the working
666 By default, the revision used is the parent of the working
666 directory; use "-r" to specify a different revision.
667 directory; use "-r" to specify a different revision.
667
668
668 To specify the type of archive to create, use "-t". Valid
669 To specify the type of archive to create, use "-t". Valid
669 types are:
670 types are:
670
671
671 "files" (default): a directory full of files
672 "files" (default): a directory full of files
672 "tar": tar archive, uncompressed
673 "tar": tar archive, uncompressed
673 "tbz2": tar archive, compressed using bzip2
674 "tbz2": tar archive, compressed using bzip2
674 "tgz": tar archive, compressed using gzip
675 "tgz": tar archive, compressed using gzip
675 "uzip": zip archive, uncompressed
676 "uzip": zip archive, uncompressed
676 "zip": zip archive, compressed using deflate
677 "zip": zip archive, compressed using deflate
677
678
678 The exact name of the destination archive or directory is given
679 The exact name of the destination archive or directory is given
679 using a format string; see "hg help export" for details.
680 using a format string; see "hg help export" for details.
680
681
681 Each member added to an archive file has a directory prefix
682 Each member added to an archive file has a directory prefix
682 prepended. Use "-p" to specify a format string for the prefix.
683 prepended. Use "-p" to specify a format string for the prefix.
683 The default is the basename of the archive, with suffixes removed.
684 The default is the basename of the archive, with suffixes removed.
684 '''
685 '''
685
686
686 node = repo.changectx(opts['rev']).node()
687 node = repo.changectx(opts['rev']).node()
687 dest = cmdutil.make_filename(repo, dest, node)
688 dest = cmdutil.make_filename(repo, dest, node)
688 if os.path.realpath(dest) == repo.root:
689 if os.path.realpath(dest) == repo.root:
689 raise util.Abort(_('repository root cannot be destination'))
690 raise util.Abort(_('repository root cannot be destination'))
690 dummy, matchfn, dummy = cmdutil.matchpats(repo, [], opts)
691 dummy, matchfn, dummy = cmdutil.matchpats(repo, [], opts)
691 kind = opts.get('type') or 'files'
692 kind = opts.get('type') or 'files'
692 prefix = opts['prefix']
693 prefix = opts['prefix']
693 if dest == '-':
694 if dest == '-':
694 if kind == 'files':
695 if kind == 'files':
695 raise util.Abort(_('cannot archive plain files to stdout'))
696 raise util.Abort(_('cannot archive plain files to stdout'))
696 dest = sys.stdout
697 dest = sys.stdout
697 if not prefix: prefix = os.path.basename(repo.root) + '-%h'
698 if not prefix: prefix = os.path.basename(repo.root) + '-%h'
698 prefix = cmdutil.make_filename(repo, prefix, node)
699 prefix = cmdutil.make_filename(repo, prefix, node)
699 archival.archive(repo, dest, node, kind, not opts['no_decode'],
700 archival.archive(repo, dest, node, kind, not opts['no_decode'],
700 matchfn, prefix)
701 matchfn, prefix)
701
702
702 def backout(ui, repo, rev, **opts):
703 def backout(ui, repo, rev, **opts):
703 '''reverse effect of earlier changeset
704 '''reverse effect of earlier changeset
704
705
705 Commit the backed out changes as a new changeset. The new
706 Commit the backed out changes as a new changeset. The new
706 changeset is a child of the backed out changeset.
707 changeset is a child of the backed out changeset.
707
708
708 If you back out a changeset other than the tip, a new head is
709 If you back out a changeset other than the tip, a new head is
709 created. This head is the parent of the working directory. If
710 created. This head is the parent of the working directory. If
710 you back out an old changeset, your working directory will appear
711 you back out an old changeset, your working directory will appear
711 old after the backout. You should merge the backout changeset
712 old after the backout. You should merge the backout changeset
712 with another head.
713 with another head.
713
714
714 The --merge option remembers the parent of the working directory
715 The --merge option remembers the parent of the working directory
715 before starting the backout, then merges the new head with that
716 before starting the backout, then merges the new head with that
716 changeset afterwards. This saves you from doing the merge by
717 changeset afterwards. This saves you from doing the merge by
717 hand. The result of this merge is not committed, as for a normal
718 hand. The result of this merge is not committed, as for a normal
718 merge.'''
719 merge.'''
719
720
720 bail_if_changed(repo)
721 bail_if_changed(repo)
721 op1, op2 = repo.dirstate.parents()
722 op1, op2 = repo.dirstate.parents()
722 if op2 != nullid:
723 if op2 != nullid:
723 raise util.Abort(_('outstanding uncommitted merge'))
724 raise util.Abort(_('outstanding uncommitted merge'))
724 node = repo.lookup(rev)
725 node = repo.lookup(rev)
725 p1, p2 = repo.changelog.parents(node)
726 p1, p2 = repo.changelog.parents(node)
726 if p1 == nullid:
727 if p1 == nullid:
727 raise util.Abort(_('cannot back out a change with no parents'))
728 raise util.Abort(_('cannot back out a change with no parents'))
728 if p2 != nullid:
729 if p2 != nullid:
729 if not opts['parent']:
730 if not opts['parent']:
730 raise util.Abort(_('cannot back out a merge changeset without '
731 raise util.Abort(_('cannot back out a merge changeset without '
731 '--parent'))
732 '--parent'))
732 p = repo.lookup(opts['parent'])
733 p = repo.lookup(opts['parent'])
733 if p not in (p1, p2):
734 if p not in (p1, p2):
734 raise util.Abort(_('%s is not a parent of %s' %
735 raise util.Abort(_('%s is not a parent of %s' %
735 (short(p), short(node))))
736 (short(p), short(node))))
736 parent = p
737 parent = p
737 else:
738 else:
738 if opts['parent']:
739 if opts['parent']:
739 raise util.Abort(_('cannot use --parent on non-merge changeset'))
740 raise util.Abort(_('cannot use --parent on non-merge changeset'))
740 parent = p1
741 parent = p1
741 hg.clean(repo, node, show_stats=False)
742 hg.clean(repo, node, show_stats=False)
742 revert_opts = opts.copy()
743 revert_opts = opts.copy()
743 revert_opts['all'] = True
744 revert_opts['all'] = True
744 revert_opts['rev'] = hex(parent)
745 revert_opts['rev'] = hex(parent)
745 revert(ui, repo, **revert_opts)
746 revert(ui, repo, **revert_opts)
746 commit_opts = opts.copy()
747 commit_opts = opts.copy()
747 commit_opts['addremove'] = False
748 commit_opts['addremove'] = False
748 if not commit_opts['message'] and not commit_opts['logfile']:
749 if not commit_opts['message'] and not commit_opts['logfile']:
749 commit_opts['message'] = _("Backed out changeset %s") % (hex(node))
750 commit_opts['message'] = _("Backed out changeset %s") % (hex(node))
750 commit_opts['force_editor'] = True
751 commit_opts['force_editor'] = True
751 commit(ui, repo, **commit_opts)
752 commit(ui, repo, **commit_opts)
752 def nice(node):
753 def nice(node):
753 return '%d:%s' % (repo.changelog.rev(node), short(node))
754 return '%d:%s' % (repo.changelog.rev(node), short(node))
754 ui.status(_('changeset %s backs out changeset %s\n') %
755 ui.status(_('changeset %s backs out changeset %s\n') %
755 (nice(repo.changelog.tip()), nice(node)))
756 (nice(repo.changelog.tip()), nice(node)))
756 if op1 != node:
757 if op1 != node:
757 if opts['merge']:
758 if opts['merge']:
758 ui.status(_('merging with changeset %s\n') % nice(op1))
759 ui.status(_('merging with changeset %s\n') % nice(op1))
759 n = _lookup(repo, hex(op1))
760 n = _lookup(repo, hex(op1))
760 hg.merge(repo, n)
761 hg.merge(repo, n)
761 else:
762 else:
762 ui.status(_('the backout changeset is a new head - '
763 ui.status(_('the backout changeset is a new head - '
763 'do not forget to merge\n'))
764 'do not forget to merge\n'))
764 ui.status(_('(use "backout --merge" '
765 ui.status(_('(use "backout --merge" '
765 'if you want to auto-merge)\n'))
766 'if you want to auto-merge)\n'))
766
767
767 def branch(ui, repo, label=None):
768 def branch(ui, repo, label=None):
768 """set or show the current branch name
769 """set or show the current branch name
769
770
770 With <name>, set the current branch name. Otherwise, show the
771 With <name>, set the current branch name. Otherwise, show the
771 current branch name.
772 current branch name.
772 """
773 """
773
774
774 if label is not None:
775 if label is not None:
775 repo.opener("branch", "w").write(label)
776 repo.opener("branch", "w").write(label)
776 else:
777 else:
777 b = repo.workingctx().branch()
778 b = repo.workingctx().branch()
778 if b:
779 if b:
779 ui.write("%s\n" % b)
780 ui.write("%s\n" % b)
780
781
781 def branches(ui, repo):
782 def branches(ui, repo):
782 """list repository named branches
783 """list repository named branches
783
784
784 List the repository's named branches.
785 List the repository's named branches.
785 """
786 """
786 b = repo.branchtags()
787 b = repo.branchtags()
787 l = [(-repo.changelog.rev(n), n, t) for t,n in b.items()]
788 l = [(-repo.changelog.rev(n), n, t) for t,n in b.items()]
788 l.sort()
789 l.sort()
789 for r, n, t in l:
790 for r, n, t in l:
790 hexfunc = ui.debugflag and hex or short
791 hexfunc = ui.debugflag and hex or short
791 if ui.quiet:
792 if ui.quiet:
792 ui.write("%s\n" % t)
793 ui.write("%s\n" % t)
793 else:
794 else:
794 ui.write("%-30s %s:%s\n" % (t, -r, hexfunc(n)))
795 ui.write("%-30s %s:%s\n" % (t, -r, hexfunc(n)))
795
796
796 def bundle(ui, repo, fname, dest=None, **opts):
797 def bundle(ui, repo, fname, dest=None, **opts):
797 """create a changegroup file
798 """create a changegroup file
798
799
799 Generate a compressed changegroup file collecting changesets not
800 Generate a compressed changegroup file collecting changesets not
800 found in the other repository.
801 found in the other repository.
801
802
802 If no destination repository is specified the destination is assumed
803 If no destination repository is specified the destination is assumed
803 to have all the nodes specified by one or more --base parameters.
804 to have all the nodes specified by one or more --base parameters.
804
805
805 The bundle file can then be transferred using conventional means and
806 The bundle file can then be transferred using conventional means and
806 applied to another repository with the unbundle or pull command.
807 applied to another repository with the unbundle or pull command.
807 This is useful when direct push and pull are not available or when
808 This is useful when direct push and pull are not available or when
808 exporting an entire repository is undesirable.
809 exporting an entire repository is undesirable.
809
810
810 Applying bundles preserves all changeset contents including
811 Applying bundles preserves all changeset contents including
811 permissions, copy/rename information, and revision history.
812 permissions, copy/rename information, and revision history.
812 """
813 """
813 revs = opts.get('rev') or None
814 revs = opts.get('rev') or None
814 if revs:
815 if revs:
815 revs = [repo.lookup(rev) for rev in revs]
816 revs = [repo.lookup(rev) for rev in revs]
816 base = opts.get('base')
817 base = opts.get('base')
817 if base:
818 if base:
818 if dest:
819 if dest:
819 raise util.Abort(_("--base is incompatible with specifiying "
820 raise util.Abort(_("--base is incompatible with specifiying "
820 "a destination"))
821 "a destination"))
821 base = [repo.lookup(rev) for rev in base]
822 base = [repo.lookup(rev) for rev in base]
822 # create the right base
823 # create the right base
823 # XXX: nodesbetween / changegroup* should be "fixed" instead
824 # XXX: nodesbetween / changegroup* should be "fixed" instead
824 o = []
825 o = []
825 has_set = sets.Set(base)
826 has_set = sets.Set(base)
826 for n in base:
827 for n in base:
827 has_set.update(repo.changelog.reachable(n))
828 has_set.update(repo.changelog.reachable(n))
828 if revs:
829 if revs:
829 visit = list(revs)
830 visit = list(revs)
830 else:
831 else:
831 visit = repo.changelog.heads()
832 visit = repo.changelog.heads()
832 seen = sets.Set(visit)
833 seen = sets.Set(visit)
833 while visit:
834 while visit:
834 n = visit.pop(0)
835 n = visit.pop(0)
835 parents = [p for p in repo.changelog.parents(n)
836 parents = [p for p in repo.changelog.parents(n)
836 if p != nullid and p not in has_set]
837 if p != nullid and p not in has_set]
837 if len(parents) == 0:
838 if len(parents) == 0:
838 o.insert(0, n)
839 o.insert(0, n)
839 else:
840 else:
840 for p in parents:
841 for p in parents:
841 if p not in seen:
842 if p not in seen:
842 seen.add(p)
843 seen.add(p)
843 visit.append(p)
844 visit.append(p)
844 else:
845 else:
845 setremoteconfig(ui, opts)
846 setremoteconfig(ui, opts)
846 dest = ui.expandpath(dest or 'default-push', dest or 'default')
847 dest = ui.expandpath(dest or 'default-push', dest or 'default')
847 other = hg.repository(ui, dest)
848 other = hg.repository(ui, dest)
848 o = repo.findoutgoing(other, force=opts['force'])
849 o = repo.findoutgoing(other, force=opts['force'])
849
850
850 if revs:
851 if revs:
851 cg = repo.changegroupsubset(o, revs, 'bundle')
852 cg = repo.changegroupsubset(o, revs, 'bundle')
852 else:
853 else:
853 cg = repo.changegroup(o, 'bundle')
854 cg = repo.changegroup(o, 'bundle')
854 write_bundle(cg, fname)
855 write_bundle(cg, fname)
855
856
856 def cat(ui, repo, file1, *pats, **opts):
857 def cat(ui, repo, file1, *pats, **opts):
857 """output the latest or given revisions of files
858 """output the latest or given revisions of files
858
859
859 Print the specified files as they were at the given revision.
860 Print the specified files as they were at the given revision.
860 If no revision is given then working dir parent is used, or tip
861 If no revision is given then working dir parent is used, or tip
861 if no revision is checked out.
862 if no revision is checked out.
862
863
863 Output may be to a file, in which case the name of the file is
864 Output may be to a file, in which case the name of the file is
864 given using a format string. The formatting rules are the same as
865 given using a format string. The formatting rules are the same as
865 for the export command, with the following additions:
866 for the export command, with the following additions:
866
867
867 %s basename of file being printed
868 %s basename of file being printed
868 %d dirname of file being printed, or '.' if in repo root
869 %d dirname of file being printed, or '.' if in repo root
869 %p root-relative path name of file being printed
870 %p root-relative path name of file being printed
870 """
871 """
871 ctx = repo.changectx(opts['rev'])
872 ctx = repo.changectx(opts['rev'])
872 for src, abs, rel, exact in cmdutil.walk(repo, (file1,) + pats, opts,
873 for src, abs, rel, exact in cmdutil.walk(repo, (file1,) + pats, opts,
873 ctx.node()):
874 ctx.node()):
874 fp = cmdutil.make_file(repo, opts['output'], ctx.node(), pathname=abs)
875 fp = cmdutil.make_file(repo, opts['output'], ctx.node(), pathname=abs)
875 fp.write(ctx.filectx(abs).data())
876 fp.write(ctx.filectx(abs).data())
876
877
877 def clone(ui, source, dest=None, **opts):
878 def clone(ui, source, dest=None, **opts):
878 """make a copy of an existing repository
879 """make a copy of an existing repository
879
880
880 Create a copy of an existing repository in a new directory.
881 Create a copy of an existing repository in a new directory.
881
882
882 If no destination directory name is specified, it defaults to the
883 If no destination directory name is specified, it defaults to the
883 basename of the source.
884 basename of the source.
884
885
885 The location of the source is added to the new repository's
886 The location of the source is added to the new repository's
886 .hg/hgrc file, as the default to be used for future pulls.
887 .hg/hgrc file, as the default to be used for future pulls.
887
888
888 For efficiency, hardlinks are used for cloning whenever the source
889 For efficiency, hardlinks are used for cloning whenever the source
889 and destination are on the same filesystem (note this applies only
890 and destination are on the same filesystem (note this applies only
890 to the repository data, not to the checked out files). Some
891 to the repository data, not to the checked out files). Some
891 filesystems, such as AFS, implement hardlinking incorrectly, but
892 filesystems, such as AFS, implement hardlinking incorrectly, but
892 do not report errors. In these cases, use the --pull option to
893 do not report errors. In these cases, use the --pull option to
893 avoid hardlinking.
894 avoid hardlinking.
894
895
895 You can safely clone repositories and checked out files using full
896 You can safely clone repositories and checked out files using full
896 hardlinks with
897 hardlinks with
897
898
898 $ cp -al REPO REPOCLONE
899 $ cp -al REPO REPOCLONE
899
900
900 which is the fastest way to clone. However, the operation is not
901 which is the fastest way to clone. However, the operation is not
901 atomic (making sure REPO is not modified during the operation is
902 atomic (making sure REPO is not modified during the operation is
902 up to you) and you have to make sure your editor breaks hardlinks
903 up to you) and you have to make sure your editor breaks hardlinks
903 (Emacs and most Linux Kernel tools do so).
904 (Emacs and most Linux Kernel tools do so).
904
905
905 If you use the -r option to clone up to a specific revision, no
906 If you use the -r option to clone up to a specific revision, no
906 subsequent revisions will be present in the cloned repository.
907 subsequent revisions will be present in the cloned repository.
907 This option implies --pull, even on local repositories.
908 This option implies --pull, even on local repositories.
908
909
909 See pull for valid source format details.
910 See pull for valid source format details.
910
911
911 It is possible to specify an ssh:// URL as the destination, but no
912 It is possible to specify an ssh:// URL as the destination, but no
912 .hg/hgrc will be created on the remote side. Look at the help text
913 .hg/hgrc will be created on the remote side. Look at the help text
913 for the pull command for important details about ssh:// URLs.
914 for the pull command for important details about ssh:// URLs.
914 """
915 """
915 setremoteconfig(ui, opts)
916 setremoteconfig(ui, opts)
916 hg.clone(ui, ui.expandpath(source), dest,
917 hg.clone(ui, ui.expandpath(source), dest,
917 pull=opts['pull'],
918 pull=opts['pull'],
918 stream=opts['uncompressed'],
919 stream=opts['uncompressed'],
919 rev=opts['rev'],
920 rev=opts['rev'],
920 update=not opts['noupdate'])
921 update=not opts['noupdate'])
921
922
922 def commit(ui, repo, *pats, **opts):
923 def commit(ui, repo, *pats, **opts):
923 """commit the specified files or all outstanding changes
924 """commit the specified files or all outstanding changes
924
925
925 Commit changes to the given files into the repository.
926 Commit changes to the given files into the repository.
926
927
927 If a list of files is omitted, all changes reported by "hg status"
928 If a list of files is omitted, all changes reported by "hg status"
928 will be committed.
929 will be committed.
929
930
930 If no commit message is specified, the editor configured in your hgrc
931 If no commit message is specified, the editor configured in your hgrc
931 or in the EDITOR environment variable is started to enter a message.
932 or in the EDITOR environment variable is started to enter a message.
932 """
933 """
933 message = logmessage(opts)
934 message = logmessage(opts)
934
935
935 if opts['addremove']:
936 if opts['addremove']:
936 cmdutil.addremove(repo, pats, opts)
937 cmdutil.addremove(repo, pats, opts)
937 fns, match, anypats = cmdutil.matchpats(repo, pats, opts)
938 fns, match, anypats = cmdutil.matchpats(repo, pats, opts)
938 if pats:
939 if pats:
939 modified, added, removed = repo.status(files=fns, match=match)[:3]
940 modified, added, removed = repo.status(files=fns, match=match)[:3]
940 files = modified + added + removed
941 files = modified + added + removed
941 else:
942 else:
942 files = []
943 files = []
943 try:
944 try:
944 repo.commit(files, message, opts['user'], opts['date'], match,
945 repo.commit(files, message, opts['user'], opts['date'], match,
945 force_editor=opts.get('force_editor'))
946 force_editor=opts.get('force_editor'))
946 except ValueError, inst:
947 except ValueError, inst:
947 raise util.Abort(str(inst))
948 raise util.Abort(str(inst))
948
949
949 def docopy(ui, repo, pats, opts, wlock):
950 def docopy(ui, repo, pats, opts, wlock):
950 # called with the repo lock held
951 # called with the repo lock held
951 cwd = repo.getcwd()
952 cwd = repo.getcwd()
952 errors = 0
953 errors = 0
953 copied = []
954 copied = []
954 targets = {}
955 targets = {}
955
956
956 def okaytocopy(abs, rel, exact):
957 def okaytocopy(abs, rel, exact):
957 reasons = {'?': _('is not managed'),
958 reasons = {'?': _('is not managed'),
958 'a': _('has been marked for add'),
959 'a': _('has been marked for add'),
959 'r': _('has been marked for remove')}
960 'r': _('has been marked for remove')}
960 state = repo.dirstate.state(abs)
961 state = repo.dirstate.state(abs)
961 reason = reasons.get(state)
962 reason = reasons.get(state)
962 if reason:
963 if reason:
963 if state == 'a':
964 if state == 'a':
964 origsrc = repo.dirstate.copied(abs)
965 origsrc = repo.dirstate.copied(abs)
965 if origsrc is not None:
966 if origsrc is not None:
966 return origsrc
967 return origsrc
967 if exact:
968 if exact:
968 ui.warn(_('%s: not copying - file %s\n') % (rel, reason))
969 ui.warn(_('%s: not copying - file %s\n') % (rel, reason))
969 else:
970 else:
970 return abs
971 return abs
971
972
972 def copy(origsrc, abssrc, relsrc, target, exact):
973 def copy(origsrc, abssrc, relsrc, target, exact):
973 abstarget = util.canonpath(repo.root, cwd, target)
974 abstarget = util.canonpath(repo.root, cwd, target)
974 reltarget = util.pathto(cwd, abstarget)
975 reltarget = util.pathto(cwd, abstarget)
975 prevsrc = targets.get(abstarget)
976 prevsrc = targets.get(abstarget)
976 if prevsrc is not None:
977 if prevsrc is not None:
977 ui.warn(_('%s: not overwriting - %s collides with %s\n') %
978 ui.warn(_('%s: not overwriting - %s collides with %s\n') %
978 (reltarget, abssrc, prevsrc))
979 (reltarget, abssrc, prevsrc))
979 return
980 return
980 if (not opts['after'] and os.path.exists(reltarget) or
981 if (not opts['after'] and os.path.exists(reltarget) or
981 opts['after'] and repo.dirstate.state(abstarget) not in '?r'):
982 opts['after'] and repo.dirstate.state(abstarget) not in '?r'):
982 if not opts['force']:
983 if not opts['force']:
983 ui.warn(_('%s: not overwriting - file exists\n') %
984 ui.warn(_('%s: not overwriting - file exists\n') %
984 reltarget)
985 reltarget)
985 return
986 return
986 if not opts['after'] and not opts.get('dry_run'):
987 if not opts['after'] and not opts.get('dry_run'):
987 os.unlink(reltarget)
988 os.unlink(reltarget)
988 if opts['after']:
989 if opts['after']:
989 if not os.path.exists(reltarget):
990 if not os.path.exists(reltarget):
990 return
991 return
991 else:
992 else:
992 targetdir = os.path.dirname(reltarget) or '.'
993 targetdir = os.path.dirname(reltarget) or '.'
993 if not os.path.isdir(targetdir) and not opts.get('dry_run'):
994 if not os.path.isdir(targetdir) and not opts.get('dry_run'):
994 os.makedirs(targetdir)
995 os.makedirs(targetdir)
995 try:
996 try:
996 restore = repo.dirstate.state(abstarget) == 'r'
997 restore = repo.dirstate.state(abstarget) == 'r'
997 if restore and not opts.get('dry_run'):
998 if restore and not opts.get('dry_run'):
998 repo.undelete([abstarget], wlock)
999 repo.undelete([abstarget], wlock)
999 try:
1000 try:
1000 if not opts.get('dry_run'):
1001 if not opts.get('dry_run'):
1001 shutil.copyfile(relsrc, reltarget)
1002 shutil.copyfile(relsrc, reltarget)
1002 shutil.copymode(relsrc, reltarget)
1003 shutil.copymode(relsrc, reltarget)
1003 restore = False
1004 restore = False
1004 finally:
1005 finally:
1005 if restore:
1006 if restore:
1006 repo.remove([abstarget], wlock)
1007 repo.remove([abstarget], wlock)
1007 except shutil.Error, inst:
1008 except shutil.Error, inst:
1008 raise util.Abort(str(inst))
1009 raise util.Abort(str(inst))
1009 except IOError, inst:
1010 except IOError, inst:
1010 if inst.errno == errno.ENOENT:
1011 if inst.errno == errno.ENOENT:
1011 ui.warn(_('%s: deleted in working copy\n') % relsrc)
1012 ui.warn(_('%s: deleted in working copy\n') % relsrc)
1012 else:
1013 else:
1013 ui.warn(_('%s: cannot copy - %s\n') %
1014 ui.warn(_('%s: cannot copy - %s\n') %
1014 (relsrc, inst.strerror))
1015 (relsrc, inst.strerror))
1015 errors += 1
1016 errors += 1
1016 return
1017 return
1017 if ui.verbose or not exact:
1018 if ui.verbose or not exact:
1018 ui.status(_('copying %s to %s\n') % (relsrc, reltarget))
1019 ui.status(_('copying %s to %s\n') % (relsrc, reltarget))
1019 targets[abstarget] = abssrc
1020 targets[abstarget] = abssrc
1020 if abstarget != origsrc and not opts.get('dry_run'):
1021 if abstarget != origsrc and not opts.get('dry_run'):
1021 repo.copy(origsrc, abstarget, wlock)
1022 repo.copy(origsrc, abstarget, wlock)
1022 copied.append((abssrc, relsrc, exact))
1023 copied.append((abssrc, relsrc, exact))
1023
1024
1024 def targetpathfn(pat, dest, srcs):
1025 def targetpathfn(pat, dest, srcs):
1025 if os.path.isdir(pat):
1026 if os.path.isdir(pat):
1026 abspfx = util.canonpath(repo.root, cwd, pat)
1027 abspfx = util.canonpath(repo.root, cwd, pat)
1027 if destdirexists:
1028 if destdirexists:
1028 striplen = len(os.path.split(abspfx)[0])
1029 striplen = len(os.path.split(abspfx)[0])
1029 else:
1030 else:
1030 striplen = len(abspfx)
1031 striplen = len(abspfx)
1031 if striplen:
1032 if striplen:
1032 striplen += len(os.sep)
1033 striplen += len(os.sep)
1033 res = lambda p: os.path.join(dest, p[striplen:])
1034 res = lambda p: os.path.join(dest, p[striplen:])
1034 elif destdirexists:
1035 elif destdirexists:
1035 res = lambda p: os.path.join(dest, os.path.basename(p))
1036 res = lambda p: os.path.join(dest, os.path.basename(p))
1036 else:
1037 else:
1037 res = lambda p: dest
1038 res = lambda p: dest
1038 return res
1039 return res
1039
1040
1040 def targetpathafterfn(pat, dest, srcs):
1041 def targetpathafterfn(pat, dest, srcs):
1041 if util.patkind(pat, None)[0]:
1042 if util.patkind(pat, None)[0]:
1042 # a mercurial pattern
1043 # a mercurial pattern
1043 res = lambda p: os.path.join(dest, os.path.basename(p))
1044 res = lambda p: os.path.join(dest, os.path.basename(p))
1044 else:
1045 else:
1045 abspfx = util.canonpath(repo.root, cwd, pat)
1046 abspfx = util.canonpath(repo.root, cwd, pat)
1046 if len(abspfx) < len(srcs[0][0]):
1047 if len(abspfx) < len(srcs[0][0]):
1047 # A directory. Either the target path contains the last
1048 # A directory. Either the target path contains the last
1048 # component of the source path or it does not.
1049 # component of the source path or it does not.
1049 def evalpath(striplen):
1050 def evalpath(striplen):
1050 score = 0
1051 score = 0
1051 for s in srcs:
1052 for s in srcs:
1052 t = os.path.join(dest, s[0][striplen:])
1053 t = os.path.join(dest, s[0][striplen:])
1053 if os.path.exists(t):
1054 if os.path.exists(t):
1054 score += 1
1055 score += 1
1055 return score
1056 return score
1056
1057
1057 striplen = len(abspfx)
1058 striplen = len(abspfx)
1058 if striplen:
1059 if striplen:
1059 striplen += len(os.sep)
1060 striplen += len(os.sep)
1060 if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])):
1061 if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])):
1061 score = evalpath(striplen)
1062 score = evalpath(striplen)
1062 striplen1 = len(os.path.split(abspfx)[0])
1063 striplen1 = len(os.path.split(abspfx)[0])
1063 if striplen1:
1064 if striplen1:
1064 striplen1 += len(os.sep)
1065 striplen1 += len(os.sep)
1065 if evalpath(striplen1) > score:
1066 if evalpath(striplen1) > score:
1066 striplen = striplen1
1067 striplen = striplen1
1067 res = lambda p: os.path.join(dest, p[striplen:])
1068 res = lambda p: os.path.join(dest, p[striplen:])
1068 else:
1069 else:
1069 # a file
1070 # a file
1070 if destdirexists:
1071 if destdirexists:
1071 res = lambda p: os.path.join(dest, os.path.basename(p))
1072 res = lambda p: os.path.join(dest, os.path.basename(p))
1072 else:
1073 else:
1073 res = lambda p: dest
1074 res = lambda p: dest
1074 return res
1075 return res
1075
1076
1076
1077
1077 pats = list(pats)
1078 pats = list(pats)
1078 if not pats:
1079 if not pats:
1079 raise util.Abort(_('no source or destination specified'))
1080 raise util.Abort(_('no source or destination specified'))
1080 if len(pats) == 1:
1081 if len(pats) == 1:
1081 raise util.Abort(_('no destination specified'))
1082 raise util.Abort(_('no destination specified'))
1082 dest = pats.pop()
1083 dest = pats.pop()
1083 destdirexists = os.path.isdir(dest)
1084 destdirexists = os.path.isdir(dest)
1084 if (len(pats) > 1 or util.patkind(pats[0], None)[0]) and not destdirexists:
1085 if (len(pats) > 1 or util.patkind(pats[0], None)[0]) and not destdirexists:
1085 raise util.Abort(_('with multiple sources, destination must be an '
1086 raise util.Abort(_('with multiple sources, destination must be an '
1086 'existing directory'))
1087 'existing directory'))
1087 if opts['after']:
1088 if opts['after']:
1088 tfn = targetpathafterfn
1089 tfn = targetpathafterfn
1089 else:
1090 else:
1090 tfn = targetpathfn
1091 tfn = targetpathfn
1091 copylist = []
1092 copylist = []
1092 for pat in pats:
1093 for pat in pats:
1093 srcs = []
1094 srcs = []
1094 for tag, abssrc, relsrc, exact in cmdutil.walk(repo, [pat], opts):
1095 for tag, abssrc, relsrc, exact in cmdutil.walk(repo, [pat], opts):
1095 origsrc = okaytocopy(abssrc, relsrc, exact)
1096 origsrc = okaytocopy(abssrc, relsrc, exact)
1096 if origsrc:
1097 if origsrc:
1097 srcs.append((origsrc, abssrc, relsrc, exact))
1098 srcs.append((origsrc, abssrc, relsrc, exact))
1098 if not srcs:
1099 if not srcs:
1099 continue
1100 continue
1100 copylist.append((tfn(pat, dest, srcs), srcs))
1101 copylist.append((tfn(pat, dest, srcs), srcs))
1101 if not copylist:
1102 if not copylist:
1102 raise util.Abort(_('no files to copy'))
1103 raise util.Abort(_('no files to copy'))
1103
1104
1104 for targetpath, srcs in copylist:
1105 for targetpath, srcs in copylist:
1105 for origsrc, abssrc, relsrc, exact in srcs:
1106 for origsrc, abssrc, relsrc, exact in srcs:
1106 copy(origsrc, abssrc, relsrc, targetpath(abssrc), exact)
1107 copy(origsrc, abssrc, relsrc, targetpath(abssrc), exact)
1107
1108
1108 if errors:
1109 if errors:
1109 ui.warn(_('(consider using --after)\n'))
1110 ui.warn(_('(consider using --after)\n'))
1110 return errors, copied
1111 return errors, copied
1111
1112
1112 def copy(ui, repo, *pats, **opts):
1113 def copy(ui, repo, *pats, **opts):
1113 """mark files as copied for the next commit
1114 """mark files as copied for the next commit
1114
1115
1115 Mark dest as having copies of source files. If dest is a
1116 Mark dest as having copies of source files. If dest is a
1116 directory, copies are put in that directory. If dest is a file,
1117 directory, copies are put in that directory. If dest is a file,
1117 there can only be one source.
1118 there can only be one source.
1118
1119
1119 By default, this command copies the contents of files as they
1120 By default, this command copies the contents of files as they
1120 stand in the working directory. If invoked with --after, the
1121 stand in the working directory. If invoked with --after, the
1121 operation is recorded, but no copying is performed.
1122 operation is recorded, but no copying is performed.
1122
1123
1123 This command takes effect in the next commit.
1124 This command takes effect in the next commit.
1124
1125
1125 NOTE: This command should be treated as experimental. While it
1126 NOTE: This command should be treated as experimental. While it
1126 should properly record copied files, this information is not yet
1127 should properly record copied files, this information is not yet
1127 fully used by merge, nor fully reported by log.
1128 fully used by merge, nor fully reported by log.
1128 """
1129 """
1129 wlock = repo.wlock(0)
1130 wlock = repo.wlock(0)
1130 errs, copied = docopy(ui, repo, pats, opts, wlock)
1131 errs, copied = docopy(ui, repo, pats, opts, wlock)
1131 return errs
1132 return errs
1132
1133
1133 def debugancestor(ui, index, rev1, rev2):
1134 def debugancestor(ui, index, rev1, rev2):
1134 """find the ancestor revision of two revisions in a given index"""
1135 """find the ancestor revision of two revisions in a given index"""
1135 r = revlog.revlog(util.opener(os.getcwd(), audit=False), index, "", 0)
1136 r = revlog.revlog(util.opener(os.getcwd(), audit=False), index, "", 0)
1136 a = r.ancestor(r.lookup(rev1), r.lookup(rev2))
1137 a = r.ancestor(r.lookup(rev1), r.lookup(rev2))
1137 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
1138 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
1138
1139
1139 def debugcomplete(ui, cmd='', **opts):
1140 def debugcomplete(ui, cmd='', **opts):
1140 """returns the completion list associated with the given command"""
1141 """returns the completion list associated with the given command"""
1141
1142
1142 if opts['options']:
1143 if opts['options']:
1143 options = []
1144 options = []
1144 otables = [globalopts]
1145 otables = [globalopts]
1145 if cmd:
1146 if cmd:
1146 aliases, entry = findcmd(ui, cmd)
1147 aliases, entry = findcmd(ui, cmd)
1147 otables.append(entry[1])
1148 otables.append(entry[1])
1148 for t in otables:
1149 for t in otables:
1149 for o in t:
1150 for o in t:
1150 if o[0]:
1151 if o[0]:
1151 options.append('-%s' % o[0])
1152 options.append('-%s' % o[0])
1152 options.append('--%s' % o[1])
1153 options.append('--%s' % o[1])
1153 ui.write("%s\n" % "\n".join(options))
1154 ui.write("%s\n" % "\n".join(options))
1154 return
1155 return
1155
1156
1156 clist = findpossible(ui, cmd).keys()
1157 clist = findpossible(ui, cmd).keys()
1157 clist.sort()
1158 clist.sort()
1158 ui.write("%s\n" % "\n".join(clist))
1159 ui.write("%s\n" % "\n".join(clist))
1159
1160
1160 def debugrebuildstate(ui, repo, rev=None):
1161 def debugrebuildstate(ui, repo, rev=None):
1161 """rebuild the dirstate as it would look like for the given revision"""
1162 """rebuild the dirstate as it would look like for the given revision"""
1162 if not rev:
1163 if not rev:
1163 rev = repo.changelog.tip()
1164 rev = repo.changelog.tip()
1164 else:
1165 else:
1165 rev = repo.lookup(rev)
1166 rev = repo.lookup(rev)
1166 change = repo.changelog.read(rev)
1167 change = repo.changelog.read(rev)
1167 n = change[0]
1168 n = change[0]
1168 files = repo.manifest.read(n)
1169 files = repo.manifest.read(n)
1169 wlock = repo.wlock()
1170 wlock = repo.wlock()
1170 repo.dirstate.rebuild(rev, files)
1171 repo.dirstate.rebuild(rev, files)
1171
1172
1172 def debugcheckstate(ui, repo):
1173 def debugcheckstate(ui, repo):
1173 """validate the correctness of the current dirstate"""
1174 """validate the correctness of the current dirstate"""
1174 parent1, parent2 = repo.dirstate.parents()
1175 parent1, parent2 = repo.dirstate.parents()
1175 repo.dirstate.read()
1176 repo.dirstate.read()
1176 dc = repo.dirstate.map
1177 dc = repo.dirstate.map
1177 keys = dc.keys()
1178 keys = dc.keys()
1178 keys.sort()
1179 keys.sort()
1179 m1n = repo.changelog.read(parent1)[0]
1180 m1n = repo.changelog.read(parent1)[0]
1180 m2n = repo.changelog.read(parent2)[0]
1181 m2n = repo.changelog.read(parent2)[0]
1181 m1 = repo.manifest.read(m1n)
1182 m1 = repo.manifest.read(m1n)
1182 m2 = repo.manifest.read(m2n)
1183 m2 = repo.manifest.read(m2n)
1183 errors = 0
1184 errors = 0
1184 for f in dc:
1185 for f in dc:
1185 state = repo.dirstate.state(f)
1186 state = repo.dirstate.state(f)
1186 if state in "nr" and f not in m1:
1187 if state in "nr" and f not in m1:
1187 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
1188 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
1188 errors += 1
1189 errors += 1
1189 if state in "a" and f in m1:
1190 if state in "a" and f in m1:
1190 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
1191 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
1191 errors += 1
1192 errors += 1
1192 if state in "m" and f not in m1 and f not in m2:
1193 if state in "m" and f not in m1 and f not in m2:
1193 ui.warn(_("%s in state %s, but not in either manifest\n") %
1194 ui.warn(_("%s in state %s, but not in either manifest\n") %
1194 (f, state))
1195 (f, state))
1195 errors += 1
1196 errors += 1
1196 for f in m1:
1197 for f in m1:
1197 state = repo.dirstate.state(f)
1198 state = repo.dirstate.state(f)
1198 if state not in "nrm":
1199 if state not in "nrm":
1199 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
1200 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
1200 errors += 1
1201 errors += 1
1201 if errors:
1202 if errors:
1202 error = _(".hg/dirstate inconsistent with current parent's manifest")
1203 error = _(".hg/dirstate inconsistent with current parent's manifest")
1203 raise util.Abort(error)
1204 raise util.Abort(error)
1204
1205
1205 def showconfig(ui, repo, *values, **opts):
1206 def showconfig(ui, repo, *values, **opts):
1206 """show combined config settings from all hgrc files
1207 """show combined config settings from all hgrc files
1207
1208
1208 With no args, print names and values of all config items.
1209 With no args, print names and values of all config items.
1209
1210
1210 With one arg of the form section.name, print just the value of
1211 With one arg of the form section.name, print just the value of
1211 that config item.
1212 that config item.
1212
1213
1213 With multiple args, print names and values of all config items
1214 With multiple args, print names and values of all config items
1214 with matching section names."""
1215 with matching section names."""
1215
1216
1216 untrusted = bool(opts.get('untrusted'))
1217 untrusted = bool(opts.get('untrusted'))
1217 if values:
1218 if values:
1218 if len([v for v in values if '.' in v]) > 1:
1219 if len([v for v in values if '.' in v]) > 1:
1219 raise util.Abort(_('only one config item permitted'))
1220 raise util.Abort(_('only one config item permitted'))
1220 for section, name, value in ui.walkconfig(untrusted=untrusted):
1221 for section, name, value in ui.walkconfig(untrusted=untrusted):
1221 sectname = section + '.' + name
1222 sectname = section + '.' + name
1222 if values:
1223 if values:
1223 for v in values:
1224 for v in values:
1224 if v == section:
1225 if v == section:
1225 ui.write('%s=%s\n' % (sectname, value))
1226 ui.write('%s=%s\n' % (sectname, value))
1226 elif v == sectname:
1227 elif v == sectname:
1227 ui.write(value, '\n')
1228 ui.write(value, '\n')
1228 else:
1229 else:
1229 ui.write('%s=%s\n' % (sectname, value))
1230 ui.write('%s=%s\n' % (sectname, value))
1230
1231
1231 def debugsetparents(ui, repo, rev1, rev2=None):
1232 def debugsetparents(ui, repo, rev1, rev2=None):
1232 """manually set the parents of the current working directory
1233 """manually set the parents of the current working directory
1233
1234
1234 This is useful for writing repository conversion tools, but should
1235 This is useful for writing repository conversion tools, but should
1235 be used with care.
1236 be used with care.
1236 """
1237 """
1237
1238
1238 if not rev2:
1239 if not rev2:
1239 rev2 = hex(nullid)
1240 rev2 = hex(nullid)
1240
1241
1241 repo.dirstate.setparents(repo.lookup(rev1), repo.lookup(rev2))
1242 repo.dirstate.setparents(repo.lookup(rev1), repo.lookup(rev2))
1242
1243
1243 def debugstate(ui, repo):
1244 def debugstate(ui, repo):
1244 """show the contents of the current dirstate"""
1245 """show the contents of the current dirstate"""
1245 repo.dirstate.read()
1246 repo.dirstate.read()
1246 dc = repo.dirstate.map
1247 dc = repo.dirstate.map
1247 keys = dc.keys()
1248 keys = dc.keys()
1248 keys.sort()
1249 keys.sort()
1249 for file_ in keys:
1250 for file_ in keys:
1250 ui.write("%c %3o %10d %s %s\n"
1251 ui.write("%c %3o %10d %s %s\n"
1251 % (dc[file_][0], dc[file_][1] & 0777, dc[file_][2],
1252 % (dc[file_][0], dc[file_][1] & 0777, dc[file_][2],
1252 time.strftime("%x %X",
1253 time.strftime("%x %X",
1253 time.localtime(dc[file_][3])), file_))
1254 time.localtime(dc[file_][3])), file_))
1254 for f in repo.dirstate.copies():
1255 for f in repo.dirstate.copies():
1255 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
1256 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
1256
1257
1257 def debugdata(ui, file_, rev):
1258 def debugdata(ui, file_, rev):
1258 """dump the contents of an data file revision"""
1259 """dump the contents of an data file revision"""
1259 r = revlog.revlog(util.opener(os.getcwd(), audit=False),
1260 r = revlog.revlog(util.opener(os.getcwd(), audit=False),
1260 file_[:-2] + ".i", file_, 0)
1261 file_[:-2] + ".i", file_, 0)
1261 try:
1262 try:
1262 ui.write(r.revision(r.lookup(rev)))
1263 ui.write(r.revision(r.lookup(rev)))
1263 except KeyError:
1264 except KeyError:
1264 raise util.Abort(_('invalid revision identifier %s') % rev)
1265 raise util.Abort(_('invalid revision identifier %s') % rev)
1265
1266
1266 def debugindex(ui, file_):
1267 def debugindex(ui, file_):
1267 """dump the contents of an index file"""
1268 """dump the contents of an index file"""
1268 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_, "", 0)
1269 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_, "", 0)
1269 ui.write(" rev offset length base linkrev" +
1270 ui.write(" rev offset length base linkrev" +
1270 " nodeid p1 p2\n")
1271 " nodeid p1 p2\n")
1271 for i in xrange(r.count()):
1272 for i in xrange(r.count()):
1272 node = r.node(i)
1273 node = r.node(i)
1273 pp = r.parents(node)
1274 pp = r.parents(node)
1274 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
1275 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
1275 i, r.start(i), r.length(i), r.base(i), r.linkrev(node),
1276 i, r.start(i), r.length(i), r.base(i), r.linkrev(node),
1276 short(node), short(pp[0]), short(pp[1])))
1277 short(node), short(pp[0]), short(pp[1])))
1277
1278
1278 def debugindexdot(ui, file_):
1279 def debugindexdot(ui, file_):
1279 """dump an index DAG as a .dot file"""
1280 """dump an index DAG as a .dot file"""
1280 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_, "", 0)
1281 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_, "", 0)
1281 ui.write("digraph G {\n")
1282 ui.write("digraph G {\n")
1282 for i in xrange(r.count()):
1283 for i in xrange(r.count()):
1283 node = r.node(i)
1284 node = r.node(i)
1284 pp = r.parents(node)
1285 pp = r.parents(node)
1285 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
1286 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
1286 if pp[1] != nullid:
1287 if pp[1] != nullid:
1287 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
1288 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
1288 ui.write("}\n")
1289 ui.write("}\n")
1289
1290
1290 def debugrename(ui, repo, file, rev=None):
1291 def debugrename(ui, repo, file, rev=None):
1291 """dump rename information"""
1292 """dump rename information"""
1292 r = repo.file(relpath(repo, [file])[0])
1293 r = repo.file(relpath(repo, [file])[0])
1293 if rev:
1294 if rev:
1294 try:
1295 try:
1295 # assume all revision numbers are for changesets
1296 # assume all revision numbers are for changesets
1296 n = repo.lookup(rev)
1297 n = repo.lookup(rev)
1297 change = repo.changelog.read(n)
1298 change = repo.changelog.read(n)
1298 m = repo.manifest.read(change[0])
1299 m = repo.manifest.read(change[0])
1299 n = m[relpath(repo, [file])[0]]
1300 n = m[relpath(repo, [file])[0]]
1300 except (hg.RepoError, KeyError):
1301 except (hg.RepoError, KeyError):
1301 n = r.lookup(rev)
1302 n = r.lookup(rev)
1302 else:
1303 else:
1303 n = r.tip()
1304 n = r.tip()
1304 m = r.renamed(n)
1305 m = r.renamed(n)
1305 if m:
1306 if m:
1306 ui.write(_("renamed from %s:%s\n") % (m[0], hex(m[1])))
1307 ui.write(_("renamed from %s:%s\n") % (m[0], hex(m[1])))
1307 else:
1308 else:
1308 ui.write(_("not renamed\n"))
1309 ui.write(_("not renamed\n"))
1309
1310
1310 def debugwalk(ui, repo, *pats, **opts):
1311 def debugwalk(ui, repo, *pats, **opts):
1311 """show how files match on given patterns"""
1312 """show how files match on given patterns"""
1312 items = list(cmdutil.walk(repo, pats, opts))
1313 items = list(cmdutil.walk(repo, pats, opts))
1313 if not items:
1314 if not items:
1314 return
1315 return
1315 fmt = '%%s %%-%ds %%-%ds %%s' % (
1316 fmt = '%%s %%-%ds %%-%ds %%s' % (
1316 max([len(abs) for (src, abs, rel, exact) in items]),
1317 max([len(abs) for (src, abs, rel, exact) in items]),
1317 max([len(rel) for (src, abs, rel, exact) in items]))
1318 max([len(rel) for (src, abs, rel, exact) in items]))
1318 for src, abs, rel, exact in items:
1319 for src, abs, rel, exact in items:
1319 line = fmt % (src, abs, rel, exact and 'exact' or '')
1320 line = fmt % (src, abs, rel, exact and 'exact' or '')
1320 ui.write("%s\n" % line.rstrip())
1321 ui.write("%s\n" % line.rstrip())
1321
1322
1322 def diff(ui, repo, *pats, **opts):
1323 def diff(ui, repo, *pats, **opts):
1323 """diff repository (or selected files)
1324 """diff repository (or selected files)
1324
1325
1325 Show differences between revisions for the specified files.
1326 Show differences between revisions for the specified files.
1326
1327
1327 Differences between files are shown using the unified diff format.
1328 Differences between files are shown using the unified diff format.
1328
1329
1329 When two revision arguments are given, then changes are shown
1330 When two revision arguments are given, then changes are shown
1330 between those revisions. If only one revision is specified then
1331 between those revisions. If only one revision is specified then
1331 that revision is compared to the working directory, and, when no
1332 that revision is compared to the working directory, and, when no
1332 revisions are specified, the working directory files are compared
1333 revisions are specified, the working directory files are compared
1333 to its parent.
1334 to its parent.
1334
1335
1335 Without the -a option, diff will avoid generating diffs of files
1336 Without the -a option, diff will avoid generating diffs of files
1336 it detects as binary. With -a, diff will generate a diff anyway,
1337 it detects as binary. With -a, diff will generate a diff anyway,
1337 probably with undesirable results.
1338 probably with undesirable results.
1338 """
1339 """
1339 node1, node2 = cmdutil.revpair(ui, repo, opts['rev'])
1340 node1, node2 = cmdutil.revpair(ui, repo, opts['rev'])
1340
1341
1341 fns, matchfn, anypats = cmdutil.matchpats(repo, pats, opts)
1342 fns, matchfn, anypats = cmdutil.matchpats(repo, pats, opts)
1342
1343
1343 patch.diff(repo, node1, node2, fns, match=matchfn,
1344 patch.diff(repo, node1, node2, fns, match=matchfn,
1344 opts=patch.diffopts(ui, opts))
1345 opts=patch.diffopts(ui, opts))
1345
1346
1346 def export(ui, repo, *changesets, **opts):
1347 def export(ui, repo, *changesets, **opts):
1347 """dump the header and diffs for one or more changesets
1348 """dump the header and diffs for one or more changesets
1348
1349
1349 Print the changeset header and diffs for one or more revisions.
1350 Print the changeset header and diffs for one or more revisions.
1350
1351
1351 The information shown in the changeset header is: author,
1352 The information shown in the changeset header is: author,
1352 changeset hash, parent and commit comment.
1353 changeset hash, parent and commit comment.
1353
1354
1354 Output may be to a file, in which case the name of the file is
1355 Output may be to a file, in which case the name of the file is
1355 given using a format string. The formatting rules are as follows:
1356 given using a format string. The formatting rules are as follows:
1356
1357
1357 %% literal "%" character
1358 %% literal "%" character
1358 %H changeset hash (40 bytes of hexadecimal)
1359 %H changeset hash (40 bytes of hexadecimal)
1359 %N number of patches being generated
1360 %N number of patches being generated
1360 %R changeset revision number
1361 %R changeset revision number
1361 %b basename of the exporting repository
1362 %b basename of the exporting repository
1362 %h short-form changeset hash (12 bytes of hexadecimal)
1363 %h short-form changeset hash (12 bytes of hexadecimal)
1363 %n zero-padded sequence number, starting at 1
1364 %n zero-padded sequence number, starting at 1
1364 %r zero-padded changeset revision number
1365 %r zero-padded changeset revision number
1365
1366
1366 Without the -a option, export will avoid generating diffs of files
1367 Without the -a option, export will avoid generating diffs of files
1367 it detects as binary. With -a, export will generate a diff anyway,
1368 it detects as binary. With -a, export will generate a diff anyway,
1368 probably with undesirable results.
1369 probably with undesirable results.
1369
1370
1370 With the --switch-parent option, the diff will be against the second
1371 With the --switch-parent option, the diff will be against the second
1371 parent. It can be useful to review a merge.
1372 parent. It can be useful to review a merge.
1372 """
1373 """
1373 if not changesets:
1374 if not changesets:
1374 raise util.Abort(_("export requires at least one changeset"))
1375 raise util.Abort(_("export requires at least one changeset"))
1375 revs = cmdutil.revrange(ui, repo, changesets)
1376 revs = cmdutil.revrange(ui, repo, changesets)
1376 if len(revs) > 1:
1377 if len(revs) > 1:
1377 ui.note(_('exporting patches:\n'))
1378 ui.note(_('exporting patches:\n'))
1378 else:
1379 else:
1379 ui.note(_('exporting patch:\n'))
1380 ui.note(_('exporting patch:\n'))
1380 patch.export(repo, map(repo.lookup, revs), template=opts['output'],
1381 patch.export(repo, map(repo.lookup, revs), template=opts['output'],
1381 switch_parent=opts['switch_parent'],
1382 switch_parent=opts['switch_parent'],
1382 opts=patch.diffopts(ui, opts))
1383 opts=patch.diffopts(ui, opts))
1383
1384
1384 def grep(ui, repo, pattern, *pats, **opts):
1385 def grep(ui, repo, pattern, *pats, **opts):
1385 """search for a pattern in specified files and revisions
1386 """search for a pattern in specified files and revisions
1386
1387
1387 Search revisions of files for a regular expression.
1388 Search revisions of files for a regular expression.
1388
1389
1389 This command behaves differently than Unix grep. It only accepts
1390 This command behaves differently than Unix grep. It only accepts
1390 Python/Perl regexps. It searches repository history, not the
1391 Python/Perl regexps. It searches repository history, not the
1391 working directory. It always prints the revision number in which
1392 working directory. It always prints the revision number in which
1392 a match appears.
1393 a match appears.
1393
1394
1394 By default, grep only prints output for the first revision of a
1395 By default, grep only prints output for the first revision of a
1395 file in which it finds a match. To get it to print every revision
1396 file in which it finds a match. To get it to print every revision
1396 that contains a change in match status ("-" for a match that
1397 that contains a change in match status ("-" for a match that
1397 becomes a non-match, or "+" for a non-match that becomes a match),
1398 becomes a non-match, or "+" for a non-match that becomes a match),
1398 use the --all flag.
1399 use the --all flag.
1399 """
1400 """
1400 reflags = 0
1401 reflags = 0
1401 if opts['ignore_case']:
1402 if opts['ignore_case']:
1402 reflags |= re.I
1403 reflags |= re.I
1403 regexp = re.compile(pattern, reflags)
1404 regexp = re.compile(pattern, reflags)
1404 sep, eol = ':', '\n'
1405 sep, eol = ':', '\n'
1405 if opts['print0']:
1406 if opts['print0']:
1406 sep = eol = '\0'
1407 sep = eol = '\0'
1407
1408
1408 fcache = {}
1409 fcache = {}
1409 def getfile(fn):
1410 def getfile(fn):
1410 if fn not in fcache:
1411 if fn not in fcache:
1411 fcache[fn] = repo.file(fn)
1412 fcache[fn] = repo.file(fn)
1412 return fcache[fn]
1413 return fcache[fn]
1413
1414
1414 def matchlines(body):
1415 def matchlines(body):
1415 begin = 0
1416 begin = 0
1416 linenum = 0
1417 linenum = 0
1417 while True:
1418 while True:
1418 match = regexp.search(body, begin)
1419 match = regexp.search(body, begin)
1419 if not match:
1420 if not match:
1420 break
1421 break
1421 mstart, mend = match.span()
1422 mstart, mend = match.span()
1422 linenum += body.count('\n', begin, mstart) + 1
1423 linenum += body.count('\n', begin, mstart) + 1
1423 lstart = body.rfind('\n', begin, mstart) + 1 or begin
1424 lstart = body.rfind('\n', begin, mstart) + 1 or begin
1424 lend = body.find('\n', mend)
1425 lend = body.find('\n', mend)
1425 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
1426 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
1426 begin = lend + 1
1427 begin = lend + 1
1427
1428
1428 class linestate(object):
1429 class linestate(object):
1429 def __init__(self, line, linenum, colstart, colend):
1430 def __init__(self, line, linenum, colstart, colend):
1430 self.line = line
1431 self.line = line
1431 self.linenum = linenum
1432 self.linenum = linenum
1432 self.colstart = colstart
1433 self.colstart = colstart
1433 self.colend = colend
1434 self.colend = colend
1434
1435
1435 def __eq__(self, other):
1436 def __eq__(self, other):
1436 return self.line == other.line
1437 return self.line == other.line
1437
1438
1438 matches = {}
1439 matches = {}
1439 copies = {}
1440 copies = {}
1440 def grepbody(fn, rev, body):
1441 def grepbody(fn, rev, body):
1441 matches[rev].setdefault(fn, [])
1442 matches[rev].setdefault(fn, [])
1442 m = matches[rev][fn]
1443 m = matches[rev][fn]
1443 for lnum, cstart, cend, line in matchlines(body):
1444 for lnum, cstart, cend, line in matchlines(body):
1444 s = linestate(line, lnum, cstart, cend)
1445 s = linestate(line, lnum, cstart, cend)
1445 m.append(s)
1446 m.append(s)
1446
1447
1447 def difflinestates(a, b):
1448 def difflinestates(a, b):
1448 sm = difflib.SequenceMatcher(None, a, b)
1449 sm = difflib.SequenceMatcher(None, a, b)
1449 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
1450 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
1450 if tag == 'insert':
1451 if tag == 'insert':
1451 for i in xrange(blo, bhi):
1452 for i in xrange(blo, bhi):
1452 yield ('+', b[i])
1453 yield ('+', b[i])
1453 elif tag == 'delete':
1454 elif tag == 'delete':
1454 for i in xrange(alo, ahi):
1455 for i in xrange(alo, ahi):
1455 yield ('-', a[i])
1456 yield ('-', a[i])
1456 elif tag == 'replace':
1457 elif tag == 'replace':
1457 for i in xrange(alo, ahi):
1458 for i in xrange(alo, ahi):
1458 yield ('-', a[i])
1459 yield ('-', a[i])
1459 for i in xrange(blo, bhi):
1460 for i in xrange(blo, bhi):
1460 yield ('+', b[i])
1461 yield ('+', b[i])
1461
1462
1462 prev = {}
1463 prev = {}
1463 def display(fn, rev, states, prevstates):
1464 def display(fn, rev, states, prevstates):
1464 counts = {'-': 0, '+': 0}
1465 counts = {'-': 0, '+': 0}
1465 filerevmatches = {}
1466 filerevmatches = {}
1466 if incrementing or not opts['all']:
1467 if incrementing or not opts['all']:
1467 a, b, r = prevstates, states, rev
1468 a, b, r = prevstates, states, rev
1468 else:
1469 else:
1469 a, b, r = states, prevstates, prev.get(fn, -1)
1470 a, b, r = states, prevstates, prev.get(fn, -1)
1470 for change, l in difflinestates(a, b):
1471 for change, l in difflinestates(a, b):
1471 cols = [fn, str(r)]
1472 cols = [fn, str(r)]
1472 if opts['line_number']:
1473 if opts['line_number']:
1473 cols.append(str(l.linenum))
1474 cols.append(str(l.linenum))
1474 if opts['all']:
1475 if opts['all']:
1475 cols.append(change)
1476 cols.append(change)
1476 if opts['user']:
1477 if opts['user']:
1477 cols.append(ui.shortuser(getchange(r)[1]))
1478 cols.append(ui.shortuser(getchange(r)[1]))
1478 if opts['files_with_matches']:
1479 if opts['files_with_matches']:
1479 c = (fn, r)
1480 c = (fn, r)
1480 if c in filerevmatches:
1481 if c in filerevmatches:
1481 continue
1482 continue
1482 filerevmatches[c] = 1
1483 filerevmatches[c] = 1
1483 else:
1484 else:
1484 cols.append(l.line)
1485 cols.append(l.line)
1485 ui.write(sep.join(cols), eol)
1486 ui.write(sep.join(cols), eol)
1486 counts[change] += 1
1487 counts[change] += 1
1487 return counts['+'], counts['-']
1488 return counts['+'], counts['-']
1488
1489
1489 fstate = {}
1490 fstate = {}
1490 skip = {}
1491 skip = {}
1491 getchange = util.cachefunc(lambda r:repo.changectx(r).changeset())
1492 getchange = util.cachefunc(lambda r:repo.changectx(r).changeset())
1492 changeiter, matchfn = walkchangerevs(ui, repo, pats, getchange, opts)
1493 changeiter, matchfn = walkchangerevs(ui, repo, pats, getchange, opts)
1493 count = 0
1494 count = 0
1494 incrementing = False
1495 incrementing = False
1495 follow = opts.get('follow')
1496 follow = opts.get('follow')
1496 for st, rev, fns in changeiter:
1497 for st, rev, fns in changeiter:
1497 if st == 'window':
1498 if st == 'window':
1498 incrementing = rev
1499 incrementing = rev
1499 matches.clear()
1500 matches.clear()
1500 elif st == 'add':
1501 elif st == 'add':
1501 mf = repo.changectx(rev).manifest()
1502 mf = repo.changectx(rev).manifest()
1502 matches[rev] = {}
1503 matches[rev] = {}
1503 for fn in fns:
1504 for fn in fns:
1504 if fn in skip:
1505 if fn in skip:
1505 continue
1506 continue
1506 fstate.setdefault(fn, {})
1507 fstate.setdefault(fn, {})
1507 try:
1508 try:
1508 grepbody(fn, rev, getfile(fn).read(mf[fn]))
1509 grepbody(fn, rev, getfile(fn).read(mf[fn]))
1509 if follow:
1510 if follow:
1510 copied = getfile(fn).renamed(mf[fn])
1511 copied = getfile(fn).renamed(mf[fn])
1511 if copied:
1512 if copied:
1512 copies.setdefault(rev, {})[fn] = copied[0]
1513 copies.setdefault(rev, {})[fn] = copied[0]
1513 except KeyError:
1514 except KeyError:
1514 pass
1515 pass
1515 elif st == 'iter':
1516 elif st == 'iter':
1516 states = matches[rev].items()
1517 states = matches[rev].items()
1517 states.sort()
1518 states.sort()
1518 for fn, m in states:
1519 for fn, m in states:
1519 copy = copies.get(rev, {}).get(fn)
1520 copy = copies.get(rev, {}).get(fn)
1520 if fn in skip:
1521 if fn in skip:
1521 if copy:
1522 if copy:
1522 skip[copy] = True
1523 skip[copy] = True
1523 continue
1524 continue
1524 if incrementing or not opts['all'] or fstate[fn]:
1525 if incrementing or not opts['all'] or fstate[fn]:
1525 pos, neg = display(fn, rev, m, fstate[fn])
1526 pos, neg = display(fn, rev, m, fstate[fn])
1526 count += pos + neg
1527 count += pos + neg
1527 if pos and not opts['all']:
1528 if pos and not opts['all']:
1528 skip[fn] = True
1529 skip[fn] = True
1529 if copy:
1530 if copy:
1530 skip[copy] = True
1531 skip[copy] = True
1531 fstate[fn] = m
1532 fstate[fn] = m
1532 if copy:
1533 if copy:
1533 fstate[copy] = m
1534 fstate[copy] = m
1534 prev[fn] = rev
1535 prev[fn] = rev
1535
1536
1536 if not incrementing:
1537 if not incrementing:
1537 fstate = fstate.items()
1538 fstate = fstate.items()
1538 fstate.sort()
1539 fstate.sort()
1539 for fn, state in fstate:
1540 for fn, state in fstate:
1540 if fn in skip:
1541 if fn in skip:
1541 continue
1542 continue
1542 if fn not in copies.get(prev[fn], {}):
1543 if fn not in copies.get(prev[fn], {}):
1543 display(fn, rev, {}, state)
1544 display(fn, rev, {}, state)
1544 return (count == 0 and 1) or 0
1545 return (count == 0 and 1) or 0
1545
1546
1546 def heads(ui, repo, **opts):
1547 def heads(ui, repo, **opts):
1547 """show current repository heads
1548 """show current repository heads
1548
1549
1549 Show all repository head changesets.
1550 Show all repository head changesets.
1550
1551
1551 Repository "heads" are changesets that don't have children
1552 Repository "heads" are changesets that don't have children
1552 changesets. They are where development generally takes place and
1553 changesets. They are where development generally takes place and
1553 are the usual targets for update and merge operations.
1554 are the usual targets for update and merge operations.
1554 """
1555 """
1555 if opts['rev']:
1556 if opts['rev']:
1556 heads = repo.heads(repo.lookup(opts['rev']))
1557 heads = repo.heads(repo.lookup(opts['rev']))
1557 else:
1558 else:
1558 heads = repo.heads()
1559 heads = repo.heads()
1559 br = None
1560 br = None
1560 if opts['branches']:
1561 if opts['branches']:
1561 ui.warn(_("the --branches option is deprecated, "
1562 ui.warn(_("the --branches option is deprecated, "
1562 "please use 'hg branches' instead\n"))
1563 "please use 'hg branches' instead\n"))
1563 br = repo.branchlookup(heads)
1564 br = repo.branchlookup(heads)
1564 displayer = show_changeset(ui, repo, opts)
1565 displayer = show_changeset(ui, repo, opts)
1565 for n in heads:
1566 for n in heads:
1566 displayer.show(changenode=n, brinfo=br)
1567 displayer.show(changenode=n, brinfo=br)
1567
1568
1568 def identify(ui, repo):
1569 def identify(ui, repo):
1569 """print information about the working copy
1570 """print information about the working copy
1570
1571
1571 Print a short summary of the current state of the repo.
1572 Print a short summary of the current state of the repo.
1572
1573
1573 This summary identifies the repository state using one or two parent
1574 This summary identifies the repository state using one or two parent
1574 hash identifiers, followed by a "+" if there are uncommitted changes
1575 hash identifiers, followed by a "+" if there are uncommitted changes
1575 in the working directory, followed by a list of tags for this revision.
1576 in the working directory, followed by a list of tags for this revision.
1576 """
1577 """
1577 parents = [p for p in repo.dirstate.parents() if p != nullid]
1578 parents = [p for p in repo.dirstate.parents() if p != nullid]
1578 if not parents:
1579 if not parents:
1579 ui.write(_("unknown\n"))
1580 ui.write(_("unknown\n"))
1580 return
1581 return
1581
1582
1582 hexfunc = ui.debugflag and hex or short
1583 hexfunc = ui.debugflag and hex or short
1583 modified, added, removed, deleted = repo.status()[:4]
1584 modified, added, removed, deleted = repo.status()[:4]
1584 output = ["%s%s" %
1585 output = ["%s%s" %
1585 ('+'.join([hexfunc(parent) for parent in parents]),
1586 ('+'.join([hexfunc(parent) for parent in parents]),
1586 (modified or added or removed or deleted) and "+" or "")]
1587 (modified or added or removed or deleted) and "+" or "")]
1587
1588
1588 if not ui.quiet:
1589 if not ui.quiet:
1589
1590
1590 branch = repo.workingctx().branch()
1591 branch = repo.workingctx().branch()
1591 if branch:
1592 if branch:
1592 output.append("(%s)" % branch)
1593 output.append("(%s)" % branch)
1593
1594
1594 # multiple tags for a single parent separated by '/'
1595 # multiple tags for a single parent separated by '/'
1595 parenttags = ['/'.join(tags)
1596 parenttags = ['/'.join(tags)
1596 for tags in map(repo.nodetags, parents) if tags]
1597 for tags in map(repo.nodetags, parents) if tags]
1597 # tags for multiple parents separated by ' + '
1598 # tags for multiple parents separated by ' + '
1598 if parenttags:
1599 if parenttags:
1599 output.append(' + '.join(parenttags))
1600 output.append(' + '.join(parenttags))
1600
1601
1601 ui.write("%s\n" % ' '.join(output))
1602 ui.write("%s\n" % ' '.join(output))
1602
1603
1603 def import_(ui, repo, patch1, *patches, **opts):
1604 def import_(ui, repo, patch1, *patches, **opts):
1604 """import an ordered set of patches
1605 """import an ordered set of patches
1605
1606
1606 Import a list of patches and commit them individually.
1607 Import a list of patches and commit them individually.
1607
1608
1608 If there are outstanding changes in the working directory, import
1609 If there are outstanding changes in the working directory, import
1609 will abort unless given the -f flag.
1610 will abort unless given the -f flag.
1610
1611
1611 You can import a patch straight from a mail message. Even patches
1612 You can import a patch straight from a mail message. Even patches
1612 as attachments work (body part must be type text/plain or
1613 as attachments work (body part must be type text/plain or
1613 text/x-patch to be used). From and Subject headers of email
1614 text/x-patch to be used). From and Subject headers of email
1614 message are used as default committer and commit message. All
1615 message are used as default committer and commit message. All
1615 text/plain body parts before first diff are added to commit
1616 text/plain body parts before first diff are added to commit
1616 message.
1617 message.
1617
1618
1618 If imported patch was generated by hg export, user and description
1619 If imported patch was generated by hg export, user and description
1619 from patch override values from message headers and body. Values
1620 from patch override values from message headers and body. Values
1620 given on command line with -m and -u override these.
1621 given on command line with -m and -u override these.
1621
1622
1622 To read a patch from standard input, use patch name "-".
1623 To read a patch from standard input, use patch name "-".
1623 """
1624 """
1624 patches = (patch1,) + patches
1625 patches = (patch1,) + patches
1625
1626
1626 if not opts['force']:
1627 if not opts['force']:
1627 bail_if_changed(repo)
1628 bail_if_changed(repo)
1628
1629
1629 d = opts["base"]
1630 d = opts["base"]
1630 strip = opts["strip"]
1631 strip = opts["strip"]
1631
1632
1632 wlock = repo.wlock()
1633 wlock = repo.wlock()
1633 lock = repo.lock()
1634 lock = repo.lock()
1634
1635
1635 for p in patches:
1636 for p in patches:
1636 pf = os.path.join(d, p)
1637 pf = os.path.join(d, p)
1637
1638
1638 if pf == '-':
1639 if pf == '-':
1639 ui.status(_("applying patch from stdin\n"))
1640 ui.status(_("applying patch from stdin\n"))
1640 tmpname, message, user, date = patch.extract(ui, sys.stdin)
1641 tmpname, message, user, date = patch.extract(ui, sys.stdin)
1641 else:
1642 else:
1642 ui.status(_("applying %s\n") % p)
1643 ui.status(_("applying %s\n") % p)
1643 tmpname, message, user, date = patch.extract(ui, file(pf))
1644 tmpname, message, user, date = patch.extract(ui, file(pf))
1644
1645
1645 if tmpname is None:
1646 if tmpname is None:
1646 raise util.Abort(_('no diffs found'))
1647 raise util.Abort(_('no diffs found'))
1647
1648
1648 try:
1649 try:
1649 if opts['message']:
1650 if opts['message']:
1650 # pickup the cmdline msg
1651 # pickup the cmdline msg
1651 message = opts['message']
1652 message = opts['message']
1652 elif message:
1653 elif message:
1653 # pickup the patch msg
1654 # pickup the patch msg
1654 message = message.strip()
1655 message = message.strip()
1655 else:
1656 else:
1656 # launch the editor
1657 # launch the editor
1657 message = None
1658 message = None
1658 ui.debug(_('message:\n%s\n') % message)
1659 ui.debug(_('message:\n%s\n') % message)
1659
1660
1660 files = {}
1661 files = {}
1661 try:
1662 try:
1662 fuzz = patch.patch(tmpname, ui, strip=strip, cwd=repo.root,
1663 fuzz = patch.patch(tmpname, ui, strip=strip, cwd=repo.root,
1663 files=files)
1664 files=files)
1664 finally:
1665 finally:
1665 files = patch.updatedir(ui, repo, files, wlock=wlock)
1666 files = patch.updatedir(ui, repo, files, wlock=wlock)
1666 repo.commit(files, message, user, date, wlock=wlock, lock=lock)
1667 repo.commit(files, message, user, date, wlock=wlock, lock=lock)
1667 finally:
1668 finally:
1668 os.unlink(tmpname)
1669 os.unlink(tmpname)
1669
1670
1670 def incoming(ui, repo, source="default", **opts):
1671 def incoming(ui, repo, source="default", **opts):
1671 """show new changesets found in source
1672 """show new changesets found in source
1672
1673
1673 Show new changesets found in the specified path/URL or the default
1674 Show new changesets found in the specified path/URL or the default
1674 pull location. These are the changesets that would be pulled if a pull
1675 pull location. These are the changesets that would be pulled if a pull
1675 was requested.
1676 was requested.
1676
1677
1677 For remote repository, using --bundle avoids downloading the changesets
1678 For remote repository, using --bundle avoids downloading the changesets
1678 twice if the incoming is followed by a pull.
1679 twice if the incoming is followed by a pull.
1679
1680
1680 See pull for valid source format details.
1681 See pull for valid source format details.
1681 """
1682 """
1682 source = ui.expandpath(source)
1683 source = ui.expandpath(source)
1683 setremoteconfig(ui, opts)
1684 setremoteconfig(ui, opts)
1684
1685
1685 other = hg.repository(ui, source)
1686 other = hg.repository(ui, source)
1686 incoming = repo.findincoming(other, force=opts["force"])
1687 incoming = repo.findincoming(other, force=opts["force"])
1687 if not incoming:
1688 if not incoming:
1688 ui.status(_("no changes found\n"))
1689 ui.status(_("no changes found\n"))
1689 return
1690 return
1690
1691
1691 cleanup = None
1692 cleanup = None
1692 try:
1693 try:
1693 fname = opts["bundle"]
1694 fname = opts["bundle"]
1694 if fname or not other.local():
1695 if fname or not other.local():
1695 # create a bundle (uncompressed if other repo is not local)
1696 # create a bundle (uncompressed if other repo is not local)
1696 cg = other.changegroup(incoming, "incoming")
1697 cg = other.changegroup(incoming, "incoming")
1697 fname = cleanup = write_bundle(cg, fname, compress=other.local())
1698 fname = cleanup = write_bundle(cg, fname, compress=other.local())
1698 # keep written bundle?
1699 # keep written bundle?
1699 if opts["bundle"]:
1700 if opts["bundle"]:
1700 cleanup = None
1701 cleanup = None
1701 if not other.local():
1702 if not other.local():
1702 # use the created uncompressed bundlerepo
1703 # use the created uncompressed bundlerepo
1703 other = bundlerepo.bundlerepository(ui, repo.root, fname)
1704 other = bundlerepo.bundlerepository(ui, repo.root, fname)
1704
1705
1705 revs = None
1706 revs = None
1706 if opts['rev']:
1707 if opts['rev']:
1707 revs = [other.lookup(rev) for rev in opts['rev']]
1708 revs = [other.lookup(rev) for rev in opts['rev']]
1708 o = other.changelog.nodesbetween(incoming, revs)[0]
1709 o = other.changelog.nodesbetween(incoming, revs)[0]
1709 if opts['newest_first']:
1710 if opts['newest_first']:
1710 o.reverse()
1711 o.reverse()
1711 displayer = show_changeset(ui, other, opts)
1712 displayer = show_changeset(ui, other, opts)
1712 for n in o:
1713 for n in o:
1713 parents = [p for p in other.changelog.parents(n) if p != nullid]
1714 parents = [p for p in other.changelog.parents(n) if p != nullid]
1714 if opts['no_merges'] and len(parents) == 2:
1715 if opts['no_merges'] and len(parents) == 2:
1715 continue
1716 continue
1716 displayer.show(changenode=n)
1717 displayer.show(changenode=n)
1717 if opts['patch']:
1718 if opts['patch']:
1718 prev = (parents and parents[0]) or nullid
1719 prev = (parents and parents[0]) or nullid
1719 patch.diff(other, prev, n, fp=repo.ui)
1720 patch.diff(other, prev, n, fp=repo.ui)
1720 ui.write("\n")
1721 ui.write("\n")
1721 finally:
1722 finally:
1722 if hasattr(other, 'close'):
1723 if hasattr(other, 'close'):
1723 other.close()
1724 other.close()
1724 if cleanup:
1725 if cleanup:
1725 os.unlink(cleanup)
1726 os.unlink(cleanup)
1726
1727
1727 def init(ui, dest=".", **opts):
1728 def init(ui, dest=".", **opts):
1728 """create a new repository in the given directory
1729 """create a new repository in the given directory
1729
1730
1730 Initialize a new repository in the given directory. If the given
1731 Initialize a new repository in the given directory. If the given
1731 directory does not exist, it is created.
1732 directory does not exist, it is created.
1732
1733
1733 If no directory is given, the current directory is used.
1734 If no directory is given, the current directory is used.
1734
1735
1735 It is possible to specify an ssh:// URL as the destination.
1736 It is possible to specify an ssh:// URL as the destination.
1736 Look at the help text for the pull command for important details
1737 Look at the help text for the pull command for important details
1737 about ssh:// URLs.
1738 about ssh:// URLs.
1738 """
1739 """
1739 setremoteconfig(ui, opts)
1740 setremoteconfig(ui, opts)
1740 hg.repository(ui, dest, create=1)
1741 hg.repository(ui, dest, create=1)
1741
1742
1742 def locate(ui, repo, *pats, **opts):
1743 def locate(ui, repo, *pats, **opts):
1743 """locate files matching specific patterns
1744 """locate files matching specific patterns
1744
1745
1745 Print all files under Mercurial control whose names match the
1746 Print all files under Mercurial control whose names match the
1746 given patterns.
1747 given patterns.
1747
1748
1748 This command searches the current directory and its
1749 This command searches the current directory and its
1749 subdirectories. To search an entire repository, move to the root
1750 subdirectories. To search an entire repository, move to the root
1750 of the repository.
1751 of the repository.
1751
1752
1752 If no patterns are given to match, this command prints all file
1753 If no patterns are given to match, this command prints all file
1753 names.
1754 names.
1754
1755
1755 If you want to feed the output of this command into the "xargs"
1756 If you want to feed the output of this command into the "xargs"
1756 command, use the "-0" option to both this command and "xargs".
1757 command, use the "-0" option to both this command and "xargs".
1757 This will avoid the problem of "xargs" treating single filenames
1758 This will avoid the problem of "xargs" treating single filenames
1758 that contain white space as multiple filenames.
1759 that contain white space as multiple filenames.
1759 """
1760 """
1760 end = opts['print0'] and '\0' or '\n'
1761 end = opts['print0'] and '\0' or '\n'
1761 rev = opts['rev']
1762 rev = opts['rev']
1762 if rev:
1763 if rev:
1763 node = repo.lookup(rev)
1764 node = repo.lookup(rev)
1764 else:
1765 else:
1765 node = None
1766 node = None
1766
1767
1767 for src, abs, rel, exact in cmdutil.walk(repo, pats, opts, node=node,
1768 for src, abs, rel, exact in cmdutil.walk(repo, pats, opts, node=node,
1768 head='(?:.*/|)'):
1769 head='(?:.*/|)'):
1769 if not node and repo.dirstate.state(abs) == '?':
1770 if not node and repo.dirstate.state(abs) == '?':
1770 continue
1771 continue
1771 if opts['fullpath']:
1772 if opts['fullpath']:
1772 ui.write(os.path.join(repo.root, abs), end)
1773 ui.write(os.path.join(repo.root, abs), end)
1773 else:
1774 else:
1774 ui.write(((pats and rel) or abs), end)
1775 ui.write(((pats and rel) or abs), end)
1775
1776
1776 def log(ui, repo, *pats, **opts):
1777 def log(ui, repo, *pats, **opts):
1777 """show revision history of entire repository or files
1778 """show revision history of entire repository or files
1778
1779
1779 Print the revision history of the specified files or the entire
1780 Print the revision history of the specified files or the entire
1780 project.
1781 project.
1781
1782
1782 File history is shown without following rename or copy history of
1783 File history is shown without following rename or copy history of
1783 files. Use -f/--follow with a file name to follow history across
1784 files. Use -f/--follow with a file name to follow history across
1784 renames and copies. --follow without a file name will only show
1785 renames and copies. --follow without a file name will only show
1785 ancestors or descendants of the starting revision. --follow-first
1786 ancestors or descendants of the starting revision. --follow-first
1786 only follows the first parent of merge revisions.
1787 only follows the first parent of merge revisions.
1787
1788
1788 If no revision range is specified, the default is tip:0 unless
1789 If no revision range is specified, the default is tip:0 unless
1789 --follow is set, in which case the working directory parent is
1790 --follow is set, in which case the working directory parent is
1790 used as the starting revision.
1791 used as the starting revision.
1791
1792
1792 By default this command outputs: changeset id and hash, tags,
1793 By default this command outputs: changeset id and hash, tags,
1793 non-trivial parents, user, date and time, and a summary for each
1794 non-trivial parents, user, date and time, and a summary for each
1794 commit. When the -v/--verbose switch is used, the list of changed
1795 commit. When the -v/--verbose switch is used, the list of changed
1795 files and full commit message is shown.
1796 files and full commit message is shown.
1796 """
1797 """
1797 class dui(object):
1798 class dui(object):
1798 # Implement and delegate some ui protocol. Save hunks of
1799 # Implement and delegate some ui protocol. Save hunks of
1799 # output for later display in the desired order.
1800 # output for later display in the desired order.
1800 def __init__(self, ui):
1801 def __init__(self, ui):
1801 self.ui = ui
1802 self.ui = ui
1802 self.hunk = {}
1803 self.hunk = {}
1803 self.header = {}
1804 self.header = {}
1804 def bump(self, rev):
1805 def bump(self, rev):
1805 self.rev = rev
1806 self.rev = rev
1806 self.hunk[rev] = []
1807 self.hunk[rev] = []
1807 self.header[rev] = []
1808 self.header[rev] = []
1808 def note(self, *args):
1809 def note(self, *args):
1809 if self.verbose:
1810 if self.verbose:
1810 self.write(*args)
1811 self.write(*args)
1811 def status(self, *args):
1812 def status(self, *args):
1812 if not self.quiet:
1813 if not self.quiet:
1813 self.write(*args)
1814 self.write(*args)
1814 def write(self, *args):
1815 def write(self, *args):
1815 self.hunk[self.rev].append(args)
1816 self.hunk[self.rev].append(args)
1816 def write_header(self, *args):
1817 def write_header(self, *args):
1817 self.header[self.rev].append(args)
1818 self.header[self.rev].append(args)
1818 def debug(self, *args):
1819 def debug(self, *args):
1819 if self.debugflag:
1820 if self.debugflag:
1820 self.write(*args)
1821 self.write(*args)
1821 def __getattr__(self, key):
1822 def __getattr__(self, key):
1822 return getattr(self.ui, key)
1823 return getattr(self.ui, key)
1823
1824
1824 getchange = util.cachefunc(lambda r:repo.changectx(r).changeset())
1825 getchange = util.cachefunc(lambda r:repo.changectx(r).changeset())
1825 changeiter, matchfn = walkchangerevs(ui, repo, pats, getchange, opts)
1826 changeiter, matchfn = walkchangerevs(ui, repo, pats, getchange, opts)
1826
1827
1827 if opts['branches']:
1828 if opts['branches']:
1828 ui.warn(_("the --branches option is deprecated, "
1829 ui.warn(_("the --branches option is deprecated, "
1829 "please use 'hg branches' instead\n"))
1830 "please use 'hg branches' instead\n"))
1830
1831
1831 if opts['limit']:
1832 if opts['limit']:
1832 try:
1833 try:
1833 limit = int(opts['limit'])
1834 limit = int(opts['limit'])
1834 except ValueError:
1835 except ValueError:
1835 raise util.Abort(_('limit must be a positive integer'))
1836 raise util.Abort(_('limit must be a positive integer'))
1836 if limit <= 0: raise util.Abort(_('limit must be positive'))
1837 if limit <= 0: raise util.Abort(_('limit must be positive'))
1837 else:
1838 else:
1838 limit = sys.maxint
1839 limit = sys.maxint
1839 count = 0
1840 count = 0
1840
1841
1841 if opts['copies'] and opts['rev']:
1842 if opts['copies'] and opts['rev']:
1842 endrev = max(cmdutil.revrange(ui, repo, opts['rev'])) + 1
1843 endrev = max(cmdutil.revrange(ui, repo, opts['rev'])) + 1
1843 else:
1844 else:
1844 endrev = repo.changelog.count()
1845 endrev = repo.changelog.count()
1845 rcache = {}
1846 rcache = {}
1846 ncache = {}
1847 ncache = {}
1847 dcache = []
1848 dcache = []
1848 def getrenamed(fn, rev, man):
1849 def getrenamed(fn, rev, man):
1849 '''looks up all renames for a file (up to endrev) the first
1850 '''looks up all renames for a file (up to endrev) the first
1850 time the file is given. It indexes on the changerev and only
1851 time the file is given. It indexes on the changerev and only
1851 parses the manifest if linkrev != changerev.
1852 parses the manifest if linkrev != changerev.
1852 Returns rename info for fn at changerev rev.'''
1853 Returns rename info for fn at changerev rev.'''
1853 if fn not in rcache:
1854 if fn not in rcache:
1854 rcache[fn] = {}
1855 rcache[fn] = {}
1855 ncache[fn] = {}
1856 ncache[fn] = {}
1856 fl = repo.file(fn)
1857 fl = repo.file(fn)
1857 for i in xrange(fl.count()):
1858 for i in xrange(fl.count()):
1858 node = fl.node(i)
1859 node = fl.node(i)
1859 lr = fl.linkrev(node)
1860 lr = fl.linkrev(node)
1860 renamed = fl.renamed(node)
1861 renamed = fl.renamed(node)
1861 rcache[fn][lr] = renamed
1862 rcache[fn][lr] = renamed
1862 if renamed:
1863 if renamed:
1863 ncache[fn][node] = renamed
1864 ncache[fn][node] = renamed
1864 if lr >= endrev:
1865 if lr >= endrev:
1865 break
1866 break
1866 if rev in rcache[fn]:
1867 if rev in rcache[fn]:
1867 return rcache[fn][rev]
1868 return rcache[fn][rev]
1868 mr = repo.manifest.rev(man)
1869 mr = repo.manifest.rev(man)
1869 if repo.manifest.parentrevs(mr) != (mr - 1, -1):
1870 if repo.manifest.parentrevs(mr) != (mr - 1, -1):
1870 return ncache[fn].get(repo.manifest.find(man, fn)[0])
1871 return ncache[fn].get(repo.manifest.find(man, fn)[0])
1871 if not dcache or dcache[0] != man:
1872 if not dcache or dcache[0] != man:
1872 dcache[:] = [man, repo.manifest.readdelta(man)]
1873 dcache[:] = [man, repo.manifest.readdelta(man)]
1873 if fn in dcache[1]:
1874 if fn in dcache[1]:
1874 return ncache[fn].get(dcache[1][fn])
1875 return ncache[fn].get(dcache[1][fn])
1875 return None
1876 return None
1876
1877
1877 displayer = show_changeset(ui, repo, opts)
1878 displayer = show_changeset(ui, repo, opts)
1878 for st, rev, fns in changeiter:
1879 for st, rev, fns in changeiter:
1879 if st == 'window':
1880 if st == 'window':
1880 du = dui(ui)
1881 du = dui(ui)
1881 displayer.ui = du
1882 displayer.ui = du
1882 elif st == 'add':
1883 elif st == 'add':
1883 du.bump(rev)
1884 du.bump(rev)
1884 changenode = repo.changelog.node(rev)
1885 changenode = repo.changelog.node(rev)
1885 parents = [p for p in repo.changelog.parents(changenode)
1886 parents = [p for p in repo.changelog.parents(changenode)
1886 if p != nullid]
1887 if p != nullid]
1887 if opts['no_merges'] and len(parents) == 2:
1888 if opts['no_merges'] and len(parents) == 2:
1888 continue
1889 continue
1889 if opts['only_merges'] and len(parents) != 2:
1890 if opts['only_merges'] and len(parents) != 2:
1890 continue
1891 continue
1891
1892
1892 if opts['keyword']:
1893 if opts['keyword']:
1893 changes = getchange(rev)
1894 changes = getchange(rev)
1894 miss = 0
1895 miss = 0
1895 for k in [kw.lower() for kw in opts['keyword']]:
1896 for k in [kw.lower() for kw in opts['keyword']]:
1896 if not (k in changes[1].lower() or
1897 if not (k in changes[1].lower() or
1897 k in changes[4].lower() or
1898 k in changes[4].lower() or
1898 k in " ".join(changes[3][:20]).lower()):
1899 k in " ".join(changes[3][:20]).lower()):
1899 miss = 1
1900 miss = 1
1900 break
1901 break
1901 if miss:
1902 if miss:
1902 continue
1903 continue
1903
1904
1904 br = None
1905 br = None
1905 if opts['branches']:
1906 if opts['branches']:
1906 br = repo.branchlookup([repo.changelog.node(rev)])
1907 br = repo.branchlookup([repo.changelog.node(rev)])
1907
1908
1908 copies = []
1909 copies = []
1909 if opts.get('copies') and rev:
1910 if opts.get('copies') and rev:
1910 mf = getchange(rev)[0]
1911 mf = getchange(rev)[0]
1911 for fn in getchange(rev)[3]:
1912 for fn in getchange(rev)[3]:
1912 rename = getrenamed(fn, rev, mf)
1913 rename = getrenamed(fn, rev, mf)
1913 if rename:
1914 if rename:
1914 copies.append((fn, rename[0]))
1915 copies.append((fn, rename[0]))
1915 displayer.show(rev, brinfo=br, copies=copies)
1916 displayer.show(rev, brinfo=br, copies=copies)
1916 if opts['patch']:
1917 if opts['patch']:
1917 prev = (parents and parents[0]) or nullid
1918 prev = (parents and parents[0]) or nullid
1918 patch.diff(repo, prev, changenode, match=matchfn, fp=du)
1919 patch.diff(repo, prev, changenode, match=matchfn, fp=du)
1919 du.write("\n\n")
1920 du.write("\n\n")
1920 elif st == 'iter':
1921 elif st == 'iter':
1921 if count == limit: break
1922 if count == limit: break
1922 if du.header[rev]:
1923 if du.header[rev]:
1923 for args in du.header[rev]:
1924 for args in du.header[rev]:
1924 ui.write_header(*args)
1925 ui.write_header(*args)
1925 if du.hunk[rev]:
1926 if du.hunk[rev]:
1926 count += 1
1927 count += 1
1927 for args in du.hunk[rev]:
1928 for args in du.hunk[rev]:
1928 ui.write(*args)
1929 ui.write(*args)
1929
1930
1930 def manifest(ui, repo, rev=None):
1931 def manifest(ui, repo, rev=None):
1931 """output the latest or given revision of the project manifest
1932 """output the latest or given revision of the project manifest
1932
1933
1933 Print a list of version controlled files for the given revision.
1934 Print a list of version controlled files for the given revision.
1934
1935
1935 The manifest is the list of files being version controlled. If no revision
1936 The manifest is the list of files being version controlled. If no revision
1936 is given then the tip is used.
1937 is given then the tip is used.
1937 """
1938 """
1938 if rev:
1939 if rev:
1939 try:
1940 try:
1940 # assume all revision numbers are for changesets
1941 # assume all revision numbers are for changesets
1941 n = repo.lookup(rev)
1942 n = repo.lookup(rev)
1942 change = repo.changelog.read(n)
1943 change = repo.changelog.read(n)
1943 n = change[0]
1944 n = change[0]
1944 except hg.RepoError:
1945 except hg.RepoError:
1945 n = repo.manifest.lookup(rev)
1946 n = repo.manifest.lookup(rev)
1946 else:
1947 else:
1947 n = repo.manifest.tip()
1948 n = repo.manifest.tip()
1948 m = repo.manifest.read(n)
1949 m = repo.manifest.read(n)
1949 files = m.keys()
1950 files = m.keys()
1950 files.sort()
1951 files.sort()
1951
1952
1952 for f in files:
1953 for f in files:
1953 ui.write("%40s %3s %s\n" % (hex(m[f]),
1954 ui.write("%40s %3s %s\n" % (hex(m[f]),
1954 m.execf(f) and "755" or "644", f))
1955 m.execf(f) and "755" or "644", f))
1955
1956
1956 def merge(ui, repo, node=None, force=None, branch=None):
1957 def merge(ui, repo, node=None, force=None, branch=None):
1957 """Merge working directory with another revision
1958 """Merge working directory with another revision
1958
1959
1959 Merge the contents of the current working directory and the
1960 Merge the contents of the current working directory and the
1960 requested revision. Files that changed between either parent are
1961 requested revision. Files that changed between either parent are
1961 marked as changed for the next commit and a commit must be
1962 marked as changed for the next commit and a commit must be
1962 performed before any further updates are allowed.
1963 performed before any further updates are allowed.
1963
1964
1964 If no revision is specified, the working directory's parent is a
1965 If no revision is specified, the working directory's parent is a
1965 head revision, and the repository contains exactly one other head,
1966 head revision, and the repository contains exactly one other head,
1966 the other head is merged with by default. Otherwise, an explicit
1967 the other head is merged with by default. Otherwise, an explicit
1967 revision to merge with must be provided.
1968 revision to merge with must be provided.
1968 """
1969 """
1969
1970
1970 if node or branch:
1971 if node or branch:
1971 node = _lookup(repo, node, branch)
1972 node = _lookup(repo, node, branch)
1972 else:
1973 else:
1973 heads = repo.heads()
1974 heads = repo.heads()
1974 if len(heads) > 2:
1975 if len(heads) > 2:
1975 raise util.Abort(_('repo has %d heads - '
1976 raise util.Abort(_('repo has %d heads - '
1976 'please merge with an explicit rev') %
1977 'please merge with an explicit rev') %
1977 len(heads))
1978 len(heads))
1978 if len(heads) == 1:
1979 if len(heads) == 1:
1979 raise util.Abort(_('there is nothing to merge - '
1980 raise util.Abort(_('there is nothing to merge - '
1980 'use "hg update" instead'))
1981 'use "hg update" instead'))
1981 parent = repo.dirstate.parents()[0]
1982 parent = repo.dirstate.parents()[0]
1982 if parent not in heads:
1983 if parent not in heads:
1983 raise util.Abort(_('working dir not at a head rev - '
1984 raise util.Abort(_('working dir not at a head rev - '
1984 'use "hg update" or merge with an explicit rev'))
1985 'use "hg update" or merge with an explicit rev'))
1985 node = parent == heads[0] and heads[-1] or heads[0]
1986 node = parent == heads[0] and heads[-1] or heads[0]
1986 return hg.merge(repo, node, force=force)
1987 return hg.merge(repo, node, force=force)
1987
1988
1988 def outgoing(ui, repo, dest=None, **opts):
1989 def outgoing(ui, repo, dest=None, **opts):
1989 """show changesets not found in destination
1990 """show changesets not found in destination
1990
1991
1991 Show changesets not found in the specified destination repository or
1992 Show changesets not found in the specified destination repository or
1992 the default push location. These are the changesets that would be pushed
1993 the default push location. These are the changesets that would be pushed
1993 if a push was requested.
1994 if a push was requested.
1994
1995
1995 See pull for valid destination format details.
1996 See pull for valid destination format details.
1996 """
1997 """
1997 dest = ui.expandpath(dest or 'default-push', dest or 'default')
1998 dest = ui.expandpath(dest or 'default-push', dest or 'default')
1998 setremoteconfig(ui, opts)
1999 setremoteconfig(ui, opts)
1999 revs = None
2000 revs = None
2000 if opts['rev']:
2001 if opts['rev']:
2001 revs = [repo.lookup(rev) for rev in opts['rev']]
2002 revs = [repo.lookup(rev) for rev in opts['rev']]
2002
2003
2003 other = hg.repository(ui, dest)
2004 other = hg.repository(ui, dest)
2004 o = repo.findoutgoing(other, force=opts['force'])
2005 o = repo.findoutgoing(other, force=opts['force'])
2005 if not o:
2006 if not o:
2006 ui.status(_("no changes found\n"))
2007 ui.status(_("no changes found\n"))
2007 return
2008 return
2008 o = repo.changelog.nodesbetween(o, revs)[0]
2009 o = repo.changelog.nodesbetween(o, revs)[0]
2009 if opts['newest_first']:
2010 if opts['newest_first']:
2010 o.reverse()
2011 o.reverse()
2011 displayer = show_changeset(ui, repo, opts)
2012 displayer = show_changeset(ui, repo, opts)
2012 for n in o:
2013 for n in o:
2013 parents = [p for p in repo.changelog.parents(n) if p != nullid]
2014 parents = [p for p in repo.changelog.parents(n) if p != nullid]
2014 if opts['no_merges'] and len(parents) == 2:
2015 if opts['no_merges'] and len(parents) == 2:
2015 continue
2016 continue
2016 displayer.show(changenode=n)
2017 displayer.show(changenode=n)
2017 if opts['patch']:
2018 if opts['patch']:
2018 prev = (parents and parents[0]) or nullid
2019 prev = (parents and parents[0]) or nullid
2019 patch.diff(repo, prev, n)
2020 patch.diff(repo, prev, n)
2020 ui.write("\n")
2021 ui.write("\n")
2021
2022
2022 def parents(ui, repo, file_=None, rev=None, branches=None, **opts):
2023 def parents(ui, repo, file_=None, rev=None, branches=None, **opts):
2023 """show the parents of the working dir or revision
2024 """show the parents of the working dir or revision
2024
2025
2025 Print the working directory's parent revisions.
2026 Print the working directory's parent revisions.
2026 """
2027 """
2027 # legacy
2028 # legacy
2028 if file_ and not rev:
2029 if file_ and not rev:
2029 try:
2030 try:
2030 rev = repo.lookup(file_)
2031 rev = repo.lookup(file_)
2031 file_ = None
2032 file_ = None
2032 except hg.RepoError:
2033 except hg.RepoError:
2033 pass
2034 pass
2034 else:
2035 else:
2035 ui.warn(_("'hg parent REV' is deprecated, "
2036 ui.warn(_("'hg parent REV' is deprecated, "
2036 "please use 'hg parents -r REV instead\n"))
2037 "please use 'hg parents -r REV instead\n"))
2037
2038
2038 if rev:
2039 if rev:
2039 if file_:
2040 if file_:
2040 ctx = repo.filectx(file_, changeid=rev)
2041 ctx = repo.filectx(file_, changeid=rev)
2041 else:
2042 else:
2042 ctx = repo.changectx(rev)
2043 ctx = repo.changectx(rev)
2043 p = [cp.node() for cp in ctx.parents()]
2044 p = [cp.node() for cp in ctx.parents()]
2044 else:
2045 else:
2045 p = repo.dirstate.parents()
2046 p = repo.dirstate.parents()
2046
2047
2047 br = None
2048 br = None
2048 if branches is not None:
2049 if branches is not None:
2049 ui.warn(_("the --branches option is deprecated, "
2050 ui.warn(_("the --branches option is deprecated, "
2050 "please use 'hg branches' instead\n"))
2051 "please use 'hg branches' instead\n"))
2051 br = repo.branchlookup(p)
2052 br = repo.branchlookup(p)
2052 displayer = show_changeset(ui, repo, opts)
2053 displayer = show_changeset(ui, repo, opts)
2053 for n in p:
2054 for n in p:
2054 if n != nullid:
2055 if n != nullid:
2055 displayer.show(changenode=n, brinfo=br)
2056 displayer.show(changenode=n, brinfo=br)
2056
2057
2057 def paths(ui, repo, search=None):
2058 def paths(ui, repo, search=None):
2058 """show definition of symbolic path names
2059 """show definition of symbolic path names
2059
2060
2060 Show definition of symbolic path name NAME. If no name is given, show
2061 Show definition of symbolic path name NAME. If no name is given, show
2061 definition of available names.
2062 definition of available names.
2062
2063
2063 Path names are defined in the [paths] section of /etc/mercurial/hgrc
2064 Path names are defined in the [paths] section of /etc/mercurial/hgrc
2064 and $HOME/.hgrc. If run inside a repository, .hg/hgrc is used, too.
2065 and $HOME/.hgrc. If run inside a repository, .hg/hgrc is used, too.
2065 """
2066 """
2066 if search:
2067 if search:
2067 for name, path in ui.configitems("paths"):
2068 for name, path in ui.configitems("paths"):
2068 if name == search:
2069 if name == search:
2069 ui.write("%s\n" % path)
2070 ui.write("%s\n" % path)
2070 return
2071 return
2071 ui.warn(_("not found!\n"))
2072 ui.warn(_("not found!\n"))
2072 return 1
2073 return 1
2073 else:
2074 else:
2074 for name, path in ui.configitems("paths"):
2075 for name, path in ui.configitems("paths"):
2075 ui.write("%s = %s\n" % (name, path))
2076 ui.write("%s = %s\n" % (name, path))
2076
2077
2077 def postincoming(ui, repo, modheads, optupdate):
2078 def postincoming(ui, repo, modheads, optupdate):
2078 if modheads == 0:
2079 if modheads == 0:
2079 return
2080 return
2080 if optupdate:
2081 if optupdate:
2081 if modheads == 1:
2082 if modheads == 1:
2082 return hg.update(repo, repo.changelog.tip()) # update
2083 return hg.update(repo, repo.changelog.tip()) # update
2083 else:
2084 else:
2084 ui.status(_("not updating, since new heads added\n"))
2085 ui.status(_("not updating, since new heads added\n"))
2085 if modheads > 1:
2086 if modheads > 1:
2086 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
2087 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
2087 else:
2088 else:
2088 ui.status(_("(run 'hg update' to get a working copy)\n"))
2089 ui.status(_("(run 'hg update' to get a working copy)\n"))
2089
2090
2090 def pull(ui, repo, source="default", **opts):
2091 def pull(ui, repo, source="default", **opts):
2091 """pull changes from the specified source
2092 """pull changes from the specified source
2092
2093
2093 Pull changes from a remote repository to a local one.
2094 Pull changes from a remote repository to a local one.
2094
2095
2095 This finds all changes from the repository at the specified path
2096 This finds all changes from the repository at the specified path
2096 or URL and adds them to the local repository. By default, this
2097 or URL and adds them to the local repository. By default, this
2097 does not update the copy of the project in the working directory.
2098 does not update the copy of the project in the working directory.
2098
2099
2099 Valid URLs are of the form:
2100 Valid URLs are of the form:
2100
2101
2101 local/filesystem/path (or file://local/filesystem/path)
2102 local/filesystem/path (or file://local/filesystem/path)
2102 http://[user@]host[:port]/[path]
2103 http://[user@]host[:port]/[path]
2103 https://[user@]host[:port]/[path]
2104 https://[user@]host[:port]/[path]
2104 ssh://[user@]host[:port]/[path]
2105 ssh://[user@]host[:port]/[path]
2105 static-http://host[:port]/[path]
2106 static-http://host[:port]/[path]
2106
2107
2107 Paths in the local filesystem can either point to Mercurial
2108 Paths in the local filesystem can either point to Mercurial
2108 repositories or to bundle files (as created by 'hg bundle' or
2109 repositories or to bundle files (as created by 'hg bundle' or
2109 'hg incoming --bundle'). The static-http:// protocol, albeit slow,
2110 'hg incoming --bundle'). The static-http:// protocol, albeit slow,
2110 allows access to a Mercurial repository where you simply use a web
2111 allows access to a Mercurial repository where you simply use a web
2111 server to publish the .hg directory as static content.
2112 server to publish the .hg directory as static content.
2112
2113
2113 Some notes about using SSH with Mercurial:
2114 Some notes about using SSH with Mercurial:
2114 - SSH requires an accessible shell account on the destination machine
2115 - SSH requires an accessible shell account on the destination machine
2115 and a copy of hg in the remote path or specified with as remotecmd.
2116 and a copy of hg in the remote path or specified with as remotecmd.
2116 - path is relative to the remote user's home directory by default.
2117 - path is relative to the remote user's home directory by default.
2117 Use an extra slash at the start of a path to specify an absolute path:
2118 Use an extra slash at the start of a path to specify an absolute path:
2118 ssh://example.com//tmp/repository
2119 ssh://example.com//tmp/repository
2119 - Mercurial doesn't use its own compression via SSH; the right thing
2120 - Mercurial doesn't use its own compression via SSH; the right thing
2120 to do is to configure it in your ~/.ssh/config, e.g.:
2121 to do is to configure it in your ~/.ssh/config, e.g.:
2121 Host *.mylocalnetwork.example.com
2122 Host *.mylocalnetwork.example.com
2122 Compression no
2123 Compression no
2123 Host *
2124 Host *
2124 Compression yes
2125 Compression yes
2125 Alternatively specify "ssh -C" as your ssh command in your hgrc or
2126 Alternatively specify "ssh -C" as your ssh command in your hgrc or
2126 with the --ssh command line option.
2127 with the --ssh command line option.
2127 """
2128 """
2128 source = ui.expandpath(source)
2129 source = ui.expandpath(source)
2129 setremoteconfig(ui, opts)
2130 setremoteconfig(ui, opts)
2130
2131
2131 other = hg.repository(ui, source)
2132 other = hg.repository(ui, source)
2132 ui.status(_('pulling from %s\n') % (source))
2133 ui.status(_('pulling from %s\n') % (source))
2133 revs = None
2134 revs = None
2134 if opts['rev']:
2135 if opts['rev']:
2135 if 'lookup' in other.capabilities:
2136 if 'lookup' in other.capabilities:
2136 revs = [other.lookup(rev) for rev in opts['rev']]
2137 revs = [other.lookup(rev) for rev in opts['rev']]
2137 else:
2138 else:
2138 error = _("Other repository doesn't support revision lookup, so a rev cannot be specified.")
2139 error = _("Other repository doesn't support revision lookup, so a rev cannot be specified.")
2139 raise util.Abort(error)
2140 raise util.Abort(error)
2140 modheads = repo.pull(other, heads=revs, force=opts['force'])
2141 modheads = repo.pull(other, heads=revs, force=opts['force'])
2141 return postincoming(ui, repo, modheads, opts['update'])
2142 return postincoming(ui, repo, modheads, opts['update'])
2142
2143
2143 def push(ui, repo, dest=None, **opts):
2144 def push(ui, repo, dest=None, **opts):
2144 """push changes to the specified destination
2145 """push changes to the specified destination
2145
2146
2146 Push changes from the local repository to the given destination.
2147 Push changes from the local repository to the given destination.
2147
2148
2148 This is the symmetrical operation for pull. It helps to move
2149 This is the symmetrical operation for pull. It helps to move
2149 changes from the current repository to a different one. If the
2150 changes from the current repository to a different one. If the
2150 destination is local this is identical to a pull in that directory
2151 destination is local this is identical to a pull in that directory
2151 from the current one.
2152 from the current one.
2152
2153
2153 By default, push will refuse to run if it detects the result would
2154 By default, push will refuse to run if it detects the result would
2154 increase the number of remote heads. This generally indicates the
2155 increase the number of remote heads. This generally indicates the
2155 the client has forgotten to sync and merge before pushing.
2156 the client has forgotten to sync and merge before pushing.
2156
2157
2157 Valid URLs are of the form:
2158 Valid URLs are of the form:
2158
2159
2159 local/filesystem/path (or file://local/filesystem/path)
2160 local/filesystem/path (or file://local/filesystem/path)
2160 ssh://[user@]host[:port]/[path]
2161 ssh://[user@]host[:port]/[path]
2161 http://[user@]host[:port]/[path]
2162 http://[user@]host[:port]/[path]
2162 https://[user@]host[:port]/[path]
2163 https://[user@]host[:port]/[path]
2163
2164
2164 Look at the help text for the pull command for important details
2165 Look at the help text for the pull command for important details
2165 about ssh:// URLs.
2166 about ssh:// URLs.
2166
2167
2167 Pushing to http:// and https:// URLs is only possible, if this
2168 Pushing to http:// and https:// URLs is only possible, if this
2168 feature is explicitly enabled on the remote Mercurial server.
2169 feature is explicitly enabled on the remote Mercurial server.
2169 """
2170 """
2170 dest = ui.expandpath(dest or 'default-push', dest or 'default')
2171 dest = ui.expandpath(dest or 'default-push', dest or 'default')
2171 setremoteconfig(ui, opts)
2172 setremoteconfig(ui, opts)
2172
2173
2173 other = hg.repository(ui, dest)
2174 other = hg.repository(ui, dest)
2174 ui.status('pushing to %s\n' % (dest))
2175 ui.status('pushing to %s\n' % (dest))
2175 revs = None
2176 revs = None
2176 if opts['rev']:
2177 if opts['rev']:
2177 revs = [repo.lookup(rev) for rev in opts['rev']]
2178 revs = [repo.lookup(rev) for rev in opts['rev']]
2178 r = repo.push(other, opts['force'], revs=revs)
2179 r = repo.push(other, opts['force'], revs=revs)
2179 return r == 0
2180 return r == 0
2180
2181
2181 def rawcommit(ui, repo, *flist, **rc):
2182 def rawcommit(ui, repo, *flist, **rc):
2182 """raw commit interface (DEPRECATED)
2183 """raw commit interface (DEPRECATED)
2183
2184
2184 (DEPRECATED)
2185 (DEPRECATED)
2185 Lowlevel commit, for use in helper scripts.
2186 Lowlevel commit, for use in helper scripts.
2186
2187
2187 This command is not intended to be used by normal users, as it is
2188 This command is not intended to be used by normal users, as it is
2188 primarily useful for importing from other SCMs.
2189 primarily useful for importing from other SCMs.
2189
2190
2190 This command is now deprecated and will be removed in a future
2191 This command is now deprecated and will be removed in a future
2191 release, please use debugsetparents and commit instead.
2192 release, please use debugsetparents and commit instead.
2192 """
2193 """
2193
2194
2194 ui.warn(_("(the rawcommit command is deprecated)\n"))
2195 ui.warn(_("(the rawcommit command is deprecated)\n"))
2195
2196
2196 message = rc['message']
2197 message = rc['message']
2197 if not message and rc['logfile']:
2198 if not message and rc['logfile']:
2198 try:
2199 try:
2199 message = open(rc['logfile']).read()
2200 message = open(rc['logfile']).read()
2200 except IOError:
2201 except IOError:
2201 pass
2202 pass
2202 if not message and not rc['logfile']:
2203 if not message and not rc['logfile']:
2203 raise util.Abort(_("missing commit message"))
2204 raise util.Abort(_("missing commit message"))
2204
2205
2205 files = relpath(repo, list(flist))
2206 files = relpath(repo, list(flist))
2206 if rc['files']:
2207 if rc['files']:
2207 files += open(rc['files']).read().splitlines()
2208 files += open(rc['files']).read().splitlines()
2208
2209
2209 rc['parent'] = map(repo.lookup, rc['parent'])
2210 rc['parent'] = map(repo.lookup, rc['parent'])
2210
2211
2211 try:
2212 try:
2212 repo.rawcommit(files, message, rc['user'], rc['date'], *rc['parent'])
2213 repo.rawcommit(files, message, rc['user'], rc['date'], *rc['parent'])
2213 except ValueError, inst:
2214 except ValueError, inst:
2214 raise util.Abort(str(inst))
2215 raise util.Abort(str(inst))
2215
2216
2216 def recover(ui, repo):
2217 def recover(ui, repo):
2217 """roll back an interrupted transaction
2218 """roll back an interrupted transaction
2218
2219
2219 Recover from an interrupted commit or pull.
2220 Recover from an interrupted commit or pull.
2220
2221
2221 This command tries to fix the repository status after an interrupted
2222 This command tries to fix the repository status after an interrupted
2222 operation. It should only be necessary when Mercurial suggests it.
2223 operation. It should only be necessary when Mercurial suggests it.
2223 """
2224 """
2224 if repo.recover():
2225 if repo.recover():
2225 return hg.verify(repo)
2226 return hg.verify(repo)
2226 return 1
2227 return 1
2227
2228
2228 def remove(ui, repo, *pats, **opts):
2229 def remove(ui, repo, *pats, **opts):
2229 """remove the specified files on the next commit
2230 """remove the specified files on the next commit
2230
2231
2231 Schedule the indicated files for removal from the repository.
2232 Schedule the indicated files for removal from the repository.
2232
2233
2233 This command schedules the files to be removed at the next commit.
2234 This command schedules the files to be removed at the next commit.
2234 This only removes files from the current branch, not from the
2235 This only removes files from the current branch, not from the
2235 entire project history. If the files still exist in the working
2236 entire project history. If the files still exist in the working
2236 directory, they will be deleted from it. If invoked with --after,
2237 directory, they will be deleted from it. If invoked with --after,
2237 files that have been manually deleted are marked as removed.
2238 files that have been manually deleted are marked as removed.
2238
2239
2239 Modified files and added files are not removed by default. To
2240 Modified files and added files are not removed by default. To
2240 remove them, use the -f/--force option.
2241 remove them, use the -f/--force option.
2241 """
2242 """
2242 names = []
2243 names = []
2243 if not opts['after'] and not pats:
2244 if not opts['after'] and not pats:
2244 raise util.Abort(_('no files specified'))
2245 raise util.Abort(_('no files specified'))
2245 files, matchfn, anypats = cmdutil.matchpats(repo, pats, opts)
2246 files, matchfn, anypats = cmdutil.matchpats(repo, pats, opts)
2246 exact = dict.fromkeys(files)
2247 exact = dict.fromkeys(files)
2247 mardu = map(dict.fromkeys, repo.status(files=files, match=matchfn))[:5]
2248 mardu = map(dict.fromkeys, repo.status(files=files, match=matchfn))[:5]
2248 modified, added, removed, deleted, unknown = mardu
2249 modified, added, removed, deleted, unknown = mardu
2249 remove, forget = [], []
2250 remove, forget = [], []
2250 for src, abs, rel, exact in cmdutil.walk(repo, pats, opts):
2251 for src, abs, rel, exact in cmdutil.walk(repo, pats, opts):
2251 reason = None
2252 reason = None
2252 if abs not in deleted and opts['after']:
2253 if abs not in deleted and opts['after']:
2253 reason = _('is still present')
2254 reason = _('is still present')
2254 elif abs in modified and not opts['force']:
2255 elif abs in modified and not opts['force']:
2255 reason = _('is modified (use -f to force removal)')
2256 reason = _('is modified (use -f to force removal)')
2256 elif abs in added:
2257 elif abs in added:
2257 if opts['force']:
2258 if opts['force']:
2258 forget.append(abs)
2259 forget.append(abs)
2259 continue
2260 continue
2260 reason = _('has been marked for add (use -f to force removal)')
2261 reason = _('has been marked for add (use -f to force removal)')
2261 elif abs in unknown:
2262 elif abs in unknown:
2262 reason = _('is not managed')
2263 reason = _('is not managed')
2263 elif abs in removed:
2264 elif abs in removed:
2264 continue
2265 continue
2265 if reason:
2266 if reason:
2266 if exact:
2267 if exact:
2267 ui.warn(_('not removing %s: file %s\n') % (rel, reason))
2268 ui.warn(_('not removing %s: file %s\n') % (rel, reason))
2268 else:
2269 else:
2269 if ui.verbose or not exact:
2270 if ui.verbose or not exact:
2270 ui.status(_('removing %s\n') % rel)
2271 ui.status(_('removing %s\n') % rel)
2271 remove.append(abs)
2272 remove.append(abs)
2272 repo.forget(forget)
2273 repo.forget(forget)
2273 repo.remove(remove, unlink=not opts['after'])
2274 repo.remove(remove, unlink=not opts['after'])
2274
2275
2275 def rename(ui, repo, *pats, **opts):
2276 def rename(ui, repo, *pats, **opts):
2276 """rename files; equivalent of copy + remove
2277 """rename files; equivalent of copy + remove
2277
2278
2278 Mark dest as copies of sources; mark sources for deletion. If
2279 Mark dest as copies of sources; mark sources for deletion. If
2279 dest is a directory, copies are put in that directory. If dest is
2280 dest is a directory, copies are put in that directory. If dest is
2280 a file, there can only be one source.
2281 a file, there can only be one source.
2281
2282
2282 By default, this command copies the contents of files as they
2283 By default, this command copies the contents of files as they
2283 stand in the working directory. If invoked with --after, the
2284 stand in the working directory. If invoked with --after, the
2284 operation is recorded, but no copying is performed.
2285 operation is recorded, but no copying is performed.
2285
2286
2286 This command takes effect in the next commit.
2287 This command takes effect in the next commit.
2287
2288
2288 NOTE: This command should be treated as experimental. While it
2289 NOTE: This command should be treated as experimental. While it
2289 should properly record rename files, this information is not yet
2290 should properly record rename files, this information is not yet
2290 fully used by merge, nor fully reported by log.
2291 fully used by merge, nor fully reported by log.
2291 """
2292 """
2292 wlock = repo.wlock(0)
2293 wlock = repo.wlock(0)
2293 errs, copied = docopy(ui, repo, pats, opts, wlock)
2294 errs, copied = docopy(ui, repo, pats, opts, wlock)
2294 names = []
2295 names = []
2295 for abs, rel, exact in copied:
2296 for abs, rel, exact in copied:
2296 if ui.verbose or not exact:
2297 if ui.verbose or not exact:
2297 ui.status(_('removing %s\n') % rel)
2298 ui.status(_('removing %s\n') % rel)
2298 names.append(abs)
2299 names.append(abs)
2299 if not opts.get('dry_run'):
2300 if not opts.get('dry_run'):
2300 repo.remove(names, True, wlock)
2301 repo.remove(names, True, wlock)
2301 return errs
2302 return errs
2302
2303
2303 def revert(ui, repo, *pats, **opts):
2304 def revert(ui, repo, *pats, **opts):
2304 """revert files or dirs to their states as of some revision
2305 """revert files or dirs to their states as of some revision
2305
2306
2306 With no revision specified, revert the named files or directories
2307 With no revision specified, revert the named files or directories
2307 to the contents they had in the parent of the working directory.
2308 to the contents they had in the parent of the working directory.
2308 This restores the contents of the affected files to an unmodified
2309 This restores the contents of the affected files to an unmodified
2309 state. If the working directory has two parents, you must
2310 state. If the working directory has two parents, you must
2310 explicitly specify the revision to revert to.
2311 explicitly specify the revision to revert to.
2311
2312
2312 Modified files are saved with a .orig suffix before reverting.
2313 Modified files are saved with a .orig suffix before reverting.
2313 To disable these backups, use --no-backup.
2314 To disable these backups, use --no-backup.
2314
2315
2315 Using the -r option, revert the given files or directories to their
2316 Using the -r option, revert the given files or directories to their
2316 contents as of a specific revision. This can be helpful to "roll
2317 contents as of a specific revision. This can be helpful to "roll
2317 back" some or all of a change that should not have been committed.
2318 back" some or all of a change that should not have been committed.
2318
2319
2319 Revert modifies the working directory. It does not commit any
2320 Revert modifies the working directory. It does not commit any
2320 changes, or change the parent of the working directory. If you
2321 changes, or change the parent of the working directory. If you
2321 revert to a revision other than the parent of the working
2322 revert to a revision other than the parent of the working
2322 directory, the reverted files will thus appear modified
2323 directory, the reverted files will thus appear modified
2323 afterwards.
2324 afterwards.
2324
2325
2325 If a file has been deleted, it is recreated. If the executable
2326 If a file has been deleted, it is recreated. If the executable
2326 mode of a file was changed, it is reset.
2327 mode of a file was changed, it is reset.
2327
2328
2328 If names are given, all files matching the names are reverted.
2329 If names are given, all files matching the names are reverted.
2329
2330
2330 If no arguments are given, no files are reverted.
2331 If no arguments are given, no files are reverted.
2331 """
2332 """
2332
2333
2333 if not pats and not opts['all']:
2334 if not pats and not opts['all']:
2334 raise util.Abort(_('no files or directories specified; '
2335 raise util.Abort(_('no files or directories specified; '
2335 'use --all to revert the whole repo'))
2336 'use --all to revert the whole repo'))
2336
2337
2337 parent, p2 = repo.dirstate.parents()
2338 parent, p2 = repo.dirstate.parents()
2338 if not opts['rev'] and p2 != nullid:
2339 if not opts['rev'] and p2 != nullid:
2339 raise util.Abort(_('uncommitted merge - please provide a '
2340 raise util.Abort(_('uncommitted merge - please provide a '
2340 'specific revision'))
2341 'specific revision'))
2341 node = repo.changectx(opts['rev']).node()
2342 node = repo.changectx(opts['rev']).node()
2342 mf = repo.manifest.read(repo.changelog.read(node)[0])
2343 mf = repo.manifest.read(repo.changelog.read(node)[0])
2343 if node == parent:
2344 if node == parent:
2344 pmf = mf
2345 pmf = mf
2345 else:
2346 else:
2346 pmf = None
2347 pmf = None
2347
2348
2348 wlock = repo.wlock()
2349 wlock = repo.wlock()
2349
2350
2350 # need all matching names in dirstate and manifest of target rev,
2351 # need all matching names in dirstate and manifest of target rev,
2351 # so have to walk both. do not print errors if files exist in one
2352 # so have to walk both. do not print errors if files exist in one
2352 # but not other.
2353 # but not other.
2353
2354
2354 names = {}
2355 names = {}
2355 target_only = {}
2356 target_only = {}
2356
2357
2357 # walk dirstate.
2358 # walk dirstate.
2358
2359
2359 for src, abs, rel, exact in cmdutil.walk(repo, pats, opts,
2360 for src, abs, rel, exact in cmdutil.walk(repo, pats, opts,
2360 badmatch=mf.has_key):
2361 badmatch=mf.has_key):
2361 names[abs] = (rel, exact)
2362 names[abs] = (rel, exact)
2362 if src == 'b':
2363 if src == 'b':
2363 target_only[abs] = True
2364 target_only[abs] = True
2364
2365
2365 # walk target manifest.
2366 # walk target manifest.
2366
2367
2367 for src, abs, rel, exact in cmdutil.walk(repo, pats, opts, node=node,
2368 for src, abs, rel, exact in cmdutil.walk(repo, pats, opts, node=node,
2368 badmatch=names.has_key):
2369 badmatch=names.has_key):
2369 if abs in names: continue
2370 if abs in names: continue
2370 names[abs] = (rel, exact)
2371 names[abs] = (rel, exact)
2371 target_only[abs] = True
2372 target_only[abs] = True
2372
2373
2373 changes = repo.status(match=names.has_key, wlock=wlock)[:5]
2374 changes = repo.status(match=names.has_key, wlock=wlock)[:5]
2374 modified, added, removed, deleted, unknown = map(dict.fromkeys, changes)
2375 modified, added, removed, deleted, unknown = map(dict.fromkeys, changes)
2375
2376
2376 revert = ([], _('reverting %s\n'))
2377 revert = ([], _('reverting %s\n'))
2377 add = ([], _('adding %s\n'))
2378 add = ([], _('adding %s\n'))
2378 remove = ([], _('removing %s\n'))
2379 remove = ([], _('removing %s\n'))
2379 forget = ([], _('forgetting %s\n'))
2380 forget = ([], _('forgetting %s\n'))
2380 undelete = ([], _('undeleting %s\n'))
2381 undelete = ([], _('undeleting %s\n'))
2381 update = {}
2382 update = {}
2382
2383
2383 disptable = (
2384 disptable = (
2384 # dispatch table:
2385 # dispatch table:
2385 # file state
2386 # file state
2386 # action if in target manifest
2387 # action if in target manifest
2387 # action if not in target manifest
2388 # action if not in target manifest
2388 # make backup if in target manifest
2389 # make backup if in target manifest
2389 # make backup if not in target manifest
2390 # make backup if not in target manifest
2390 (modified, revert, remove, True, True),
2391 (modified, revert, remove, True, True),
2391 (added, revert, forget, True, False),
2392 (added, revert, forget, True, False),
2392 (removed, undelete, None, False, False),
2393 (removed, undelete, None, False, False),
2393 (deleted, revert, remove, False, False),
2394 (deleted, revert, remove, False, False),
2394 (unknown, add, None, True, False),
2395 (unknown, add, None, True, False),
2395 (target_only, add, None, False, False),
2396 (target_only, add, None, False, False),
2396 )
2397 )
2397
2398
2398 entries = names.items()
2399 entries = names.items()
2399 entries.sort()
2400 entries.sort()
2400
2401
2401 for abs, (rel, exact) in entries:
2402 for abs, (rel, exact) in entries:
2402 mfentry = mf.get(abs)
2403 mfentry = mf.get(abs)
2403 def handle(xlist, dobackup):
2404 def handle(xlist, dobackup):
2404 xlist[0].append(abs)
2405 xlist[0].append(abs)
2405 update[abs] = 1
2406 update[abs] = 1
2406 if dobackup and not opts['no_backup'] and os.path.exists(rel):
2407 if dobackup and not opts['no_backup'] and os.path.exists(rel):
2407 bakname = "%s.orig" % rel
2408 bakname = "%s.orig" % rel
2408 ui.note(_('saving current version of %s as %s\n') %
2409 ui.note(_('saving current version of %s as %s\n') %
2409 (rel, bakname))
2410 (rel, bakname))
2410 if not opts.get('dry_run'):
2411 if not opts.get('dry_run'):
2411 shutil.copyfile(rel, bakname)
2412 shutil.copyfile(rel, bakname)
2412 shutil.copymode(rel, bakname)
2413 shutil.copymode(rel, bakname)
2413 if ui.verbose or not exact:
2414 if ui.verbose or not exact:
2414 ui.status(xlist[1] % rel)
2415 ui.status(xlist[1] % rel)
2415 for table, hitlist, misslist, backuphit, backupmiss in disptable:
2416 for table, hitlist, misslist, backuphit, backupmiss in disptable:
2416 if abs not in table: continue
2417 if abs not in table: continue
2417 # file has changed in dirstate
2418 # file has changed in dirstate
2418 if mfentry:
2419 if mfentry:
2419 handle(hitlist, backuphit)
2420 handle(hitlist, backuphit)
2420 elif misslist is not None:
2421 elif misslist is not None:
2421 handle(misslist, backupmiss)
2422 handle(misslist, backupmiss)
2422 else:
2423 else:
2423 if exact: ui.warn(_('file not managed: %s\n' % rel))
2424 if exact: ui.warn(_('file not managed: %s\n' % rel))
2424 break
2425 break
2425 else:
2426 else:
2426 # file has not changed in dirstate
2427 # file has not changed in dirstate
2427 if node == parent:
2428 if node == parent:
2428 if exact: ui.warn(_('no changes needed to %s\n' % rel))
2429 if exact: ui.warn(_('no changes needed to %s\n' % rel))
2429 continue
2430 continue
2430 if pmf is None:
2431 if pmf is None:
2431 # only need parent manifest in this unlikely case,
2432 # only need parent manifest in this unlikely case,
2432 # so do not read by default
2433 # so do not read by default
2433 pmf = repo.manifest.read(repo.changelog.read(parent)[0])
2434 pmf = repo.manifest.read(repo.changelog.read(parent)[0])
2434 if abs in pmf:
2435 if abs in pmf:
2435 if mfentry:
2436 if mfentry:
2436 # if version of file is same in parent and target
2437 # if version of file is same in parent and target
2437 # manifests, do nothing
2438 # manifests, do nothing
2438 if pmf[abs] != mfentry:
2439 if pmf[abs] != mfentry:
2439 handle(revert, False)
2440 handle(revert, False)
2440 else:
2441 else:
2441 handle(remove, False)
2442 handle(remove, False)
2442
2443
2443 if not opts.get('dry_run'):
2444 if not opts.get('dry_run'):
2444 repo.dirstate.forget(forget[0])
2445 repo.dirstate.forget(forget[0])
2445 r = hg.revert(repo, node, update.has_key, wlock)
2446 r = hg.revert(repo, node, update.has_key, wlock)
2446 repo.dirstate.update(add[0], 'a')
2447 repo.dirstate.update(add[0], 'a')
2447 repo.dirstate.update(undelete[0], 'n')
2448 repo.dirstate.update(undelete[0], 'n')
2448 repo.dirstate.update(remove[0], 'r')
2449 repo.dirstate.update(remove[0], 'r')
2449 return r
2450 return r
2450
2451
2451 def rollback(ui, repo):
2452 def rollback(ui, repo):
2452 """roll back the last transaction in this repository
2453 """roll back the last transaction in this repository
2453
2454
2454 Roll back the last transaction in this repository, restoring the
2455 Roll back the last transaction in this repository, restoring the
2455 project to its state prior to the transaction.
2456 project to its state prior to the transaction.
2456
2457
2457 Transactions are used to encapsulate the effects of all commands
2458 Transactions are used to encapsulate the effects of all commands
2458 that create new changesets or propagate existing changesets into a
2459 that create new changesets or propagate existing changesets into a
2459 repository. For example, the following commands are transactional,
2460 repository. For example, the following commands are transactional,
2460 and their effects can be rolled back:
2461 and their effects can be rolled back:
2461
2462
2462 commit
2463 commit
2463 import
2464 import
2464 pull
2465 pull
2465 push (with this repository as destination)
2466 push (with this repository as destination)
2466 unbundle
2467 unbundle
2467
2468
2468 This command should be used with care. There is only one level of
2469 This command should be used with care. There is only one level of
2469 rollback, and there is no way to undo a rollback.
2470 rollback, and there is no way to undo a rollback.
2470
2471
2471 This command is not intended for use on public repositories. Once
2472 This command is not intended for use on public repositories. Once
2472 changes are visible for pull by other users, rolling a transaction
2473 changes are visible for pull by other users, rolling a transaction
2473 back locally is ineffective (someone else may already have pulled
2474 back locally is ineffective (someone else may already have pulled
2474 the changes). Furthermore, a race is possible with readers of the
2475 the changes). Furthermore, a race is possible with readers of the
2475 repository; for example an in-progress pull from the repository
2476 repository; for example an in-progress pull from the repository
2476 may fail if a rollback is performed.
2477 may fail if a rollback is performed.
2477 """
2478 """
2478 repo.rollback()
2479 repo.rollback()
2479
2480
2480 def root(ui, repo):
2481 def root(ui, repo):
2481 """print the root (top) of the current working dir
2482 """print the root (top) of the current working dir
2482
2483
2483 Print the root directory of the current repository.
2484 Print the root directory of the current repository.
2484 """
2485 """
2485 ui.write(repo.root + "\n")
2486 ui.write(repo.root + "\n")
2486
2487
2487 def serve(ui, repo, **opts):
2488 def serve(ui, repo, **opts):
2488 """export the repository via HTTP
2489 """export the repository via HTTP
2489
2490
2490 Start a local HTTP repository browser and pull server.
2491 Start a local HTTP repository browser and pull server.
2491
2492
2492 By default, the server logs accesses to stdout and errors to
2493 By default, the server logs accesses to stdout and errors to
2493 stderr. Use the "-A" and "-E" options to log to files.
2494 stderr. Use the "-A" and "-E" options to log to files.
2494 """
2495 """
2495
2496
2496 if opts["stdio"]:
2497 if opts["stdio"]:
2497 if repo is None:
2498 if repo is None:
2498 raise hg.RepoError(_("There is no Mercurial repository here"
2499 raise hg.RepoError(_("There is no Mercurial repository here"
2499 " (.hg not found)"))
2500 " (.hg not found)"))
2500 s = sshserver.sshserver(ui, repo)
2501 s = sshserver.sshserver(ui, repo)
2501 s.serve_forever()
2502 s.serve_forever()
2502
2503
2503 optlist = ("name templates style address port ipv6"
2504 optlist = ("name templates style address port ipv6"
2504 " accesslog errorlog webdir_conf")
2505 " accesslog errorlog webdir_conf")
2505 for o in optlist.split():
2506 for o in optlist.split():
2506 if opts[o]:
2507 if opts[o]:
2507 ui.setconfig("web", o, str(opts[o]))
2508 ui.setconfig("web", o, str(opts[o]))
2508
2509
2509 if repo is None and not ui.config("web", "webdir_conf"):
2510 if repo is None and not ui.config("web", "webdir_conf"):
2510 raise hg.RepoError(_("There is no Mercurial repository here"
2511 raise hg.RepoError(_("There is no Mercurial repository here"
2511 " (.hg not found)"))
2512 " (.hg not found)"))
2512
2513
2513 if opts['daemon'] and not opts['daemon_pipefds']:
2514 if opts['daemon'] and not opts['daemon_pipefds']:
2514 rfd, wfd = os.pipe()
2515 rfd, wfd = os.pipe()
2515 args = sys.argv[:]
2516 args = sys.argv[:]
2516 args.append('--daemon-pipefds=%d,%d' % (rfd, wfd))
2517 args.append('--daemon-pipefds=%d,%d' % (rfd, wfd))
2517 pid = os.spawnvp(os.P_NOWAIT | getattr(os, 'P_DETACH', 0),
2518 pid = os.spawnvp(os.P_NOWAIT | getattr(os, 'P_DETACH', 0),
2518 args[0], args)
2519 args[0], args)
2519 os.close(wfd)
2520 os.close(wfd)
2520 os.read(rfd, 1)
2521 os.read(rfd, 1)
2521 os._exit(0)
2522 os._exit(0)
2522
2523
2523 try:
2524 try:
2524 httpd = hgweb.server.create_server(ui, repo)
2525 httpd = hgweb.server.create_server(ui, repo)
2525 except socket.error, inst:
2526 except socket.error, inst:
2526 raise util.Abort(_('cannot start server: %s') % inst.args[1])
2527 raise util.Abort(_('cannot start server: %s') % inst.args[1])
2527
2528
2528 if ui.verbose:
2529 if ui.verbose:
2529 addr, port = httpd.socket.getsockname()
2530 addr, port = httpd.socket.getsockname()
2530 if addr == '0.0.0.0':
2531 if addr == '0.0.0.0':
2531 addr = socket.gethostname()
2532 addr = socket.gethostname()
2532 else:
2533 else:
2533 try:
2534 try:
2534 addr = socket.gethostbyaddr(addr)[0]
2535 addr = socket.gethostbyaddr(addr)[0]
2535 except socket.error:
2536 except socket.error:
2536 pass
2537 pass
2537 if port != 80:
2538 if port != 80:
2538 ui.status(_('listening at http://%s:%d/\n') % (addr, port))
2539 ui.status(_('listening at http://%s:%d/\n') % (addr, port))
2539 else:
2540 else:
2540 ui.status(_('listening at http://%s/\n') % addr)
2541 ui.status(_('listening at http://%s/\n') % addr)
2541
2542
2542 if opts['pid_file']:
2543 if opts['pid_file']:
2543 fp = open(opts['pid_file'], 'w')
2544 fp = open(opts['pid_file'], 'w')
2544 fp.write(str(os.getpid()) + '\n')
2545 fp.write(str(os.getpid()) + '\n')
2545 fp.close()
2546 fp.close()
2546
2547
2547 if opts['daemon_pipefds']:
2548 if opts['daemon_pipefds']:
2548 rfd, wfd = [int(x) for x in opts['daemon_pipefds'].split(',')]
2549 rfd, wfd = [int(x) for x in opts['daemon_pipefds'].split(',')]
2549 os.close(rfd)
2550 os.close(rfd)
2550 os.write(wfd, 'y')
2551 os.write(wfd, 'y')
2551 os.close(wfd)
2552 os.close(wfd)
2552 sys.stdout.flush()
2553 sys.stdout.flush()
2553 sys.stderr.flush()
2554 sys.stderr.flush()
2554 fd = os.open(util.nulldev, os.O_RDWR)
2555 fd = os.open(util.nulldev, os.O_RDWR)
2555 if fd != 0: os.dup2(fd, 0)
2556 if fd != 0: os.dup2(fd, 0)
2556 if fd != 1: os.dup2(fd, 1)
2557 if fd != 1: os.dup2(fd, 1)
2557 if fd != 2: os.dup2(fd, 2)
2558 if fd != 2: os.dup2(fd, 2)
2558 if fd not in (0, 1, 2): os.close(fd)
2559 if fd not in (0, 1, 2): os.close(fd)
2559
2560
2560 httpd.serve_forever()
2561 httpd.serve_forever()
2561
2562
2562 def status(ui, repo, *pats, **opts):
2563 def status(ui, repo, *pats, **opts):
2563 """show changed files in the working directory
2564 """show changed files in the working directory
2564
2565
2565 Show status of files in the repository. If names are given, only
2566 Show status of files in the repository. If names are given, only
2566 files that match are shown. Files that are clean or ignored, are
2567 files that match are shown. Files that are clean or ignored, are
2567 not listed unless -c (clean), -i (ignored) or -A is given.
2568 not listed unless -c (clean), -i (ignored) or -A is given.
2568
2569
2569 If one revision is given, it is used as the base revision.
2570 If one revision is given, it is used as the base revision.
2570 If two revisions are given, the difference between them is shown.
2571 If two revisions are given, the difference between them is shown.
2571
2572
2572 The codes used to show the status of files are:
2573 The codes used to show the status of files are:
2573 M = modified
2574 M = modified
2574 A = added
2575 A = added
2575 R = removed
2576 R = removed
2576 C = clean
2577 C = clean
2577 ! = deleted, but still tracked
2578 ! = deleted, but still tracked
2578 ? = not tracked
2579 ? = not tracked
2579 I = ignored (not shown by default)
2580 I = ignored (not shown by default)
2580 = the previous added file was copied from here
2581 = the previous added file was copied from here
2581 """
2582 """
2582
2583
2583 all = opts['all']
2584 all = opts['all']
2584 node1, node2 = cmdutil.revpair(ui, repo, opts.get('rev'))
2585 node1, node2 = cmdutil.revpair(ui, repo, opts.get('rev'))
2585
2586
2586 files, matchfn, anypats = cmdutil.matchpats(repo, pats, opts)
2587 files, matchfn, anypats = cmdutil.matchpats(repo, pats, opts)
2587 cwd = (pats and repo.getcwd()) or ''
2588 cwd = (pats and repo.getcwd()) or ''
2588 modified, added, removed, deleted, unknown, ignored, clean = [
2589 modified, added, removed, deleted, unknown, ignored, clean = [
2589 [util.pathto(cwd, x) for x in n]
2590 [util.pathto(cwd, x) for x in n]
2590 for n in repo.status(node1=node1, node2=node2, files=files,
2591 for n in repo.status(node1=node1, node2=node2, files=files,
2591 match=matchfn,
2592 match=matchfn,
2592 list_ignored=all or opts['ignored'],
2593 list_ignored=all or opts['ignored'],
2593 list_clean=all or opts['clean'])]
2594 list_clean=all or opts['clean'])]
2594
2595
2595 changetypes = (('modified', 'M', modified),
2596 changetypes = (('modified', 'M', modified),
2596 ('added', 'A', added),
2597 ('added', 'A', added),
2597 ('removed', 'R', removed),
2598 ('removed', 'R', removed),
2598 ('deleted', '!', deleted),
2599 ('deleted', '!', deleted),
2599 ('unknown', '?', unknown),
2600 ('unknown', '?', unknown),
2600 ('ignored', 'I', ignored))
2601 ('ignored', 'I', ignored))
2601
2602
2602 explicit_changetypes = changetypes + (('clean', 'C', clean),)
2603 explicit_changetypes = changetypes + (('clean', 'C', clean),)
2603
2604
2604 end = opts['print0'] and '\0' or '\n'
2605 end = opts['print0'] and '\0' or '\n'
2605
2606
2606 for opt, char, changes in ([ct for ct in explicit_changetypes
2607 for opt, char, changes in ([ct for ct in explicit_changetypes
2607 if all or opts[ct[0]]]
2608 if all or opts[ct[0]]]
2608 or changetypes):
2609 or changetypes):
2609 if opts['no_status']:
2610 if opts['no_status']:
2610 format = "%%s%s" % end
2611 format = "%%s%s" % end
2611 else:
2612 else:
2612 format = "%s %%s%s" % (char, end)
2613 format = "%s %%s%s" % (char, end)
2613
2614
2614 for f in changes:
2615 for f in changes:
2615 ui.write(format % f)
2616 ui.write(format % f)
2616 if ((all or opts.get('copies')) and not opts.get('no_status')):
2617 if ((all or opts.get('copies')) and not opts.get('no_status')):
2617 copied = repo.dirstate.copied(f)
2618 copied = repo.dirstate.copied(f)
2618 if copied:
2619 if copied:
2619 ui.write(' %s%s' % (copied, end))
2620 ui.write(' %s%s' % (copied, end))
2620
2621
2621 def tag(ui, repo, name, rev_=None, **opts):
2622 def tag(ui, repo, name, rev_=None, **opts):
2622 """add a tag for the current tip or a given revision
2623 """add a tag for the current tip or a given revision
2623
2624
2624 Name a particular revision using <name>.
2625 Name a particular revision using <name>.
2625
2626
2626 Tags are used to name particular revisions of the repository and are
2627 Tags are used to name particular revisions of the repository and are
2627 very useful to compare different revision, to go back to significant
2628 very useful to compare different revision, to go back to significant
2628 earlier versions or to mark branch points as releases, etc.
2629 earlier versions or to mark branch points as releases, etc.
2629
2630
2630 If no revision is given, the parent of the working directory is used.
2631 If no revision is given, the parent of the working directory is used.
2631
2632
2632 To facilitate version control, distribution, and merging of tags,
2633 To facilitate version control, distribution, and merging of tags,
2633 they are stored as a file named ".hgtags" which is managed
2634 they are stored as a file named ".hgtags" which is managed
2634 similarly to other project files and can be hand-edited if
2635 similarly to other project files and can be hand-edited if
2635 necessary. The file '.hg/localtags' is used for local tags (not
2636 necessary. The file '.hg/localtags' is used for local tags (not
2636 shared among repositories).
2637 shared among repositories).
2637 """
2638 """
2638 if name in ['tip', '.']:
2639 if name in ['tip', '.']:
2639 raise util.Abort(_("the name '%s' is reserved") % name)
2640 raise util.Abort(_("the name '%s' is reserved") % name)
2640 if rev_ is not None:
2641 if rev_ is not None:
2641 ui.warn(_("use of 'hg tag NAME [REV]' is deprecated, "
2642 ui.warn(_("use of 'hg tag NAME [REV]' is deprecated, "
2642 "please use 'hg tag [-r REV] NAME' instead\n"))
2643 "please use 'hg tag [-r REV] NAME' instead\n"))
2643 if opts['rev']:
2644 if opts['rev']:
2644 raise util.Abort(_("use only one form to specify the revision"))
2645 raise util.Abort(_("use only one form to specify the revision"))
2645 if opts['rev']:
2646 if opts['rev']:
2646 rev_ = opts['rev']
2647 rev_ = opts['rev']
2647 if not rev_ and repo.dirstate.parents()[1] != nullid:
2648 if not rev_ and repo.dirstate.parents()[1] != nullid:
2648 raise util.Abort(_('uncommitted merge - please provide a '
2649 raise util.Abort(_('uncommitted merge - please provide a '
2649 'specific revision'))
2650 'specific revision'))
2650 r = repo.changectx(rev_).node()
2651 r = repo.changectx(rev_).node()
2651
2652
2652 message = opts['message']
2653 message = opts['message']
2653 if not message:
2654 if not message:
2654 message = _('Added tag %s for changeset %s') % (name, short(r))
2655 message = _('Added tag %s for changeset %s') % (name, short(r))
2655
2656
2656 repo.tag(name, r, message, opts['local'], opts['user'], opts['date'])
2657 repo.tag(name, r, message, opts['local'], opts['user'], opts['date'])
2657
2658
2658 def tags(ui, repo):
2659 def tags(ui, repo):
2659 """list repository tags
2660 """list repository tags
2660
2661
2661 List the repository tags.
2662 List the repository tags.
2662
2663
2663 This lists both regular and local tags.
2664 This lists both regular and local tags.
2664 """
2665 """
2665
2666
2666 l = repo.tagslist()
2667 l = repo.tagslist()
2667 l.reverse()
2668 l.reverse()
2668 hexfunc = ui.debugflag and hex or short
2669 hexfunc = ui.debugflag and hex or short
2669 for t, n in l:
2670 for t, n in l:
2670 try:
2671 try:
2671 r = "%5d:%s" % (repo.changelog.rev(n), hexfunc(n))
2672 r = "%5d:%s" % (repo.changelog.rev(n), hexfunc(n))
2672 except KeyError:
2673 except KeyError:
2673 r = " ?:?"
2674 r = " ?:?"
2674 if ui.quiet:
2675 if ui.quiet:
2675 ui.write("%s\n" % t)
2676 ui.write("%s\n" % t)
2676 else:
2677 else:
2677 ui.write("%-30s %s\n" % (t, r))
2678 ui.write("%-30s %s\n" % (t, r))
2678
2679
2679 def tip(ui, repo, **opts):
2680 def tip(ui, repo, **opts):
2680 """show the tip revision
2681 """show the tip revision
2681
2682
2682 Show the tip revision.
2683 Show the tip revision.
2683 """
2684 """
2684 n = repo.changelog.tip()
2685 n = repo.changelog.tip()
2685 br = None
2686 br = None
2686 if opts['branches']:
2687 if opts['branches']:
2687 ui.warn(_("the --branches option is deprecated, "
2688 ui.warn(_("the --branches option is deprecated, "
2688 "please use 'hg branches' instead\n"))
2689 "please use 'hg branches' instead\n"))
2689 br = repo.branchlookup([n])
2690 br = repo.branchlookup([n])
2690 show_changeset(ui, repo, opts).show(changenode=n, brinfo=br)
2691 show_changeset(ui, repo, opts).show(changenode=n, brinfo=br)
2691 if opts['patch']:
2692 if opts['patch']:
2692 patch.diff(repo, repo.changelog.parents(n)[0], n)
2693 patch.diff(repo, repo.changelog.parents(n)[0], n)
2693
2694
2694 def unbundle(ui, repo, fname, **opts):
2695 def unbundle(ui, repo, fname, **opts):
2695 """apply a changegroup file
2696 """apply a changegroup file
2696
2697
2697 Apply a compressed changegroup file generated by the bundle
2698 Apply a compressed changegroup file generated by the bundle
2698 command.
2699 command.
2699 """
2700 """
2700 f = urllib.urlopen(fname)
2701 f = urllib.urlopen(fname)
2701
2702
2702 header = f.read(6)
2703 header = f.read(6)
2703 if not header.startswith("HG"):
2704 if not header.startswith("HG"):
2704 raise util.Abort(_("%s: not a Mercurial bundle file") % fname)
2705 raise util.Abort(_("%s: not a Mercurial bundle file") % fname)
2705 elif not header.startswith("HG10"):
2706 elif not header.startswith("HG10"):
2706 raise util.Abort(_("%s: unknown bundle version") % fname)
2707 raise util.Abort(_("%s: unknown bundle version") % fname)
2707 elif header == "HG10BZ":
2708 elif header == "HG10BZ":
2708 def generator(f):
2709 def generator(f):
2709 zd = bz2.BZ2Decompressor()
2710 zd = bz2.BZ2Decompressor()
2710 zd.decompress("BZ")
2711 zd.decompress("BZ")
2711 for chunk in f:
2712 for chunk in f:
2712 yield zd.decompress(chunk)
2713 yield zd.decompress(chunk)
2713 elif header == "HG10UN":
2714 elif header == "HG10UN":
2714 def generator(f):
2715 def generator(f):
2715 for chunk in f:
2716 for chunk in f:
2716 yield chunk
2717 yield chunk
2717 else:
2718 else:
2718 raise util.Abort(_("%s: unknown bundle compression type")
2719 raise util.Abort(_("%s: unknown bundle compression type")
2719 % fname)
2720 % fname)
2720 gen = generator(util.filechunkiter(f, 4096))
2721 gen = generator(util.filechunkiter(f, 4096))
2721 modheads = repo.addchangegroup(util.chunkbuffer(gen), 'unbundle',
2722 modheads = repo.addchangegroup(util.chunkbuffer(gen), 'unbundle',
2722 'bundle:' + fname)
2723 'bundle:' + fname)
2723 return postincoming(ui, repo, modheads, opts['update'])
2724 return postincoming(ui, repo, modheads, opts['update'])
2724
2725
2725 def update(ui, repo, node=None, merge=False, clean=False, force=None,
2726 def update(ui, repo, node=None, merge=False, clean=False, force=None,
2726 branch=None):
2727 branch=None):
2727 """update or merge working directory
2728 """update or merge working directory
2728
2729
2729 Update the working directory to the specified revision.
2730 Update the working directory to the specified revision.
2730
2731
2731 If there are no outstanding changes in the working directory and
2732 If there are no outstanding changes in the working directory and
2732 there is a linear relationship between the current version and the
2733 there is a linear relationship between the current version and the
2733 requested version, the result is the requested version.
2734 requested version, the result is the requested version.
2734
2735
2735 To merge the working directory with another revision, use the
2736 To merge the working directory with another revision, use the
2736 merge command.
2737 merge command.
2737
2738
2738 By default, update will refuse to run if doing so would require
2739 By default, update will refuse to run if doing so would require
2739 merging or discarding local changes.
2740 merging or discarding local changes.
2740 """
2741 """
2741 node = _lookup(repo, node, branch)
2742 node = _lookup(repo, node, branch)
2742 if clean:
2743 if clean:
2743 return hg.clean(repo, node)
2744 return hg.clean(repo, node)
2744 else:
2745 else:
2745 return hg.update(repo, node)
2746 return hg.update(repo, node)
2746
2747
2747 def _lookup(repo, node, branch=None):
2748 def _lookup(repo, node, branch=None):
2748 if branch:
2749 if branch:
2749 repo.ui.warn(_("the --branch option is deprecated, "
2750 repo.ui.warn(_("the --branch option is deprecated, "
2750 "please use 'hg branch' instead\n"))
2751 "please use 'hg branch' instead\n"))
2751 br = repo.branchlookup(branch=branch)
2752 br = repo.branchlookup(branch=branch)
2752 found = []
2753 found = []
2753 for x in br:
2754 for x in br:
2754 if branch in br[x]:
2755 if branch in br[x]:
2755 found.append(x)
2756 found.append(x)
2756 if len(found) > 1:
2757 if len(found) > 1:
2757 repo.ui.warn(_("Found multiple heads for %s\n") % branch)
2758 repo.ui.warn(_("Found multiple heads for %s\n") % branch)
2758 for x in found:
2759 for x in found:
2759 show_changeset(ui, repo, {}).show(changenode=x, brinfo=br)
2760 show_changeset(ui, repo, {}).show(changenode=x, brinfo=br)
2760 raise util.Abort("")
2761 raise util.Abort("")
2761 if len(found) == 1:
2762 if len(found) == 1:
2762 node = found[0]
2763 node = found[0]
2763 repo.ui.warn(_("Using head %s for branch %s\n")
2764 repo.ui.warn(_("Using head %s for branch %s\n")
2764 % (short(node), branch))
2765 % (short(node), branch))
2765 else:
2766 else:
2766 raise util.Abort(_("branch %s not found") % branch)
2767 raise util.Abort(_("branch %s not found") % branch)
2767 else:
2768 else:
2768 node = node and repo.lookup(node) or repo.changelog.tip()
2769 node = node and repo.lookup(node) or repo.changelog.tip()
2769 return node
2770 return node
2770
2771
2771 def verify(ui, repo):
2772 def verify(ui, repo):
2772 """verify the integrity of the repository
2773 """verify the integrity of the repository
2773
2774
2774 Verify the integrity of the current repository.
2775 Verify the integrity of the current repository.
2775
2776
2776 This will perform an extensive check of the repository's
2777 This will perform an extensive check of the repository's
2777 integrity, validating the hashes and checksums of each entry in
2778 integrity, validating the hashes and checksums of each entry in
2778 the changelog, manifest, and tracked files, as well as the
2779 the changelog, manifest, and tracked files, as well as the
2779 integrity of their crosslinks and indices.
2780 integrity of their crosslinks and indices.
2780 """
2781 """
2781 return hg.verify(repo)
2782 return hg.verify(repo)
2782
2783
2783 # Command options and aliases are listed here, alphabetically
2784 # Command options and aliases are listed here, alphabetically
2784
2785
2785 globalopts = [
2786 globalopts = [
2786 ('R', 'repository', '',
2787 ('R', 'repository', '',
2787 _('repository root directory or symbolic path name')),
2788 _('repository root directory or symbolic path name')),
2788 ('', 'cwd', '', _('change working directory')),
2789 ('', 'cwd', '', _('change working directory')),
2789 ('y', 'noninteractive', None,
2790 ('y', 'noninteractive', None,
2790 _('do not prompt, assume \'yes\' for any required answers')),
2791 _('do not prompt, assume \'yes\' for any required answers')),
2791 ('q', 'quiet', None, _('suppress output')),
2792 ('q', 'quiet', None, _('suppress output')),
2792 ('v', 'verbose', None, _('enable additional output')),
2793 ('v', 'verbose', None, _('enable additional output')),
2793 ('', 'config', [], _('set/override config option')),
2794 ('', 'config', [], _('set/override config option')),
2794 ('', 'debug', None, _('enable debugging output')),
2795 ('', 'debug', None, _('enable debugging output')),
2795 ('', 'debugger', None, _('start debugger')),
2796 ('', 'debugger', None, _('start debugger')),
2796 ('', 'lsprof', None, _('print improved command execution profile')),
2797 ('', 'lsprof', None, _('print improved command execution profile')),
2797 ('', 'traceback', None, _('print traceback on exception')),
2798 ('', 'traceback', None, _('print traceback on exception')),
2798 ('', 'time', None, _('time how long the command takes')),
2799 ('', 'time', None, _('time how long the command takes')),
2799 ('', 'profile', None, _('print command execution profile')),
2800 ('', 'profile', None, _('print command execution profile')),
2800 ('', 'version', None, _('output version information and exit')),
2801 ('', 'version', None, _('output version information and exit')),
2801 ('h', 'help', None, _('display help and exit')),
2802 ('h', 'help', None, _('display help and exit')),
2802 ]
2803 ]
2803
2804
2804 dryrunopts = [('n', 'dry-run', None,
2805 dryrunopts = [('n', 'dry-run', None,
2805 _('do not perform actions, just print output'))]
2806 _('do not perform actions, just print output'))]
2806
2807
2807 remoteopts = [
2808 remoteopts = [
2808 ('e', 'ssh', '', _('specify ssh command to use')),
2809 ('e', 'ssh', '', _('specify ssh command to use')),
2809 ('', 'remotecmd', '', _('specify hg command to run on the remote side')),
2810 ('', 'remotecmd', '', _('specify hg command to run on the remote side')),
2810 ]
2811 ]
2811
2812
2812 walkopts = [
2813 walkopts = [
2813 ('I', 'include', [], _('include names matching the given patterns')),
2814 ('I', 'include', [], _('include names matching the given patterns')),
2814 ('X', 'exclude', [], _('exclude names matching the given patterns')),
2815 ('X', 'exclude', [], _('exclude names matching the given patterns')),
2815 ]
2816 ]
2816
2817
2817 table = {
2818 table = {
2818 "^add":
2819 "^add":
2819 (add,
2820 (add,
2820 walkopts + dryrunopts,
2821 walkopts + dryrunopts,
2821 _('hg add [OPTION]... [FILE]...')),
2822 _('hg add [OPTION]... [FILE]...')),
2822 "addremove":
2823 "addremove":
2823 (addremove,
2824 (addremove,
2824 [('s', 'similarity', '',
2825 [('s', 'similarity', '',
2825 _('guess renamed files by similarity (0<=s<=100)')),
2826 _('guess renamed files by similarity (0<=s<=100)')),
2826 ] + walkopts + dryrunopts,
2827 ] + walkopts + dryrunopts,
2827 _('hg addremove [OPTION]... [FILE]...')),
2828 _('hg addremove [OPTION]... [FILE]...')),
2828 "^annotate":
2829 "^annotate":
2829 (annotate,
2830 (annotate,
2830 [('r', 'rev', '', _('annotate the specified revision')),
2831 [('r', 'rev', '', _('annotate the specified revision')),
2831 ('f', 'follow', None, _('follow file copies and renames')),
2832 ('f', 'follow', None, _('follow file copies and renames')),
2832 ('a', 'text', None, _('treat all files as text')),
2833 ('a', 'text', None, _('treat all files as text')),
2833 ('u', 'user', None, _('list the author')),
2834 ('u', 'user', None, _('list the author')),
2834 ('d', 'date', None, _('list the date')),
2835 ('d', 'date', None, _('list the date')),
2835 ('n', 'number', None, _('list the revision number (default)')),
2836 ('n', 'number', None, _('list the revision number (default)')),
2836 ('c', 'changeset', None, _('list the changeset')),
2837 ('c', 'changeset', None, _('list the changeset')),
2837 ] + walkopts,
2838 ] + walkopts,
2838 _('hg annotate [-r REV] [-a] [-u] [-d] [-n] [-c] FILE...')),
2839 _('hg annotate [-r REV] [-a] [-u] [-d] [-n] [-c] FILE...')),
2839 "archive":
2840 "archive":
2840 (archive,
2841 (archive,
2841 [('', 'no-decode', None, _('do not pass files through decoders')),
2842 [('', 'no-decode', None, _('do not pass files through decoders')),
2842 ('p', 'prefix', '', _('directory prefix for files in archive')),
2843 ('p', 'prefix', '', _('directory prefix for files in archive')),
2843 ('r', 'rev', '', _('revision to distribute')),
2844 ('r', 'rev', '', _('revision to distribute')),
2844 ('t', 'type', '', _('type of distribution to create')),
2845 ('t', 'type', '', _('type of distribution to create')),
2845 ] + walkopts,
2846 ] + walkopts,
2846 _('hg archive [OPTION]... DEST')),
2847 _('hg archive [OPTION]... DEST')),
2847 "backout":
2848 "backout":
2848 (backout,
2849 (backout,
2849 [('', 'merge', None,
2850 [('', 'merge', None,
2850 _('merge with old dirstate parent after backout')),
2851 _('merge with old dirstate parent after backout')),
2851 ('m', 'message', '', _('use <text> as commit message')),
2852 ('m', 'message', '', _('use <text> as commit message')),
2852 ('l', 'logfile', '', _('read commit message from <file>')),
2853 ('l', 'logfile', '', _('read commit message from <file>')),
2853 ('d', 'date', '', _('record datecode as commit date')),
2854 ('d', 'date', '', _('record datecode as commit date')),
2854 ('', 'parent', '', _('parent to choose when backing out merge')),
2855 ('', 'parent', '', _('parent to choose when backing out merge')),
2855 ('u', 'user', '', _('record user as committer')),
2856 ('u', 'user', '', _('record user as committer')),
2856 ] + walkopts,
2857 ] + walkopts,
2857 _('hg backout [OPTION]... REV')),
2858 _('hg backout [OPTION]... REV')),
2858 "branch": (branch, [], _('hg branch [NAME]')),
2859 "branch": (branch, [], _('hg branch [NAME]')),
2859 "branches": (branches, [], _('hg branches')),
2860 "branches": (branches, [], _('hg branches')),
2860 "bundle":
2861 "bundle":
2861 (bundle,
2862 (bundle,
2862 [('f', 'force', None,
2863 [('f', 'force', None,
2863 _('run even when remote repository is unrelated')),
2864 _('run even when remote repository is unrelated')),
2864 ('r', 'rev', [],
2865 ('r', 'rev', [],
2865 _('a changeset you would like to bundle')),
2866 _('a changeset you would like to bundle')),
2866 ('', 'base', [],
2867 ('', 'base', [],
2867 _('a base changeset to specify instead of a destination')),
2868 _('a base changeset to specify instead of a destination')),
2868 ] + remoteopts,
2869 ] + remoteopts,
2869 _('hg bundle [--base REV]... [--rev REV]... FILE [DEST]')),
2870 _('hg bundle [--base REV]... [--rev REV]... FILE [DEST]')),
2870 "cat":
2871 "cat":
2871 (cat,
2872 (cat,
2872 [('o', 'output', '', _('print output to file with formatted name')),
2873 [('o', 'output', '', _('print output to file with formatted name')),
2873 ('r', 'rev', '', _('print the given revision')),
2874 ('r', 'rev', '', _('print the given revision')),
2874 ] + walkopts,
2875 ] + walkopts,
2875 _('hg cat [OPTION]... FILE...')),
2876 _('hg cat [OPTION]... FILE...')),
2876 "^clone":
2877 "^clone":
2877 (clone,
2878 (clone,
2878 [('U', 'noupdate', None, _('do not update the new working directory')),
2879 [('U', 'noupdate', None, _('do not update the new working directory')),
2879 ('r', 'rev', [],
2880 ('r', 'rev', [],
2880 _('a changeset you would like to have after cloning')),
2881 _('a changeset you would like to have after cloning')),
2881 ('', 'pull', None, _('use pull protocol to copy metadata')),
2882 ('', 'pull', None, _('use pull protocol to copy metadata')),
2882 ('', 'uncompressed', None,
2883 ('', 'uncompressed', None,
2883 _('use uncompressed transfer (fast over LAN)')),
2884 _('use uncompressed transfer (fast over LAN)')),
2884 ] + remoteopts,
2885 ] + remoteopts,
2885 _('hg clone [OPTION]... SOURCE [DEST]')),
2886 _('hg clone [OPTION]... SOURCE [DEST]')),
2886 "^commit|ci":
2887 "^commit|ci":
2887 (commit,
2888 (commit,
2888 [('A', 'addremove', None,
2889 [('A', 'addremove', None,
2889 _('mark new/missing files as added/removed before committing')),
2890 _('mark new/missing files as added/removed before committing')),
2890 ('m', 'message', '', _('use <text> as commit message')),
2891 ('m', 'message', '', _('use <text> as commit message')),
2891 ('l', 'logfile', '', _('read the commit message from <file>')),
2892 ('l', 'logfile', '', _('read the commit message from <file>')),
2892 ('d', 'date', '', _('record datecode as commit date')),
2893 ('d', 'date', '', _('record datecode as commit date')),
2893 ('u', 'user', '', _('record user as commiter')),
2894 ('u', 'user', '', _('record user as commiter')),
2894 ] + walkopts,
2895 ] + walkopts,
2895 _('hg commit [OPTION]... [FILE]...')),
2896 _('hg commit [OPTION]... [FILE]...')),
2896 "copy|cp":
2897 "copy|cp":
2897 (copy,
2898 (copy,
2898 [('A', 'after', None, _('record a copy that has already occurred')),
2899 [('A', 'after', None, _('record a copy that has already occurred')),
2899 ('f', 'force', None,
2900 ('f', 'force', None,
2900 _('forcibly copy over an existing managed file')),
2901 _('forcibly copy over an existing managed file')),
2901 ] + walkopts + dryrunopts,
2902 ] + walkopts + dryrunopts,
2902 _('hg copy [OPTION]... [SOURCE]... DEST')),
2903 _('hg copy [OPTION]... [SOURCE]... DEST')),
2903 "debugancestor": (debugancestor, [], _('debugancestor INDEX REV1 REV2')),
2904 "debugancestor": (debugancestor, [], _('debugancestor INDEX REV1 REV2')),
2904 "debugcomplete":
2905 "debugcomplete":
2905 (debugcomplete,
2906 (debugcomplete,
2906 [('o', 'options', None, _('show the command options'))],
2907 [('o', 'options', None, _('show the command options'))],
2907 _('debugcomplete [-o] CMD')),
2908 _('debugcomplete [-o] CMD')),
2908 "debugrebuildstate":
2909 "debugrebuildstate":
2909 (debugrebuildstate,
2910 (debugrebuildstate,
2910 [('r', 'rev', '', _('revision to rebuild to'))],
2911 [('r', 'rev', '', _('revision to rebuild to'))],
2911 _('debugrebuildstate [-r REV] [REV]')),
2912 _('debugrebuildstate [-r REV] [REV]')),
2912 "debugcheckstate": (debugcheckstate, [], _('debugcheckstate')),
2913 "debugcheckstate": (debugcheckstate, [], _('debugcheckstate')),
2913 "debugsetparents": (debugsetparents, [], _('debugsetparents REV1 [REV2]')),
2914 "debugsetparents": (debugsetparents, [], _('debugsetparents REV1 [REV2]')),
2914 "debugstate": (debugstate, [], _('debugstate')),
2915 "debugstate": (debugstate, [], _('debugstate')),
2915 "debugdata": (debugdata, [], _('debugdata FILE REV')),
2916 "debugdata": (debugdata, [], _('debugdata FILE REV')),
2916 "debugindex": (debugindex, [], _('debugindex FILE')),
2917 "debugindex": (debugindex, [], _('debugindex FILE')),
2917 "debugindexdot": (debugindexdot, [], _('debugindexdot FILE')),
2918 "debugindexdot": (debugindexdot, [], _('debugindexdot FILE')),
2918 "debugrename": (debugrename, [], _('debugrename FILE [REV]')),
2919 "debugrename": (debugrename, [], _('debugrename FILE [REV]')),
2919 "debugwalk":
2920 "debugwalk":
2920 (debugwalk, walkopts, _('debugwalk [OPTION]... [FILE]...')),
2921 (debugwalk, walkopts, _('debugwalk [OPTION]... [FILE]...')),
2921 "^diff":
2922 "^diff":
2922 (diff,
2923 (diff,
2923 [('r', 'rev', [], _('revision')),
2924 [('r', 'rev', [], _('revision')),
2924 ('a', 'text', None, _('treat all files as text')),
2925 ('a', 'text', None, _('treat all files as text')),
2925 ('p', 'show-function', None,
2926 ('p', 'show-function', None,
2926 _('show which function each change is in')),
2927 _('show which function each change is in')),
2927 ('g', 'git', None, _('use git extended diff format')),
2928 ('g', 'git', None, _('use git extended diff format')),
2928 ('', 'nodates', None, _("don't include dates in diff headers")),
2929 ('', 'nodates', None, _("don't include dates in diff headers")),
2929 ('w', 'ignore-all-space', None,
2930 ('w', 'ignore-all-space', None,
2930 _('ignore white space when comparing lines')),
2931 _('ignore white space when comparing lines')),
2931 ('b', 'ignore-space-change', None,
2932 ('b', 'ignore-space-change', None,
2932 _('ignore changes in the amount of white space')),
2933 _('ignore changes in the amount of white space')),
2933 ('B', 'ignore-blank-lines', None,
2934 ('B', 'ignore-blank-lines', None,
2934 _('ignore changes whose lines are all blank')),
2935 _('ignore changes whose lines are all blank')),
2935 ] + walkopts,
2936 ] + walkopts,
2936 _('hg diff [-a] [-I] [-X] [-r REV1 [-r REV2]] [FILE]...')),
2937 _('hg diff [-a] [-I] [-X] [-r REV1 [-r REV2]] [FILE]...')),
2937 "^export":
2938 "^export":
2938 (export,
2939 (export,
2939 [('o', 'output', '', _('print output to file with formatted name')),
2940 [('o', 'output', '', _('print output to file with formatted name')),
2940 ('a', 'text', None, _('treat all files as text')),
2941 ('a', 'text', None, _('treat all files as text')),
2941 ('g', 'git', None, _('use git extended diff format')),
2942 ('g', 'git', None, _('use git extended diff format')),
2942 ('', 'nodates', None, _("don't include dates in diff headers")),
2943 ('', 'nodates', None, _("don't include dates in diff headers")),
2943 ('', 'switch-parent', None, _('diff against the second parent'))],
2944 ('', 'switch-parent', None, _('diff against the second parent'))],
2944 _('hg export [-a] [-o OUTFILESPEC] REV...')),
2945 _('hg export [-a] [-o OUTFILESPEC] REV...')),
2945 "grep":
2946 "grep":
2946 (grep,
2947 (grep,
2947 [('0', 'print0', None, _('end fields with NUL')),
2948 [('0', 'print0', None, _('end fields with NUL')),
2948 ('', 'all', None, _('print all revisions that match')),
2949 ('', 'all', None, _('print all revisions that match')),
2949 ('f', 'follow', None,
2950 ('f', 'follow', None,
2950 _('follow changeset history, or file history across copies and renames')),
2951 _('follow changeset history, or file history across copies and renames')),
2951 ('i', 'ignore-case', None, _('ignore case when matching')),
2952 ('i', 'ignore-case', None, _('ignore case when matching')),
2952 ('l', 'files-with-matches', None,
2953 ('l', 'files-with-matches', None,
2953 _('print only filenames and revs that match')),
2954 _('print only filenames and revs that match')),
2954 ('n', 'line-number', None, _('print matching line numbers')),
2955 ('n', 'line-number', None, _('print matching line numbers')),
2955 ('r', 'rev', [], _('search in given revision range')),
2956 ('r', 'rev', [], _('search in given revision range')),
2956 ('u', 'user', None, _('print user who committed change')),
2957 ('u', 'user', None, _('print user who committed change')),
2957 ] + walkopts,
2958 ] + walkopts,
2958 _('hg grep [OPTION]... PATTERN [FILE]...')),
2959 _('hg grep [OPTION]... PATTERN [FILE]...')),
2959 "heads":
2960 "heads":
2960 (heads,
2961 (heads,
2961 [('b', 'branches', None, _('show branches (DEPRECATED)')),
2962 [('b', 'branches', None, _('show branches (DEPRECATED)')),
2962 ('', 'style', '', _('display using template map file')),
2963 ('', 'style', '', _('display using template map file')),
2963 ('r', 'rev', '', _('show only heads which are descendants of rev')),
2964 ('r', 'rev', '', _('show only heads which are descendants of rev')),
2964 ('', 'template', '', _('display with template'))],
2965 ('', 'template', '', _('display with template'))],
2965 _('hg heads [-r REV]')),
2966 _('hg heads [-r REV]')),
2966 "help": (help_, [], _('hg help [COMMAND]')),
2967 "help": (help_, [], _('hg help [COMMAND]')),
2967 "identify|id": (identify, [], _('hg identify')),
2968 "identify|id": (identify, [], _('hg identify')),
2968 "import|patch":
2969 "import|patch":
2969 (import_,
2970 (import_,
2970 [('p', 'strip', 1,
2971 [('p', 'strip', 1,
2971 _('directory strip option for patch. This has the same\n'
2972 _('directory strip option for patch. This has the same\n'
2972 'meaning as the corresponding patch option')),
2973 'meaning as the corresponding patch option')),
2973 ('m', 'message', '', _('use <text> as commit message')),
2974 ('m', 'message', '', _('use <text> as commit message')),
2974 ('b', 'base', '', _('base path (DEPRECATED)')),
2975 ('b', 'base', '', _('base path (DEPRECATED)')),
2975 ('f', 'force', None,
2976 ('f', 'force', None,
2976 _('skip check for outstanding uncommitted changes'))],
2977 _('skip check for outstanding uncommitted changes'))],
2977 _('hg import [-p NUM] [-m MESSAGE] [-f] PATCH...')),
2978 _('hg import [-p NUM] [-m MESSAGE] [-f] PATCH...')),
2978 "incoming|in": (incoming,
2979 "incoming|in": (incoming,
2979 [('M', 'no-merges', None, _('do not show merges')),
2980 [('M', 'no-merges', None, _('do not show merges')),
2980 ('f', 'force', None,
2981 ('f', 'force', None,
2981 _('run even when remote repository is unrelated')),
2982 _('run even when remote repository is unrelated')),
2982 ('', 'style', '', _('display using template map file')),
2983 ('', 'style', '', _('display using template map file')),
2983 ('n', 'newest-first', None, _('show newest record first')),
2984 ('n', 'newest-first', None, _('show newest record first')),
2984 ('', 'bundle', '', _('file to store the bundles into')),
2985 ('', 'bundle', '', _('file to store the bundles into')),
2985 ('p', 'patch', None, _('show patch')),
2986 ('p', 'patch', None, _('show patch')),
2986 ('r', 'rev', [], _('a specific revision up to which you would like to pull')),
2987 ('r', 'rev', [], _('a specific revision up to which you would like to pull')),
2987 ('', 'template', '', _('display with template')),
2988 ('', 'template', '', _('display with template')),
2988 ] + remoteopts,
2989 ] + remoteopts,
2989 _('hg incoming [-p] [-n] [-M] [-r REV]...'
2990 _('hg incoming [-p] [-n] [-M] [-r REV]...'
2990 ' [--bundle FILENAME] [SOURCE]')),
2991 ' [--bundle FILENAME] [SOURCE]')),
2991 "^init":
2992 "^init":
2992 (init, remoteopts, _('hg init [-e FILE] [--remotecmd FILE] [DEST]')),
2993 (init, remoteopts, _('hg init [-e FILE] [--remotecmd FILE] [DEST]')),
2993 "locate":
2994 "locate":
2994 (locate,
2995 (locate,
2995 [('r', 'rev', '', _('search the repository as it stood at rev')),
2996 [('r', 'rev', '', _('search the repository as it stood at rev')),
2996 ('0', 'print0', None,
2997 ('0', 'print0', None,
2997 _('end filenames with NUL, for use with xargs')),
2998 _('end filenames with NUL, for use with xargs')),
2998 ('f', 'fullpath', None,
2999 ('f', 'fullpath', None,
2999 _('print complete paths from the filesystem root')),
3000 _('print complete paths from the filesystem root')),
3000 ] + walkopts,
3001 ] + walkopts,
3001 _('hg locate [OPTION]... [PATTERN]...')),
3002 _('hg locate [OPTION]... [PATTERN]...')),
3002 "^log|history":
3003 "^log|history":
3003 (log,
3004 (log,
3004 [('b', 'branches', None, _('show branches (DEPRECATED)')),
3005 [('b', 'branches', None, _('show branches (DEPRECATED)')),
3005 ('f', 'follow', None,
3006 ('f', 'follow', None,
3006 _('follow changeset history, or file history across copies and renames')),
3007 _('follow changeset history, or file history across copies and renames')),
3007 ('', 'follow-first', None,
3008 ('', 'follow-first', None,
3008 _('only follow the first parent of merge changesets')),
3009 _('only follow the first parent of merge changesets')),
3009 ('C', 'copies', None, _('show copied files')),
3010 ('C', 'copies', None, _('show copied files')),
3010 ('k', 'keyword', [], _('search for a keyword')),
3011 ('k', 'keyword', [], _('search for a keyword')),
3011 ('l', 'limit', '', _('limit number of changes displayed')),
3012 ('l', 'limit', '', _('limit number of changes displayed')),
3012 ('r', 'rev', [], _('show the specified revision or range')),
3013 ('r', 'rev', [], _('show the specified revision or range')),
3013 ('M', 'no-merges', None, _('do not show merges')),
3014 ('M', 'no-merges', None, _('do not show merges')),
3014 ('', 'style', '', _('display using template map file')),
3015 ('', 'style', '', _('display using template map file')),
3015 ('m', 'only-merges', None, _('show only merges')),
3016 ('m', 'only-merges', None, _('show only merges')),
3016 ('p', 'patch', None, _('show patch')),
3017 ('p', 'patch', None, _('show patch')),
3017 ('P', 'prune', [], _('do not display revision or any of its ancestors')),
3018 ('P', 'prune', [], _('do not display revision or any of its ancestors')),
3018 ('', 'template', '', _('display with template')),
3019 ('', 'template', '', _('display with template')),
3019 ] + walkopts,
3020 ] + walkopts,
3020 _('hg log [OPTION]... [FILE]')),
3021 _('hg log [OPTION]... [FILE]')),
3021 "manifest": (manifest, [], _('hg manifest [REV]')),
3022 "manifest": (manifest, [], _('hg manifest [REV]')),
3022 "merge":
3023 "merge":
3023 (merge,
3024 (merge,
3024 [('b', 'branch', '', _('merge with head of a specific branch (DEPRECATED)')),
3025 [('b', 'branch', '', _('merge with head of a specific branch (DEPRECATED)')),
3025 ('f', 'force', None, _('force a merge with outstanding changes'))],
3026 ('f', 'force', None, _('force a merge with outstanding changes'))],
3026 _('hg merge [-f] [REV]')),
3027 _('hg merge [-f] [REV]')),
3027 "outgoing|out": (outgoing,
3028 "outgoing|out": (outgoing,
3028 [('M', 'no-merges', None, _('do not show merges')),
3029 [('M', 'no-merges', None, _('do not show merges')),
3029 ('f', 'force', None,
3030 ('f', 'force', None,
3030 _('run even when remote repository is unrelated')),
3031 _('run even when remote repository is unrelated')),
3031 ('p', 'patch', None, _('show patch')),
3032 ('p', 'patch', None, _('show patch')),
3032 ('', 'style', '', _('display using template map file')),
3033 ('', 'style', '', _('display using template map file')),
3033 ('r', 'rev', [], _('a specific revision you would like to push')),
3034 ('r', 'rev', [], _('a specific revision you would like to push')),
3034 ('n', 'newest-first', None, _('show newest record first')),
3035 ('n', 'newest-first', None, _('show newest record first')),
3035 ('', 'template', '', _('display with template')),
3036 ('', 'template', '', _('display with template')),
3036 ] + remoteopts,
3037 ] + remoteopts,
3037 _('hg outgoing [-M] [-p] [-n] [-r REV]... [DEST]')),
3038 _('hg outgoing [-M] [-p] [-n] [-r REV]... [DEST]')),
3038 "^parents":
3039 "^parents":
3039 (parents,
3040 (parents,
3040 [('b', 'branches', None, _('show branches (DEPRECATED)')),
3041 [('b', 'branches', None, _('show branches (DEPRECATED)')),
3041 ('r', 'rev', '', _('show parents from the specified rev')),
3042 ('r', 'rev', '', _('show parents from the specified rev')),
3042 ('', 'style', '', _('display using template map file')),
3043 ('', 'style', '', _('display using template map file')),
3043 ('', 'template', '', _('display with template'))],
3044 ('', 'template', '', _('display with template'))],
3044 _('hg parents [-r REV] [FILE]')),
3045 _('hg parents [-r REV] [FILE]')),
3045 "paths": (paths, [], _('hg paths [NAME]')),
3046 "paths": (paths, [], _('hg paths [NAME]')),
3046 "^pull":
3047 "^pull":
3047 (pull,
3048 (pull,
3048 [('u', 'update', None,
3049 [('u', 'update', None,
3049 _('update to new tip if changesets were pulled')),
3050 _('update to new tip if changesets were pulled')),
3050 ('f', 'force', None,
3051 ('f', 'force', None,
3051 _('run even when remote repository is unrelated')),
3052 _('run even when remote repository is unrelated')),
3052 ('r', 'rev', [], _('a specific revision up to which you would like to pull')),
3053 ('r', 'rev', [], _('a specific revision up to which you would like to pull')),
3053 ] + remoteopts,
3054 ] + remoteopts,
3054 _('hg pull [-u] [-r REV]... [-e FILE] [--remotecmd FILE] [SOURCE]')),
3055 _('hg pull [-u] [-r REV]... [-e FILE] [--remotecmd FILE] [SOURCE]')),
3055 "^push":
3056 "^push":
3056 (push,
3057 (push,
3057 [('f', 'force', None, _('force push')),
3058 [('f', 'force', None, _('force push')),
3058 ('r', 'rev', [], _('a specific revision you would like to push')),
3059 ('r', 'rev', [], _('a specific revision you would like to push')),
3059 ] + remoteopts,
3060 ] + remoteopts,
3060 _('hg push [-f] [-r REV]... [-e FILE] [--remotecmd FILE] [DEST]')),
3061 _('hg push [-f] [-r REV]... [-e FILE] [--remotecmd FILE] [DEST]')),
3061 "debugrawcommit|rawcommit":
3062 "debugrawcommit|rawcommit":
3062 (rawcommit,
3063 (rawcommit,
3063 [('p', 'parent', [], _('parent')),
3064 [('p', 'parent', [], _('parent')),
3064 ('d', 'date', '', _('date code')),
3065 ('d', 'date', '', _('date code')),
3065 ('u', 'user', '', _('user')),
3066 ('u', 'user', '', _('user')),
3066 ('F', 'files', '', _('file list')),
3067 ('F', 'files', '', _('file list')),
3067 ('m', 'message', '', _('commit message')),
3068 ('m', 'message', '', _('commit message')),
3068 ('l', 'logfile', '', _('commit message file'))],
3069 ('l', 'logfile', '', _('commit message file'))],
3069 _('hg debugrawcommit [OPTION]... [FILE]...')),
3070 _('hg debugrawcommit [OPTION]... [FILE]...')),
3070 "recover": (recover, [], _('hg recover')),
3071 "recover": (recover, [], _('hg recover')),
3071 "^remove|rm":
3072 "^remove|rm":
3072 (remove,
3073 (remove,
3073 [('A', 'after', None, _('record remove that has already occurred')),
3074 [('A', 'after', None, _('record remove that has already occurred')),
3074 ('f', 'force', None, _('remove file even if modified')),
3075 ('f', 'force', None, _('remove file even if modified')),
3075 ] + walkopts,
3076 ] + walkopts,
3076 _('hg remove [OPTION]... FILE...')),
3077 _('hg remove [OPTION]... FILE...')),
3077 "rename|mv":
3078 "rename|mv":
3078 (rename,
3079 (rename,
3079 [('A', 'after', None, _('record a rename that has already occurred')),
3080 [('A', 'after', None, _('record a rename that has already occurred')),
3080 ('f', 'force', None,
3081 ('f', 'force', None,
3081 _('forcibly copy over an existing managed file')),
3082 _('forcibly copy over an existing managed file')),
3082 ] + walkopts + dryrunopts,
3083 ] + walkopts + dryrunopts,
3083 _('hg rename [OPTION]... SOURCE... DEST')),
3084 _('hg rename [OPTION]... SOURCE... DEST')),
3084 "^revert":
3085 "^revert":
3085 (revert,
3086 (revert,
3086 [('a', 'all', None, _('revert all changes when no arguments given')),
3087 [('a', 'all', None, _('revert all changes when no arguments given')),
3087 ('r', 'rev', '', _('revision to revert to')),
3088 ('r', 'rev', '', _('revision to revert to')),
3088 ('', 'no-backup', None, _('do not save backup copies of files')),
3089 ('', 'no-backup', None, _('do not save backup copies of files')),
3089 ] + walkopts + dryrunopts,
3090 ] + walkopts + dryrunopts,
3090 _('hg revert [-r REV] [NAME]...')),
3091 _('hg revert [-r REV] [NAME]...')),
3091 "rollback": (rollback, [], _('hg rollback')),
3092 "rollback": (rollback, [], _('hg rollback')),
3092 "root": (root, [], _('hg root')),
3093 "root": (root, [], _('hg root')),
3093 "showconfig|debugconfig":
3094 "showconfig|debugconfig":
3094 (showconfig,
3095 (showconfig,
3095 [('u', 'untrusted', None, _('show untrusted configuration options'))],
3096 [('u', 'untrusted', None, _('show untrusted configuration options'))],
3096 _('showconfig [-u] [NAME]...')),
3097 _('showconfig [-u] [NAME]...')),
3097 "^serve":
3098 "^serve":
3098 (serve,
3099 (serve,
3099 [('A', 'accesslog', '', _('name of access log file to write to')),
3100 [('A', 'accesslog', '', _('name of access log file to write to')),
3100 ('d', 'daemon', None, _('run server in background')),
3101 ('d', 'daemon', None, _('run server in background')),
3101 ('', 'daemon-pipefds', '', _('used internally by daemon mode')),
3102 ('', 'daemon-pipefds', '', _('used internally by daemon mode')),
3102 ('E', 'errorlog', '', _('name of error log file to write to')),
3103 ('E', 'errorlog', '', _('name of error log file to write to')),
3103 ('p', 'port', 0, _('port to use (default: 8000)')),
3104 ('p', 'port', 0, _('port to use (default: 8000)')),
3104 ('a', 'address', '', _('address to use')),
3105 ('a', 'address', '', _('address to use')),
3105 ('n', 'name', '',
3106 ('n', 'name', '',
3106 _('name to show in web pages (default: working dir)')),
3107 _('name to show in web pages (default: working dir)')),
3107 ('', 'webdir-conf', '', _('name of the webdir config file'
3108 ('', 'webdir-conf', '', _('name of the webdir config file'
3108 ' (serve more than one repo)')),
3109 ' (serve more than one repo)')),
3109 ('', 'pid-file', '', _('name of file to write process ID to')),
3110 ('', 'pid-file', '', _('name of file to write process ID to')),
3110 ('', 'stdio', None, _('for remote clients')),
3111 ('', 'stdio', None, _('for remote clients')),
3111 ('t', 'templates', '', _('web templates to use')),
3112 ('t', 'templates', '', _('web templates to use')),
3112 ('', 'style', '', _('template style to use')),
3113 ('', 'style', '', _('template style to use')),
3113 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4'))],
3114 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4'))],
3114 _('hg serve [OPTION]...')),
3115 _('hg serve [OPTION]...')),
3115 "^status|st":
3116 "^status|st":
3116 (status,
3117 (status,
3117 [('A', 'all', None, _('show status of all files')),
3118 [('A', 'all', None, _('show status of all files')),
3118 ('m', 'modified', None, _('show only modified files')),
3119 ('m', 'modified', None, _('show only modified files')),
3119 ('a', 'added', None, _('show only added files')),
3120 ('a', 'added', None, _('show only added files')),
3120 ('r', 'removed', None, _('show only removed files')),
3121 ('r', 'removed', None, _('show only removed files')),
3121 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
3122 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
3122 ('c', 'clean', None, _('show only files without changes')),
3123 ('c', 'clean', None, _('show only files without changes')),
3123 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
3124 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
3124 ('i', 'ignored', None, _('show ignored files')),
3125 ('i', 'ignored', None, _('show ignored files')),
3125 ('n', 'no-status', None, _('hide status prefix')),
3126 ('n', 'no-status', None, _('hide status prefix')),
3126 ('C', 'copies', None, _('show source of copied files')),
3127 ('C', 'copies', None, _('show source of copied files')),
3127 ('0', 'print0', None,
3128 ('0', 'print0', None,
3128 _('end filenames with NUL, for use with xargs')),
3129 _('end filenames with NUL, for use with xargs')),
3129 ('', 'rev', [], _('show difference from revision')),
3130 ('', 'rev', [], _('show difference from revision')),
3130 ] + walkopts,
3131 ] + walkopts,
3131 _('hg status [OPTION]... [FILE]...')),
3132 _('hg status [OPTION]... [FILE]...')),
3132 "tag":
3133 "tag":
3133 (tag,
3134 (tag,
3134 [('l', 'local', None, _('make the tag local')),
3135 [('l', 'local', None, _('make the tag local')),
3135 ('m', 'message', '', _('message for tag commit log entry')),
3136 ('m', 'message', '', _('message for tag commit log entry')),
3136 ('d', 'date', '', _('record datecode as commit date')),
3137 ('d', 'date', '', _('record datecode as commit date')),
3137 ('u', 'user', '', _('record user as commiter')),
3138 ('u', 'user', '', _('record user as commiter')),
3138 ('r', 'rev', '', _('revision to tag'))],
3139 ('r', 'rev', '', _('revision to tag'))],
3139 _('hg tag [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME')),
3140 _('hg tag [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME')),
3140 "tags": (tags, [], _('hg tags')),
3141 "tags": (tags, [], _('hg tags')),
3141 "tip":
3142 "tip":
3142 (tip,
3143 (tip,
3143 [('b', 'branches', None, _('show branches (DEPRECATED)')),
3144 [('b', 'branches', None, _('show branches (DEPRECATED)')),
3144 ('', 'style', '', _('display using template map file')),
3145 ('', 'style', '', _('display using template map file')),
3145 ('p', 'patch', None, _('show patch')),
3146 ('p', 'patch', None, _('show patch')),
3146 ('', 'template', '', _('display with template'))],
3147 ('', 'template', '', _('display with template'))],
3147 _('hg tip [-p]')),
3148 _('hg tip [-p]')),
3148 "unbundle":
3149 "unbundle":
3149 (unbundle,
3150 (unbundle,
3150 [('u', 'update', None,
3151 [('u', 'update', None,
3151 _('update to new tip if changesets were unbundled'))],
3152 _('update to new tip if changesets were unbundled'))],
3152 _('hg unbundle [-u] FILE')),
3153 _('hg unbundle [-u] FILE')),
3153 "^update|up|checkout|co":
3154 "^update|up|checkout|co":
3154 (update,
3155 (update,
3155 [('b', 'branch', '',
3156 [('b', 'branch', '',
3156 _('checkout the head of a specific branch (DEPRECATED)')),
3157 _('checkout the head of a specific branch (DEPRECATED)')),
3157 ('m', 'merge', None, _('allow merging of branches (DEPRECATED)')),
3158 ('m', 'merge', None, _('allow merging of branches (DEPRECATED)')),
3158 ('C', 'clean', None, _('overwrite locally modified files')),
3159 ('C', 'clean', None, _('overwrite locally modified files')),
3159 ('f', 'force', None, _('force a merge with outstanding changes'))],
3160 ('f', 'force', None, _('force a merge with outstanding changes'))],
3160 _('hg update [-C] [-f] [REV]')),
3161 _('hg update [-C] [-f] [REV]')),
3161 "verify": (verify, [], _('hg verify')),
3162 "verify": (verify, [], _('hg verify')),
3162 "version": (show_version, [], _('hg version')),
3163 "version": (show_version, [], _('hg version')),
3163 }
3164 }
3164
3165
3165 norepo = ("clone init version help debugancestor debugcomplete debugdata"
3166 norepo = ("clone init version help debugancestor debugcomplete debugdata"
3166 " debugindex debugindexdot")
3167 " debugindex debugindexdot")
3167 optionalrepo = ("paths serve showconfig")
3168 optionalrepo = ("paths serve showconfig")
3168
3169
3169 def findpossible(ui, cmd):
3170 def findpossible(ui, cmd):
3170 """
3171 """
3171 Return cmd -> (aliases, command table entry)
3172 Return cmd -> (aliases, command table entry)
3172 for each matching command.
3173 for each matching command.
3173 Return debug commands (or their aliases) only if no normal command matches.
3174 Return debug commands (or their aliases) only if no normal command matches.
3174 """
3175 """
3175 choice = {}
3176 choice = {}
3176 debugchoice = {}
3177 debugchoice = {}
3177 for e in table.keys():
3178 for e in table.keys():
3178 aliases = e.lstrip("^").split("|")
3179 aliases = e.lstrip("^").split("|")
3179 found = None
3180 found = None
3180 if cmd in aliases:
3181 if cmd in aliases:
3181 found = cmd
3182 found = cmd
3182 elif not ui.config("ui", "strict"):
3183 elif not ui.config("ui", "strict"):
3183 for a in aliases:
3184 for a in aliases:
3184 if a.startswith(cmd):
3185 if a.startswith(cmd):
3185 found = a
3186 found = a
3186 break
3187 break
3187 if found is not None:
3188 if found is not None:
3188 if aliases[0].startswith("debug") or found.startswith("debug"):
3189 if aliases[0].startswith("debug") or found.startswith("debug"):
3189 debugchoice[found] = (aliases, table[e])
3190 debugchoice[found] = (aliases, table[e])
3190 else:
3191 else:
3191 choice[found] = (aliases, table[e])
3192 choice[found] = (aliases, table[e])
3192
3193
3193 if not choice and debugchoice:
3194 if not choice and debugchoice:
3194 choice = debugchoice
3195 choice = debugchoice
3195
3196
3196 return choice
3197 return choice
3197
3198
3198 def findcmd(ui, cmd):
3199 def findcmd(ui, cmd):
3199 """Return (aliases, command table entry) for command string."""
3200 """Return (aliases, command table entry) for command string."""
3200 choice = findpossible(ui, cmd)
3201 choice = findpossible(ui, cmd)
3201
3202
3202 if choice.has_key(cmd):
3203 if choice.has_key(cmd):
3203 return choice[cmd]
3204 return choice[cmd]
3204
3205
3205 if len(choice) > 1:
3206 if len(choice) > 1:
3206 clist = choice.keys()
3207 clist = choice.keys()
3207 clist.sort()
3208 clist.sort()
3208 raise AmbiguousCommand(cmd, clist)
3209 raise AmbiguousCommand(cmd, clist)
3209
3210
3210 if choice:
3211 if choice:
3211 return choice.values()[0]
3212 return choice.values()[0]
3212
3213
3213 raise UnknownCommand(cmd)
3214 raise UnknownCommand(cmd)
3214
3215
3215 def catchterm(*args):
3216 def catchterm(*args):
3216 raise util.SignalInterrupt
3217 raise util.SignalInterrupt
3217
3218
3218 def run():
3219 def run():
3219 sys.exit(dispatch(sys.argv[1:]))
3220 sys.exit(dispatch(sys.argv[1:]))
3220
3221
3221 class ParseError(Exception):
3222 class ParseError(Exception):
3222 """Exception raised on errors in parsing the command line."""
3223 """Exception raised on errors in parsing the command line."""
3223
3224
3224 def parse(ui, args):
3225 def parse(ui, args):
3225 options = {}
3226 options = {}
3226 cmdoptions = {}
3227 cmdoptions = {}
3227
3228
3228 try:
3229 try:
3229 args = fancyopts.fancyopts(args, globalopts, options)
3230 args = fancyopts.fancyopts(args, globalopts, options)
3230 except fancyopts.getopt.GetoptError, inst:
3231 except fancyopts.getopt.GetoptError, inst:
3231 raise ParseError(None, inst)
3232 raise ParseError(None, inst)
3232
3233
3233 if args:
3234 if args:
3234 cmd, args = args[0], args[1:]
3235 cmd, args = args[0], args[1:]
3235 aliases, i = findcmd(ui, cmd)
3236 aliases, i = findcmd(ui, cmd)
3236 cmd = aliases[0]
3237 cmd = aliases[0]
3237 defaults = ui.config("defaults", cmd)
3238 defaults = ui.config("defaults", cmd)
3238 if defaults:
3239 if defaults:
3239 args = shlex.split(defaults) + args
3240 args = shlex.split(defaults) + args
3240 c = list(i[1])
3241 c = list(i[1])
3241 else:
3242 else:
3242 cmd = None
3243 cmd = None
3243 c = []
3244 c = []
3244
3245
3245 # combine global options into local
3246 # combine global options into local
3246 for o in globalopts:
3247 for o in globalopts:
3247 c.append((o[0], o[1], options[o[1]], o[3]))
3248 c.append((o[0], o[1], options[o[1]], o[3]))
3248
3249
3249 try:
3250 try:
3250 args = fancyopts.fancyopts(args, c, cmdoptions)
3251 args = fancyopts.fancyopts(args, c, cmdoptions)
3251 except fancyopts.getopt.GetoptError, inst:
3252 except fancyopts.getopt.GetoptError, inst:
3252 raise ParseError(cmd, inst)
3253 raise ParseError(cmd, inst)
3253
3254
3254 # separate global options back out
3255 # separate global options back out
3255 for o in globalopts:
3256 for o in globalopts:
3256 n = o[1]
3257 n = o[1]
3257 options[n] = cmdoptions[n]
3258 options[n] = cmdoptions[n]
3258 del cmdoptions[n]
3259 del cmdoptions[n]
3259
3260
3260 return (cmd, cmd and i[0] or None, args, options, cmdoptions)
3261 return (cmd, cmd and i[0] or None, args, options, cmdoptions)
3261
3262
3262 external = {}
3263 external = {}
3263
3264
3264 def findext(name):
3265 def findext(name):
3265 '''return module with given extension name'''
3266 '''return module with given extension name'''
3266 try:
3267 try:
3267 return sys.modules[external[name]]
3268 return sys.modules[external[name]]
3268 except KeyError:
3269 except KeyError:
3269 for k, v in external.iteritems():
3270 for k, v in external.iteritems():
3270 if k.endswith('.' + name) or k.endswith('/' + name) or v == name:
3271 if k.endswith('.' + name) or k.endswith('/' + name) or v == name:
3271 return sys.modules[v]
3272 return sys.modules[v]
3272 raise KeyError(name)
3273 raise KeyError(name)
3273
3274
3274 def load_extensions(ui):
3275 def load_extensions(ui):
3275 added = []
3276 added = []
3276 for ext_name, load_from_name in ui.extensions():
3277 for ext_name, load_from_name in ui.extensions():
3277 if ext_name in external:
3278 if ext_name in external:
3278 continue
3279 continue
3279 try:
3280 try:
3280 if load_from_name:
3281 if load_from_name:
3281 # the module will be loaded in sys.modules
3282 # the module will be loaded in sys.modules
3282 # choose an unique name so that it doesn't
3283 # choose an unique name so that it doesn't
3283 # conflicts with other modules
3284 # conflicts with other modules
3284 module_name = "hgext_%s" % ext_name.replace('.', '_')
3285 module_name = "hgext_%s" % ext_name.replace('.', '_')
3285 mod = imp.load_source(module_name, load_from_name)
3286 mod = imp.load_source(module_name, load_from_name)
3286 else:
3287 else:
3287 def importh(name):
3288 def importh(name):
3288 mod = __import__(name)
3289 mod = __import__(name)
3289 components = name.split('.')
3290 components = name.split('.')
3290 for comp in components[1:]:
3291 for comp in components[1:]:
3291 mod = getattr(mod, comp)
3292 mod = getattr(mod, comp)
3292 return mod
3293 return mod
3293 try:
3294 try:
3294 mod = importh("hgext.%s" % ext_name)
3295 mod = importh("hgext.%s" % ext_name)
3295 except ImportError:
3296 except ImportError:
3296 mod = importh(ext_name)
3297 mod = importh(ext_name)
3297 external[ext_name] = mod.__name__
3298 external[ext_name] = mod.__name__
3298 added.append((mod, ext_name))
3299 added.append((mod, ext_name))
3299 except (util.SignalInterrupt, KeyboardInterrupt):
3300 except (util.SignalInterrupt, KeyboardInterrupt):
3300 raise
3301 raise
3301 except Exception, inst:
3302 except Exception, inst:
3302 ui.warn(_("*** failed to import extension %s: %s\n") %
3303 ui.warn(_("*** failed to import extension %s: %s\n") %
3303 (ext_name, inst))
3304 (ext_name, inst))
3304 if ui.print_exc():
3305 if ui.print_exc():
3305 return 1
3306 return 1
3306
3307
3307 for mod, name in added:
3308 for mod, name in added:
3308 uisetup = getattr(mod, 'uisetup', None)
3309 uisetup = getattr(mod, 'uisetup', None)
3309 if uisetup:
3310 if uisetup:
3310 uisetup(ui)
3311 uisetup(ui)
3311 cmdtable = getattr(mod, 'cmdtable', {})
3312 cmdtable = getattr(mod, 'cmdtable', {})
3312 for t in cmdtable:
3313 for t in cmdtable:
3313 if t in table:
3314 if t in table:
3314 ui.warn(_("module %s overrides %s\n") % (name, t))
3315 ui.warn(_("module %s overrides %s\n") % (name, t))
3315 table.update(cmdtable)
3316 table.update(cmdtable)
3316
3317
3317 def parseconfig(config):
3318 def parseconfig(config):
3318 """parse the --config options from the command line"""
3319 """parse the --config options from the command line"""
3319 parsed = []
3320 parsed = []
3320 for cfg in config:
3321 for cfg in config:
3321 try:
3322 try:
3322 name, value = cfg.split('=', 1)
3323 name, value = cfg.split('=', 1)
3323 section, name = name.split('.', 1)
3324 section, name = name.split('.', 1)
3324 if not section or not name:
3325 if not section or not name:
3325 raise IndexError
3326 raise IndexError
3326 parsed.append((section, name, value))
3327 parsed.append((section, name, value))
3327 except (IndexError, ValueError):
3328 except (IndexError, ValueError):
3328 raise util.Abort(_('malformed --config option: %s') % cfg)
3329 raise util.Abort(_('malformed --config option: %s') % cfg)
3329 return parsed
3330 return parsed
3330
3331
3331 def dispatch(args):
3332 def dispatch(args):
3332 for name in 'SIGBREAK', 'SIGHUP', 'SIGTERM':
3333 for name in 'SIGBREAK', 'SIGHUP', 'SIGTERM':
3333 num = getattr(signal, name, None)
3334 num = getattr(signal, name, None)
3334 if num: signal.signal(num, catchterm)
3335 if num: signal.signal(num, catchterm)
3335
3336
3336 try:
3337 try:
3337 u = ui.ui(traceback='--traceback' in sys.argv[1:])
3338 u = ui.ui(traceback='--traceback' in sys.argv[1:])
3338 except util.Abort, inst:
3339 except util.Abort, inst:
3339 sys.stderr.write(_("abort: %s\n") % inst)
3340 sys.stderr.write(_("abort: %s\n") % inst)
3340 return -1
3341 return -1
3341
3342
3342 load_extensions(u)
3343 load_extensions(u)
3343 u.addreadhook(load_extensions)
3344 u.addreadhook(load_extensions)
3344
3345
3345 try:
3346 try:
3346 cmd, func, args, options, cmdoptions = parse(u, args)
3347 cmd, func, args, options, cmdoptions = parse(u, args)
3347 if options["time"]:
3348 if options["time"]:
3348 def get_times():
3349 def get_times():
3349 t = os.times()
3350 t = os.times()
3350 if t[4] == 0.0: # Windows leaves this as zero, so use time.clock()
3351 if t[4] == 0.0: # Windows leaves this as zero, so use time.clock()
3351 t = (t[0], t[1], t[2], t[3], time.clock())
3352 t = (t[0], t[1], t[2], t[3], time.clock())
3352 return t
3353 return t
3353 s = get_times()
3354 s = get_times()
3354 def print_time():
3355 def print_time():
3355 t = get_times()
3356 t = get_times()
3356 u.warn(_("Time: real %.3f secs (user %.3f+%.3f sys %.3f+%.3f)\n") %
3357 u.warn(_("Time: real %.3f secs (user %.3f+%.3f sys %.3f+%.3f)\n") %
3357 (t[4]-s[4], t[0]-s[0], t[2]-s[2], t[1]-s[1], t[3]-s[3]))
3358 (t[4]-s[4], t[0]-s[0], t[2]-s[2], t[1]-s[1], t[3]-s[3]))
3358 atexit.register(print_time)
3359 atexit.register(print_time)
3359
3360
3360 # enter the debugger before command execution
3361 # enter the debugger before command execution
3361 if options['debugger']:
3362 if options['debugger']:
3362 pdb.set_trace()
3363 pdb.set_trace()
3363
3364
3364 try:
3365 try:
3365 if options['cwd']:
3366 if options['cwd']:
3366 try:
3367 try:
3367 os.chdir(options['cwd'])
3368 os.chdir(options['cwd'])
3368 except OSError, inst:
3369 except OSError, inst:
3369 raise util.Abort('%s: %s' %
3370 raise util.Abort('%s: %s' %
3370 (options['cwd'], inst.strerror))
3371 (options['cwd'], inst.strerror))
3371
3372
3372 u.updateopts(options["verbose"], options["debug"], options["quiet"],
3373 u.updateopts(options["verbose"], options["debug"], options["quiet"],
3373 not options["noninteractive"], options["traceback"],
3374 not options["noninteractive"], options["traceback"],
3374 parseconfig(options["config"]))
3375 parseconfig(options["config"]))
3375
3376
3376 path = u.expandpath(options["repository"]) or ""
3377 path = u.expandpath(options["repository"]) or ""
3377 repo = path and hg.repository(u, path=path) or None
3378 repo = path and hg.repository(u, path=path) or None
3378 if repo and not repo.local():
3379 if repo and not repo.local():
3379 raise util.Abort(_("repository '%s' is not local") % path)
3380 raise util.Abort(_("repository '%s' is not local") % path)
3380
3381
3381 if options['help']:
3382 if options['help']:
3382 return help_(u, cmd, options['version'])
3383 return help_(u, cmd, options['version'])
3383 elif options['version']:
3384 elif options['version']:
3384 return show_version(u)
3385 return show_version(u)
3385 elif not cmd:
3386 elif not cmd:
3386 return help_(u, 'shortlist')
3387 return help_(u, 'shortlist')
3387
3388
3388 if cmd not in norepo.split():
3389 if cmd not in norepo.split():
3389 try:
3390 try:
3390 if not repo:
3391 if not repo:
3391 repo = hg.repository(u, path=path)
3392 repo = hg.repository(u, path=path)
3392 u = repo.ui
3393 u = repo.ui
3393 for name in external.itervalues():
3394 for name in external.itervalues():
3394 mod = sys.modules[name]
3395 mod = sys.modules[name]
3395 if hasattr(mod, 'reposetup'):
3396 if hasattr(mod, 'reposetup'):
3396 mod.reposetup(u, repo)
3397 mod.reposetup(u, repo)
3397 hg.repo_setup_hooks.append(mod.reposetup)
3398 hg.repo_setup_hooks.append(mod.reposetup)
3398 except hg.RepoError:
3399 except hg.RepoError:
3399 if cmd not in optionalrepo.split():
3400 if cmd not in optionalrepo.split():
3400 raise
3401 raise
3401 d = lambda: func(u, repo, *args, **cmdoptions)
3402 d = lambda: func(u, repo, *args, **cmdoptions)
3402 else:
3403 else:
3403 d = lambda: func(u, *args, **cmdoptions)
3404 d = lambda: func(u, *args, **cmdoptions)
3404
3405
3405 try:
3406 try:
3406 if options['profile']:
3407 if options['profile']:
3407 import hotshot, hotshot.stats
3408 import hotshot, hotshot.stats
3408 prof = hotshot.Profile("hg.prof")
3409 prof = hotshot.Profile("hg.prof")
3409 try:
3410 try:
3410 try:
3411 try:
3411 return prof.runcall(d)
3412 return prof.runcall(d)
3412 except:
3413 except:
3413 try:
3414 try:
3414 u.warn(_('exception raised - generating '
3415 u.warn(_('exception raised - generating '
3415 'profile anyway\n'))
3416 'profile anyway\n'))
3416 except:
3417 except:
3417 pass
3418 pass
3418 raise
3419 raise
3419 finally:
3420 finally:
3420 prof.close()
3421 prof.close()
3421 stats = hotshot.stats.load("hg.prof")
3422 stats = hotshot.stats.load("hg.prof")
3422 stats.strip_dirs()
3423 stats.strip_dirs()
3423 stats.sort_stats('time', 'calls')
3424 stats.sort_stats('time', 'calls')
3424 stats.print_stats(40)
3425 stats.print_stats(40)
3425 elif options['lsprof']:
3426 elif options['lsprof']:
3426 try:
3427 try:
3427 from mercurial import lsprof
3428 from mercurial import lsprof
3428 except ImportError:
3429 except ImportError:
3429 raise util.Abort(_(
3430 raise util.Abort(_(
3430 'lsprof not available - install from '
3431 'lsprof not available - install from '
3431 'http://codespeak.net/svn/user/arigo/hack/misc/lsprof/'))
3432 'http://codespeak.net/svn/user/arigo/hack/misc/lsprof/'))
3432 p = lsprof.Profiler()
3433 p = lsprof.Profiler()
3433 p.enable(subcalls=True)
3434 p.enable(subcalls=True)
3434 try:
3435 try:
3435 return d()
3436 return d()
3436 finally:
3437 finally:
3437 p.disable()
3438 p.disable()
3438 stats = lsprof.Stats(p.getstats())
3439 stats = lsprof.Stats(p.getstats())
3439 stats.sort()
3440 stats.sort()
3440 stats.pprint(top=10, file=sys.stderr, climit=5)
3441 stats.pprint(top=10, file=sys.stderr, climit=5)
3441 else:
3442 else:
3442 return d()
3443 return d()
3443 finally:
3444 finally:
3444 u.flush()
3445 u.flush()
3445 except:
3446 except:
3446 # enter the debugger when we hit an exception
3447 # enter the debugger when we hit an exception
3447 if options['debugger']:
3448 if options['debugger']:
3448 pdb.post_mortem(sys.exc_info()[2])
3449 pdb.post_mortem(sys.exc_info()[2])
3449 u.print_exc()
3450 u.print_exc()
3450 raise
3451 raise
3451 except ParseError, inst:
3452 except ParseError, inst:
3452 if inst.args[0]:
3453 if inst.args[0]:
3453 u.warn(_("hg %s: %s\n") % (inst.args[0], inst.args[1]))
3454 u.warn(_("hg %s: %s\n") % (inst.args[0], inst.args[1]))
3454 help_(u, inst.args[0])
3455 help_(u, inst.args[0])
3455 else:
3456 else:
3456 u.warn(_("hg: %s\n") % inst.args[1])
3457 u.warn(_("hg: %s\n") % inst.args[1])
3457 help_(u, 'shortlist')
3458 help_(u, 'shortlist')
3458 except AmbiguousCommand, inst:
3459 except AmbiguousCommand, inst:
3459 u.warn(_("hg: command '%s' is ambiguous:\n %s\n") %
3460 u.warn(_("hg: command '%s' is ambiguous:\n %s\n") %
3460 (inst.args[0], " ".join(inst.args[1])))
3461 (inst.args[0], " ".join(inst.args[1])))
3461 except UnknownCommand, inst:
3462 except UnknownCommand, inst:
3462 u.warn(_("hg: unknown command '%s'\n") % inst.args[0])
3463 u.warn(_("hg: unknown command '%s'\n") % inst.args[0])
3463 help_(u, 'shortlist')
3464 help_(u, 'shortlist')
3464 except hg.RepoError, inst:
3465 except hg.RepoError, inst:
3465 u.warn(_("abort: %s!\n") % inst)
3466 u.warn(_("abort: %s!\n") % inst)
3466 except lock.LockHeld, inst:
3467 except lock.LockHeld, inst:
3467 if inst.errno == errno.ETIMEDOUT:
3468 if inst.errno == errno.ETIMEDOUT:
3468 reason = _('timed out waiting for lock held by %s') % inst.locker
3469 reason = _('timed out waiting for lock held by %s') % inst.locker
3469 else:
3470 else:
3470 reason = _('lock held by %s') % inst.locker
3471 reason = _('lock held by %s') % inst.locker
3471 u.warn(_("abort: %s: %s\n") % (inst.desc or inst.filename, reason))
3472 u.warn(_("abort: %s: %s\n") % (inst.desc or inst.filename, reason))
3472 except lock.LockUnavailable, inst:
3473 except lock.LockUnavailable, inst:
3473 u.warn(_("abort: could not lock %s: %s\n") %
3474 u.warn(_("abort: could not lock %s: %s\n") %
3474 (inst.desc or inst.filename, inst.strerror))
3475 (inst.desc or inst.filename, inst.strerror))
3475 except revlog.RevlogError, inst:
3476 except revlog.RevlogError, inst:
3476 u.warn(_("abort: %s!\n") % inst)
3477 u.warn(_("abort: %s!\n") % inst)
3477 except util.SignalInterrupt:
3478 except util.SignalInterrupt:
3478 u.warn(_("killed!\n"))
3479 u.warn(_("killed!\n"))
3479 except KeyboardInterrupt:
3480 except KeyboardInterrupt:
3480 try:
3481 try:
3481 u.warn(_("interrupted!\n"))
3482 u.warn(_("interrupted!\n"))
3482 except IOError, inst:
3483 except IOError, inst:
3483 if inst.errno == errno.EPIPE:
3484 if inst.errno == errno.EPIPE:
3484 if u.debugflag:
3485 if u.debugflag:
3485 u.warn(_("\nbroken pipe\n"))
3486 u.warn(_("\nbroken pipe\n"))
3486 else:
3487 else:
3487 raise
3488 raise
3488 except IOError, inst:
3489 except IOError, inst:
3489 if hasattr(inst, "code"):
3490 if hasattr(inst, "code"):
3490 u.warn(_("abort: %s\n") % inst)
3491 u.warn(_("abort: %s\n") % inst)
3491 elif hasattr(inst, "reason"):
3492 elif hasattr(inst, "reason"):
3492 u.warn(_("abort: error: %s\n") % inst.reason[1])
3493 u.warn(_("abort: error: %s\n") % inst.reason[1])
3493 elif hasattr(inst, "args") and inst[0] == errno.EPIPE:
3494 elif hasattr(inst, "args") and inst[0] == errno.EPIPE:
3494 if u.debugflag:
3495 if u.debugflag:
3495 u.warn(_("broken pipe\n"))
3496 u.warn(_("broken pipe\n"))
3496 elif getattr(inst, "strerror", None):
3497 elif getattr(inst, "strerror", None):
3497 if getattr(inst, "filename", None):
3498 if getattr(inst, "filename", None):
3498 u.warn(_("abort: %s: %s\n") % (inst.strerror, inst.filename))
3499 u.warn(_("abort: %s: %s\n") % (inst.strerror, inst.filename))
3499 else:
3500 else:
3500 u.warn(_("abort: %s\n") % inst.strerror)
3501 u.warn(_("abort: %s\n") % inst.strerror)
3501 else:
3502 else:
3502 raise
3503 raise
3503 except OSError, inst:
3504 except OSError, inst:
3504 if getattr(inst, "filename", None):
3505 if getattr(inst, "filename", None):
3505 u.warn(_("abort: %s: %s\n") % (inst.strerror, inst.filename))
3506 u.warn(_("abort: %s: %s\n") % (inst.strerror, inst.filename))
3506 else:
3507 else:
3507 u.warn(_("abort: %s\n") % inst.strerror)
3508 u.warn(_("abort: %s\n") % inst.strerror)
3508 except util.UnexpectedOutput, inst:
3509 except util.UnexpectedOutput, inst:
3509 u.warn(_("abort: %s") % inst[0])
3510 u.warn(_("abort: %s") % inst[0])
3510 if not isinstance(inst[1], basestring):
3511 if not isinstance(inst[1], basestring):
3511 u.warn(" %r\n" % (inst[1],))
3512 u.warn(" %r\n" % (inst[1],))
3512 elif not inst[1]:
3513 elif not inst[1]:
3513 u.warn(_(" empty string\n"))
3514 u.warn(_(" empty string\n"))
3514 else:
3515 else:
3515 u.warn("\n%r%s\n" %
3516 u.warn("\n%r%s\n" %
3516 (inst[1][:400], len(inst[1]) > 400 and '...' or ''))
3517 (inst[1][:400], len(inst[1]) > 400 and '...' or ''))
3517 except util.Abort, inst:
3518 except util.Abort, inst:
3518 u.warn(_("abort: %s\n") % inst)
3519 u.warn(_("abort: %s\n") % inst)
3519 except TypeError, inst:
3520 except TypeError, inst:
3520 # was this an argument error?
3521 # was this an argument error?
3521 tb = traceback.extract_tb(sys.exc_info()[2])
3522 tb = traceback.extract_tb(sys.exc_info()[2])
3522 if len(tb) > 2: # no
3523 if len(tb) > 2: # no
3523 raise
3524 raise
3524 u.debug(inst, "\n")
3525 u.debug(inst, "\n")
3525 u.warn(_("%s: invalid arguments\n") % cmd)
3526 u.warn(_("%s: invalid arguments\n") % cmd)
3526 help_(u, cmd)
3527 help_(u, cmd)
3527 except SystemExit, inst:
3528 except SystemExit, inst:
3528 # Commands shouldn't sys.exit directly, but give a return code.
3529 # Commands shouldn't sys.exit directly, but give a return code.
3529 # Just in case catch this and and pass exit code to caller.
3530 # Just in case catch this and and pass exit code to caller.
3530 return inst.code
3531 return inst.code
3531 except:
3532 except:
3532 u.warn(_("** unknown exception encountered, details follow\n"))
3533 u.warn(_("** unknown exception encountered, details follow\n"))
3533 u.warn(_("** report bug details to "
3534 u.warn(_("** report bug details to "
3534 "http://www.selenic.com/mercurial/bts\n"))
3535 "http://www.selenic.com/mercurial/bts\n"))
3535 u.warn(_("** or mercurial@selenic.com\n"))
3536 u.warn(_("** or mercurial@selenic.com\n"))
3536 u.warn(_("** Mercurial Distributed SCM (version %s)\n")
3537 u.warn(_("** Mercurial Distributed SCM (version %s)\n")
3537 % version.get_version())
3538 % version.get_version())
3538 raise
3539 raise
3539
3540
3540 return -1
3541 return -1
General Comments 0
You need to be logged in to leave comments. Login now