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