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