##// END OF EJS Templates
Show ambiguous aliases, if they are not simple abbreviations. Sort output.
Thomas Arendsen Hein -
r1849:360d0f8d default
parent child Browse files
Show More
@@ -1,2960 +1,2967 b''
1 # commands.py - command processing for mercurial
1 # commands.py - command processing for mercurial
2 #
2 #
3 # Copyright 2005 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005 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")
11 demandload(globals(), "os re sys signal shutil imp urllib pdb")
12 demandload(globals(), "fancyopts ui hg util lock revlog")
12 demandload(globals(), "fancyopts ui hg util lock revlog")
13 demandload(globals(), "fnmatch hgweb mdiff random signal time traceback")
13 demandload(globals(), "fnmatch hgweb mdiff random signal time traceback")
14 demandload(globals(), "errno socket version struct atexit sets bz2")
14 demandload(globals(), "errno socket version struct atexit sets bz2")
15
15
16 class UnknownCommand(Exception):
16 class UnknownCommand(Exception):
17 """Exception raised if command is not in the command table."""
17 """Exception raised if command is not in the command table."""
18 class AmbiguousCommand(Exception):
18 class AmbiguousCommand(Exception):
19 """Exception raised if command shortcut matches more than one command."""
19 """Exception raised if command shortcut matches more than one command."""
20
20
21 def filterfiles(filters, files):
21 def filterfiles(filters, files):
22 l = [x for x in files if x in filters]
22 l = [x for x in files if x in filters]
23
23
24 for t in filters:
24 for t in filters:
25 if t and t[-1] != "/":
25 if t and t[-1] != "/":
26 t += "/"
26 t += "/"
27 l += [x for x in files if x.startswith(t)]
27 l += [x for x in files if x.startswith(t)]
28 return l
28 return l
29
29
30 def relpath(repo, args):
30 def relpath(repo, args):
31 cwd = repo.getcwd()
31 cwd = repo.getcwd()
32 if cwd:
32 if cwd:
33 return [util.normpath(os.path.join(cwd, x)) for x in args]
33 return [util.normpath(os.path.join(cwd, x)) for x in args]
34 return args
34 return args
35
35
36 def matchpats(repo, pats=[], opts={}, head=''):
36 def matchpats(repo, pats=[], opts={}, head=''):
37 cwd = repo.getcwd()
37 cwd = repo.getcwd()
38 if not pats and cwd:
38 if not pats and cwd:
39 opts['include'] = [os.path.join(cwd, i) for i in opts['include']]
39 opts['include'] = [os.path.join(cwd, i) for i in opts['include']]
40 opts['exclude'] = [os.path.join(cwd, x) for x in opts['exclude']]
40 opts['exclude'] = [os.path.join(cwd, x) for x in opts['exclude']]
41 cwd = ''
41 cwd = ''
42 return util.cmdmatcher(repo.root, cwd, pats or ['.'], opts.get('include'),
42 return util.cmdmatcher(repo.root, cwd, pats or ['.'], opts.get('include'),
43 opts.get('exclude'), head)
43 opts.get('exclude'), head)
44
44
45 def makewalk(repo, pats, opts, node=None, head=''):
45 def makewalk(repo, pats, opts, node=None, head=''):
46 files, matchfn, anypats = matchpats(repo, pats, opts, head)
46 files, matchfn, anypats = matchpats(repo, pats, opts, head)
47 exact = dict(zip(files, files))
47 exact = dict(zip(files, files))
48 def walk():
48 def walk():
49 for src, fn in repo.walk(node=node, files=files, match=matchfn):
49 for src, fn in repo.walk(node=node, files=files, match=matchfn):
50 yield src, fn, util.pathto(repo.getcwd(), fn), fn in exact
50 yield src, fn, util.pathto(repo.getcwd(), fn), fn in exact
51 return files, matchfn, walk()
51 return files, matchfn, walk()
52
52
53 def walk(repo, pats, opts, node=None, head=''):
53 def walk(repo, pats, opts, node=None, head=''):
54 files, matchfn, results = makewalk(repo, pats, opts, node, head)
54 files, matchfn, results = makewalk(repo, pats, opts, node, head)
55 for r in results:
55 for r in results:
56 yield r
56 yield r
57
57
58 def walkchangerevs(ui, repo, pats, opts):
58 def walkchangerevs(ui, repo, pats, opts):
59 '''Iterate over files and the revs they changed in.
59 '''Iterate over files and the revs they changed in.
60
60
61 Callers most commonly need to iterate backwards over the history
61 Callers most commonly need to iterate backwards over the history
62 it is interested in. Doing so has awful (quadratic-looking)
62 it is interested in. Doing so has awful (quadratic-looking)
63 performance, so we use iterators in a "windowed" way.
63 performance, so we use iterators in a "windowed" way.
64
64
65 We walk a window of revisions in the desired order. Within the
65 We walk a window of revisions in the desired order. Within the
66 window, we first walk forwards to gather data, then in the desired
66 window, we first walk forwards to gather data, then in the desired
67 order (usually backwards) to display it.
67 order (usually backwards) to display it.
68
68
69 This function returns an (iterator, getchange, matchfn) tuple. The
69 This function returns an (iterator, getchange, matchfn) tuple. The
70 getchange function returns the changelog entry for a numeric
70 getchange function returns the changelog entry for a numeric
71 revision. The iterator yields 3-tuples. They will be of one of
71 revision. The iterator yields 3-tuples. They will be of one of
72 the following forms:
72 the following forms:
73
73
74 "window", incrementing, lastrev: stepping through a window,
74 "window", incrementing, lastrev: stepping through a window,
75 positive if walking forwards through revs, last rev in the
75 positive if walking forwards through revs, last rev in the
76 sequence iterated over - use to reset state for the current window
76 sequence iterated over - use to reset state for the current window
77
77
78 "add", rev, fns: out-of-order traversal of the given file names
78 "add", rev, fns: out-of-order traversal of the given file names
79 fns, which changed during revision rev - use to gather data for
79 fns, which changed during revision rev - use to gather data for
80 possible display
80 possible display
81
81
82 "iter", rev, None: in-order traversal of the revs earlier iterated
82 "iter", rev, None: in-order traversal of the revs earlier iterated
83 over with "add" - use to display data'''
83 over with "add" - use to display data'''
84
84
85 def increasing_windows(start, end, windowsize=8, sizelimit=512):
85 def increasing_windows(start, end, windowsize=8, sizelimit=512):
86 if start < end:
86 if start < end:
87 while start < end:
87 while start < end:
88 yield start, min(windowsize, end-start)
88 yield start, min(windowsize, end-start)
89 start += windowsize
89 start += windowsize
90 if windowsize < sizelimit:
90 if windowsize < sizelimit:
91 windowsize *= 2
91 windowsize *= 2
92 else:
92 else:
93 while start > end:
93 while start > end:
94 yield start, min(windowsize, start-end-1)
94 yield start, min(windowsize, start-end-1)
95 start -= windowsize
95 start -= windowsize
96 if windowsize < sizelimit:
96 if windowsize < sizelimit:
97 windowsize *= 2
97 windowsize *= 2
98
98
99
99
100 files, matchfn, anypats = matchpats(repo, pats, opts)
100 files, matchfn, anypats = matchpats(repo, pats, opts)
101
101
102 if repo.changelog.count() == 0:
102 if repo.changelog.count() == 0:
103 return [], False, matchfn
103 return [], False, matchfn
104
104
105 revs = map(int, revrange(ui, repo, opts['rev'] or ['tip:0']))
105 revs = map(int, revrange(ui, repo, opts['rev'] or ['tip:0']))
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 if not slowpath:
120 if not slowpath:
121 # Only files, no patterns. Check the history of each file.
121 # Only files, no patterns. Check the history of each file.
122 def filerevgen(filelog):
122 def filerevgen(filelog):
123 for i, window in increasing_windows(filelog.count()-1, -1):
123 for i, window in increasing_windows(filelog.count()-1, -1):
124 revs = []
124 revs = []
125 for j in xrange(i - window, i + 1):
125 for j in xrange(i - window, i + 1):
126 revs.append(filelog.linkrev(filelog.node(j)))
126 revs.append(filelog.linkrev(filelog.node(j)))
127 revs.reverse()
127 revs.reverse()
128 for rev in revs:
128 for rev in revs:
129 yield rev
129 yield rev
130
130
131 minrev, maxrev = min(revs), max(revs)
131 minrev, maxrev = min(revs), max(revs)
132 for file_ in files:
132 for file_ in files:
133 filelog = repo.file(file_)
133 filelog = repo.file(file_)
134 # A zero count may be a directory or deleted file, so
134 # A zero count may be a directory or deleted file, so
135 # try to find matching entries on the slow path.
135 # try to find matching entries on the slow path.
136 if filelog.count() == 0:
136 if filelog.count() == 0:
137 slowpath = True
137 slowpath = True
138 break
138 break
139 for rev in filerevgen(filelog):
139 for rev in filerevgen(filelog):
140 if rev <= maxrev:
140 if rev <= maxrev:
141 if rev < minrev:
141 if rev < minrev:
142 break
142 break
143 fncache.setdefault(rev, [])
143 fncache.setdefault(rev, [])
144 fncache[rev].append(file_)
144 fncache[rev].append(file_)
145 wanted[rev] = 1
145 wanted[rev] = 1
146 if slowpath:
146 if slowpath:
147 # The slow path checks files modified in every changeset.
147 # The slow path checks files modified in every changeset.
148 def changerevgen():
148 def changerevgen():
149 for i, window in increasing_windows(repo.changelog.count()-1, -1):
149 for i, window in increasing_windows(repo.changelog.count()-1, -1):
150 for j in xrange(i - window, i + 1):
150 for j in xrange(i - window, i + 1):
151 yield j, getchange(j)[3]
151 yield j, getchange(j)[3]
152
152
153 for rev, changefiles in changerevgen():
153 for rev, changefiles in changerevgen():
154 matches = filter(matchfn, changefiles)
154 matches = filter(matchfn, changefiles)
155 if matches:
155 if matches:
156 fncache[rev] = matches
156 fncache[rev] = matches
157 wanted[rev] = 1
157 wanted[rev] = 1
158
158
159 def iterate():
159 def iterate():
160 for i, window in increasing_windows(0, len(revs)):
160 for i, window in increasing_windows(0, len(revs)):
161 yield 'window', revs[0] < revs[-1], revs[-1]
161 yield 'window', revs[0] < revs[-1], revs[-1]
162 nrevs = [rev for rev in revs[i:i+window]
162 nrevs = [rev for rev in revs[i:i+window]
163 if rev in wanted]
163 if rev in wanted]
164 srevs = list(nrevs)
164 srevs = list(nrevs)
165 srevs.sort()
165 srevs.sort()
166 for rev in srevs:
166 for rev in srevs:
167 fns = fncache.get(rev) or filter(matchfn, getchange(rev)[3])
167 fns = fncache.get(rev) or filter(matchfn, getchange(rev)[3])
168 yield 'add', rev, fns
168 yield 'add', rev, fns
169 for rev in nrevs:
169 for rev in nrevs:
170 yield 'iter', rev, None
170 yield 'iter', rev, None
171 return iterate(), getchange, matchfn
171 return iterate(), getchange, matchfn
172
172
173 revrangesep = ':'
173 revrangesep = ':'
174
174
175 def revrange(ui, repo, revs, revlog=None):
175 def revrange(ui, repo, revs, revlog=None):
176 """Yield revision as strings from a list of revision specifications."""
176 """Yield revision as strings from a list of revision specifications."""
177 if revlog is None:
177 if revlog is None:
178 revlog = repo.changelog
178 revlog = repo.changelog
179 revcount = revlog.count()
179 revcount = revlog.count()
180 def fix(val, defval):
180 def fix(val, defval):
181 if not val:
181 if not val:
182 return defval
182 return defval
183 try:
183 try:
184 num = int(val)
184 num = int(val)
185 if str(num) != val:
185 if str(num) != val:
186 raise ValueError
186 raise ValueError
187 if num < 0:
187 if num < 0:
188 num += revcount
188 num += revcount
189 if num < 0:
189 if num < 0:
190 num = 0
190 num = 0
191 elif num >= revcount:
191 elif num >= revcount:
192 raise ValueError
192 raise ValueError
193 except ValueError:
193 except ValueError:
194 try:
194 try:
195 num = repo.changelog.rev(repo.lookup(val))
195 num = repo.changelog.rev(repo.lookup(val))
196 except KeyError:
196 except KeyError:
197 try:
197 try:
198 num = revlog.rev(revlog.lookup(val))
198 num = revlog.rev(revlog.lookup(val))
199 except KeyError:
199 except KeyError:
200 raise util.Abort(_('invalid revision identifier %s'), val)
200 raise util.Abort(_('invalid revision identifier %s'), val)
201 return num
201 return num
202 seen = {}
202 seen = {}
203 for spec in revs:
203 for spec in revs:
204 if spec.find(revrangesep) >= 0:
204 if spec.find(revrangesep) >= 0:
205 start, end = spec.split(revrangesep, 1)
205 start, end = spec.split(revrangesep, 1)
206 start = fix(start, 0)
206 start = fix(start, 0)
207 end = fix(end, revcount - 1)
207 end = fix(end, revcount - 1)
208 step = start > end and -1 or 1
208 step = start > end and -1 or 1
209 for rev in xrange(start, end+step, step):
209 for rev in xrange(start, end+step, step):
210 if rev in seen:
210 if rev in seen:
211 continue
211 continue
212 seen[rev] = 1
212 seen[rev] = 1
213 yield str(rev)
213 yield str(rev)
214 else:
214 else:
215 rev = fix(spec, None)
215 rev = fix(spec, None)
216 if rev in seen:
216 if rev in seen:
217 continue
217 continue
218 seen[rev] = 1
218 seen[rev] = 1
219 yield str(rev)
219 yield str(rev)
220
220
221 def make_filename(repo, r, pat, node=None,
221 def make_filename(repo, r, pat, node=None,
222 total=None, seqno=None, revwidth=None, pathname=None):
222 total=None, seqno=None, revwidth=None, pathname=None):
223 node_expander = {
223 node_expander = {
224 'H': lambda: hex(node),
224 'H': lambda: hex(node),
225 'R': lambda: str(r.rev(node)),
225 'R': lambda: str(r.rev(node)),
226 'h': lambda: short(node),
226 'h': lambda: short(node),
227 }
227 }
228 expander = {
228 expander = {
229 '%': lambda: '%',
229 '%': lambda: '%',
230 'b': lambda: os.path.basename(repo.root),
230 'b': lambda: os.path.basename(repo.root),
231 }
231 }
232
232
233 try:
233 try:
234 if node:
234 if node:
235 expander.update(node_expander)
235 expander.update(node_expander)
236 if node and revwidth is not None:
236 if node and revwidth is not None:
237 expander['r'] = lambda: str(r.rev(node)).zfill(revwidth)
237 expander['r'] = lambda: str(r.rev(node)).zfill(revwidth)
238 if total is not None:
238 if total is not None:
239 expander['N'] = lambda: str(total)
239 expander['N'] = lambda: str(total)
240 if seqno is not None:
240 if seqno is not None:
241 expander['n'] = lambda: str(seqno)
241 expander['n'] = lambda: str(seqno)
242 if total is not None and seqno is not None:
242 if total is not None and seqno is not None:
243 expander['n'] = lambda:str(seqno).zfill(len(str(total)))
243 expander['n'] = lambda:str(seqno).zfill(len(str(total)))
244 if pathname is not None:
244 if pathname is not None:
245 expander['s'] = lambda: os.path.basename(pathname)
245 expander['s'] = lambda: os.path.basename(pathname)
246 expander['d'] = lambda: os.path.dirname(pathname) or '.'
246 expander['d'] = lambda: os.path.dirname(pathname) or '.'
247 expander['p'] = lambda: pathname
247 expander['p'] = lambda: pathname
248
248
249 newname = []
249 newname = []
250 patlen = len(pat)
250 patlen = len(pat)
251 i = 0
251 i = 0
252 while i < patlen:
252 while i < patlen:
253 c = pat[i]
253 c = pat[i]
254 if c == '%':
254 if c == '%':
255 i += 1
255 i += 1
256 c = pat[i]
256 c = pat[i]
257 c = expander[c]()
257 c = expander[c]()
258 newname.append(c)
258 newname.append(c)
259 i += 1
259 i += 1
260 return ''.join(newname)
260 return ''.join(newname)
261 except KeyError, inst:
261 except KeyError, inst:
262 raise util.Abort(_("invalid format spec '%%%s' in output file name"),
262 raise util.Abort(_("invalid format spec '%%%s' in output file name"),
263 inst.args[0])
263 inst.args[0])
264
264
265 def make_file(repo, r, pat, node=None,
265 def make_file(repo, r, pat, node=None,
266 total=None, seqno=None, revwidth=None, mode='wb', pathname=None):
266 total=None, seqno=None, revwidth=None, mode='wb', pathname=None):
267 if not pat or pat == '-':
267 if not pat or pat == '-':
268 return 'w' in mode and sys.stdout or sys.stdin
268 return 'w' in mode and sys.stdout or sys.stdin
269 if hasattr(pat, 'write') and 'w' in mode:
269 if hasattr(pat, 'write') and 'w' in mode:
270 return pat
270 return pat
271 if hasattr(pat, 'read') and 'r' in mode:
271 if hasattr(pat, 'read') and 'r' in mode:
272 return pat
272 return pat
273 return open(make_filename(repo, r, pat, node, total, seqno, revwidth,
273 return open(make_filename(repo, r, pat, node, total, seqno, revwidth,
274 pathname),
274 pathname),
275 mode)
275 mode)
276
276
277 def dodiff(fp, ui, repo, node1, node2, files=None, match=util.always,
277 def dodiff(fp, ui, repo, node1, node2, files=None, match=util.always,
278 changes=None, text=False, opts={}):
278 changes=None, text=False, opts={}):
279 if not node1:
279 if not node1:
280 node1 = repo.dirstate.parents()[0]
280 node1 = repo.dirstate.parents()[0]
281 # reading the data for node1 early allows it to play nicely
281 # reading the data for node1 early allows it to play nicely
282 # with repo.changes and the revlog cache.
282 # with repo.changes and the revlog cache.
283 change = repo.changelog.read(node1)
283 change = repo.changelog.read(node1)
284 mmap = repo.manifest.read(change[0])
284 mmap = repo.manifest.read(change[0])
285 date1 = util.datestr(change[2])
285 date1 = util.datestr(change[2])
286
286
287 if not changes:
287 if not changes:
288 changes = repo.changes(node1, node2, files, match=match)
288 changes = repo.changes(node1, node2, files, match=match)
289 modified, added, removed, deleted, unknown = changes
289 modified, added, removed, deleted, unknown = changes
290 if files:
290 if files:
291 modified, added, removed = map(lambda x: filterfiles(files, x),
291 modified, added, removed = map(lambda x: filterfiles(files, x),
292 (modified, added, removed))
292 (modified, added, removed))
293
293
294 if not modified and not added and not removed:
294 if not modified and not added and not removed:
295 return
295 return
296
296
297 if node2:
297 if node2:
298 change = repo.changelog.read(node2)
298 change = repo.changelog.read(node2)
299 mmap2 = repo.manifest.read(change[0])
299 mmap2 = repo.manifest.read(change[0])
300 date2 = util.datestr(change[2])
300 date2 = util.datestr(change[2])
301 def read(f):
301 def read(f):
302 return repo.file(f).read(mmap2[f])
302 return repo.file(f).read(mmap2[f])
303 else:
303 else:
304 date2 = util.datestr()
304 date2 = util.datestr()
305 def read(f):
305 def read(f):
306 return repo.wread(f)
306 return repo.wread(f)
307
307
308 if ui.quiet:
308 if ui.quiet:
309 r = None
309 r = None
310 else:
310 else:
311 hexfunc = ui.verbose and hex or short
311 hexfunc = ui.verbose and hex or short
312 r = [hexfunc(node) for node in [node1, node2] if node]
312 r = [hexfunc(node) for node in [node1, node2] if node]
313
313
314 diffopts = ui.diffopts()
314 diffopts = ui.diffopts()
315 showfunc = opts.get('show_function') or diffopts['showfunc']
315 showfunc = opts.get('show_function') or diffopts['showfunc']
316 ignorews = opts.get('ignore_all_space') or diffopts['ignorews']
316 ignorews = opts.get('ignore_all_space') or diffopts['ignorews']
317 for f in modified:
317 for f in modified:
318 to = None
318 to = None
319 if f in mmap:
319 if f in mmap:
320 to = repo.file(f).read(mmap[f])
320 to = repo.file(f).read(mmap[f])
321 tn = read(f)
321 tn = read(f)
322 fp.write(mdiff.unidiff(to, date1, tn, date2, f, r, text=text,
322 fp.write(mdiff.unidiff(to, date1, tn, date2, f, r, text=text,
323 showfunc=showfunc, ignorews=ignorews))
323 showfunc=showfunc, ignorews=ignorews))
324 for f in added:
324 for f in added:
325 to = None
325 to = None
326 tn = read(f)
326 tn = read(f)
327 fp.write(mdiff.unidiff(to, date1, tn, date2, f, r, text=text,
327 fp.write(mdiff.unidiff(to, date1, tn, date2, f, r, text=text,
328 showfunc=showfunc, ignorews=ignorews))
328 showfunc=showfunc, ignorews=ignorews))
329 for f in removed:
329 for f in removed:
330 to = repo.file(f).read(mmap[f])
330 to = repo.file(f).read(mmap[f])
331 tn = None
331 tn = None
332 fp.write(mdiff.unidiff(to, date1, tn, date2, f, r, text=text,
332 fp.write(mdiff.unidiff(to, date1, tn, date2, f, r, text=text,
333 showfunc=showfunc, ignorews=ignorews))
333 showfunc=showfunc, ignorews=ignorews))
334
334
335 def trimuser(ui, name, rev, revcache):
335 def trimuser(ui, name, rev, revcache):
336 """trim the name of the user who committed a change"""
336 """trim the name of the user who committed a change"""
337 user = revcache.get(rev)
337 user = revcache.get(rev)
338 if user is None:
338 if user is None:
339 user = revcache[rev] = ui.shortuser(name)
339 user = revcache[rev] = ui.shortuser(name)
340 return user
340 return user
341
341
342 def show_changeset(ui, repo, rev=0, changenode=None, brinfo=None):
342 def show_changeset(ui, repo, rev=0, changenode=None, brinfo=None):
343 """show a single changeset or file revision"""
343 """show a single changeset or file revision"""
344 log = repo.changelog
344 log = repo.changelog
345 if changenode is None:
345 if changenode is None:
346 changenode = log.node(rev)
346 changenode = log.node(rev)
347 elif not rev:
347 elif not rev:
348 rev = log.rev(changenode)
348 rev = log.rev(changenode)
349
349
350 if ui.quiet:
350 if ui.quiet:
351 ui.write("%d:%s\n" % (rev, short(changenode)))
351 ui.write("%d:%s\n" % (rev, short(changenode)))
352 return
352 return
353
353
354 changes = log.read(changenode)
354 changes = log.read(changenode)
355 date = util.datestr(changes[2])
355 date = util.datestr(changes[2])
356
356
357 parents = [(log.rev(p), ui.verbose and hex(p) or short(p))
357 parents = [(log.rev(p), ui.verbose and hex(p) or short(p))
358 for p in log.parents(changenode)
358 for p in log.parents(changenode)
359 if ui.debugflag or p != nullid]
359 if ui.debugflag or p != nullid]
360 if not ui.debugflag and len(parents) == 1 and parents[0][0] == rev-1:
360 if not ui.debugflag and len(parents) == 1 and parents[0][0] == rev-1:
361 parents = []
361 parents = []
362
362
363 if ui.verbose:
363 if ui.verbose:
364 ui.write(_("changeset: %d:%s\n") % (rev, hex(changenode)))
364 ui.write(_("changeset: %d:%s\n") % (rev, hex(changenode)))
365 else:
365 else:
366 ui.write(_("changeset: %d:%s\n") % (rev, short(changenode)))
366 ui.write(_("changeset: %d:%s\n") % (rev, short(changenode)))
367
367
368 for tag in repo.nodetags(changenode):
368 for tag in repo.nodetags(changenode):
369 ui.status(_("tag: %s\n") % tag)
369 ui.status(_("tag: %s\n") % tag)
370 for parent in parents:
370 for parent in parents:
371 ui.write(_("parent: %d:%s\n") % parent)
371 ui.write(_("parent: %d:%s\n") % parent)
372
372
373 if brinfo and changenode in brinfo:
373 if brinfo and changenode in brinfo:
374 br = brinfo[changenode]
374 br = brinfo[changenode]
375 ui.write(_("branch: %s\n") % " ".join(br))
375 ui.write(_("branch: %s\n") % " ".join(br))
376
376
377 ui.debug(_("manifest: %d:%s\n") % (repo.manifest.rev(changes[0]),
377 ui.debug(_("manifest: %d:%s\n") % (repo.manifest.rev(changes[0]),
378 hex(changes[0])))
378 hex(changes[0])))
379 ui.status(_("user: %s\n") % changes[1])
379 ui.status(_("user: %s\n") % changes[1])
380 ui.status(_("date: %s\n") % date)
380 ui.status(_("date: %s\n") % date)
381
381
382 if ui.debugflag:
382 if ui.debugflag:
383 files = repo.changes(log.parents(changenode)[0], changenode)
383 files = repo.changes(log.parents(changenode)[0], changenode)
384 for key, value in zip([_("files:"), _("files+:"), _("files-:")], files):
384 for key, value in zip([_("files:"), _("files+:"), _("files-:")], files):
385 if value:
385 if value:
386 ui.note("%-12s %s\n" % (key, " ".join(value)))
386 ui.note("%-12s %s\n" % (key, " ".join(value)))
387 else:
387 else:
388 ui.note(_("files: %s\n") % " ".join(changes[3]))
388 ui.note(_("files: %s\n") % " ".join(changes[3]))
389
389
390 description = changes[4].strip()
390 description = changes[4].strip()
391 if description:
391 if description:
392 if ui.verbose:
392 if ui.verbose:
393 ui.status(_("description:\n"))
393 ui.status(_("description:\n"))
394 ui.status(description)
394 ui.status(description)
395 ui.status("\n\n")
395 ui.status("\n\n")
396 else:
396 else:
397 ui.status(_("summary: %s\n") % description.splitlines()[0])
397 ui.status(_("summary: %s\n") % description.splitlines()[0])
398 ui.status("\n")
398 ui.status("\n")
399
399
400 def show_version(ui):
400 def show_version(ui):
401 """output version and copyright information"""
401 """output version and copyright information"""
402 ui.write(_("Mercurial Distributed SCM (version %s)\n")
402 ui.write(_("Mercurial Distributed SCM (version %s)\n")
403 % version.get_version())
403 % version.get_version())
404 ui.status(_(
404 ui.status(_(
405 "\nCopyright (C) 2005 Matt Mackall <mpm@selenic.com>\n"
405 "\nCopyright (C) 2005 Matt Mackall <mpm@selenic.com>\n"
406 "This is free software; see the source for copying conditions. "
406 "This is free software; see the source for copying conditions. "
407 "There is NO\nwarranty; "
407 "There is NO\nwarranty; "
408 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
408 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
409 ))
409 ))
410
410
411 def help_(ui, cmd=None, with_version=False):
411 def help_(ui, cmd=None, with_version=False):
412 """show help for a given command or all commands"""
412 """show help for a given command or all commands"""
413 option_lists = []
413 option_lists = []
414 if cmd and cmd != 'shortlist':
414 if cmd and cmd != 'shortlist':
415 if with_version:
415 if with_version:
416 show_version(ui)
416 show_version(ui)
417 ui.write('\n')
417 ui.write('\n')
418 aliases, i = find(cmd)
418 aliases, i = find(cmd)
419 # synopsis
419 # synopsis
420 ui.write("%s\n\n" % i[2])
420 ui.write("%s\n\n" % i[2])
421
421
422 # description
422 # description
423 doc = i[0].__doc__
423 doc = i[0].__doc__
424 if not doc:
424 if not doc:
425 doc = _("(No help text available)")
425 doc = _("(No help text available)")
426 if ui.quiet:
426 if ui.quiet:
427 doc = doc.splitlines(0)[0]
427 doc = doc.splitlines(0)[0]
428 ui.write("%s\n" % doc.rstrip())
428 ui.write("%s\n" % doc.rstrip())
429
429
430 if not ui.quiet:
430 if not ui.quiet:
431 # aliases
431 # aliases
432 if len(aliases) > 1:
432 if len(aliases) > 1:
433 ui.write(_("\naliases: %s\n") % ', '.join(aliases[1:]))
433 ui.write(_("\naliases: %s\n") % ', '.join(aliases[1:]))
434
434
435 # options
435 # options
436 if i[1]:
436 if i[1]:
437 option_lists.append(("options", i[1]))
437 option_lists.append(("options", i[1]))
438
438
439 else:
439 else:
440 # program name
440 # program name
441 if ui.verbose or with_version:
441 if ui.verbose or with_version:
442 show_version(ui)
442 show_version(ui)
443 else:
443 else:
444 ui.status(_("Mercurial Distributed SCM\n"))
444 ui.status(_("Mercurial Distributed SCM\n"))
445 ui.status('\n')
445 ui.status('\n')
446
446
447 # list of commands
447 # list of commands
448 if cmd == "shortlist":
448 if cmd == "shortlist":
449 ui.status(_('basic commands (use "hg help" '
449 ui.status(_('basic commands (use "hg help" '
450 'for the full list or option "-v" for details):\n\n'))
450 'for the full list or option "-v" for details):\n\n'))
451 elif ui.verbose:
451 elif ui.verbose:
452 ui.status(_('list of commands:\n\n'))
452 ui.status(_('list of commands:\n\n'))
453 else:
453 else:
454 ui.status(_('list of commands (use "hg help -v" '
454 ui.status(_('list of commands (use "hg help -v" '
455 'to show aliases and global options):\n\n'))
455 'to show aliases and global options):\n\n'))
456
456
457 h = {}
457 h = {}
458 cmds = {}
458 cmds = {}
459 for c, e in table.items():
459 for c, e in table.items():
460 f = c.split("|")[0]
460 f = c.split("|")[0]
461 if cmd == "shortlist" and not f.startswith("^"):
461 if cmd == "shortlist" and not f.startswith("^"):
462 continue
462 continue
463 f = f.lstrip("^")
463 f = f.lstrip("^")
464 if not ui.debugflag and f.startswith("debug"):
464 if not ui.debugflag and f.startswith("debug"):
465 continue
465 continue
466 doc = e[0].__doc__
466 doc = e[0].__doc__
467 if not doc:
467 if not doc:
468 doc = _("(No help text available)")
468 doc = _("(No help text available)")
469 h[f] = doc.splitlines(0)[0].rstrip()
469 h[f] = doc.splitlines(0)[0].rstrip()
470 cmds[f] = c.lstrip("^")
470 cmds[f] = c.lstrip("^")
471
471
472 fns = h.keys()
472 fns = h.keys()
473 fns.sort()
473 fns.sort()
474 m = max(map(len, fns))
474 m = max(map(len, fns))
475 for f in fns:
475 for f in fns:
476 if ui.verbose:
476 if ui.verbose:
477 commands = cmds[f].replace("|",", ")
477 commands = cmds[f].replace("|",", ")
478 ui.write(" %s:\n %s\n"%(commands, h[f]))
478 ui.write(" %s:\n %s\n"%(commands, h[f]))
479 else:
479 else:
480 ui.write(' %-*s %s\n' % (m, f, h[f]))
480 ui.write(' %-*s %s\n' % (m, f, h[f]))
481
481
482 # global options
482 # global options
483 if ui.verbose:
483 if ui.verbose:
484 option_lists.append(("global options", globalopts))
484 option_lists.append(("global options", globalopts))
485
485
486 # list all option lists
486 # list all option lists
487 opt_output = []
487 opt_output = []
488 for title, options in option_lists:
488 for title, options in option_lists:
489 opt_output.append(("\n%s:\n" % title, None))
489 opt_output.append(("\n%s:\n" % title, None))
490 for shortopt, longopt, default, desc in options:
490 for shortopt, longopt, default, desc in options:
491 opt_output.append(("%2s%s" % (shortopt and "-%s" % shortopt,
491 opt_output.append(("%2s%s" % (shortopt and "-%s" % shortopt,
492 longopt and " --%s" % longopt),
492 longopt and " --%s" % longopt),
493 "%s%s" % (desc,
493 "%s%s" % (desc,
494 default
494 default
495 and _(" (default: %s)") % default
495 and _(" (default: %s)") % default
496 or "")))
496 or "")))
497
497
498 if opt_output:
498 if opt_output:
499 opts_len = max([len(line[0]) for line in opt_output if line[1]])
499 opts_len = max([len(line[0]) for line in opt_output if line[1]])
500 for first, second in opt_output:
500 for first, second in opt_output:
501 if second:
501 if second:
502 ui.write(" %-*s %s\n" % (opts_len, first, second))
502 ui.write(" %-*s %s\n" % (opts_len, first, second))
503 else:
503 else:
504 ui.write("%s\n" % first)
504 ui.write("%s\n" % first)
505
505
506 # Commands start here, listed alphabetically
506 # Commands start here, listed alphabetically
507
507
508 def add(ui, repo, *pats, **opts):
508 def add(ui, repo, *pats, **opts):
509 """add the specified files on the next commit
509 """add the specified files on the next commit
510
510
511 Schedule files to be version controlled and added to the repository.
511 Schedule files to be version controlled and added to the repository.
512
512
513 The files will be added to the repository at the next commit.
513 The files will be added to the repository at the next commit.
514
514
515 If no names are given, add all files in the repository.
515 If no names are given, add all files in the repository.
516 """
516 """
517
517
518 names = []
518 names = []
519 for src, abs, rel, exact in walk(repo, pats, opts):
519 for src, abs, rel, exact in walk(repo, pats, opts):
520 if exact:
520 if exact:
521 if ui.verbose:
521 if ui.verbose:
522 ui.status(_('adding %s\n') % rel)
522 ui.status(_('adding %s\n') % rel)
523 names.append(abs)
523 names.append(abs)
524 elif repo.dirstate.state(abs) == '?':
524 elif repo.dirstate.state(abs) == '?':
525 ui.status(_('adding %s\n') % rel)
525 ui.status(_('adding %s\n') % rel)
526 names.append(abs)
526 names.append(abs)
527 repo.add(names)
527 repo.add(names)
528
528
529 def addremove(ui, repo, *pats, **opts):
529 def addremove(ui, repo, *pats, **opts):
530 """add all new files, delete all missing files
530 """add all new files, delete all missing files
531
531
532 Add all new files and remove all missing files from the repository.
532 Add all new files and remove all missing files from the repository.
533
533
534 New files are ignored if they match any of the patterns in .hgignore. As
534 New files are ignored if they match any of the patterns in .hgignore. As
535 with add, these changes take effect at the next commit.
535 with add, these changes take effect at the next commit.
536 """
536 """
537 return addremove_lock(ui, repo, pats, opts)
537 return addremove_lock(ui, repo, pats, opts)
538
538
539 def addremove_lock(ui, repo, pats, opts, wlock=None):
539 def addremove_lock(ui, repo, pats, opts, wlock=None):
540 add, remove = [], []
540 add, remove = [], []
541 for src, abs, rel, exact in walk(repo, pats, opts):
541 for src, abs, rel, exact in walk(repo, pats, opts):
542 if src == 'f' and repo.dirstate.state(abs) == '?':
542 if src == 'f' and repo.dirstate.state(abs) == '?':
543 add.append(abs)
543 add.append(abs)
544 if ui.verbose or not exact:
544 if ui.verbose or not exact:
545 ui.status(_('adding %s\n') % ((pats and rel) or abs))
545 ui.status(_('adding %s\n') % ((pats and rel) or abs))
546 if repo.dirstate.state(abs) != 'r' and not os.path.exists(rel):
546 if repo.dirstate.state(abs) != 'r' and not os.path.exists(rel):
547 remove.append(abs)
547 remove.append(abs)
548 if ui.verbose or not exact:
548 if ui.verbose or not exact:
549 ui.status(_('removing %s\n') % ((pats and rel) or abs))
549 ui.status(_('removing %s\n') % ((pats and rel) or abs))
550 repo.add(add, wlock=wlock)
550 repo.add(add, wlock=wlock)
551 repo.remove(remove, wlock=wlock)
551 repo.remove(remove, wlock=wlock)
552
552
553 def annotate(ui, repo, *pats, **opts):
553 def annotate(ui, repo, *pats, **opts):
554 """show changeset information per file line
554 """show changeset information per file line
555
555
556 List changes in files, showing the revision id responsible for each line
556 List changes in files, showing the revision id responsible for each line
557
557
558 This command is useful to discover who did a change or when a change took
558 This command is useful to discover who did a change or when a change took
559 place.
559 place.
560
560
561 Without the -a option, annotate will avoid processing files it
561 Without the -a option, annotate will avoid processing files it
562 detects as binary. With -a, annotate will generate an annotation
562 detects as binary. With -a, annotate will generate an annotation
563 anyway, probably with undesirable results.
563 anyway, probably with undesirable results.
564 """
564 """
565 def getnode(rev):
565 def getnode(rev):
566 return short(repo.changelog.node(rev))
566 return short(repo.changelog.node(rev))
567
567
568 ucache = {}
568 ucache = {}
569 def getname(rev):
569 def getname(rev):
570 cl = repo.changelog.read(repo.changelog.node(rev))
570 cl = repo.changelog.read(repo.changelog.node(rev))
571 return trimuser(ui, cl[1], rev, ucache)
571 return trimuser(ui, cl[1], rev, ucache)
572
572
573 dcache = {}
573 dcache = {}
574 def getdate(rev):
574 def getdate(rev):
575 datestr = dcache.get(rev)
575 datestr = dcache.get(rev)
576 if datestr is None:
576 if datestr is None:
577 cl = repo.changelog.read(repo.changelog.node(rev))
577 cl = repo.changelog.read(repo.changelog.node(rev))
578 datestr = dcache[rev] = util.datestr(cl[2])
578 datestr = dcache[rev] = util.datestr(cl[2])
579 return datestr
579 return datestr
580
580
581 if not pats:
581 if not pats:
582 raise util.Abort(_('at least one file name or pattern required'))
582 raise util.Abort(_('at least one file name or pattern required'))
583
583
584 opmap = [['user', getname], ['number', str], ['changeset', getnode],
584 opmap = [['user', getname], ['number', str], ['changeset', getnode],
585 ['date', getdate]]
585 ['date', getdate]]
586 if not opts['user'] and not opts['changeset'] and not opts['date']:
586 if not opts['user'] and not opts['changeset'] and not opts['date']:
587 opts['number'] = 1
587 opts['number'] = 1
588
588
589 if opts['rev']:
589 if opts['rev']:
590 node = repo.changelog.lookup(opts['rev'])
590 node = repo.changelog.lookup(opts['rev'])
591 else:
591 else:
592 node = repo.dirstate.parents()[0]
592 node = repo.dirstate.parents()[0]
593 change = repo.changelog.read(node)
593 change = repo.changelog.read(node)
594 mmap = repo.manifest.read(change[0])
594 mmap = repo.manifest.read(change[0])
595
595
596 for src, abs, rel, exact in walk(repo, pats, opts):
596 for src, abs, rel, exact in walk(repo, pats, opts):
597 if abs not in mmap:
597 if abs not in mmap:
598 ui.warn(_("warning: %s is not in the repository!\n") %
598 ui.warn(_("warning: %s is not in the repository!\n") %
599 ((pats and rel) or abs))
599 ((pats and rel) or abs))
600 continue
600 continue
601
601
602 f = repo.file(abs)
602 f = repo.file(abs)
603 if not opts['text'] and util.binary(f.read(mmap[abs])):
603 if not opts['text'] and util.binary(f.read(mmap[abs])):
604 ui.write(_("%s: binary file\n") % ((pats and rel) or abs))
604 ui.write(_("%s: binary file\n") % ((pats and rel) or abs))
605 continue
605 continue
606
606
607 lines = f.annotate(mmap[abs])
607 lines = f.annotate(mmap[abs])
608 pieces = []
608 pieces = []
609
609
610 for o, f in opmap:
610 for o, f in opmap:
611 if opts[o]:
611 if opts[o]:
612 l = [f(n) for n, dummy in lines]
612 l = [f(n) for n, dummy in lines]
613 if l:
613 if l:
614 m = max(map(len, l))
614 m = max(map(len, l))
615 pieces.append(["%*s" % (m, x) for x in l])
615 pieces.append(["%*s" % (m, x) for x in l])
616
616
617 if pieces:
617 if pieces:
618 for p, l in zip(zip(*pieces), lines):
618 for p, l in zip(zip(*pieces), lines):
619 ui.write("%s: %s" % (" ".join(p), l[1]))
619 ui.write("%s: %s" % (" ".join(p), l[1]))
620
620
621 def bundle(ui, repo, fname, dest="default-push", **opts):
621 def bundle(ui, repo, fname, dest="default-push", **opts):
622 """create a changegroup file
622 """create a changegroup file
623
623
624 Generate a compressed changegroup file collecting all changesets
624 Generate a compressed changegroup file collecting all changesets
625 not found in the other repository.
625 not found in the other repository.
626
626
627 This file can then be transferred using conventional means and
627 This file can then be transferred using conventional means and
628 applied to another repository with the unbundle command. This is
628 applied to another repository with the unbundle command. This is
629 useful when native push and pull are not available or when
629 useful when native push and pull are not available or when
630 exporting an entire repository is undesirable. The standard file
630 exporting an entire repository is undesirable. The standard file
631 extension is ".hg".
631 extension is ".hg".
632
632
633 Unlike import/export, this exactly preserves all changeset
633 Unlike import/export, this exactly preserves all changeset
634 contents including permissions, rename data, and revision history.
634 contents including permissions, rename data, and revision history.
635 """
635 """
636 f = open(fname, "wb")
636 f = open(fname, "wb")
637 dest = ui.expandpath(dest, repo.root)
637 dest = ui.expandpath(dest, repo.root)
638 other = hg.repository(ui, dest)
638 other = hg.repository(ui, dest)
639 o = repo.findoutgoing(other)
639 o = repo.findoutgoing(other)
640 cg = repo.changegroup(o, 'bundle')
640 cg = repo.changegroup(o, 'bundle')
641
641
642 try:
642 try:
643 f.write("HG10")
643 f.write("HG10")
644 z = bz2.BZ2Compressor(9)
644 z = bz2.BZ2Compressor(9)
645 while 1:
645 while 1:
646 chunk = cg.read(4096)
646 chunk = cg.read(4096)
647 if not chunk:
647 if not chunk:
648 break
648 break
649 f.write(z.compress(chunk))
649 f.write(z.compress(chunk))
650 f.write(z.flush())
650 f.write(z.flush())
651 except:
651 except:
652 os.unlink(fname)
652 os.unlink(fname)
653 raise
653 raise
654
654
655 def cat(ui, repo, file1, *pats, **opts):
655 def cat(ui, repo, file1, *pats, **opts):
656 """output the latest or given revisions of files
656 """output the latest or given revisions of files
657
657
658 Print the specified files as they were at the given revision.
658 Print the specified files as they were at the given revision.
659 If no revision is given then the tip is used.
659 If no revision is given then the tip is used.
660
660
661 Output may be to a file, in which case the name of the file is
661 Output may be to a file, in which case the name of the file is
662 given using a format string. The formatting rules are the same as
662 given using a format string. The formatting rules are the same as
663 for the export command, with the following additions:
663 for the export command, with the following additions:
664
664
665 %s basename of file being printed
665 %s basename of file being printed
666 %d dirname of file being printed, or '.' if in repo root
666 %d dirname of file being printed, or '.' if in repo root
667 %p root-relative path name of file being printed
667 %p root-relative path name of file being printed
668 """
668 """
669 mf = {}
669 mf = {}
670 rev = opts['rev']
670 rev = opts['rev']
671 if rev:
671 if rev:
672 node = repo.lookup(rev)
672 node = repo.lookup(rev)
673 else:
673 else:
674 node = repo.changelog.tip()
674 node = repo.changelog.tip()
675 change = repo.changelog.read(node)
675 change = repo.changelog.read(node)
676 mf = repo.manifest.read(change[0])
676 mf = repo.manifest.read(change[0])
677 for src, abs, rel, exact in walk(repo, (file1,) + pats, opts, node):
677 for src, abs, rel, exact in walk(repo, (file1,) + pats, opts, node):
678 r = repo.file(abs)
678 r = repo.file(abs)
679 n = mf[abs]
679 n = mf[abs]
680 fp = make_file(repo, r, opts['output'], node=n, pathname=abs)
680 fp = make_file(repo, r, opts['output'], node=n, pathname=abs)
681 fp.write(r.read(n))
681 fp.write(r.read(n))
682
682
683 def clone(ui, source, dest=None, **opts):
683 def clone(ui, source, dest=None, **opts):
684 """make a copy of an existing repository
684 """make a copy of an existing repository
685
685
686 Create a copy of an existing repository in a new directory.
686 Create a copy of an existing repository in a new directory.
687
687
688 If no destination directory name is specified, it defaults to the
688 If no destination directory name is specified, it defaults to the
689 basename of the source.
689 basename of the source.
690
690
691 The location of the source is added to the new repository's
691 The location of the source is added to the new repository's
692 .hg/hgrc file, as the default to be used for future pulls.
692 .hg/hgrc file, as the default to be used for future pulls.
693
693
694 For efficiency, hardlinks are used for cloning whenever the source
694 For efficiency, hardlinks are used for cloning whenever the source
695 and destination are on the same filesystem. Some filesystems,
695 and destination are on the same filesystem. Some filesystems,
696 such as AFS, implement hardlinking incorrectly, but do not report
696 such as AFS, implement hardlinking incorrectly, but do not report
697 errors. In these cases, use the --pull option to avoid
697 errors. In these cases, use the --pull option to avoid
698 hardlinking.
698 hardlinking.
699
699
700 See pull for valid source format details.
700 See pull for valid source format details.
701 """
701 """
702 if dest is None:
702 if dest is None:
703 dest = os.path.basename(os.path.normpath(source))
703 dest = os.path.basename(os.path.normpath(source))
704
704
705 if os.path.exists(dest):
705 if os.path.exists(dest):
706 raise util.Abort(_("destination '%s' already exists"), dest)
706 raise util.Abort(_("destination '%s' already exists"), dest)
707
707
708 dest = os.path.realpath(dest)
708 dest = os.path.realpath(dest)
709
709
710 class Dircleanup(object):
710 class Dircleanup(object):
711 def __init__(self, dir_):
711 def __init__(self, dir_):
712 self.rmtree = shutil.rmtree
712 self.rmtree = shutil.rmtree
713 self.dir_ = dir_
713 self.dir_ = dir_
714 os.mkdir(dir_)
714 os.mkdir(dir_)
715 def close(self):
715 def close(self):
716 self.dir_ = None
716 self.dir_ = None
717 def __del__(self):
717 def __del__(self):
718 if self.dir_:
718 if self.dir_:
719 self.rmtree(self.dir_, True)
719 self.rmtree(self.dir_, True)
720
720
721 if opts['ssh']:
721 if opts['ssh']:
722 ui.setconfig("ui", "ssh", opts['ssh'])
722 ui.setconfig("ui", "ssh", opts['ssh'])
723 if opts['remotecmd']:
723 if opts['remotecmd']:
724 ui.setconfig("ui", "remotecmd", opts['remotecmd'])
724 ui.setconfig("ui", "remotecmd", opts['remotecmd'])
725
725
726 if not os.path.exists(source):
726 if not os.path.exists(source):
727 source = ui.expandpath(source)
727 source = ui.expandpath(source)
728
728
729 d = Dircleanup(dest)
729 d = Dircleanup(dest)
730 abspath = source
730 abspath = source
731 other = hg.repository(ui, source)
731 other = hg.repository(ui, source)
732
732
733 copy = False
733 copy = False
734 if other.dev() != -1:
734 if other.dev() != -1:
735 abspath = os.path.abspath(source)
735 abspath = os.path.abspath(source)
736 if not opts['pull'] and not opts['rev']:
736 if not opts['pull'] and not opts['rev']:
737 copy = True
737 copy = True
738
738
739 if copy:
739 if copy:
740 try:
740 try:
741 # we use a lock here because if we race with commit, we
741 # we use a lock here because if we race with commit, we
742 # can end up with extra data in the cloned revlogs that's
742 # can end up with extra data in the cloned revlogs that's
743 # not pointed to by changesets, thus causing verify to
743 # not pointed to by changesets, thus causing verify to
744 # fail
744 # fail
745 l1 = other.lock()
745 l1 = other.lock()
746 except lock.LockException:
746 except lock.LockException:
747 copy = False
747 copy = False
748
748
749 if copy:
749 if copy:
750 # we lock here to avoid premature writing to the target
750 # we lock here to avoid premature writing to the target
751 os.mkdir(os.path.join(dest, ".hg"))
751 os.mkdir(os.path.join(dest, ".hg"))
752 l2 = lock.lock(os.path.join(dest, ".hg", "lock"))
752 l2 = lock.lock(os.path.join(dest, ".hg", "lock"))
753
753
754 files = "data 00manifest.d 00manifest.i 00changelog.d 00changelog.i"
754 files = "data 00manifest.d 00manifest.i 00changelog.d 00changelog.i"
755 for f in files.split():
755 for f in files.split():
756 src = os.path.join(source, ".hg", f)
756 src = os.path.join(source, ".hg", f)
757 dst = os.path.join(dest, ".hg", f)
757 dst = os.path.join(dest, ".hg", f)
758 try:
758 try:
759 util.copyfiles(src, dst)
759 util.copyfiles(src, dst)
760 except OSError, inst:
760 except OSError, inst:
761 if inst.errno != errno.ENOENT:
761 if inst.errno != errno.ENOENT:
762 raise
762 raise
763
763
764 repo = hg.repository(ui, dest)
764 repo = hg.repository(ui, dest)
765
765
766 else:
766 else:
767 revs = None
767 revs = None
768 if opts['rev']:
768 if opts['rev']:
769 if not other.local():
769 if not other.local():
770 error = _("clone -r not supported yet for remote repositories.")
770 error = _("clone -r not supported yet for remote repositories.")
771 raise util.Abort(error)
771 raise util.Abort(error)
772 else:
772 else:
773 revs = [other.lookup(rev) for rev in opts['rev']]
773 revs = [other.lookup(rev) for rev in opts['rev']]
774 repo = hg.repository(ui, dest, create=1)
774 repo = hg.repository(ui, dest, create=1)
775 repo.pull(other, heads = revs)
775 repo.pull(other, heads = revs)
776
776
777 f = repo.opener("hgrc", "w", text=True)
777 f = repo.opener("hgrc", "w", text=True)
778 f.write("[paths]\n")
778 f.write("[paths]\n")
779 f.write("default = %s\n" % abspath)
779 f.write("default = %s\n" % abspath)
780 f.close()
780 f.close()
781
781
782 if not opts['noupdate']:
782 if not opts['noupdate']:
783 update(repo.ui, repo)
783 update(repo.ui, repo)
784
784
785 d.close()
785 d.close()
786
786
787 def commit(ui, repo, *pats, **opts):
787 def commit(ui, repo, *pats, **opts):
788 """commit the specified files or all outstanding changes
788 """commit the specified files or all outstanding changes
789
789
790 Commit changes to the given files into the repository.
790 Commit changes to the given files into the repository.
791
791
792 If a list of files is omitted, all changes reported by "hg status"
792 If a list of files is omitted, all changes reported by "hg status"
793 will be commited.
793 will be commited.
794
794
795 The HGEDITOR or EDITOR environment variables are used to start an
795 The HGEDITOR or EDITOR environment variables are used to start an
796 editor to add a commit comment.
796 editor to add a commit comment.
797 """
797 """
798 message = opts['message']
798 message = opts['message']
799 logfile = opts['logfile']
799 logfile = opts['logfile']
800
800
801 if message and logfile:
801 if message and logfile:
802 raise util.Abort(_('options --message and --logfile are mutually '
802 raise util.Abort(_('options --message and --logfile are mutually '
803 'exclusive'))
803 'exclusive'))
804 if not message and logfile:
804 if not message and logfile:
805 try:
805 try:
806 if logfile == '-':
806 if logfile == '-':
807 message = sys.stdin.read()
807 message = sys.stdin.read()
808 else:
808 else:
809 message = open(logfile).read()
809 message = open(logfile).read()
810 except IOError, inst:
810 except IOError, inst:
811 raise util.Abort(_("can't read commit message '%s': %s") %
811 raise util.Abort(_("can't read commit message '%s': %s") %
812 (logfile, inst.strerror))
812 (logfile, inst.strerror))
813
813
814 if opts['addremove']:
814 if opts['addremove']:
815 addremove(ui, repo, *pats, **opts)
815 addremove(ui, repo, *pats, **opts)
816 fns, match, anypats = matchpats(repo, pats, opts)
816 fns, match, anypats = matchpats(repo, pats, opts)
817 if pats:
817 if pats:
818 modified, added, removed, deleted, unknown = (
818 modified, added, removed, deleted, unknown = (
819 repo.changes(files=fns, match=match))
819 repo.changes(files=fns, match=match))
820 files = modified + added + removed
820 files = modified + added + removed
821 else:
821 else:
822 files = []
822 files = []
823 try:
823 try:
824 repo.commit(files, message, opts['user'], opts['date'], match)
824 repo.commit(files, message, opts['user'], opts['date'], match)
825 except ValueError, inst:
825 except ValueError, inst:
826 raise util.Abort(str(inst))
826 raise util.Abort(str(inst))
827
827
828 def docopy(ui, repo, pats, opts, wlock):
828 def docopy(ui, repo, pats, opts, wlock):
829 # called with the repo lock held
829 # called with the repo lock held
830 cwd = repo.getcwd()
830 cwd = repo.getcwd()
831 errors = 0
831 errors = 0
832 copied = []
832 copied = []
833 targets = {}
833 targets = {}
834
834
835 def okaytocopy(abs, rel, exact):
835 def okaytocopy(abs, rel, exact):
836 reasons = {'?': _('is not managed'),
836 reasons = {'?': _('is not managed'),
837 'a': _('has been marked for add'),
837 'a': _('has been marked for add'),
838 'r': _('has been marked for remove')}
838 'r': _('has been marked for remove')}
839 state = repo.dirstate.state(abs)
839 state = repo.dirstate.state(abs)
840 reason = reasons.get(state)
840 reason = reasons.get(state)
841 if reason:
841 if reason:
842 if state == 'a':
842 if state == 'a':
843 origsrc = repo.dirstate.copied(abs)
843 origsrc = repo.dirstate.copied(abs)
844 if origsrc is not None:
844 if origsrc is not None:
845 return origsrc
845 return origsrc
846 if exact:
846 if exact:
847 ui.warn(_('%s: not copying - file %s\n') % (rel, reason))
847 ui.warn(_('%s: not copying - file %s\n') % (rel, reason))
848 else:
848 else:
849 return abs
849 return abs
850
850
851 def copy(origsrc, abssrc, relsrc, target, exact):
851 def copy(origsrc, abssrc, relsrc, target, exact):
852 abstarget = util.canonpath(repo.root, cwd, target)
852 abstarget = util.canonpath(repo.root, cwd, target)
853 reltarget = util.pathto(cwd, abstarget)
853 reltarget = util.pathto(cwd, abstarget)
854 prevsrc = targets.get(abstarget)
854 prevsrc = targets.get(abstarget)
855 if prevsrc is not None:
855 if prevsrc is not None:
856 ui.warn(_('%s: not overwriting - %s collides with %s\n') %
856 ui.warn(_('%s: not overwriting - %s collides with %s\n') %
857 (reltarget, abssrc, prevsrc))
857 (reltarget, abssrc, prevsrc))
858 return
858 return
859 if (not opts['after'] and os.path.exists(reltarget) or
859 if (not opts['after'] and os.path.exists(reltarget) or
860 opts['after'] and repo.dirstate.state(abstarget) not in '?r'):
860 opts['after'] and repo.dirstate.state(abstarget) not in '?r'):
861 if not opts['force']:
861 if not opts['force']:
862 ui.warn(_('%s: not overwriting - file exists\n') %
862 ui.warn(_('%s: not overwriting - file exists\n') %
863 reltarget)
863 reltarget)
864 return
864 return
865 if not opts['after']:
865 if not opts['after']:
866 os.unlink(reltarget)
866 os.unlink(reltarget)
867 if opts['after']:
867 if opts['after']:
868 if not os.path.exists(reltarget):
868 if not os.path.exists(reltarget):
869 return
869 return
870 else:
870 else:
871 targetdir = os.path.dirname(reltarget) or '.'
871 targetdir = os.path.dirname(reltarget) or '.'
872 if not os.path.isdir(targetdir):
872 if not os.path.isdir(targetdir):
873 os.makedirs(targetdir)
873 os.makedirs(targetdir)
874 try:
874 try:
875 restore = repo.dirstate.state(abstarget) == 'r'
875 restore = repo.dirstate.state(abstarget) == 'r'
876 if restore:
876 if restore:
877 repo.undelete([abstarget], wlock)
877 repo.undelete([abstarget], wlock)
878 try:
878 try:
879 shutil.copyfile(relsrc, reltarget)
879 shutil.copyfile(relsrc, reltarget)
880 shutil.copymode(relsrc, reltarget)
880 shutil.copymode(relsrc, reltarget)
881 restore = False
881 restore = False
882 finally:
882 finally:
883 if restore:
883 if restore:
884 repo.remove([abstarget], wlock)
884 repo.remove([abstarget], wlock)
885 except shutil.Error, inst:
885 except shutil.Error, inst:
886 raise util.Abort(str(inst))
886 raise util.Abort(str(inst))
887 except IOError, inst:
887 except IOError, inst:
888 if inst.errno == errno.ENOENT:
888 if inst.errno == errno.ENOENT:
889 ui.warn(_('%s: deleted in working copy\n') % relsrc)
889 ui.warn(_('%s: deleted in working copy\n') % relsrc)
890 else:
890 else:
891 ui.warn(_('%s: cannot copy - %s\n') %
891 ui.warn(_('%s: cannot copy - %s\n') %
892 (relsrc, inst.strerror))
892 (relsrc, inst.strerror))
893 errors += 1
893 errors += 1
894 return
894 return
895 if ui.verbose or not exact:
895 if ui.verbose or not exact:
896 ui.status(_('copying %s to %s\n') % (relsrc, reltarget))
896 ui.status(_('copying %s to %s\n') % (relsrc, reltarget))
897 targets[abstarget] = abssrc
897 targets[abstarget] = abssrc
898 if abstarget != origsrc:
898 if abstarget != origsrc:
899 repo.copy(origsrc, abstarget, wlock)
899 repo.copy(origsrc, abstarget, wlock)
900 copied.append((abssrc, relsrc, exact))
900 copied.append((abssrc, relsrc, exact))
901
901
902 def targetpathfn(pat, dest, srcs):
902 def targetpathfn(pat, dest, srcs):
903 if os.path.isdir(pat):
903 if os.path.isdir(pat):
904 abspfx = util.canonpath(repo.root, cwd, pat)
904 abspfx = util.canonpath(repo.root, cwd, pat)
905 if destdirexists:
905 if destdirexists:
906 striplen = len(os.path.split(abspfx)[0])
906 striplen = len(os.path.split(abspfx)[0])
907 else:
907 else:
908 striplen = len(abspfx)
908 striplen = len(abspfx)
909 if striplen:
909 if striplen:
910 striplen += len(os.sep)
910 striplen += len(os.sep)
911 res = lambda p: os.path.join(dest, p[striplen:])
911 res = lambda p: os.path.join(dest, p[striplen:])
912 elif destdirexists:
912 elif destdirexists:
913 res = lambda p: os.path.join(dest, os.path.basename(p))
913 res = lambda p: os.path.join(dest, os.path.basename(p))
914 else:
914 else:
915 res = lambda p: dest
915 res = lambda p: dest
916 return res
916 return res
917
917
918 def targetpathafterfn(pat, dest, srcs):
918 def targetpathafterfn(pat, dest, srcs):
919 if util.patkind(pat, None)[0]:
919 if util.patkind(pat, None)[0]:
920 # a mercurial pattern
920 # a mercurial pattern
921 res = lambda p: os.path.join(dest, os.path.basename(p))
921 res = lambda p: os.path.join(dest, os.path.basename(p))
922 else:
922 else:
923 abspfx = util.canonpath(repo.root, cwd, pat)
923 abspfx = util.canonpath(repo.root, cwd, pat)
924 if len(abspfx) < len(srcs[0][0]):
924 if len(abspfx) < len(srcs[0][0]):
925 # A directory. Either the target path contains the last
925 # A directory. Either the target path contains the last
926 # component of the source path or it does not.
926 # component of the source path or it does not.
927 def evalpath(striplen):
927 def evalpath(striplen):
928 score = 0
928 score = 0
929 for s in srcs:
929 for s in srcs:
930 t = os.path.join(dest, s[0][striplen:])
930 t = os.path.join(dest, s[0][striplen:])
931 if os.path.exists(t):
931 if os.path.exists(t):
932 score += 1
932 score += 1
933 return score
933 return score
934
934
935 striplen = len(abspfx)
935 striplen = len(abspfx)
936 if striplen:
936 if striplen:
937 striplen += len(os.sep)
937 striplen += len(os.sep)
938 if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])):
938 if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])):
939 score = evalpath(striplen)
939 score = evalpath(striplen)
940 striplen1 = len(os.path.split(abspfx)[0])
940 striplen1 = len(os.path.split(abspfx)[0])
941 if striplen1:
941 if striplen1:
942 striplen1 += len(os.sep)
942 striplen1 += len(os.sep)
943 if evalpath(striplen1) > score:
943 if evalpath(striplen1) > score:
944 striplen = striplen1
944 striplen = striplen1
945 res = lambda p: os.path.join(dest, p[striplen:])
945 res = lambda p: os.path.join(dest, p[striplen:])
946 else:
946 else:
947 # a file
947 # a file
948 if destdirexists:
948 if destdirexists:
949 res = lambda p: os.path.join(dest, os.path.basename(p))
949 res = lambda p: os.path.join(dest, os.path.basename(p))
950 else:
950 else:
951 res = lambda p: dest
951 res = lambda p: dest
952 return res
952 return res
953
953
954
954
955 pats = list(pats)
955 pats = list(pats)
956 if not pats:
956 if not pats:
957 raise util.Abort(_('no source or destination specified'))
957 raise util.Abort(_('no source or destination specified'))
958 if len(pats) == 1:
958 if len(pats) == 1:
959 raise util.Abort(_('no destination specified'))
959 raise util.Abort(_('no destination specified'))
960 dest = pats.pop()
960 dest = pats.pop()
961 destdirexists = os.path.isdir(dest)
961 destdirexists = os.path.isdir(dest)
962 if (len(pats) > 1 or util.patkind(pats[0], None)[0]) and not destdirexists:
962 if (len(pats) > 1 or util.patkind(pats[0], None)[0]) and not destdirexists:
963 raise util.Abort(_('with multiple sources, destination must be an '
963 raise util.Abort(_('with multiple sources, destination must be an '
964 'existing directory'))
964 'existing directory'))
965 if opts['after']:
965 if opts['after']:
966 tfn = targetpathafterfn
966 tfn = targetpathafterfn
967 else:
967 else:
968 tfn = targetpathfn
968 tfn = targetpathfn
969 copylist = []
969 copylist = []
970 for pat in pats:
970 for pat in pats:
971 srcs = []
971 srcs = []
972 for tag, abssrc, relsrc, exact in walk(repo, [pat], opts):
972 for tag, abssrc, relsrc, exact in walk(repo, [pat], opts):
973 origsrc = okaytocopy(abssrc, relsrc, exact)
973 origsrc = okaytocopy(abssrc, relsrc, exact)
974 if origsrc:
974 if origsrc:
975 srcs.append((origsrc, abssrc, relsrc, exact))
975 srcs.append((origsrc, abssrc, relsrc, exact))
976 if not srcs:
976 if not srcs:
977 continue
977 continue
978 copylist.append((tfn(pat, dest, srcs), srcs))
978 copylist.append((tfn(pat, dest, srcs), srcs))
979 if not copylist:
979 if not copylist:
980 raise util.Abort(_('no files to copy'))
980 raise util.Abort(_('no files to copy'))
981
981
982 for targetpath, srcs in copylist:
982 for targetpath, srcs in copylist:
983 for origsrc, abssrc, relsrc, exact in srcs:
983 for origsrc, abssrc, relsrc, exact in srcs:
984 copy(origsrc, abssrc, relsrc, targetpath(abssrc), exact)
984 copy(origsrc, abssrc, relsrc, targetpath(abssrc), exact)
985
985
986 if errors:
986 if errors:
987 ui.warn(_('(consider using --after)\n'))
987 ui.warn(_('(consider using --after)\n'))
988 return errors, copied
988 return errors, copied
989
989
990 def copy(ui, repo, *pats, **opts):
990 def copy(ui, repo, *pats, **opts):
991 """mark files as copied for the next commit
991 """mark files as copied for the next commit
992
992
993 Mark dest as having copies of source files. If dest is a
993 Mark dest as having copies of source files. If dest is a
994 directory, copies are put in that directory. If dest is a file,
994 directory, copies are put in that directory. If dest is a file,
995 there can only be one source.
995 there can only be one source.
996
996
997 By default, this command copies the contents of files as they
997 By default, this command copies the contents of files as they
998 stand in the working directory. If invoked with --after, the
998 stand in the working directory. If invoked with --after, the
999 operation is recorded, but no copying is performed.
999 operation is recorded, but no copying is performed.
1000
1000
1001 This command takes effect in the next commit.
1001 This command takes effect in the next commit.
1002
1002
1003 NOTE: This command should be treated as experimental. While it
1003 NOTE: This command should be treated as experimental. While it
1004 should properly record copied files, this information is not yet
1004 should properly record copied files, this information is not yet
1005 fully used by merge, nor fully reported by log.
1005 fully used by merge, nor fully reported by log.
1006 """
1006 """
1007 try:
1007 try:
1008 wlock = repo.wlock(0)
1008 wlock = repo.wlock(0)
1009 errs, copied = docopy(ui, repo, pats, opts, wlock)
1009 errs, copied = docopy(ui, repo, pats, opts, wlock)
1010 except lock.LockHeld, inst:
1010 except lock.LockHeld, inst:
1011 ui.warn(_("repository lock held by %s\n") % inst.args[0])
1011 ui.warn(_("repository lock held by %s\n") % inst.args[0])
1012 errs = 1
1012 errs = 1
1013 return errs
1013 return errs
1014
1014
1015 def debugancestor(ui, index, rev1, rev2):
1015 def debugancestor(ui, index, rev1, rev2):
1016 """find the ancestor revision of two revisions in a given index"""
1016 """find the ancestor revision of two revisions in a given index"""
1017 r = revlog.revlog(util.opener(os.getcwd(), audit=False), index, "")
1017 r = revlog.revlog(util.opener(os.getcwd(), audit=False), index, "")
1018 a = r.ancestor(r.lookup(rev1), r.lookup(rev2))
1018 a = r.ancestor(r.lookup(rev1), r.lookup(rev2))
1019 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
1019 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
1020
1020
1021 def debugrebuildstate(ui, repo, rev=None):
1021 def debugrebuildstate(ui, repo, rev=None):
1022 """rebuild the dirstate as it would look like for the given revision"""
1022 """rebuild the dirstate as it would look like for the given revision"""
1023 if not rev:
1023 if not rev:
1024 rev = repo.changelog.tip()
1024 rev = repo.changelog.tip()
1025 else:
1025 else:
1026 rev = repo.lookup(rev)
1026 rev = repo.lookup(rev)
1027 change = repo.changelog.read(rev)
1027 change = repo.changelog.read(rev)
1028 n = change[0]
1028 n = change[0]
1029 files = repo.manifest.readflags(n)
1029 files = repo.manifest.readflags(n)
1030 wlock = repo.wlock()
1030 wlock = repo.wlock()
1031 repo.dirstate.rebuild(rev, files.iteritems())
1031 repo.dirstate.rebuild(rev, files.iteritems())
1032
1032
1033 def debugcheckstate(ui, repo):
1033 def debugcheckstate(ui, repo):
1034 """validate the correctness of the current dirstate"""
1034 """validate the correctness of the current dirstate"""
1035 parent1, parent2 = repo.dirstate.parents()
1035 parent1, parent2 = repo.dirstate.parents()
1036 repo.dirstate.read()
1036 repo.dirstate.read()
1037 dc = repo.dirstate.map
1037 dc = repo.dirstate.map
1038 keys = dc.keys()
1038 keys = dc.keys()
1039 keys.sort()
1039 keys.sort()
1040 m1n = repo.changelog.read(parent1)[0]
1040 m1n = repo.changelog.read(parent1)[0]
1041 m2n = repo.changelog.read(parent2)[0]
1041 m2n = repo.changelog.read(parent2)[0]
1042 m1 = repo.manifest.read(m1n)
1042 m1 = repo.manifest.read(m1n)
1043 m2 = repo.manifest.read(m2n)
1043 m2 = repo.manifest.read(m2n)
1044 errors = 0
1044 errors = 0
1045 for f in dc:
1045 for f in dc:
1046 state = repo.dirstate.state(f)
1046 state = repo.dirstate.state(f)
1047 if state in "nr" and f not in m1:
1047 if state in "nr" and f not in m1:
1048 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
1048 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
1049 errors += 1
1049 errors += 1
1050 if state in "a" and f in m1:
1050 if state in "a" and f in m1:
1051 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
1051 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
1052 errors += 1
1052 errors += 1
1053 if state in "m" and f not in m1 and f not in m2:
1053 if state in "m" and f not in m1 and f not in m2:
1054 ui.warn(_("%s in state %s, but not in either manifest\n") %
1054 ui.warn(_("%s in state %s, but not in either manifest\n") %
1055 (f, state))
1055 (f, state))
1056 errors += 1
1056 errors += 1
1057 for f in m1:
1057 for f in m1:
1058 state = repo.dirstate.state(f)
1058 state = repo.dirstate.state(f)
1059 if state not in "nrm":
1059 if state not in "nrm":
1060 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
1060 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
1061 errors += 1
1061 errors += 1
1062 if errors:
1062 if errors:
1063 error = _(".hg/dirstate inconsistent with current parent's manifest")
1063 error = _(".hg/dirstate inconsistent with current parent's manifest")
1064 raise util.Abort(error)
1064 raise util.Abort(error)
1065
1065
1066 def debugconfig(ui):
1066 def debugconfig(ui):
1067 """show combined config settings from all hgrc files"""
1067 """show combined config settings from all hgrc files"""
1068 try:
1068 try:
1069 repo = hg.repository(ui)
1069 repo = hg.repository(ui)
1070 ui = repo.ui
1070 ui = repo.ui
1071 except hg.RepoError:
1071 except hg.RepoError:
1072 pass
1072 pass
1073 for section, name, value in ui.walkconfig():
1073 for section, name, value in ui.walkconfig():
1074 ui.write('%s.%s=%s\n' % (section, name, value))
1074 ui.write('%s.%s=%s\n' % (section, name, value))
1075
1075
1076 def debugsetparents(ui, repo, rev1, rev2=None):
1076 def debugsetparents(ui, repo, rev1, rev2=None):
1077 """manually set the parents of the current working directory
1077 """manually set the parents of the current working directory
1078
1078
1079 This is useful for writing repository conversion tools, but should
1079 This is useful for writing repository conversion tools, but should
1080 be used with care.
1080 be used with care.
1081 """
1081 """
1082
1082
1083 if not rev2:
1083 if not rev2:
1084 rev2 = hex(nullid)
1084 rev2 = hex(nullid)
1085
1085
1086 repo.dirstate.setparents(repo.lookup(rev1), repo.lookup(rev2))
1086 repo.dirstate.setparents(repo.lookup(rev1), repo.lookup(rev2))
1087
1087
1088 def debugstate(ui, repo):
1088 def debugstate(ui, repo):
1089 """show the contents of the current dirstate"""
1089 """show the contents of the current dirstate"""
1090 repo.dirstate.read()
1090 repo.dirstate.read()
1091 dc = repo.dirstate.map
1091 dc = repo.dirstate.map
1092 keys = dc.keys()
1092 keys = dc.keys()
1093 keys.sort()
1093 keys.sort()
1094 for file_ in keys:
1094 for file_ in keys:
1095 ui.write("%c %3o %10d %s %s\n"
1095 ui.write("%c %3o %10d %s %s\n"
1096 % (dc[file_][0], dc[file_][1] & 0777, dc[file_][2],
1096 % (dc[file_][0], dc[file_][1] & 0777, dc[file_][2],
1097 time.strftime("%x %X",
1097 time.strftime("%x %X",
1098 time.localtime(dc[file_][3])), file_))
1098 time.localtime(dc[file_][3])), file_))
1099 for f in repo.dirstate.copies:
1099 for f in repo.dirstate.copies:
1100 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copies[f], f))
1100 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copies[f], f))
1101
1101
1102 def debugdata(ui, file_, rev):
1102 def debugdata(ui, file_, rev):
1103 """dump the contents of an data file revision"""
1103 """dump the contents of an data file revision"""
1104 r = revlog.revlog(util.opener(os.getcwd(), audit=False),
1104 r = revlog.revlog(util.opener(os.getcwd(), audit=False),
1105 file_[:-2] + ".i", file_)
1105 file_[:-2] + ".i", file_)
1106 try:
1106 try:
1107 ui.write(r.revision(r.lookup(rev)))
1107 ui.write(r.revision(r.lookup(rev)))
1108 except KeyError:
1108 except KeyError:
1109 raise util.Abort(_('invalid revision identifier %s'), rev)
1109 raise util.Abort(_('invalid revision identifier %s'), rev)
1110
1110
1111 def debugindex(ui, file_):
1111 def debugindex(ui, file_):
1112 """dump the contents of an index file"""
1112 """dump the contents of an index file"""
1113 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_, "")
1113 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_, "")
1114 ui.write(" rev offset length base linkrev" +
1114 ui.write(" rev offset length base linkrev" +
1115 " nodeid p1 p2\n")
1115 " nodeid p1 p2\n")
1116 for i in range(r.count()):
1116 for i in range(r.count()):
1117 e = r.index[i]
1117 e = r.index[i]
1118 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
1118 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
1119 i, e[0], e[1], e[2], e[3],
1119 i, e[0], e[1], e[2], e[3],
1120 short(e[6]), short(e[4]), short(e[5])))
1120 short(e[6]), short(e[4]), short(e[5])))
1121
1121
1122 def debugindexdot(ui, file_):
1122 def debugindexdot(ui, file_):
1123 """dump an index DAG as a .dot file"""
1123 """dump an index DAG as a .dot file"""
1124 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_, "")
1124 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_, "")
1125 ui.write("digraph G {\n")
1125 ui.write("digraph G {\n")
1126 for i in range(r.count()):
1126 for i in range(r.count()):
1127 e = r.index[i]
1127 e = r.index[i]
1128 ui.write("\t%d -> %d\n" % (r.rev(e[4]), i))
1128 ui.write("\t%d -> %d\n" % (r.rev(e[4]), i))
1129 if e[5] != nullid:
1129 if e[5] != nullid:
1130 ui.write("\t%d -> %d\n" % (r.rev(e[5]), i))
1130 ui.write("\t%d -> %d\n" % (r.rev(e[5]), i))
1131 ui.write("}\n")
1131 ui.write("}\n")
1132
1132
1133 def debugrename(ui, repo, file, rev=None):
1133 def debugrename(ui, repo, file, rev=None):
1134 """dump rename information"""
1134 """dump rename information"""
1135 r = repo.file(relpath(repo, [file])[0])
1135 r = repo.file(relpath(repo, [file])[0])
1136 if rev:
1136 if rev:
1137 try:
1137 try:
1138 # assume all revision numbers are for changesets
1138 # assume all revision numbers are for changesets
1139 n = repo.lookup(rev)
1139 n = repo.lookup(rev)
1140 change = repo.changelog.read(n)
1140 change = repo.changelog.read(n)
1141 m = repo.manifest.read(change[0])
1141 m = repo.manifest.read(change[0])
1142 n = m[relpath(repo, [file])[0]]
1142 n = m[relpath(repo, [file])[0]]
1143 except (hg.RepoError, KeyError):
1143 except (hg.RepoError, KeyError):
1144 n = r.lookup(rev)
1144 n = r.lookup(rev)
1145 else:
1145 else:
1146 n = r.tip()
1146 n = r.tip()
1147 m = r.renamed(n)
1147 m = r.renamed(n)
1148 if m:
1148 if m:
1149 ui.write(_("renamed from %s:%s\n") % (m[0], hex(m[1])))
1149 ui.write(_("renamed from %s:%s\n") % (m[0], hex(m[1])))
1150 else:
1150 else:
1151 ui.write(_("not renamed\n"))
1151 ui.write(_("not renamed\n"))
1152
1152
1153 def debugwalk(ui, repo, *pats, **opts):
1153 def debugwalk(ui, repo, *pats, **opts):
1154 """show how files match on given patterns"""
1154 """show how files match on given patterns"""
1155 items = list(walk(repo, pats, opts))
1155 items = list(walk(repo, pats, opts))
1156 if not items:
1156 if not items:
1157 return
1157 return
1158 fmt = '%%s %%-%ds %%-%ds %%s' % (
1158 fmt = '%%s %%-%ds %%-%ds %%s' % (
1159 max([len(abs) for (src, abs, rel, exact) in items]),
1159 max([len(abs) for (src, abs, rel, exact) in items]),
1160 max([len(rel) for (src, abs, rel, exact) in items]))
1160 max([len(rel) for (src, abs, rel, exact) in items]))
1161 for src, abs, rel, exact in items:
1161 for src, abs, rel, exact in items:
1162 line = fmt % (src, abs, rel, exact and 'exact' or '')
1162 line = fmt % (src, abs, rel, exact and 'exact' or '')
1163 ui.write("%s\n" % line.rstrip())
1163 ui.write("%s\n" % line.rstrip())
1164
1164
1165 def diff(ui, repo, *pats, **opts):
1165 def diff(ui, repo, *pats, **opts):
1166 """diff repository (or selected files)
1166 """diff repository (or selected files)
1167
1167
1168 Show differences between revisions for the specified files.
1168 Show differences between revisions for the specified files.
1169
1169
1170 Differences between files are shown using the unified diff format.
1170 Differences between files are shown using the unified diff format.
1171
1171
1172 When two revision arguments are given, then changes are shown
1172 When two revision arguments are given, then changes are shown
1173 between those revisions. If only one revision is specified then
1173 between those revisions. If only one revision is specified then
1174 that revision is compared to the working directory, and, when no
1174 that revision is compared to the working directory, and, when no
1175 revisions are specified, the working directory files are compared
1175 revisions are specified, the working directory files are compared
1176 to its parent.
1176 to its parent.
1177
1177
1178 Without the -a option, diff will avoid generating diffs of files
1178 Without the -a option, diff will avoid generating diffs of files
1179 it detects as binary. With -a, diff will generate a diff anyway,
1179 it detects as binary. With -a, diff will generate a diff anyway,
1180 probably with undesirable results.
1180 probably with undesirable results.
1181 """
1181 """
1182 node1, node2 = None, None
1182 node1, node2 = None, None
1183 revs = [repo.lookup(x) for x in opts['rev']]
1183 revs = [repo.lookup(x) for x in opts['rev']]
1184
1184
1185 if len(revs) > 0:
1185 if len(revs) > 0:
1186 node1 = revs[0]
1186 node1 = revs[0]
1187 if len(revs) > 1:
1187 if len(revs) > 1:
1188 node2 = revs[1]
1188 node2 = revs[1]
1189 if len(revs) > 2:
1189 if len(revs) > 2:
1190 raise util.Abort(_("too many revisions to diff"))
1190 raise util.Abort(_("too many revisions to diff"))
1191
1191
1192 fns, matchfn, anypats = matchpats(repo, pats, opts)
1192 fns, matchfn, anypats = matchpats(repo, pats, opts)
1193
1193
1194 dodiff(sys.stdout, ui, repo, node1, node2, fns, match=matchfn,
1194 dodiff(sys.stdout, ui, repo, node1, node2, fns, match=matchfn,
1195 text=opts['text'], opts=opts)
1195 text=opts['text'], opts=opts)
1196
1196
1197 def doexport(ui, repo, changeset, seqno, total, revwidth, opts):
1197 def doexport(ui, repo, changeset, seqno, total, revwidth, opts):
1198 node = repo.lookup(changeset)
1198 node = repo.lookup(changeset)
1199 parents = [p for p in repo.changelog.parents(node) if p != nullid]
1199 parents = [p for p in repo.changelog.parents(node) if p != nullid]
1200 if opts['switch_parent']:
1200 if opts['switch_parent']:
1201 parents.reverse()
1201 parents.reverse()
1202 prev = (parents and parents[0]) or nullid
1202 prev = (parents and parents[0]) or nullid
1203 change = repo.changelog.read(node)
1203 change = repo.changelog.read(node)
1204
1204
1205 fp = make_file(repo, repo.changelog, opts['output'],
1205 fp = make_file(repo, repo.changelog, opts['output'],
1206 node=node, total=total, seqno=seqno,
1206 node=node, total=total, seqno=seqno,
1207 revwidth=revwidth)
1207 revwidth=revwidth)
1208 if fp != sys.stdout:
1208 if fp != sys.stdout:
1209 ui.note("%s\n" % fp.name)
1209 ui.note("%s\n" % fp.name)
1210
1210
1211 fp.write("# HG changeset patch\n")
1211 fp.write("# HG changeset patch\n")
1212 fp.write("# User %s\n" % change[1])
1212 fp.write("# User %s\n" % change[1])
1213 fp.write("# Node ID %s\n" % hex(node))
1213 fp.write("# Node ID %s\n" % hex(node))
1214 fp.write("# Parent %s\n" % hex(prev))
1214 fp.write("# Parent %s\n" % hex(prev))
1215 if len(parents) > 1:
1215 if len(parents) > 1:
1216 fp.write("# Parent %s\n" % hex(parents[1]))
1216 fp.write("# Parent %s\n" % hex(parents[1]))
1217 fp.write(change[4].rstrip())
1217 fp.write(change[4].rstrip())
1218 fp.write("\n\n")
1218 fp.write("\n\n")
1219
1219
1220 dodiff(fp, ui, repo, prev, node, text=opts['text'])
1220 dodiff(fp, ui, repo, prev, node, text=opts['text'])
1221 if fp != sys.stdout:
1221 if fp != sys.stdout:
1222 fp.close()
1222 fp.close()
1223
1223
1224 def export(ui, repo, *changesets, **opts):
1224 def export(ui, repo, *changesets, **opts):
1225 """dump the header and diffs for one or more changesets
1225 """dump the header and diffs for one or more changesets
1226
1226
1227 Print the changeset header and diffs for one or more revisions.
1227 Print the changeset header and diffs for one or more revisions.
1228
1228
1229 The information shown in the changeset header is: author,
1229 The information shown in the changeset header is: author,
1230 changeset hash, parent and commit comment.
1230 changeset hash, parent and commit comment.
1231
1231
1232 Output may be to a file, in which case the name of the file is
1232 Output may be to a file, in which case the name of the file is
1233 given using a format string. The formatting rules are as follows:
1233 given using a format string. The formatting rules are as follows:
1234
1234
1235 %% literal "%" character
1235 %% literal "%" character
1236 %H changeset hash (40 bytes of hexadecimal)
1236 %H changeset hash (40 bytes of hexadecimal)
1237 %N number of patches being generated
1237 %N number of patches being generated
1238 %R changeset revision number
1238 %R changeset revision number
1239 %b basename of the exporting repository
1239 %b basename of the exporting repository
1240 %h short-form changeset hash (12 bytes of hexadecimal)
1240 %h short-form changeset hash (12 bytes of hexadecimal)
1241 %n zero-padded sequence number, starting at 1
1241 %n zero-padded sequence number, starting at 1
1242 %r zero-padded changeset revision number
1242 %r zero-padded changeset revision number
1243
1243
1244 Without the -a option, export will avoid generating diffs of files
1244 Without the -a option, export will avoid generating diffs of files
1245 it detects as binary. With -a, export will generate a diff anyway,
1245 it detects as binary. With -a, export will generate a diff anyway,
1246 probably with undesirable results.
1246 probably with undesirable results.
1247
1247
1248 With the --switch-parent option, the diff will be against the second
1248 With the --switch-parent option, the diff will be against the second
1249 parent. It can be useful to review a merge.
1249 parent. It can be useful to review a merge.
1250 """
1250 """
1251 if not changesets:
1251 if not changesets:
1252 raise util.Abort(_("export requires at least one changeset"))
1252 raise util.Abort(_("export requires at least one changeset"))
1253 seqno = 0
1253 seqno = 0
1254 revs = list(revrange(ui, repo, changesets))
1254 revs = list(revrange(ui, repo, changesets))
1255 total = len(revs)
1255 total = len(revs)
1256 revwidth = max(map(len, revs))
1256 revwidth = max(map(len, revs))
1257 msg = len(revs) > 1 and _("Exporting patches:\n") or _("Exporting patch:\n")
1257 msg = len(revs) > 1 and _("Exporting patches:\n") or _("Exporting patch:\n")
1258 ui.note(msg)
1258 ui.note(msg)
1259 for cset in revs:
1259 for cset in revs:
1260 seqno += 1
1260 seqno += 1
1261 doexport(ui, repo, cset, seqno, total, revwidth, opts)
1261 doexport(ui, repo, cset, seqno, total, revwidth, opts)
1262
1262
1263 def forget(ui, repo, *pats, **opts):
1263 def forget(ui, repo, *pats, **opts):
1264 """don't add the specified files on the next commit
1264 """don't add the specified files on the next commit
1265
1265
1266 Undo an 'hg add' scheduled for the next commit.
1266 Undo an 'hg add' scheduled for the next commit.
1267 """
1267 """
1268 forget = []
1268 forget = []
1269 for src, abs, rel, exact in walk(repo, pats, opts):
1269 for src, abs, rel, exact in walk(repo, pats, opts):
1270 if repo.dirstate.state(abs) == 'a':
1270 if repo.dirstate.state(abs) == 'a':
1271 forget.append(abs)
1271 forget.append(abs)
1272 if ui.verbose or not exact:
1272 if ui.verbose or not exact:
1273 ui.status(_('forgetting %s\n') % ((pats and rel) or abs))
1273 ui.status(_('forgetting %s\n') % ((pats and rel) or abs))
1274 repo.forget(forget)
1274 repo.forget(forget)
1275
1275
1276 def grep(ui, repo, pattern, *pats, **opts):
1276 def grep(ui, repo, pattern, *pats, **opts):
1277 """search for a pattern in specified files and revisions
1277 """search for a pattern in specified files and revisions
1278
1278
1279 Search revisions of files for a regular expression.
1279 Search revisions of files for a regular expression.
1280
1280
1281 This command behaves differently than Unix grep. It only accepts
1281 This command behaves differently than Unix grep. It only accepts
1282 Python/Perl regexps. It searches repository history, not the
1282 Python/Perl regexps. It searches repository history, not the
1283 working directory. It always prints the revision number in which
1283 working directory. It always prints the revision number in which
1284 a match appears.
1284 a match appears.
1285
1285
1286 By default, grep only prints output for the first revision of a
1286 By default, grep only prints output for the first revision of a
1287 file in which it finds a match. To get it to print every revision
1287 file in which it finds a match. To get it to print every revision
1288 that contains a change in match status ("-" for a match that
1288 that contains a change in match status ("-" for a match that
1289 becomes a non-match, or "+" for a non-match that becomes a match),
1289 becomes a non-match, or "+" for a non-match that becomes a match),
1290 use the --all flag.
1290 use the --all flag.
1291 """
1291 """
1292 reflags = 0
1292 reflags = 0
1293 if opts['ignore_case']:
1293 if opts['ignore_case']:
1294 reflags |= re.I
1294 reflags |= re.I
1295 regexp = re.compile(pattern, reflags)
1295 regexp = re.compile(pattern, reflags)
1296 sep, eol = ':', '\n'
1296 sep, eol = ':', '\n'
1297 if opts['print0']:
1297 if opts['print0']:
1298 sep = eol = '\0'
1298 sep = eol = '\0'
1299
1299
1300 fcache = {}
1300 fcache = {}
1301 def getfile(fn):
1301 def getfile(fn):
1302 if fn not in fcache:
1302 if fn not in fcache:
1303 fcache[fn] = repo.file(fn)
1303 fcache[fn] = repo.file(fn)
1304 return fcache[fn]
1304 return fcache[fn]
1305
1305
1306 def matchlines(body):
1306 def matchlines(body):
1307 begin = 0
1307 begin = 0
1308 linenum = 0
1308 linenum = 0
1309 while True:
1309 while True:
1310 match = regexp.search(body, begin)
1310 match = regexp.search(body, begin)
1311 if not match:
1311 if not match:
1312 break
1312 break
1313 mstart, mend = match.span()
1313 mstart, mend = match.span()
1314 linenum += body.count('\n', begin, mstart) + 1
1314 linenum += body.count('\n', begin, mstart) + 1
1315 lstart = body.rfind('\n', begin, mstart) + 1 or begin
1315 lstart = body.rfind('\n', begin, mstart) + 1 or begin
1316 lend = body.find('\n', mend)
1316 lend = body.find('\n', mend)
1317 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
1317 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
1318 begin = lend + 1
1318 begin = lend + 1
1319
1319
1320 class linestate(object):
1320 class linestate(object):
1321 def __init__(self, line, linenum, colstart, colend):
1321 def __init__(self, line, linenum, colstart, colend):
1322 self.line = line
1322 self.line = line
1323 self.linenum = linenum
1323 self.linenum = linenum
1324 self.colstart = colstart
1324 self.colstart = colstart
1325 self.colend = colend
1325 self.colend = colend
1326 def __eq__(self, other):
1326 def __eq__(self, other):
1327 return self.line == other.line
1327 return self.line == other.line
1328 def __hash__(self):
1328 def __hash__(self):
1329 return hash(self.line)
1329 return hash(self.line)
1330
1330
1331 matches = {}
1331 matches = {}
1332 def grepbody(fn, rev, body):
1332 def grepbody(fn, rev, body):
1333 matches[rev].setdefault(fn, {})
1333 matches[rev].setdefault(fn, {})
1334 m = matches[rev][fn]
1334 m = matches[rev][fn]
1335 for lnum, cstart, cend, line in matchlines(body):
1335 for lnum, cstart, cend, line in matchlines(body):
1336 s = linestate(line, lnum, cstart, cend)
1336 s = linestate(line, lnum, cstart, cend)
1337 m[s] = s
1337 m[s] = s
1338
1338
1339 # FIXME: prev isn't used, why ?
1339 # FIXME: prev isn't used, why ?
1340 prev = {}
1340 prev = {}
1341 ucache = {}
1341 ucache = {}
1342 def display(fn, rev, states, prevstates):
1342 def display(fn, rev, states, prevstates):
1343 diff = list(sets.Set(states).symmetric_difference(sets.Set(prevstates)))
1343 diff = list(sets.Set(states).symmetric_difference(sets.Set(prevstates)))
1344 diff.sort(lambda x, y: cmp(x.linenum, y.linenum))
1344 diff.sort(lambda x, y: cmp(x.linenum, y.linenum))
1345 counts = {'-': 0, '+': 0}
1345 counts = {'-': 0, '+': 0}
1346 filerevmatches = {}
1346 filerevmatches = {}
1347 for l in diff:
1347 for l in diff:
1348 if incrementing or not opts['all']:
1348 if incrementing or not opts['all']:
1349 change = ((l in prevstates) and '-') or '+'
1349 change = ((l in prevstates) and '-') or '+'
1350 r = rev
1350 r = rev
1351 else:
1351 else:
1352 change = ((l in states) and '-') or '+'
1352 change = ((l in states) and '-') or '+'
1353 r = prev[fn]
1353 r = prev[fn]
1354 cols = [fn, str(rev)]
1354 cols = [fn, str(rev)]
1355 if opts['line_number']:
1355 if opts['line_number']:
1356 cols.append(str(l.linenum))
1356 cols.append(str(l.linenum))
1357 if opts['all']:
1357 if opts['all']:
1358 cols.append(change)
1358 cols.append(change)
1359 if opts['user']:
1359 if opts['user']:
1360 cols.append(trimuser(ui, getchange(rev)[1], rev,
1360 cols.append(trimuser(ui, getchange(rev)[1], rev,
1361 ucache))
1361 ucache))
1362 if opts['files_with_matches']:
1362 if opts['files_with_matches']:
1363 c = (fn, rev)
1363 c = (fn, rev)
1364 if c in filerevmatches:
1364 if c in filerevmatches:
1365 continue
1365 continue
1366 filerevmatches[c] = 1
1366 filerevmatches[c] = 1
1367 else:
1367 else:
1368 cols.append(l.line)
1368 cols.append(l.line)
1369 ui.write(sep.join(cols), eol)
1369 ui.write(sep.join(cols), eol)
1370 counts[change] += 1
1370 counts[change] += 1
1371 return counts['+'], counts['-']
1371 return counts['+'], counts['-']
1372
1372
1373 fstate = {}
1373 fstate = {}
1374 skip = {}
1374 skip = {}
1375 changeiter, getchange, matchfn = walkchangerevs(ui, repo, pats, opts)
1375 changeiter, getchange, matchfn = walkchangerevs(ui, repo, pats, opts)
1376 count = 0
1376 count = 0
1377 incrementing = False
1377 incrementing = False
1378 for st, rev, fns in changeiter:
1378 for st, rev, fns in changeiter:
1379 if st == 'window':
1379 if st == 'window':
1380 incrementing = rev
1380 incrementing = rev
1381 matches.clear()
1381 matches.clear()
1382 elif st == 'add':
1382 elif st == 'add':
1383 change = repo.changelog.read(repo.lookup(str(rev)))
1383 change = repo.changelog.read(repo.lookup(str(rev)))
1384 mf = repo.manifest.read(change[0])
1384 mf = repo.manifest.read(change[0])
1385 matches[rev] = {}
1385 matches[rev] = {}
1386 for fn in fns:
1386 for fn in fns:
1387 if fn in skip:
1387 if fn in skip:
1388 continue
1388 continue
1389 fstate.setdefault(fn, {})
1389 fstate.setdefault(fn, {})
1390 try:
1390 try:
1391 grepbody(fn, rev, getfile(fn).read(mf[fn]))
1391 grepbody(fn, rev, getfile(fn).read(mf[fn]))
1392 except KeyError:
1392 except KeyError:
1393 pass
1393 pass
1394 elif st == 'iter':
1394 elif st == 'iter':
1395 states = matches[rev].items()
1395 states = matches[rev].items()
1396 states.sort()
1396 states.sort()
1397 for fn, m in states:
1397 for fn, m in states:
1398 if fn in skip:
1398 if fn in skip:
1399 continue
1399 continue
1400 if incrementing or not opts['all'] or fstate[fn]:
1400 if incrementing or not opts['all'] or fstate[fn]:
1401 pos, neg = display(fn, rev, m, fstate[fn])
1401 pos, neg = display(fn, rev, m, fstate[fn])
1402 count += pos + neg
1402 count += pos + neg
1403 if pos and not opts['all']:
1403 if pos and not opts['all']:
1404 skip[fn] = True
1404 skip[fn] = True
1405 fstate[fn] = m
1405 fstate[fn] = m
1406 prev[fn] = rev
1406 prev[fn] = rev
1407
1407
1408 if not incrementing:
1408 if not incrementing:
1409 fstate = fstate.items()
1409 fstate = fstate.items()
1410 fstate.sort()
1410 fstate.sort()
1411 for fn, state in fstate:
1411 for fn, state in fstate:
1412 if fn in skip:
1412 if fn in skip:
1413 continue
1413 continue
1414 display(fn, rev, {}, state)
1414 display(fn, rev, {}, state)
1415 return (count == 0 and 1) or 0
1415 return (count == 0 and 1) or 0
1416
1416
1417 def heads(ui, repo, **opts):
1417 def heads(ui, repo, **opts):
1418 """show current repository heads
1418 """show current repository heads
1419
1419
1420 Show all repository head changesets.
1420 Show all repository head changesets.
1421
1421
1422 Repository "heads" are changesets that don't have children
1422 Repository "heads" are changesets that don't have children
1423 changesets. They are where development generally takes place and
1423 changesets. They are where development generally takes place and
1424 are the usual targets for update and merge operations.
1424 are the usual targets for update and merge operations.
1425 """
1425 """
1426 if opts['rev']:
1426 if opts['rev']:
1427 heads = repo.heads(repo.lookup(opts['rev']))
1427 heads = repo.heads(repo.lookup(opts['rev']))
1428 else:
1428 else:
1429 heads = repo.heads()
1429 heads = repo.heads()
1430 br = None
1430 br = None
1431 if opts['branches']:
1431 if opts['branches']:
1432 br = repo.branchlookup(heads)
1432 br = repo.branchlookup(heads)
1433 for n in heads:
1433 for n in heads:
1434 show_changeset(ui, repo, changenode=n, brinfo=br)
1434 show_changeset(ui, repo, changenode=n, brinfo=br)
1435
1435
1436 def identify(ui, repo):
1436 def identify(ui, repo):
1437 """print information about the working copy
1437 """print information about the working copy
1438
1438
1439 Print a short summary of the current state of the repo.
1439 Print a short summary of the current state of the repo.
1440
1440
1441 This summary identifies the repository state using one or two parent
1441 This summary identifies the repository state using one or two parent
1442 hash identifiers, followed by a "+" if there are uncommitted changes
1442 hash identifiers, followed by a "+" if there are uncommitted changes
1443 in the working directory, followed by a list of tags for this revision.
1443 in the working directory, followed by a list of tags for this revision.
1444 """
1444 """
1445 parents = [p for p in repo.dirstate.parents() if p != nullid]
1445 parents = [p for p in repo.dirstate.parents() if p != nullid]
1446 if not parents:
1446 if not parents:
1447 ui.write(_("unknown\n"))
1447 ui.write(_("unknown\n"))
1448 return
1448 return
1449
1449
1450 hexfunc = ui.verbose and hex or short
1450 hexfunc = ui.verbose and hex or short
1451 modified, added, removed, deleted, unknown = repo.changes()
1451 modified, added, removed, deleted, unknown = repo.changes()
1452 output = ["%s%s" %
1452 output = ["%s%s" %
1453 ('+'.join([hexfunc(parent) for parent in parents]),
1453 ('+'.join([hexfunc(parent) for parent in parents]),
1454 (modified or added or removed or deleted) and "+" or "")]
1454 (modified or added or removed or deleted) and "+" or "")]
1455
1455
1456 if not ui.quiet:
1456 if not ui.quiet:
1457 # multiple tags for a single parent separated by '/'
1457 # multiple tags for a single parent separated by '/'
1458 parenttags = ['/'.join(tags)
1458 parenttags = ['/'.join(tags)
1459 for tags in map(repo.nodetags, parents) if tags]
1459 for tags in map(repo.nodetags, parents) if tags]
1460 # tags for multiple parents separated by ' + '
1460 # tags for multiple parents separated by ' + '
1461 if parenttags:
1461 if parenttags:
1462 output.append(' + '.join(parenttags))
1462 output.append(' + '.join(parenttags))
1463
1463
1464 ui.write("%s\n" % ' '.join(output))
1464 ui.write("%s\n" % ' '.join(output))
1465
1465
1466 def import_(ui, repo, patch1, *patches, **opts):
1466 def import_(ui, repo, patch1, *patches, **opts):
1467 """import an ordered set of patches
1467 """import an ordered set of patches
1468
1468
1469 Import a list of patches and commit them individually.
1469 Import a list of patches and commit them individually.
1470
1470
1471 If there are outstanding changes in the working directory, import
1471 If there are outstanding changes in the working directory, import
1472 will abort unless given the -f flag.
1472 will abort unless given the -f flag.
1473
1473
1474 If a patch looks like a mail message (its first line starts with
1474 If a patch looks like a mail message (its first line starts with
1475 "From " or looks like an RFC822 header), it will not be applied
1475 "From " or looks like an RFC822 header), it will not be applied
1476 unless the -f option is used. The importer neither parses nor
1476 unless the -f option is used. The importer neither parses nor
1477 discards mail headers, so use -f only to override the "mailness"
1477 discards mail headers, so use -f only to override the "mailness"
1478 safety check, not to import a real mail message.
1478 safety check, not to import a real mail message.
1479 """
1479 """
1480 patches = (patch1,) + patches
1480 patches = (patch1,) + patches
1481
1481
1482 if not opts['force']:
1482 if not opts['force']:
1483 modified, added, removed, deleted, unknown = repo.changes()
1483 modified, added, removed, deleted, unknown = repo.changes()
1484 if modified or added or removed or deleted:
1484 if modified or added or removed or deleted:
1485 raise util.Abort(_("outstanding uncommitted changes"))
1485 raise util.Abort(_("outstanding uncommitted changes"))
1486
1486
1487 d = opts["base"]
1487 d = opts["base"]
1488 strip = opts["strip"]
1488 strip = opts["strip"]
1489
1489
1490 mailre = re.compile(r'(?:From |[\w-]+:)')
1490 mailre = re.compile(r'(?:From |[\w-]+:)')
1491
1491
1492 # attempt to detect the start of a patch
1492 # attempt to detect the start of a patch
1493 # (this heuristic is borrowed from quilt)
1493 # (this heuristic is borrowed from quilt)
1494 diffre = re.compile(r'(?:Index:[ \t]|diff[ \t]|RCS file: |' +
1494 diffre = re.compile(r'(?:Index:[ \t]|diff[ \t]|RCS file: |' +
1495 'retrieving revision [0-9]+(\.[0-9]+)*$|' +
1495 'retrieving revision [0-9]+(\.[0-9]+)*$|' +
1496 '(---|\*\*\*)[ \t])')
1496 '(---|\*\*\*)[ \t])')
1497
1497
1498 for patch in patches:
1498 for patch in patches:
1499 ui.status(_("applying %s\n") % patch)
1499 ui.status(_("applying %s\n") % patch)
1500 pf = os.path.join(d, patch)
1500 pf = os.path.join(d, patch)
1501
1501
1502 message = []
1502 message = []
1503 user = None
1503 user = None
1504 hgpatch = False
1504 hgpatch = False
1505 for line in file(pf):
1505 for line in file(pf):
1506 line = line.rstrip()
1506 line = line.rstrip()
1507 if (not message and not hgpatch and
1507 if (not message and not hgpatch and
1508 mailre.match(line) and not opts['force']):
1508 mailre.match(line) and not opts['force']):
1509 if len(line) > 35:
1509 if len(line) > 35:
1510 line = line[:32] + '...'
1510 line = line[:32] + '...'
1511 raise util.Abort(_('first line looks like a '
1511 raise util.Abort(_('first line looks like a '
1512 'mail header: ') + line)
1512 'mail header: ') + line)
1513 if diffre.match(line):
1513 if diffre.match(line):
1514 break
1514 break
1515 elif hgpatch:
1515 elif hgpatch:
1516 # parse values when importing the result of an hg export
1516 # parse values when importing the result of an hg export
1517 if line.startswith("# User "):
1517 if line.startswith("# User "):
1518 user = line[7:]
1518 user = line[7:]
1519 ui.debug(_('User: %s\n') % user)
1519 ui.debug(_('User: %s\n') % user)
1520 elif not line.startswith("# ") and line:
1520 elif not line.startswith("# ") and line:
1521 message.append(line)
1521 message.append(line)
1522 hgpatch = False
1522 hgpatch = False
1523 elif line == '# HG changeset patch':
1523 elif line == '# HG changeset patch':
1524 hgpatch = True
1524 hgpatch = True
1525 message = [] # We may have collected garbage
1525 message = [] # We may have collected garbage
1526 else:
1526 else:
1527 message.append(line)
1527 message.append(line)
1528
1528
1529 # make sure message isn't empty
1529 # make sure message isn't empty
1530 if not message:
1530 if not message:
1531 message = _("imported patch %s\n") % patch
1531 message = _("imported patch %s\n") % patch
1532 else:
1532 else:
1533 message = "%s\n" % '\n'.join(message)
1533 message = "%s\n" % '\n'.join(message)
1534 ui.debug(_('message:\n%s\n') % message)
1534 ui.debug(_('message:\n%s\n') % message)
1535
1535
1536 files = util.patch(strip, pf, ui)
1536 files = util.patch(strip, pf, ui)
1537
1537
1538 if len(files) > 0:
1538 if len(files) > 0:
1539 addremove(ui, repo, *files)
1539 addremove(ui, repo, *files)
1540 repo.commit(files, message, user)
1540 repo.commit(files, message, user)
1541
1541
1542 def incoming(ui, repo, source="default", **opts):
1542 def incoming(ui, repo, source="default", **opts):
1543 """show new changesets found in source
1543 """show new changesets found in source
1544
1544
1545 Show new changesets found in the specified repo or the default
1545 Show new changesets found in the specified repo or the default
1546 pull repo. These are the changesets that would be pulled if a pull
1546 pull repo. These are the changesets that would be pulled if a pull
1547 was requested.
1547 was requested.
1548
1548
1549 Currently only local repositories are supported.
1549 Currently only local repositories are supported.
1550 """
1550 """
1551 source = ui.expandpath(source, repo.root)
1551 source = ui.expandpath(source, repo.root)
1552 other = hg.repository(ui, source)
1552 other = hg.repository(ui, source)
1553 if not other.local():
1553 if not other.local():
1554 raise util.Abort(_("incoming doesn't work for remote repositories yet"))
1554 raise util.Abort(_("incoming doesn't work for remote repositories yet"))
1555 o = repo.findincoming(other)
1555 o = repo.findincoming(other)
1556 if not o:
1556 if not o:
1557 return
1557 return
1558 o = other.changelog.nodesbetween(o)[0]
1558 o = other.changelog.nodesbetween(o)[0]
1559 if opts['newest_first']:
1559 if opts['newest_first']:
1560 o.reverse()
1560 o.reverse()
1561 for n in o:
1561 for n in o:
1562 parents = [p for p in other.changelog.parents(n) if p != nullid]
1562 parents = [p for p in other.changelog.parents(n) if p != nullid]
1563 if opts['no_merges'] and len(parents) == 2:
1563 if opts['no_merges'] and len(parents) == 2:
1564 continue
1564 continue
1565 show_changeset(ui, other, changenode=n)
1565 show_changeset(ui, other, changenode=n)
1566 if opts['patch']:
1566 if opts['patch']:
1567 prev = (parents and parents[0]) or nullid
1567 prev = (parents and parents[0]) or nullid
1568 dodiff(ui, ui, other, prev, n)
1568 dodiff(ui, ui, other, prev, n)
1569 ui.write("\n")
1569 ui.write("\n")
1570
1570
1571 def init(ui, dest="."):
1571 def init(ui, dest="."):
1572 """create a new repository in the given directory
1572 """create a new repository in the given directory
1573
1573
1574 Initialize a new repository in the given directory. If the given
1574 Initialize a new repository in the given directory. If the given
1575 directory does not exist, it is created.
1575 directory does not exist, it is created.
1576
1576
1577 If no directory is given, the current directory is used.
1577 If no directory is given, the current directory is used.
1578 """
1578 """
1579 if not os.path.exists(dest):
1579 if not os.path.exists(dest):
1580 os.mkdir(dest)
1580 os.mkdir(dest)
1581 hg.repository(ui, dest, create=1)
1581 hg.repository(ui, dest, create=1)
1582
1582
1583 def locate(ui, repo, *pats, **opts):
1583 def locate(ui, repo, *pats, **opts):
1584 """locate files matching specific patterns
1584 """locate files matching specific patterns
1585
1585
1586 Print all files under Mercurial control whose names match the
1586 Print all files under Mercurial control whose names match the
1587 given patterns.
1587 given patterns.
1588
1588
1589 This command searches the current directory and its
1589 This command searches the current directory and its
1590 subdirectories. To search an entire repository, move to the root
1590 subdirectories. To search an entire repository, move to the root
1591 of the repository.
1591 of the repository.
1592
1592
1593 If no patterns are given to match, this command prints all file
1593 If no patterns are given to match, this command prints all file
1594 names.
1594 names.
1595
1595
1596 If you want to feed the output of this command into the "xargs"
1596 If you want to feed the output of this command into the "xargs"
1597 command, use the "-0" option to both this command and "xargs".
1597 command, use the "-0" option to both this command and "xargs".
1598 This will avoid the problem of "xargs" treating single filenames
1598 This will avoid the problem of "xargs" treating single filenames
1599 that contain white space as multiple filenames.
1599 that contain white space as multiple filenames.
1600 """
1600 """
1601 end = opts['print0'] and '\0' or '\n'
1601 end = opts['print0'] and '\0' or '\n'
1602 rev = opts['rev']
1602 rev = opts['rev']
1603 if rev:
1603 if rev:
1604 node = repo.lookup(rev)
1604 node = repo.lookup(rev)
1605 else:
1605 else:
1606 node = None
1606 node = None
1607
1607
1608 for src, abs, rel, exact in walk(repo, pats, opts, node=node,
1608 for src, abs, rel, exact in walk(repo, pats, opts, node=node,
1609 head='(?:.*/|)'):
1609 head='(?:.*/|)'):
1610 if not node and repo.dirstate.state(abs) == '?':
1610 if not node and repo.dirstate.state(abs) == '?':
1611 continue
1611 continue
1612 if opts['fullpath']:
1612 if opts['fullpath']:
1613 ui.write(os.path.join(repo.root, abs), end)
1613 ui.write(os.path.join(repo.root, abs), end)
1614 else:
1614 else:
1615 ui.write(((pats and rel) or abs), end)
1615 ui.write(((pats and rel) or abs), end)
1616
1616
1617 def log(ui, repo, *pats, **opts):
1617 def log(ui, repo, *pats, **opts):
1618 """show revision history of entire repository or files
1618 """show revision history of entire repository or files
1619
1619
1620 Print the revision history of the specified files or the entire project.
1620 Print the revision history of the specified files or the entire project.
1621
1621
1622 By default this command outputs: changeset id and hash, tags,
1622 By default this command outputs: changeset id and hash, tags,
1623 non-trivial parents, user, date and time, and a summary for each
1623 non-trivial parents, user, date and time, and a summary for each
1624 commit. When the -v/--verbose switch is used, the list of changed
1624 commit. When the -v/--verbose switch is used, the list of changed
1625 files and full commit message is shown.
1625 files and full commit message is shown.
1626 """
1626 """
1627 class dui(object):
1627 class dui(object):
1628 # Implement and delegate some ui protocol. Save hunks of
1628 # Implement and delegate some ui protocol. Save hunks of
1629 # output for later display in the desired order.
1629 # output for later display in the desired order.
1630 def __init__(self, ui):
1630 def __init__(self, ui):
1631 self.ui = ui
1631 self.ui = ui
1632 self.hunk = {}
1632 self.hunk = {}
1633 def bump(self, rev):
1633 def bump(self, rev):
1634 self.rev = rev
1634 self.rev = rev
1635 self.hunk[rev] = []
1635 self.hunk[rev] = []
1636 def note(self, *args):
1636 def note(self, *args):
1637 if self.verbose:
1637 if self.verbose:
1638 self.write(*args)
1638 self.write(*args)
1639 def status(self, *args):
1639 def status(self, *args):
1640 if not self.quiet:
1640 if not self.quiet:
1641 self.write(*args)
1641 self.write(*args)
1642 def write(self, *args):
1642 def write(self, *args):
1643 self.hunk[self.rev].append(args)
1643 self.hunk[self.rev].append(args)
1644 def debug(self, *args):
1644 def debug(self, *args):
1645 if self.debugflag:
1645 if self.debugflag:
1646 self.write(*args)
1646 self.write(*args)
1647 def __getattr__(self, key):
1647 def __getattr__(self, key):
1648 return getattr(self.ui, key)
1648 return getattr(self.ui, key)
1649
1649
1650 changeiter, getchange, matchfn = walkchangerevs(ui, repo, pats, opts)
1650 changeiter, getchange, matchfn = walkchangerevs(ui, repo, pats, opts)
1651
1651
1652 if opts['limit']:
1652 if opts['limit']:
1653 try:
1653 try:
1654 limit = int(opts['limit'])
1654 limit = int(opts['limit'])
1655 except ValueError:
1655 except ValueError:
1656 raise util.Abort(_('limit must be a positive integer'))
1656 raise util.Abort(_('limit must be a positive integer'))
1657 if limit <= 0: raise util.Abort(_('limit must be positive'))
1657 if limit <= 0: raise util.Abort(_('limit must be positive'))
1658 else:
1658 else:
1659 limit = sys.maxint
1659 limit = sys.maxint
1660 count = 0
1660 count = 0
1661
1661
1662 for st, rev, fns in changeiter:
1662 for st, rev, fns in changeiter:
1663 if st == 'window':
1663 if st == 'window':
1664 du = dui(ui)
1664 du = dui(ui)
1665 elif st == 'add':
1665 elif st == 'add':
1666 du.bump(rev)
1666 du.bump(rev)
1667 changenode = repo.changelog.node(rev)
1667 changenode = repo.changelog.node(rev)
1668 parents = [p for p in repo.changelog.parents(changenode)
1668 parents = [p for p in repo.changelog.parents(changenode)
1669 if p != nullid]
1669 if p != nullid]
1670 if opts['no_merges'] and len(parents) == 2:
1670 if opts['no_merges'] and len(parents) == 2:
1671 continue
1671 continue
1672 if opts['only_merges'] and len(parents) != 2:
1672 if opts['only_merges'] and len(parents) != 2:
1673 continue
1673 continue
1674
1674
1675 if opts['keyword']:
1675 if opts['keyword']:
1676 changes = getchange(rev)
1676 changes = getchange(rev)
1677 miss = 0
1677 miss = 0
1678 for k in [kw.lower() for kw in opts['keyword']]:
1678 for k in [kw.lower() for kw in opts['keyword']]:
1679 if not (k in changes[1].lower() or
1679 if not (k in changes[1].lower() or
1680 k in changes[4].lower() or
1680 k in changes[4].lower() or
1681 k in " ".join(changes[3][:20]).lower()):
1681 k in " ".join(changes[3][:20]).lower()):
1682 miss = 1
1682 miss = 1
1683 break
1683 break
1684 if miss:
1684 if miss:
1685 continue
1685 continue
1686
1686
1687 br = None
1687 br = None
1688 if opts['branches']:
1688 if opts['branches']:
1689 br = repo.branchlookup([repo.changelog.node(rev)])
1689 br = repo.branchlookup([repo.changelog.node(rev)])
1690
1690
1691 show_changeset(du, repo, rev, brinfo=br)
1691 show_changeset(du, repo, rev, brinfo=br)
1692 if opts['patch']:
1692 if opts['patch']:
1693 prev = (parents and parents[0]) or nullid
1693 prev = (parents and parents[0]) or nullid
1694 dodiff(du, du, repo, prev, changenode, match=matchfn)
1694 dodiff(du, du, repo, prev, changenode, match=matchfn)
1695 du.write("\n\n")
1695 du.write("\n\n")
1696 elif st == 'iter':
1696 elif st == 'iter':
1697 if count == limit: break
1697 if count == limit: break
1698 if du.hunk[rev]:
1698 if du.hunk[rev]:
1699 count += 1
1699 count += 1
1700 for args in du.hunk[rev]:
1700 for args in du.hunk[rev]:
1701 ui.write(*args)
1701 ui.write(*args)
1702
1702
1703 def manifest(ui, repo, rev=None):
1703 def manifest(ui, repo, rev=None):
1704 """output the latest or given revision of the project manifest
1704 """output the latest or given revision of the project manifest
1705
1705
1706 Print a list of version controlled files for the given revision.
1706 Print a list of version controlled files for the given revision.
1707
1707
1708 The manifest is the list of files being version controlled. If no revision
1708 The manifest is the list of files being version controlled. If no revision
1709 is given then the tip is used.
1709 is given then the tip is used.
1710 """
1710 """
1711 if rev:
1711 if rev:
1712 try:
1712 try:
1713 # assume all revision numbers are for changesets
1713 # assume all revision numbers are for changesets
1714 n = repo.lookup(rev)
1714 n = repo.lookup(rev)
1715 change = repo.changelog.read(n)
1715 change = repo.changelog.read(n)
1716 n = change[0]
1716 n = change[0]
1717 except hg.RepoError:
1717 except hg.RepoError:
1718 n = repo.manifest.lookup(rev)
1718 n = repo.manifest.lookup(rev)
1719 else:
1719 else:
1720 n = repo.manifest.tip()
1720 n = repo.manifest.tip()
1721 m = repo.manifest.read(n)
1721 m = repo.manifest.read(n)
1722 mf = repo.manifest.readflags(n)
1722 mf = repo.manifest.readflags(n)
1723 files = m.keys()
1723 files = m.keys()
1724 files.sort()
1724 files.sort()
1725
1725
1726 for f in files:
1726 for f in files:
1727 ui.write("%40s %3s %s\n" % (hex(m[f]), mf[f] and "755" or "644", f))
1727 ui.write("%40s %3s %s\n" % (hex(m[f]), mf[f] and "755" or "644", f))
1728
1728
1729 def outgoing(ui, repo, dest="default-push", **opts):
1729 def outgoing(ui, repo, dest="default-push", **opts):
1730 """show changesets not found in destination
1730 """show changesets not found in destination
1731
1731
1732 Show changesets not found in the specified destination repo or the
1732 Show changesets not found in the specified destination repo or the
1733 default push repo. These are the changesets that would be pushed
1733 default push repo. These are the changesets that would be pushed
1734 if a push was requested.
1734 if a push was requested.
1735
1735
1736 See pull for valid source format details.
1736 See pull for valid source format details.
1737 """
1737 """
1738 dest = ui.expandpath(dest, repo.root)
1738 dest = ui.expandpath(dest, repo.root)
1739 other = hg.repository(ui, dest)
1739 other = hg.repository(ui, dest)
1740 o = repo.findoutgoing(other)
1740 o = repo.findoutgoing(other)
1741 o = repo.changelog.nodesbetween(o)[0]
1741 o = repo.changelog.nodesbetween(o)[0]
1742 if opts['newest_first']:
1742 if opts['newest_first']:
1743 o.reverse()
1743 o.reverse()
1744 for n in o:
1744 for n in o:
1745 parents = [p for p in repo.changelog.parents(n) if p != nullid]
1745 parents = [p for p in repo.changelog.parents(n) if p != nullid]
1746 if opts['no_merges'] and len(parents) == 2:
1746 if opts['no_merges'] and len(parents) == 2:
1747 continue
1747 continue
1748 show_changeset(ui, repo, changenode=n)
1748 show_changeset(ui, repo, changenode=n)
1749 if opts['patch']:
1749 if opts['patch']:
1750 prev = (parents and parents[0]) or nullid
1750 prev = (parents and parents[0]) or nullid
1751 dodiff(ui, ui, repo, prev, n)
1751 dodiff(ui, ui, repo, prev, n)
1752 ui.write("\n")
1752 ui.write("\n")
1753
1753
1754 def parents(ui, repo, rev=None, branches=None):
1754 def parents(ui, repo, rev=None, branches=None):
1755 """show the parents of the working dir or revision
1755 """show the parents of the working dir or revision
1756
1756
1757 Print the working directory's parent revisions.
1757 Print the working directory's parent revisions.
1758 """
1758 """
1759 if rev:
1759 if rev:
1760 p = repo.changelog.parents(repo.lookup(rev))
1760 p = repo.changelog.parents(repo.lookup(rev))
1761 else:
1761 else:
1762 p = repo.dirstate.parents()
1762 p = repo.dirstate.parents()
1763
1763
1764 br = None
1764 br = None
1765 if branches is not None:
1765 if branches is not None:
1766 br = repo.branchlookup(p)
1766 br = repo.branchlookup(p)
1767 for n in p:
1767 for n in p:
1768 if n != nullid:
1768 if n != nullid:
1769 show_changeset(ui, repo, changenode=n, brinfo=br)
1769 show_changeset(ui, repo, changenode=n, brinfo=br)
1770
1770
1771 def paths(ui, search=None):
1771 def paths(ui, search=None):
1772 """show definition of symbolic path names
1772 """show definition of symbolic path names
1773
1773
1774 Show definition of symbolic path name NAME. If no name is given, show
1774 Show definition of symbolic path name NAME. If no name is given, show
1775 definition of available names.
1775 definition of available names.
1776
1776
1777 Path names are defined in the [paths] section of /etc/mercurial/hgrc
1777 Path names are defined in the [paths] section of /etc/mercurial/hgrc
1778 and $HOME/.hgrc. If run inside a repository, .hg/hgrc is used, too.
1778 and $HOME/.hgrc. If run inside a repository, .hg/hgrc is used, too.
1779 """
1779 """
1780 try:
1780 try:
1781 repo = hg.repository(ui)
1781 repo = hg.repository(ui)
1782 ui = repo.ui
1782 ui = repo.ui
1783 except hg.RepoError:
1783 except hg.RepoError:
1784 pass
1784 pass
1785
1785
1786 if search:
1786 if search:
1787 for name, path in ui.configitems("paths"):
1787 for name, path in ui.configitems("paths"):
1788 if name == search:
1788 if name == search:
1789 ui.write("%s\n" % path)
1789 ui.write("%s\n" % path)
1790 return
1790 return
1791 ui.warn(_("not found!\n"))
1791 ui.warn(_("not found!\n"))
1792 return 1
1792 return 1
1793 else:
1793 else:
1794 for name, path in ui.configitems("paths"):
1794 for name, path in ui.configitems("paths"):
1795 ui.write("%s = %s\n" % (name, path))
1795 ui.write("%s = %s\n" % (name, path))
1796
1796
1797 def pull(ui, repo, source="default", **opts):
1797 def pull(ui, repo, source="default", **opts):
1798 """pull changes from the specified source
1798 """pull changes from the specified source
1799
1799
1800 Pull changes from a remote repository to a local one.
1800 Pull changes from a remote repository to a local one.
1801
1801
1802 This finds all changes from the repository at the specified path
1802 This finds all changes from the repository at the specified path
1803 or URL and adds them to the local repository. By default, this
1803 or URL and adds them to the local repository. By default, this
1804 does not update the copy of the project in the working directory.
1804 does not update the copy of the project in the working directory.
1805
1805
1806 Valid URLs are of the form:
1806 Valid URLs are of the form:
1807
1807
1808 local/filesystem/path
1808 local/filesystem/path
1809 http://[user@]host[:port][/path]
1809 http://[user@]host[:port][/path]
1810 https://[user@]host[:port][/path]
1810 https://[user@]host[:port][/path]
1811 ssh://[user@]host[:port][/path]
1811 ssh://[user@]host[:port][/path]
1812
1812
1813 SSH requires an accessible shell account on the destination machine
1813 SSH requires an accessible shell account on the destination machine
1814 and a copy of hg in the remote path. With SSH, paths are relative
1814 and a copy of hg in the remote path. With SSH, paths are relative
1815 to the remote user's home directory by default; use two slashes at
1815 to the remote user's home directory by default; use two slashes at
1816 the start of a path to specify it as relative to the filesystem root.
1816 the start of a path to specify it as relative to the filesystem root.
1817 """
1817 """
1818 source = ui.expandpath(source, repo.root)
1818 source = ui.expandpath(source, repo.root)
1819 ui.status(_('pulling from %s\n') % (source))
1819 ui.status(_('pulling from %s\n') % (source))
1820
1820
1821 if opts['ssh']:
1821 if opts['ssh']:
1822 ui.setconfig("ui", "ssh", opts['ssh'])
1822 ui.setconfig("ui", "ssh", opts['ssh'])
1823 if opts['remotecmd']:
1823 if opts['remotecmd']:
1824 ui.setconfig("ui", "remotecmd", opts['remotecmd'])
1824 ui.setconfig("ui", "remotecmd", opts['remotecmd'])
1825
1825
1826 other = hg.repository(ui, source)
1826 other = hg.repository(ui, source)
1827 revs = None
1827 revs = None
1828 if opts['rev'] and not other.local():
1828 if opts['rev'] and not other.local():
1829 raise util.Abort(_("pull -r doesn't work for remote repositories yet"))
1829 raise util.Abort(_("pull -r doesn't work for remote repositories yet"))
1830 elif opts['rev']:
1830 elif opts['rev']:
1831 revs = [other.lookup(rev) for rev in opts['rev']]
1831 revs = [other.lookup(rev) for rev in opts['rev']]
1832 r = repo.pull(other, heads=revs)
1832 r = repo.pull(other, heads=revs)
1833 if not r:
1833 if not r:
1834 if opts['update']:
1834 if opts['update']:
1835 return update(ui, repo)
1835 return update(ui, repo)
1836 else:
1836 else:
1837 ui.status(_("(run 'hg update' to get a working copy)\n"))
1837 ui.status(_("(run 'hg update' to get a working copy)\n"))
1838
1838
1839 return r
1839 return r
1840
1840
1841 def push(ui, repo, dest="default-push", **opts):
1841 def push(ui, repo, dest="default-push", **opts):
1842 """push changes to the specified destination
1842 """push changes to the specified destination
1843
1843
1844 Push changes from the local repository to the given destination.
1844 Push changes from the local repository to the given destination.
1845
1845
1846 This is the symmetrical operation for pull. It helps to move
1846 This is the symmetrical operation for pull. It helps to move
1847 changes from the current repository to a different one. If the
1847 changes from the current repository to a different one. If the
1848 destination is local this is identical to a pull in that directory
1848 destination is local this is identical to a pull in that directory
1849 from the current one.
1849 from the current one.
1850
1850
1851 By default, push will refuse to run if it detects the result would
1851 By default, push will refuse to run if it detects the result would
1852 increase the number of remote heads. This generally indicates the
1852 increase the number of remote heads. This generally indicates the
1853 the client has forgotten to sync and merge before pushing.
1853 the client has forgotten to sync and merge before pushing.
1854
1854
1855 Valid URLs are of the form:
1855 Valid URLs are of the form:
1856
1856
1857 local/filesystem/path
1857 local/filesystem/path
1858 ssh://[user@]host[:port][/path]
1858 ssh://[user@]host[:port][/path]
1859
1859
1860 SSH requires an accessible shell account on the destination
1860 SSH requires an accessible shell account on the destination
1861 machine and a copy of hg in the remote path.
1861 machine and a copy of hg in the remote path.
1862 """
1862 """
1863 dest = ui.expandpath(dest, repo.root)
1863 dest = ui.expandpath(dest, repo.root)
1864 ui.status('pushing to %s\n' % (dest))
1864 ui.status('pushing to %s\n' % (dest))
1865
1865
1866 if opts['ssh']:
1866 if opts['ssh']:
1867 ui.setconfig("ui", "ssh", opts['ssh'])
1867 ui.setconfig("ui", "ssh", opts['ssh'])
1868 if opts['remotecmd']:
1868 if opts['remotecmd']:
1869 ui.setconfig("ui", "remotecmd", opts['remotecmd'])
1869 ui.setconfig("ui", "remotecmd", opts['remotecmd'])
1870
1870
1871 other = hg.repository(ui, dest)
1871 other = hg.repository(ui, dest)
1872 revs = None
1872 revs = None
1873 if opts['rev']:
1873 if opts['rev']:
1874 revs = [repo.lookup(rev) for rev in opts['rev']]
1874 revs = [repo.lookup(rev) for rev in opts['rev']]
1875 r = repo.push(other, opts['force'], revs=revs)
1875 r = repo.push(other, opts['force'], revs=revs)
1876 return r
1876 return r
1877
1877
1878 def rawcommit(ui, repo, *flist, **rc):
1878 def rawcommit(ui, repo, *flist, **rc):
1879 """raw commit interface (DEPRECATED)
1879 """raw commit interface (DEPRECATED)
1880
1880
1881 (DEPRECATED)
1881 (DEPRECATED)
1882 Lowlevel commit, for use in helper scripts.
1882 Lowlevel commit, for use in helper scripts.
1883
1883
1884 This command is not intended to be used by normal users, as it is
1884 This command is not intended to be used by normal users, as it is
1885 primarily useful for importing from other SCMs.
1885 primarily useful for importing from other SCMs.
1886
1886
1887 This command is now deprecated and will be removed in a future
1887 This command is now deprecated and will be removed in a future
1888 release, please use debugsetparents and commit instead.
1888 release, please use debugsetparents and commit instead.
1889 """
1889 """
1890
1890
1891 ui.warn(_("(the rawcommit command is deprecated)\n"))
1891 ui.warn(_("(the rawcommit command is deprecated)\n"))
1892
1892
1893 message = rc['message']
1893 message = rc['message']
1894 if not message and rc['logfile']:
1894 if not message and rc['logfile']:
1895 try:
1895 try:
1896 message = open(rc['logfile']).read()
1896 message = open(rc['logfile']).read()
1897 except IOError:
1897 except IOError:
1898 pass
1898 pass
1899 if not message and not rc['logfile']:
1899 if not message and not rc['logfile']:
1900 raise util.Abort(_("missing commit message"))
1900 raise util.Abort(_("missing commit message"))
1901
1901
1902 files = relpath(repo, list(flist))
1902 files = relpath(repo, list(flist))
1903 if rc['files']:
1903 if rc['files']:
1904 files += open(rc['files']).read().splitlines()
1904 files += open(rc['files']).read().splitlines()
1905
1905
1906 rc['parent'] = map(repo.lookup, rc['parent'])
1906 rc['parent'] = map(repo.lookup, rc['parent'])
1907
1907
1908 try:
1908 try:
1909 repo.rawcommit(files, message, rc['user'], rc['date'], *rc['parent'])
1909 repo.rawcommit(files, message, rc['user'], rc['date'], *rc['parent'])
1910 except ValueError, inst:
1910 except ValueError, inst:
1911 raise util.Abort(str(inst))
1911 raise util.Abort(str(inst))
1912
1912
1913 def recover(ui, repo):
1913 def recover(ui, repo):
1914 """roll back an interrupted transaction
1914 """roll back an interrupted transaction
1915
1915
1916 Recover from an interrupted commit or pull.
1916 Recover from an interrupted commit or pull.
1917
1917
1918 This command tries to fix the repository status after an interrupted
1918 This command tries to fix the repository status after an interrupted
1919 operation. It should only be necessary when Mercurial suggests it.
1919 operation. It should only be necessary when Mercurial suggests it.
1920 """
1920 """
1921 if repo.recover():
1921 if repo.recover():
1922 return repo.verify()
1922 return repo.verify()
1923 return False
1923 return False
1924
1924
1925 def remove(ui, repo, pat, *pats, **opts):
1925 def remove(ui, repo, pat, *pats, **opts):
1926 """remove the specified files on the next commit
1926 """remove the specified files on the next commit
1927
1927
1928 Schedule the indicated files for removal from the repository.
1928 Schedule the indicated files for removal from the repository.
1929
1929
1930 This command schedules the files to be removed at the next commit.
1930 This command schedules the files to be removed at the next commit.
1931 This only removes files from the current branch, not from the
1931 This only removes files from the current branch, not from the
1932 entire project history. If the files still exist in the working
1932 entire project history. If the files still exist in the working
1933 directory, they will be deleted from it.
1933 directory, they will be deleted from it.
1934 """
1934 """
1935 names = []
1935 names = []
1936 def okaytoremove(abs, rel, exact):
1936 def okaytoremove(abs, rel, exact):
1937 modified, added, removed, deleted, unknown = repo.changes(files=[abs])
1937 modified, added, removed, deleted, unknown = repo.changes(files=[abs])
1938 reason = None
1938 reason = None
1939 if modified:
1939 if modified:
1940 reason = _('is modified')
1940 reason = _('is modified')
1941 elif added:
1941 elif added:
1942 reason = _('has been marked for add')
1942 reason = _('has been marked for add')
1943 elif unknown:
1943 elif unknown:
1944 reason = _('is not managed')
1944 reason = _('is not managed')
1945 if reason:
1945 if reason:
1946 if exact:
1946 if exact:
1947 ui.warn(_('not removing %s: file %s\n') % (rel, reason))
1947 ui.warn(_('not removing %s: file %s\n') % (rel, reason))
1948 else:
1948 else:
1949 return True
1949 return True
1950 for src, abs, rel, exact in walk(repo, (pat,) + pats, opts):
1950 for src, abs, rel, exact in walk(repo, (pat,) + pats, opts):
1951 if okaytoremove(abs, rel, exact):
1951 if okaytoremove(abs, rel, exact):
1952 if ui.verbose or not exact:
1952 if ui.verbose or not exact:
1953 ui.status(_('removing %s\n') % rel)
1953 ui.status(_('removing %s\n') % rel)
1954 names.append(abs)
1954 names.append(abs)
1955 repo.remove(names, unlink=True)
1955 repo.remove(names, unlink=True)
1956
1956
1957 def rename(ui, repo, *pats, **opts):
1957 def rename(ui, repo, *pats, **opts):
1958 """rename files; equivalent of copy + remove
1958 """rename files; equivalent of copy + remove
1959
1959
1960 Mark dest as copies of sources; mark sources for deletion. If
1960 Mark dest as copies of sources; mark sources for deletion. If
1961 dest is a directory, copies are put in that directory. If dest is
1961 dest is a directory, copies are put in that directory. If dest is
1962 a file, there can only be one source.
1962 a file, there can only be one source.
1963
1963
1964 By default, this command copies the contents of files as they
1964 By default, this command copies the contents of files as they
1965 stand in the working directory. If invoked with --after, the
1965 stand in the working directory. If invoked with --after, the
1966 operation is recorded, but no copying is performed.
1966 operation is recorded, but no copying is performed.
1967
1967
1968 This command takes effect in the next commit.
1968 This command takes effect in the next commit.
1969
1969
1970 NOTE: This command should be treated as experimental. While it
1970 NOTE: This command should be treated as experimental. While it
1971 should properly record rename files, this information is not yet
1971 should properly record rename files, this information is not yet
1972 fully used by merge, nor fully reported by log.
1972 fully used by merge, nor fully reported by log.
1973 """
1973 """
1974 try:
1974 try:
1975 wlock = repo.wlock(0)
1975 wlock = repo.wlock(0)
1976 errs, copied = docopy(ui, repo, pats, opts, wlock)
1976 errs, copied = docopy(ui, repo, pats, opts, wlock)
1977 names = []
1977 names = []
1978 for abs, rel, exact in copied:
1978 for abs, rel, exact in copied:
1979 if ui.verbose or not exact:
1979 if ui.verbose or not exact:
1980 ui.status(_('removing %s\n') % rel)
1980 ui.status(_('removing %s\n') % rel)
1981 names.append(abs)
1981 names.append(abs)
1982 repo.remove(names, True, wlock)
1982 repo.remove(names, True, wlock)
1983 except lock.LockHeld, inst:
1983 except lock.LockHeld, inst:
1984 ui.warn(_("repository lock held by %s\n") % inst.args[0])
1984 ui.warn(_("repository lock held by %s\n") % inst.args[0])
1985 errs = 1
1985 errs = 1
1986 return errs
1986 return errs
1987
1987
1988 def revert(ui, repo, *pats, **opts):
1988 def revert(ui, repo, *pats, **opts):
1989 """revert modified files or dirs back to their unmodified states
1989 """revert modified files or dirs back to their unmodified states
1990
1990
1991 In its default mode, it reverts any uncommitted modifications made
1991 In its default mode, it reverts any uncommitted modifications made
1992 to the named files or directories. This restores the contents of
1992 to the named files or directories. This restores the contents of
1993 the affected files to an unmodified state.
1993 the affected files to an unmodified state.
1994
1994
1995 Using the -r option, it reverts the given files or directories to
1995 Using the -r option, it reverts the given files or directories to
1996 their state as of an earlier revision. This can be helpful to "roll
1996 their state as of an earlier revision. This can be helpful to "roll
1997 back" some or all of a change that should not have been committed.
1997 back" some or all of a change that should not have been committed.
1998
1998
1999 Revert modifies the working directory. It does not commit any
1999 Revert modifies the working directory. It does not commit any
2000 changes, or change the parent of the current working directory.
2000 changes, or change the parent of the current working directory.
2001
2001
2002 If a file has been deleted, it is recreated. If the executable
2002 If a file has been deleted, it is recreated. If the executable
2003 mode of a file was changed, it is reset.
2003 mode of a file was changed, it is reset.
2004
2004
2005 If names are given, all files matching the names are reverted.
2005 If names are given, all files matching the names are reverted.
2006
2006
2007 If no arguments are given, all files in the repository are reverted.
2007 If no arguments are given, all files in the repository are reverted.
2008 """
2008 """
2009 node = opts['rev'] and repo.lookup(opts['rev']) or \
2009 node = opts['rev'] and repo.lookup(opts['rev']) or \
2010 repo.dirstate.parents()[0]
2010 repo.dirstate.parents()[0]
2011
2011
2012 files, choose, anypats = matchpats(repo, pats, opts)
2012 files, choose, anypats = matchpats(repo, pats, opts)
2013 modified, added, removed, deleted, unknown = repo.changes(match=choose)
2013 modified, added, removed, deleted, unknown = repo.changes(match=choose)
2014 repo.forget(added)
2014 repo.forget(added)
2015 repo.undelete(removed)
2015 repo.undelete(removed)
2016
2016
2017 return repo.update(node, False, True, choose, False)
2017 return repo.update(node, False, True, choose, False)
2018
2018
2019 def root(ui, repo):
2019 def root(ui, repo):
2020 """print the root (top) of the current working dir
2020 """print the root (top) of the current working dir
2021
2021
2022 Print the root directory of the current repository.
2022 Print the root directory of the current repository.
2023 """
2023 """
2024 ui.write(repo.root + "\n")
2024 ui.write(repo.root + "\n")
2025
2025
2026 def serve(ui, repo, **opts):
2026 def serve(ui, repo, **opts):
2027 """export the repository via HTTP
2027 """export the repository via HTTP
2028
2028
2029 Start a local HTTP repository browser and pull server.
2029 Start a local HTTP repository browser and pull server.
2030
2030
2031 By default, the server logs accesses to stdout and errors to
2031 By default, the server logs accesses to stdout and errors to
2032 stderr. Use the "-A" and "-E" options to log to files.
2032 stderr. Use the "-A" and "-E" options to log to files.
2033 """
2033 """
2034
2034
2035 if opts["stdio"]:
2035 if opts["stdio"]:
2036 fin, fout = sys.stdin, sys.stdout
2036 fin, fout = sys.stdin, sys.stdout
2037 sys.stdout = sys.stderr
2037 sys.stdout = sys.stderr
2038
2038
2039 # Prevent insertion/deletion of CRs
2039 # Prevent insertion/deletion of CRs
2040 util.set_binary(fin)
2040 util.set_binary(fin)
2041 util.set_binary(fout)
2041 util.set_binary(fout)
2042
2042
2043 def getarg():
2043 def getarg():
2044 argline = fin.readline()[:-1]
2044 argline = fin.readline()[:-1]
2045 arg, l = argline.split()
2045 arg, l = argline.split()
2046 val = fin.read(int(l))
2046 val = fin.read(int(l))
2047 return arg, val
2047 return arg, val
2048 def respond(v):
2048 def respond(v):
2049 fout.write("%d\n" % len(v))
2049 fout.write("%d\n" % len(v))
2050 fout.write(v)
2050 fout.write(v)
2051 fout.flush()
2051 fout.flush()
2052
2052
2053 lock = None
2053 lock = None
2054
2054
2055 while 1:
2055 while 1:
2056 cmd = fin.readline()[:-1]
2056 cmd = fin.readline()[:-1]
2057 if cmd == '':
2057 if cmd == '':
2058 return
2058 return
2059 if cmd == "heads":
2059 if cmd == "heads":
2060 h = repo.heads()
2060 h = repo.heads()
2061 respond(" ".join(map(hex, h)) + "\n")
2061 respond(" ".join(map(hex, h)) + "\n")
2062 if cmd == "lock":
2062 if cmd == "lock":
2063 lock = repo.lock()
2063 lock = repo.lock()
2064 respond("")
2064 respond("")
2065 if cmd == "unlock":
2065 if cmd == "unlock":
2066 if lock:
2066 if lock:
2067 lock.release()
2067 lock.release()
2068 lock = None
2068 lock = None
2069 respond("")
2069 respond("")
2070 elif cmd == "branches":
2070 elif cmd == "branches":
2071 arg, nodes = getarg()
2071 arg, nodes = getarg()
2072 nodes = map(bin, nodes.split(" "))
2072 nodes = map(bin, nodes.split(" "))
2073 r = []
2073 r = []
2074 for b in repo.branches(nodes):
2074 for b in repo.branches(nodes):
2075 r.append(" ".join(map(hex, b)) + "\n")
2075 r.append(" ".join(map(hex, b)) + "\n")
2076 respond("".join(r))
2076 respond("".join(r))
2077 elif cmd == "between":
2077 elif cmd == "between":
2078 arg, pairs = getarg()
2078 arg, pairs = getarg()
2079 pairs = [map(bin, p.split("-")) for p in pairs.split(" ")]
2079 pairs = [map(bin, p.split("-")) for p in pairs.split(" ")]
2080 r = []
2080 r = []
2081 for b in repo.between(pairs):
2081 for b in repo.between(pairs):
2082 r.append(" ".join(map(hex, b)) + "\n")
2082 r.append(" ".join(map(hex, b)) + "\n")
2083 respond("".join(r))
2083 respond("".join(r))
2084 elif cmd == "changegroup":
2084 elif cmd == "changegroup":
2085 nodes = []
2085 nodes = []
2086 arg, roots = getarg()
2086 arg, roots = getarg()
2087 nodes = map(bin, roots.split(" "))
2087 nodes = map(bin, roots.split(" "))
2088
2088
2089 cg = repo.changegroup(nodes, 'serve')
2089 cg = repo.changegroup(nodes, 'serve')
2090 while 1:
2090 while 1:
2091 d = cg.read(4096)
2091 d = cg.read(4096)
2092 if not d:
2092 if not d:
2093 break
2093 break
2094 fout.write(d)
2094 fout.write(d)
2095
2095
2096 fout.flush()
2096 fout.flush()
2097
2097
2098 elif cmd == "addchangegroup":
2098 elif cmd == "addchangegroup":
2099 if not lock:
2099 if not lock:
2100 respond("not locked")
2100 respond("not locked")
2101 continue
2101 continue
2102 respond("")
2102 respond("")
2103
2103
2104 r = repo.addchangegroup(fin)
2104 r = repo.addchangegroup(fin)
2105 respond("")
2105 respond("")
2106
2106
2107 optlist = "name templates style address port ipv6 accesslog errorlog"
2107 optlist = "name templates style address port ipv6 accesslog errorlog"
2108 for o in optlist.split():
2108 for o in optlist.split():
2109 if opts[o]:
2109 if opts[o]:
2110 ui.setconfig("web", o, opts[o])
2110 ui.setconfig("web", o, opts[o])
2111
2111
2112 if opts['daemon'] and not opts['daemon_pipefds']:
2112 if opts['daemon'] and not opts['daemon_pipefds']:
2113 rfd, wfd = os.pipe()
2113 rfd, wfd = os.pipe()
2114 args = sys.argv[:]
2114 args = sys.argv[:]
2115 args.append('--daemon-pipefds=%d,%d' % (rfd, wfd))
2115 args.append('--daemon-pipefds=%d,%d' % (rfd, wfd))
2116 pid = os.spawnvp(os.P_NOWAIT | getattr(os, 'P_DETACH', 0),
2116 pid = os.spawnvp(os.P_NOWAIT | getattr(os, 'P_DETACH', 0),
2117 args[0], args)
2117 args[0], args)
2118 os.close(wfd)
2118 os.close(wfd)
2119 os.read(rfd, 1)
2119 os.read(rfd, 1)
2120 os._exit(0)
2120 os._exit(0)
2121
2121
2122 try:
2122 try:
2123 httpd = hgweb.create_server(repo)
2123 httpd = hgweb.create_server(repo)
2124 except socket.error, inst:
2124 except socket.error, inst:
2125 raise util.Abort(_('cannot start server: ') + inst.args[1])
2125 raise util.Abort(_('cannot start server: ') + inst.args[1])
2126
2126
2127 if ui.verbose:
2127 if ui.verbose:
2128 addr, port = httpd.socket.getsockname()
2128 addr, port = httpd.socket.getsockname()
2129 if addr == '0.0.0.0':
2129 if addr == '0.0.0.0':
2130 addr = socket.gethostname()
2130 addr = socket.gethostname()
2131 else:
2131 else:
2132 try:
2132 try:
2133 addr = socket.gethostbyaddr(addr)[0]
2133 addr = socket.gethostbyaddr(addr)[0]
2134 except socket.error:
2134 except socket.error:
2135 pass
2135 pass
2136 if port != 80:
2136 if port != 80:
2137 ui.status(_('listening at http://%s:%d/\n') % (addr, port))
2137 ui.status(_('listening at http://%s:%d/\n') % (addr, port))
2138 else:
2138 else:
2139 ui.status(_('listening at http://%s/\n') % addr)
2139 ui.status(_('listening at http://%s/\n') % addr)
2140
2140
2141 if opts['pid_file']:
2141 if opts['pid_file']:
2142 fp = open(opts['pid_file'], 'w')
2142 fp = open(opts['pid_file'], 'w')
2143 fp.write(str(os.getpid()))
2143 fp.write(str(os.getpid()))
2144 fp.close()
2144 fp.close()
2145
2145
2146 if opts['daemon_pipefds']:
2146 if opts['daemon_pipefds']:
2147 rfd, wfd = [int(x) for x in opts['daemon_pipefds'].split(',')]
2147 rfd, wfd = [int(x) for x in opts['daemon_pipefds'].split(',')]
2148 os.close(rfd)
2148 os.close(rfd)
2149 os.write(wfd, 'y')
2149 os.write(wfd, 'y')
2150 os.close(wfd)
2150 os.close(wfd)
2151 sys.stdout.flush()
2151 sys.stdout.flush()
2152 sys.stderr.flush()
2152 sys.stderr.flush()
2153 fd = os.open(util.nulldev, os.O_RDWR)
2153 fd = os.open(util.nulldev, os.O_RDWR)
2154 if fd != 0: os.dup2(fd, 0)
2154 if fd != 0: os.dup2(fd, 0)
2155 if fd != 1: os.dup2(fd, 1)
2155 if fd != 1: os.dup2(fd, 1)
2156 if fd != 2: os.dup2(fd, 2)
2156 if fd != 2: os.dup2(fd, 2)
2157 if fd not in (0, 1, 2): os.close(fd)
2157 if fd not in (0, 1, 2): os.close(fd)
2158
2158
2159 httpd.serve_forever()
2159 httpd.serve_forever()
2160
2160
2161 def status(ui, repo, *pats, **opts):
2161 def status(ui, repo, *pats, **opts):
2162 """show changed files in the working directory
2162 """show changed files in the working directory
2163
2163
2164 Show changed files in the repository. If names are
2164 Show changed files in the repository. If names are
2165 given, only files that match are shown.
2165 given, only files that match are shown.
2166
2166
2167 The codes used to show the status of files are:
2167 The codes used to show the status of files are:
2168 M = modified
2168 M = modified
2169 A = added
2169 A = added
2170 R = removed
2170 R = removed
2171 ! = deleted, but still tracked
2171 ! = deleted, but still tracked
2172 ? = not tracked
2172 ? = not tracked
2173 """
2173 """
2174
2174
2175 files, matchfn, anypats = matchpats(repo, pats, opts)
2175 files, matchfn, anypats = matchpats(repo, pats, opts)
2176 cwd = (pats and repo.getcwd()) or ''
2176 cwd = (pats and repo.getcwd()) or ''
2177 modified, added, removed, deleted, unknown = [
2177 modified, added, removed, deleted, unknown = [
2178 [util.pathto(cwd, x) for x in n]
2178 [util.pathto(cwd, x) for x in n]
2179 for n in repo.changes(files=files, match=matchfn)]
2179 for n in repo.changes(files=files, match=matchfn)]
2180
2180
2181 changetypes = [(_('modified'), 'M', modified),
2181 changetypes = [(_('modified'), 'M', modified),
2182 (_('added'), 'A', added),
2182 (_('added'), 'A', added),
2183 (_('removed'), 'R', removed),
2183 (_('removed'), 'R', removed),
2184 (_('deleted'), '!', deleted),
2184 (_('deleted'), '!', deleted),
2185 (_('unknown'), '?', unknown)]
2185 (_('unknown'), '?', unknown)]
2186
2186
2187 end = opts['print0'] and '\0' or '\n'
2187 end = opts['print0'] and '\0' or '\n'
2188
2188
2189 for opt, char, changes in ([ct for ct in changetypes if opts[ct[0]]]
2189 for opt, char, changes in ([ct for ct in changetypes if opts[ct[0]]]
2190 or changetypes):
2190 or changetypes):
2191 if opts['no_status']:
2191 if opts['no_status']:
2192 format = "%%s%s" % end
2192 format = "%%s%s" % end
2193 else:
2193 else:
2194 format = "%s %%s%s" % (char, end);
2194 format = "%s %%s%s" % (char, end);
2195
2195
2196 for f in changes:
2196 for f in changes:
2197 ui.write(format % f)
2197 ui.write(format % f)
2198
2198
2199 def tag(ui, repo, name, rev_=None, **opts):
2199 def tag(ui, repo, name, rev_=None, **opts):
2200 """add a tag for the current tip or a given revision
2200 """add a tag for the current tip or a given revision
2201
2201
2202 Name a particular revision using <name>.
2202 Name a particular revision using <name>.
2203
2203
2204 Tags are used to name particular revisions of the repository and are
2204 Tags are used to name particular revisions of the repository and are
2205 very useful to compare different revision, to go back to significant
2205 very useful to compare different revision, to go back to significant
2206 earlier versions or to mark branch points as releases, etc.
2206 earlier versions or to mark branch points as releases, etc.
2207
2207
2208 If no revision is given, the tip is used.
2208 If no revision is given, the tip is used.
2209
2209
2210 To facilitate version control, distribution, and merging of tags,
2210 To facilitate version control, distribution, and merging of tags,
2211 they are stored as a file named ".hgtags" which is managed
2211 they are stored as a file named ".hgtags" which is managed
2212 similarly to other project files and can be hand-edited if
2212 similarly to other project files and can be hand-edited if
2213 necessary. The file '.hg/localtags' is used for local tags (not
2213 necessary. The file '.hg/localtags' is used for local tags (not
2214 shared among repositories).
2214 shared among repositories).
2215 """
2215 """
2216 if name == "tip":
2216 if name == "tip":
2217 raise util.Abort(_("the name 'tip' is reserved"))
2217 raise util.Abort(_("the name 'tip' is reserved"))
2218 if rev_ is not None:
2218 if rev_ is not None:
2219 ui.warn(_("use of 'hg tag NAME [REV]' is deprecated, "
2219 ui.warn(_("use of 'hg tag NAME [REV]' is deprecated, "
2220 "please use 'hg tag [-r REV] NAME' instead\n"))
2220 "please use 'hg tag [-r REV] NAME' instead\n"))
2221 if opts['rev']:
2221 if opts['rev']:
2222 raise util.Abort(_("use only one form to specify the revision"))
2222 raise util.Abort(_("use only one form to specify the revision"))
2223 if opts['rev']:
2223 if opts['rev']:
2224 rev_ = opts['rev']
2224 rev_ = opts['rev']
2225 if rev_:
2225 if rev_:
2226 r = hex(repo.lookup(rev_))
2226 r = hex(repo.lookup(rev_))
2227 else:
2227 else:
2228 r = hex(repo.changelog.tip())
2228 r = hex(repo.changelog.tip())
2229
2229
2230 disallowed = (revrangesep, '\r', '\n')
2230 disallowed = (revrangesep, '\r', '\n')
2231 for c in disallowed:
2231 for c in disallowed:
2232 if name.find(c) >= 0:
2232 if name.find(c) >= 0:
2233 raise util.Abort(_("%s cannot be used in a tag name") % repr(c))
2233 raise util.Abort(_("%s cannot be used in a tag name") % repr(c))
2234
2234
2235 repo.hook('pretag', throw=True, node=r, tag=name,
2235 repo.hook('pretag', throw=True, node=r, tag=name,
2236 local=int(not not opts['local']))
2236 local=int(not not opts['local']))
2237
2237
2238 if opts['local']:
2238 if opts['local']:
2239 repo.opener("localtags", "a").write("%s %s\n" % (r, name))
2239 repo.opener("localtags", "a").write("%s %s\n" % (r, name))
2240 repo.hook('tag', node=r, tag=name, local=1)
2240 repo.hook('tag', node=r, tag=name, local=1)
2241 return
2241 return
2242
2242
2243 for x in repo.changes():
2243 for x in repo.changes():
2244 if ".hgtags" in x:
2244 if ".hgtags" in x:
2245 raise util.Abort(_("working copy of .hgtags is changed "
2245 raise util.Abort(_("working copy of .hgtags is changed "
2246 "(please commit .hgtags manually)"))
2246 "(please commit .hgtags manually)"))
2247
2247
2248 repo.wfile(".hgtags", "ab").write("%s %s\n" % (r, name))
2248 repo.wfile(".hgtags", "ab").write("%s %s\n" % (r, name))
2249 if repo.dirstate.state(".hgtags") == '?':
2249 if repo.dirstate.state(".hgtags") == '?':
2250 repo.add([".hgtags"])
2250 repo.add([".hgtags"])
2251
2251
2252 message = (opts['message'] or
2252 message = (opts['message'] or
2253 _("Added tag %s for changeset %s") % (name, r))
2253 _("Added tag %s for changeset %s") % (name, r))
2254 try:
2254 try:
2255 repo.commit([".hgtags"], message, opts['user'], opts['date'])
2255 repo.commit([".hgtags"], message, opts['user'], opts['date'])
2256 repo.hook('tag', node=r, tag=name, local=0)
2256 repo.hook('tag', node=r, tag=name, local=0)
2257 except ValueError, inst:
2257 except ValueError, inst:
2258 raise util.Abort(str(inst))
2258 raise util.Abort(str(inst))
2259
2259
2260 def tags(ui, repo):
2260 def tags(ui, repo):
2261 """list repository tags
2261 """list repository tags
2262
2262
2263 List the repository tags.
2263 List the repository tags.
2264
2264
2265 This lists both regular and local tags.
2265 This lists both regular and local tags.
2266 """
2266 """
2267
2267
2268 l = repo.tagslist()
2268 l = repo.tagslist()
2269 l.reverse()
2269 l.reverse()
2270 for t, n in l:
2270 for t, n in l:
2271 try:
2271 try:
2272 r = "%5d:%s" % (repo.changelog.rev(n), hex(n))
2272 r = "%5d:%s" % (repo.changelog.rev(n), hex(n))
2273 except KeyError:
2273 except KeyError:
2274 r = " ?:?"
2274 r = " ?:?"
2275 ui.write("%-30s %s\n" % (t, r))
2275 ui.write("%-30s %s\n" % (t, r))
2276
2276
2277 def tip(ui, repo, **opts):
2277 def tip(ui, repo, **opts):
2278 """show the tip revision
2278 """show the tip revision
2279
2279
2280 Show the tip revision.
2280 Show the tip revision.
2281 """
2281 """
2282 n = repo.changelog.tip()
2282 n = repo.changelog.tip()
2283 br = None
2283 br = None
2284 if opts['branches']:
2284 if opts['branches']:
2285 br = repo.branchlookup([n])
2285 br = repo.branchlookup([n])
2286 show_changeset(ui, repo, changenode=n, brinfo=br)
2286 show_changeset(ui, repo, changenode=n, brinfo=br)
2287 if opts['patch']:
2287 if opts['patch']:
2288 dodiff(ui, ui, repo, repo.changelog.parents(n)[0], n)
2288 dodiff(ui, ui, repo, repo.changelog.parents(n)[0], n)
2289
2289
2290 def unbundle(ui, repo, fname, **opts):
2290 def unbundle(ui, repo, fname, **opts):
2291 """apply a changegroup file
2291 """apply a changegroup file
2292
2292
2293 Apply a compressed changegroup file generated by the bundle
2293 Apply a compressed changegroup file generated by the bundle
2294 command.
2294 command.
2295 """
2295 """
2296 f = urllib.urlopen(fname)
2296 f = urllib.urlopen(fname)
2297
2297
2298 if f.read(4) != "HG10":
2298 if f.read(4) != "HG10":
2299 raise util.Abort(_("%s: not a Mercurial bundle file") % fname)
2299 raise util.Abort(_("%s: not a Mercurial bundle file") % fname)
2300
2300
2301 def bzgenerator(f):
2301 def bzgenerator(f):
2302 zd = bz2.BZ2Decompressor()
2302 zd = bz2.BZ2Decompressor()
2303 for chunk in f:
2303 for chunk in f:
2304 yield zd.decompress(chunk)
2304 yield zd.decompress(chunk)
2305
2305
2306 bzgen = bzgenerator(util.filechunkiter(f, 4096))
2306 bzgen = bzgenerator(util.filechunkiter(f, 4096))
2307 if repo.addchangegroup(util.chunkbuffer(bzgen)):
2307 if repo.addchangegroup(util.chunkbuffer(bzgen)):
2308 return 1
2308 return 1
2309
2309
2310 if opts['update']:
2310 if opts['update']:
2311 return update(ui, repo)
2311 return update(ui, repo)
2312 else:
2312 else:
2313 ui.status(_("(run 'hg update' to get a working copy)\n"))
2313 ui.status(_("(run 'hg update' to get a working copy)\n"))
2314
2314
2315 def undo(ui, repo):
2315 def undo(ui, repo):
2316 """undo the last commit or pull
2316 """undo the last commit or pull
2317
2317
2318 Roll back the last pull or commit transaction on the
2318 Roll back the last pull or commit transaction on the
2319 repository, restoring the project to its earlier state.
2319 repository, restoring the project to its earlier state.
2320
2320
2321 This command should be used with care. There is only one level of
2321 This command should be used with care. There is only one level of
2322 undo and there is no redo.
2322 undo and there is no redo.
2323
2323
2324 This command is not intended for use on public repositories. Once
2324 This command is not intended for use on public repositories. Once
2325 a change is visible for pull by other users, undoing it locally is
2325 a change is visible for pull by other users, undoing it locally is
2326 ineffective.
2326 ineffective.
2327 """
2327 """
2328 repo.undo()
2328 repo.undo()
2329
2329
2330 def update(ui, repo, node=None, merge=False, clean=False, force=None,
2330 def update(ui, repo, node=None, merge=False, clean=False, force=None,
2331 branch=None):
2331 branch=None):
2332 """update or merge working directory
2332 """update or merge working directory
2333
2333
2334 Update the working directory to the specified revision.
2334 Update the working directory to the specified revision.
2335
2335
2336 If there are no outstanding changes in the working directory and
2336 If there are no outstanding changes in the working directory and
2337 there is a linear relationship between the current version and the
2337 there is a linear relationship between the current version and the
2338 requested version, the result is the requested version.
2338 requested version, the result is the requested version.
2339
2339
2340 Otherwise the result is a merge between the contents of the
2340 Otherwise the result is a merge between the contents of the
2341 current working directory and the requested version. Files that
2341 current working directory and the requested version. Files that
2342 changed between either parent are marked as changed for the next
2342 changed between either parent are marked as changed for the next
2343 commit and a commit must be performed before any further updates
2343 commit and a commit must be performed before any further updates
2344 are allowed.
2344 are allowed.
2345
2345
2346 By default, update will refuse to run if doing so would require
2346 By default, update will refuse to run if doing so would require
2347 merging or discarding local changes.
2347 merging or discarding local changes.
2348 """
2348 """
2349 if branch:
2349 if branch:
2350 br = repo.branchlookup(branch=branch)
2350 br = repo.branchlookup(branch=branch)
2351 found = []
2351 found = []
2352 for x in br:
2352 for x in br:
2353 if branch in br[x]:
2353 if branch in br[x]:
2354 found.append(x)
2354 found.append(x)
2355 if len(found) > 1:
2355 if len(found) > 1:
2356 ui.warn(_("Found multiple heads for %s\n") % branch)
2356 ui.warn(_("Found multiple heads for %s\n") % branch)
2357 for x in found:
2357 for x in found:
2358 show_changeset(ui, repo, changenode=x, brinfo=br)
2358 show_changeset(ui, repo, changenode=x, brinfo=br)
2359 return 1
2359 return 1
2360 if len(found) == 1:
2360 if len(found) == 1:
2361 node = found[0]
2361 node = found[0]
2362 ui.warn(_("Using head %s for branch %s\n") % (short(node), branch))
2362 ui.warn(_("Using head %s for branch %s\n") % (short(node), branch))
2363 else:
2363 else:
2364 ui.warn(_("branch %s not found\n") % (branch))
2364 ui.warn(_("branch %s not found\n") % (branch))
2365 return 1
2365 return 1
2366 else:
2366 else:
2367 node = node and repo.lookup(node) or repo.changelog.tip()
2367 node = node and repo.lookup(node) or repo.changelog.tip()
2368 return repo.update(node, allow=merge, force=clean, forcemerge=force)
2368 return repo.update(node, allow=merge, force=clean, forcemerge=force)
2369
2369
2370 def verify(ui, repo):
2370 def verify(ui, repo):
2371 """verify the integrity of the repository
2371 """verify the integrity of the repository
2372
2372
2373 Verify the integrity of the current repository.
2373 Verify the integrity of the current repository.
2374
2374
2375 This will perform an extensive check of the repository's
2375 This will perform an extensive check of the repository's
2376 integrity, validating the hashes and checksums of each entry in
2376 integrity, validating the hashes and checksums of each entry in
2377 the changelog, manifest, and tracked files, as well as the
2377 the changelog, manifest, and tracked files, as well as the
2378 integrity of their crosslinks and indices.
2378 integrity of their crosslinks and indices.
2379 """
2379 """
2380 return repo.verify()
2380 return repo.verify()
2381
2381
2382 # Command options and aliases are listed here, alphabetically
2382 # Command options and aliases are listed here, alphabetically
2383
2383
2384 table = {
2384 table = {
2385 "^add":
2385 "^add":
2386 (add,
2386 (add,
2387 [('I', 'include', [], _('include names matching the given patterns')),
2387 [('I', 'include', [], _('include names matching the given patterns')),
2388 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2388 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2389 _('hg add [OPTION]... [FILE]...')),
2389 _('hg add [OPTION]... [FILE]...')),
2390 "addremove":
2390 "addremove":
2391 (addremove,
2391 (addremove,
2392 [('I', 'include', [], _('include names matching the given patterns')),
2392 [('I', 'include', [], _('include names matching the given patterns')),
2393 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2393 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2394 _('hg addremove [OPTION]... [FILE]...')),
2394 _('hg addremove [OPTION]... [FILE]...')),
2395 "^annotate":
2395 "^annotate":
2396 (annotate,
2396 (annotate,
2397 [('r', 'rev', '', _('annotate the specified revision')),
2397 [('r', 'rev', '', _('annotate the specified revision')),
2398 ('a', 'text', None, _('treat all files as text')),
2398 ('a', 'text', None, _('treat all files as text')),
2399 ('u', 'user', None, _('list the author')),
2399 ('u', 'user', None, _('list the author')),
2400 ('d', 'date', None, _('list the date')),
2400 ('d', 'date', None, _('list the date')),
2401 ('n', 'number', None, _('list the revision number (default)')),
2401 ('n', 'number', None, _('list the revision number (default)')),
2402 ('c', 'changeset', None, _('list the changeset')),
2402 ('c', 'changeset', None, _('list the changeset')),
2403 ('I', 'include', [], _('include names matching the given patterns')),
2403 ('I', 'include', [], _('include names matching the given patterns')),
2404 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2404 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2405 _('hg annotate [-r REV] [-a] [-u] [-d] [-n] [-c] FILE...')),
2405 _('hg annotate [-r REV] [-a] [-u] [-d] [-n] [-c] FILE...')),
2406 "bundle":
2406 "bundle":
2407 (bundle,
2407 (bundle,
2408 [],
2408 [],
2409 _('hg bundle FILE DEST')),
2409 _('hg bundle FILE DEST')),
2410 "cat":
2410 "cat":
2411 (cat,
2411 (cat,
2412 [('o', 'output', '', _('print output to file with formatted name')),
2412 [('o', 'output', '', _('print output to file with formatted name')),
2413 ('r', 'rev', '', _('print the given revision')),
2413 ('r', 'rev', '', _('print the given revision')),
2414 ('I', 'include', [], _('include names matching the given patterns')),
2414 ('I', 'include', [], _('include names matching the given patterns')),
2415 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2415 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2416 _('hg cat [OPTION]... FILE...')),
2416 _('hg cat [OPTION]... FILE...')),
2417 "^clone":
2417 "^clone":
2418 (clone,
2418 (clone,
2419 [('U', 'noupdate', None, _('do not update the new working directory')),
2419 [('U', 'noupdate', None, _('do not update the new working directory')),
2420 ('r', 'rev', [],
2420 ('r', 'rev', [],
2421 _('a changeset you would like to have after cloning')),
2421 _('a changeset you would like to have after cloning')),
2422 ('', 'pull', None, _('use pull protocol to copy metadata')),
2422 ('', 'pull', None, _('use pull protocol to copy metadata')),
2423 ('e', 'ssh', '', _('specify ssh command to use')),
2423 ('e', 'ssh', '', _('specify ssh command to use')),
2424 ('', 'remotecmd', '',
2424 ('', 'remotecmd', '',
2425 _('specify hg command to run on the remote side'))],
2425 _('specify hg command to run on the remote side'))],
2426 _('hg clone [OPTION]... SOURCE [DEST]')),
2426 _('hg clone [OPTION]... SOURCE [DEST]')),
2427 "^commit|ci":
2427 "^commit|ci":
2428 (commit,
2428 (commit,
2429 [('A', 'addremove', None, _('run addremove during commit')),
2429 [('A', 'addremove', None, _('run addremove during commit')),
2430 ('m', 'message', '', _('use <text> as commit message')),
2430 ('m', 'message', '', _('use <text> as commit message')),
2431 ('l', 'logfile', '', _('read the commit message from <file>')),
2431 ('l', 'logfile', '', _('read the commit message from <file>')),
2432 ('d', 'date', '', _('record datecode as commit date')),
2432 ('d', 'date', '', _('record datecode as commit date')),
2433 ('u', 'user', '', _('record user as commiter')),
2433 ('u', 'user', '', _('record user as commiter')),
2434 ('I', 'include', [], _('include names matching the given patterns')),
2434 ('I', 'include', [], _('include names matching the given patterns')),
2435 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2435 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2436 _('hg commit [OPTION]... [FILE]...')),
2436 _('hg commit [OPTION]... [FILE]...')),
2437 "copy|cp":
2437 "copy|cp":
2438 (copy,
2438 (copy,
2439 [('A', 'after', None, _('record a copy that has already occurred')),
2439 [('A', 'after', None, _('record a copy that has already occurred')),
2440 ('f', 'force', None,
2440 ('f', 'force', None,
2441 _('forcibly copy over an existing managed file')),
2441 _('forcibly copy over an existing managed file')),
2442 ('I', 'include', [], _('include names matching the given patterns')),
2442 ('I', 'include', [], _('include names matching the given patterns')),
2443 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2443 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2444 _('hg copy [OPTION]... [SOURCE]... DEST')),
2444 _('hg copy [OPTION]... [SOURCE]... DEST')),
2445 "debugancestor": (debugancestor, [], _('debugancestor INDEX REV1 REV2')),
2445 "debugancestor": (debugancestor, [], _('debugancestor INDEX REV1 REV2')),
2446 "debugrebuildstate":
2446 "debugrebuildstate":
2447 (debugrebuildstate,
2447 (debugrebuildstate,
2448 [('r', 'rev', '', _('revision to rebuild to'))],
2448 [('r', 'rev', '', _('revision to rebuild to'))],
2449 _('debugrebuildstate [-r REV] [REV]')),
2449 _('debugrebuildstate [-r REV] [REV]')),
2450 "debugcheckstate": (debugcheckstate, [], _('debugcheckstate')),
2450 "debugcheckstate": (debugcheckstate, [], _('debugcheckstate')),
2451 "debugconfig": (debugconfig, [], _('debugconfig')),
2451 "debugconfig": (debugconfig, [], _('debugconfig')),
2452 "debugsetparents": (debugsetparents, [], _('debugsetparents REV1 [REV2]')),
2452 "debugsetparents": (debugsetparents, [], _('debugsetparents REV1 [REV2]')),
2453 "debugstate": (debugstate, [], _('debugstate')),
2453 "debugstate": (debugstate, [], _('debugstate')),
2454 "debugdata": (debugdata, [], _('debugdata FILE REV')),
2454 "debugdata": (debugdata, [], _('debugdata FILE REV')),
2455 "debugindex": (debugindex, [], _('debugindex FILE')),
2455 "debugindex": (debugindex, [], _('debugindex FILE')),
2456 "debugindexdot": (debugindexdot, [], _('debugindexdot FILE')),
2456 "debugindexdot": (debugindexdot, [], _('debugindexdot FILE')),
2457 "debugrename": (debugrename, [], _('debugrename FILE [REV]')),
2457 "debugrename": (debugrename, [], _('debugrename FILE [REV]')),
2458 "debugwalk":
2458 "debugwalk":
2459 (debugwalk,
2459 (debugwalk,
2460 [('I', 'include', [], _('include names matching the given patterns')),
2460 [('I', 'include', [], _('include names matching the given patterns')),
2461 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2461 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2462 _('debugwalk [OPTION]... [FILE]...')),
2462 _('debugwalk [OPTION]... [FILE]...')),
2463 "^diff":
2463 "^diff":
2464 (diff,
2464 (diff,
2465 [('r', 'rev', [], _('revision')),
2465 [('r', 'rev', [], _('revision')),
2466 ('a', 'text', None, _('treat all files as text')),
2466 ('a', 'text', None, _('treat all files as text')),
2467 ('p', 'show-function', None,
2467 ('p', 'show-function', None,
2468 _('show which function each change is in')),
2468 _('show which function each change is in')),
2469 ('w', 'ignore-all-space', None,
2469 ('w', 'ignore-all-space', None,
2470 _('ignore white space when comparing lines')),
2470 _('ignore white space when comparing lines')),
2471 ('I', 'include', [], _('include names matching the given patterns')),
2471 ('I', 'include', [], _('include names matching the given patterns')),
2472 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2472 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2473 _('hg diff [-a] [-I] [-X] [-r REV1 [-r REV2]] [FILE]...')),
2473 _('hg diff [-a] [-I] [-X] [-r REV1 [-r REV2]] [FILE]...')),
2474 "^export":
2474 "^export":
2475 (export,
2475 (export,
2476 [('o', 'output', '', _('print output to file with formatted name')),
2476 [('o', 'output', '', _('print output to file with formatted name')),
2477 ('a', 'text', None, _('treat all files as text')),
2477 ('a', 'text', None, _('treat all files as text')),
2478 ('', 'switch-parent', None, _('diff against the second parent'))],
2478 ('', 'switch-parent', None, _('diff against the second parent'))],
2479 _('hg export [-a] [-o OUTFILESPEC] REV...')),
2479 _('hg export [-a] [-o OUTFILESPEC] REV...')),
2480 "forget":
2480 "forget":
2481 (forget,
2481 (forget,
2482 [('I', 'include', [], _('include names matching the given patterns')),
2482 [('I', 'include', [], _('include names matching the given patterns')),
2483 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2483 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2484 _('hg forget [OPTION]... FILE...')),
2484 _('hg forget [OPTION]... FILE...')),
2485 "grep":
2485 "grep":
2486 (grep,
2486 (grep,
2487 [('0', 'print0', None, _('end fields with NUL')),
2487 [('0', 'print0', None, _('end fields with NUL')),
2488 ('', 'all', None, _('print all revisions that match')),
2488 ('', 'all', None, _('print all revisions that match')),
2489 ('i', 'ignore-case', None, _('ignore case when matching')),
2489 ('i', 'ignore-case', None, _('ignore case when matching')),
2490 ('l', 'files-with-matches', None,
2490 ('l', 'files-with-matches', None,
2491 _('print only filenames and revs that match')),
2491 _('print only filenames and revs that match')),
2492 ('n', 'line-number', None, _('print matching line numbers')),
2492 ('n', 'line-number', None, _('print matching line numbers')),
2493 ('r', 'rev', [], _('search in given revision range')),
2493 ('r', 'rev', [], _('search in given revision range')),
2494 ('u', 'user', None, _('print user who committed change')),
2494 ('u', 'user', None, _('print user who committed change')),
2495 ('I', 'include', [], _('include names matching the given patterns')),
2495 ('I', 'include', [], _('include names matching the given patterns')),
2496 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2496 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2497 _('hg grep [OPTION]... PATTERN [FILE]...')),
2497 _('hg grep [OPTION]... PATTERN [FILE]...')),
2498 "heads":
2498 "heads":
2499 (heads,
2499 (heads,
2500 [('b', 'branches', None, _('show branches')),
2500 [('b', 'branches', None, _('show branches')),
2501 ('r', 'rev', '', _('show only heads which are descendants of rev'))],
2501 ('r', 'rev', '', _('show only heads which are descendants of rev'))],
2502 _('hg heads [-b] [-r <rev>]')),
2502 _('hg heads [-b] [-r <rev>]')),
2503 "help": (help_, [], _('hg help [COMMAND]')),
2503 "help": (help_, [], _('hg help [COMMAND]')),
2504 "identify|id": (identify, [], _('hg identify')),
2504 "identify|id": (identify, [], _('hg identify')),
2505 "import|patch":
2505 "import|patch":
2506 (import_,
2506 (import_,
2507 [('p', 'strip', 1,
2507 [('p', 'strip', 1,
2508 _('directory strip option for patch. This has the same\n') +
2508 _('directory strip option for patch. This has the same\n') +
2509 _('meaning as the corresponding patch option')),
2509 _('meaning as the corresponding patch option')),
2510 ('b', 'base', '', _('base path')),
2510 ('b', 'base', '', _('base path')),
2511 ('f', 'force', None,
2511 ('f', 'force', None,
2512 _('skip check for outstanding uncommitted changes'))],
2512 _('skip check for outstanding uncommitted changes'))],
2513 _('hg import [-p NUM] [-b BASE] [-f] PATCH...')),
2513 _('hg import [-p NUM] [-b BASE] [-f] PATCH...')),
2514 "incoming|in": (incoming,
2514 "incoming|in": (incoming,
2515 [('M', 'no-merges', None, _('do not show merges')),
2515 [('M', 'no-merges', None, _('do not show merges')),
2516 ('p', 'patch', None, _('show patch')),
2516 ('p', 'patch', None, _('show patch')),
2517 ('n', 'newest-first', None, _('show newest record first'))],
2517 ('n', 'newest-first', None, _('show newest record first'))],
2518 _('hg incoming [-p] [-n] [-M] [SOURCE]')),
2518 _('hg incoming [-p] [-n] [-M] [SOURCE]')),
2519 "^init": (init, [], _('hg init [DEST]')),
2519 "^init": (init, [], _('hg init [DEST]')),
2520 "locate":
2520 "locate":
2521 (locate,
2521 (locate,
2522 [('r', 'rev', '', _('search the repository as it stood at rev')),
2522 [('r', 'rev', '', _('search the repository as it stood at rev')),
2523 ('0', 'print0', None,
2523 ('0', 'print0', None,
2524 _('end filenames with NUL, for use with xargs')),
2524 _('end filenames with NUL, for use with xargs')),
2525 ('f', 'fullpath', None,
2525 ('f', 'fullpath', None,
2526 _('print complete paths from the filesystem root')),
2526 _('print complete paths from the filesystem root')),
2527 ('I', 'include', [], _('include names matching the given patterns')),
2527 ('I', 'include', [], _('include names matching the given patterns')),
2528 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2528 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2529 _('hg locate [OPTION]... [PATTERN]...')),
2529 _('hg locate [OPTION]... [PATTERN]...')),
2530 "^log|history":
2530 "^log|history":
2531 (log,
2531 (log,
2532 [('b', 'branches', None, _('show branches')),
2532 [('b', 'branches', None, _('show branches')),
2533 ('k', 'keyword', [], _('search for a keyword')),
2533 ('k', 'keyword', [], _('search for a keyword')),
2534 ('l', 'limit', '', _('limit number of changes displayed')),
2534 ('l', 'limit', '', _('limit number of changes displayed')),
2535 ('r', 'rev', [], _('show the specified revision or range')),
2535 ('r', 'rev', [], _('show the specified revision or range')),
2536 ('M', 'no-merges', None, _('do not show merges')),
2536 ('M', 'no-merges', None, _('do not show merges')),
2537 ('m', 'only-merges', None, _('show only merges')),
2537 ('m', 'only-merges', None, _('show only merges')),
2538 ('p', 'patch', None, _('show patch')),
2538 ('p', 'patch', None, _('show patch')),
2539 ('I', 'include', [], _('include names matching the given patterns')),
2539 ('I', 'include', [], _('include names matching the given patterns')),
2540 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2540 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2541 _('hg log [OPTION]... [FILE]')),
2541 _('hg log [OPTION]... [FILE]')),
2542 "manifest": (manifest, [], _('hg manifest [REV]')),
2542 "manifest": (manifest, [], _('hg manifest [REV]')),
2543 "outgoing|out": (outgoing,
2543 "outgoing|out": (outgoing,
2544 [('M', 'no-merges', None, _('do not show merges')),
2544 [('M', 'no-merges', None, _('do not show merges')),
2545 ('p', 'patch', None, _('show patch')),
2545 ('p', 'patch', None, _('show patch')),
2546 ('n', 'newest-first', None, _('show newest record first'))],
2546 ('n', 'newest-first', None, _('show newest record first'))],
2547 _('hg outgoing [-M] [-p] [-n] [DEST]')),
2547 _('hg outgoing [-M] [-p] [-n] [DEST]')),
2548 "^parents":
2548 "^parents":
2549 (parents,
2549 (parents,
2550 [('b', 'branches', None, _('show branches'))],
2550 [('b', 'branches', None, _('show branches'))],
2551 _('hg parents [-b] [REV]')),
2551 _('hg parents [-b] [REV]')),
2552 "paths": (paths, [], _('hg paths [NAME]')),
2552 "paths": (paths, [], _('hg paths [NAME]')),
2553 "^pull":
2553 "^pull":
2554 (pull,
2554 (pull,
2555 [('u', 'update', None,
2555 [('u', 'update', None,
2556 _('update the working directory to tip after pull')),
2556 _('update the working directory to tip after pull')),
2557 ('e', 'ssh', '', _('specify ssh command to use')),
2557 ('e', 'ssh', '', _('specify ssh command to use')),
2558 ('r', 'rev', [], _('a specific revision you would like to pull')),
2558 ('r', 'rev', [], _('a specific revision you would like to pull')),
2559 ('', 'remotecmd', '',
2559 ('', 'remotecmd', '',
2560 _('specify hg command to run on the remote side'))],
2560 _('specify hg command to run on the remote side'))],
2561 _('hg pull [-u] [-e FILE] [-r REV]... [--remotecmd FILE] [SOURCE]')),
2561 _('hg pull [-u] [-e FILE] [-r REV]... [--remotecmd FILE] [SOURCE]')),
2562 "^push":
2562 "^push":
2563 (push,
2563 (push,
2564 [('f', 'force', None, _('force push')),
2564 [('f', 'force', None, _('force push')),
2565 ('e', 'ssh', '', _('specify ssh command to use')),
2565 ('e', 'ssh', '', _('specify ssh command to use')),
2566 ('r', 'rev', [], _('a specific revision you would like to push')),
2566 ('r', 'rev', [], _('a specific revision you would like to push')),
2567 ('', 'remotecmd', '',
2567 ('', 'remotecmd', '',
2568 _('specify hg command to run on the remote side'))],
2568 _('specify hg command to run on the remote side'))],
2569 _('hg push [-f] [-e FILE] [-r REV]... [--remotecmd FILE] [DEST]')),
2569 _('hg push [-f] [-e FILE] [-r REV]... [--remotecmd FILE] [DEST]')),
2570 "debugrawcommit|rawcommit":
2570 "debugrawcommit|rawcommit":
2571 (rawcommit,
2571 (rawcommit,
2572 [('p', 'parent', [], _('parent')),
2572 [('p', 'parent', [], _('parent')),
2573 ('d', 'date', '', _('date code')),
2573 ('d', 'date', '', _('date code')),
2574 ('u', 'user', '', _('user')),
2574 ('u', 'user', '', _('user')),
2575 ('F', 'files', '', _('file list')),
2575 ('F', 'files', '', _('file list')),
2576 ('m', 'message', '', _('commit message')),
2576 ('m', 'message', '', _('commit message')),
2577 ('l', 'logfile', '', _('commit message file'))],
2577 ('l', 'logfile', '', _('commit message file'))],
2578 _('hg debugrawcommit [OPTION]... [FILE]...')),
2578 _('hg debugrawcommit [OPTION]... [FILE]...')),
2579 "recover": (recover, [], _('hg recover')),
2579 "recover": (recover, [], _('hg recover')),
2580 "^remove|rm":
2580 "^remove|rm":
2581 (remove,
2581 (remove,
2582 [('I', 'include', [], _('include names matching the given patterns')),
2582 [('I', 'include', [], _('include names matching the given patterns')),
2583 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2583 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2584 _('hg remove [OPTION]... FILE...')),
2584 _('hg remove [OPTION]... FILE...')),
2585 "rename|mv":
2585 "rename|mv":
2586 (rename,
2586 (rename,
2587 [('A', 'after', None, _('record a rename that has already occurred')),
2587 [('A', 'after', None, _('record a rename that has already occurred')),
2588 ('f', 'force', None,
2588 ('f', 'force', None,
2589 _('forcibly copy over an existing managed file')),
2589 _('forcibly copy over an existing managed file')),
2590 ('I', 'include', [], _('include names matching the given patterns')),
2590 ('I', 'include', [], _('include names matching the given patterns')),
2591 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2591 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2592 _('hg rename [OPTION]... [SOURCE]... DEST')),
2592 _('hg rename [OPTION]... [SOURCE]... DEST')),
2593 "^revert":
2593 "^revert":
2594 (revert,
2594 (revert,
2595 [('r', 'rev', '', _('revision to revert to')),
2595 [('r', 'rev', '', _('revision to revert to')),
2596 ('I', 'include', [], _('include names matching the given patterns')),
2596 ('I', 'include', [], _('include names matching the given patterns')),
2597 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2597 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2598 _('hg revert [-r REV] [NAME]...')),
2598 _('hg revert [-r REV] [NAME]...')),
2599 "root": (root, [], _('hg root')),
2599 "root": (root, [], _('hg root')),
2600 "^serve":
2600 "^serve":
2601 (serve,
2601 (serve,
2602 [('A', 'accesslog', '', _('name of access log file to write to')),
2602 [('A', 'accesslog', '', _('name of access log file to write to')),
2603 ('d', 'daemon', None, _('run server in background')),
2603 ('d', 'daemon', None, _('run server in background')),
2604 ('', 'daemon-pipefds', '', _('used internally by daemon mode')),
2604 ('', 'daemon-pipefds', '', _('used internally by daemon mode')),
2605 ('E', 'errorlog', '', _('name of error log file to write to')),
2605 ('E', 'errorlog', '', _('name of error log file to write to')),
2606 ('p', 'port', 0, _('port to use (default: 8000)')),
2606 ('p', 'port', 0, _('port to use (default: 8000)')),
2607 ('a', 'address', '', _('address to use')),
2607 ('a', 'address', '', _('address to use')),
2608 ('n', 'name', '',
2608 ('n', 'name', '',
2609 _('name to show in web pages (default: working dir)')),
2609 _('name to show in web pages (default: working dir)')),
2610 ('', 'pid-file', '', _('name of file to write process ID to')),
2610 ('', 'pid-file', '', _('name of file to write process ID to')),
2611 ('', 'stdio', None, _('for remote clients')),
2611 ('', 'stdio', None, _('for remote clients')),
2612 ('t', 'templates', '', _('web templates to use')),
2612 ('t', 'templates', '', _('web templates to use')),
2613 ('', 'style', '', _('template style to use')),
2613 ('', 'style', '', _('template style to use')),
2614 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4'))],
2614 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4'))],
2615 _('hg serve [OPTION]...')),
2615 _('hg serve [OPTION]...')),
2616 "^status|st":
2616 "^status|st":
2617 (status,
2617 (status,
2618 [('m', 'modified', None, _('show only modified files')),
2618 [('m', 'modified', None, _('show only modified files')),
2619 ('a', 'added', None, _('show only added files')),
2619 ('a', 'added', None, _('show only added files')),
2620 ('r', 'removed', None, _('show only removed files')),
2620 ('r', 'removed', None, _('show only removed files')),
2621 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
2621 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
2622 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
2622 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
2623 ('n', 'no-status', None, _('hide status prefix')),
2623 ('n', 'no-status', None, _('hide status prefix')),
2624 ('0', 'print0', None,
2624 ('0', 'print0', None,
2625 _('end filenames with NUL, for use with xargs')),
2625 _('end filenames with NUL, for use with xargs')),
2626 ('I', 'include', [], _('include names matching the given patterns')),
2626 ('I', 'include', [], _('include names matching the given patterns')),
2627 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2627 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2628 _('hg status [OPTION]... [FILE]...')),
2628 _('hg status [OPTION]... [FILE]...')),
2629 "tag":
2629 "tag":
2630 (tag,
2630 (tag,
2631 [('l', 'local', None, _('make the tag local')),
2631 [('l', 'local', None, _('make the tag local')),
2632 ('m', 'message', '', _('message for tag commit log entry')),
2632 ('m', 'message', '', _('message for tag commit log entry')),
2633 ('d', 'date', '', _('record datecode as commit date')),
2633 ('d', 'date', '', _('record datecode as commit date')),
2634 ('u', 'user', '', _('record user as commiter')),
2634 ('u', 'user', '', _('record user as commiter')),
2635 ('r', 'rev', '', _('revision to tag'))],
2635 ('r', 'rev', '', _('revision to tag'))],
2636 _('hg tag [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME')),
2636 _('hg tag [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME')),
2637 "tags": (tags, [], _('hg tags')),
2637 "tags": (tags, [], _('hg tags')),
2638 "tip":
2638 "tip":
2639 (tip,
2639 (tip,
2640 [('b', 'branches', None, _('show branches')),
2640 [('b', 'branches', None, _('show branches')),
2641 ('p', 'patch', None, _('show patch'))],
2641 ('p', 'patch', None, _('show patch'))],
2642 _('hg tip [-b] [-p]')),
2642 _('hg tip [-b] [-p]')),
2643 "unbundle":
2643 "unbundle":
2644 (unbundle,
2644 (unbundle,
2645 [('u', 'update', None,
2645 [('u', 'update', None,
2646 _('update the working directory to tip after unbundle'))],
2646 _('update the working directory to tip after unbundle'))],
2647 _('hg unbundle [-u] FILE')),
2647 _('hg unbundle [-u] FILE')),
2648 "undo": (undo, [], _('hg undo')),
2648 "undo": (undo, [], _('hg undo')),
2649 "^update|up|checkout|co":
2649 "^update|up|checkout|co":
2650 (update,
2650 (update,
2651 [('b', 'branch', '', _('checkout the head of a specific branch')),
2651 [('b', 'branch', '', _('checkout the head of a specific branch')),
2652 ('m', 'merge', None, _('allow merging of branches')),
2652 ('m', 'merge', None, _('allow merging of branches')),
2653 ('C', 'clean', None, _('overwrite locally modified files')),
2653 ('C', 'clean', None, _('overwrite locally modified files')),
2654 ('f', 'force', None, _('force a merge with outstanding changes'))],
2654 ('f', 'force', None, _('force a merge with outstanding changes'))],
2655 _('hg update [-b TAG] [-m] [-C] [-f] [REV]')),
2655 _('hg update [-b TAG] [-m] [-C] [-f] [REV]')),
2656 "verify": (verify, [], _('hg verify')),
2656 "verify": (verify, [], _('hg verify')),
2657 "version": (show_version, [], _('hg version')),
2657 "version": (show_version, [], _('hg version')),
2658 }
2658 }
2659
2659
2660 globalopts = [
2660 globalopts = [
2661 ('R', 'repository', '', _('repository root directory')),
2661 ('R', 'repository', '', _('repository root directory')),
2662 ('', 'cwd', '', _('change working directory')),
2662 ('', 'cwd', '', _('change working directory')),
2663 ('y', 'noninteractive', None,
2663 ('y', 'noninteractive', None,
2664 _('do not prompt, assume \'yes\' for any required answers')),
2664 _('do not prompt, assume \'yes\' for any required answers')),
2665 ('q', 'quiet', None, _('suppress output')),
2665 ('q', 'quiet', None, _('suppress output')),
2666 ('v', 'verbose', None, _('enable additional output')),
2666 ('v', 'verbose', None, _('enable additional output')),
2667 ('', 'debug', None, _('enable debugging output')),
2667 ('', 'debug', None, _('enable debugging output')),
2668 ('', 'debugger', None, _('start debugger')),
2668 ('', 'debugger', None, _('start debugger')),
2669 ('', 'traceback', None, _('print traceback on exception')),
2669 ('', 'traceback', None, _('print traceback on exception')),
2670 ('', 'time', None, _('time how long the command takes')),
2670 ('', 'time', None, _('time how long the command takes')),
2671 ('', 'profile', None, _('print command execution profile')),
2671 ('', 'profile', None, _('print command execution profile')),
2672 ('', 'version', None, _('output version information and exit')),
2672 ('', 'version', None, _('output version information and exit')),
2673 ('h', 'help', None, _('display help and exit')),
2673 ('h', 'help', None, _('display help and exit')),
2674 ]
2674 ]
2675
2675
2676 norepo = ("clone init version help debugancestor debugconfig debugdata"
2676 norepo = ("clone init version help debugancestor debugconfig debugdata"
2677 " debugindex debugindexdot paths")
2677 " debugindex debugindexdot paths")
2678
2678
2679 def find(cmd):
2679 def find(cmd):
2680 """Return (aliases, command table entry) for command string."""
2680 """Return (aliases, command table entry) for command string."""
2681 choice = []
2681 choice = []
2682 for e in table.keys():
2682 for e in table.keys():
2683 aliases = e.lstrip("^").split("|")
2683 aliases = e.lstrip("^").split("|")
2684 if cmd in aliases:
2684 if cmd in aliases:
2685 return aliases, table[e]
2685 return aliases, table[e]
2686 for a in aliases:
2686 for a in aliases:
2687 if a.startswith(cmd):
2687 if a.startswith(cmd):
2688 choice.append([aliases, table[e]])
2688 choice.append([aliases, table[e]])
2689 break
2689 break
2690
2690
2691 if len(choice) > 1:
2691 if len(choice) > 1:
2692 clist = [x[0][0] for x in choice]
2692 clist = []
2693 for aliases, table_e in choice:
2694 if aliases[0].startswith(cmd):
2695 clist.append(aliases[0])
2696 for a in aliases[1:]:
2697 if a.startswith(cmd) and not aliases[0].startswith(a):
2698 clist.append(a)
2699 clist.sort()
2693 raise AmbiguousCommand(cmd, clist)
2700 raise AmbiguousCommand(cmd, clist)
2694
2701
2695 if choice:
2702 if choice:
2696 return choice[0]
2703 return choice[0]
2697
2704
2698 raise UnknownCommand(cmd)
2705 raise UnknownCommand(cmd)
2699
2706
2700 class SignalInterrupt(Exception):
2707 class SignalInterrupt(Exception):
2701 """Exception raised on SIGTERM and SIGHUP."""
2708 """Exception raised on SIGTERM and SIGHUP."""
2702
2709
2703 def catchterm(*args):
2710 def catchterm(*args):
2704 raise SignalInterrupt
2711 raise SignalInterrupt
2705
2712
2706 def run():
2713 def run():
2707 sys.exit(dispatch(sys.argv[1:]))
2714 sys.exit(dispatch(sys.argv[1:]))
2708
2715
2709 class ParseError(Exception):
2716 class ParseError(Exception):
2710 """Exception raised on errors in parsing the command line."""
2717 """Exception raised on errors in parsing the command line."""
2711
2718
2712 def parse(ui, args):
2719 def parse(ui, args):
2713 options = {}
2720 options = {}
2714 cmdoptions = {}
2721 cmdoptions = {}
2715
2722
2716 try:
2723 try:
2717 args = fancyopts.fancyopts(args, globalopts, options)
2724 args = fancyopts.fancyopts(args, globalopts, options)
2718 except fancyopts.getopt.GetoptError, inst:
2725 except fancyopts.getopt.GetoptError, inst:
2719 raise ParseError(None, inst)
2726 raise ParseError(None, inst)
2720
2727
2721 if args:
2728 if args:
2722 cmd, args = args[0], args[1:]
2729 cmd, args = args[0], args[1:]
2723 aliases, i = find(cmd)
2730 aliases, i = find(cmd)
2724 cmd = aliases[0]
2731 cmd = aliases[0]
2725 defaults = ui.config("defaults", cmd)
2732 defaults = ui.config("defaults", cmd)
2726 if defaults:
2733 if defaults:
2727 args = defaults.split() + args
2734 args = defaults.split() + args
2728 c = list(i[1])
2735 c = list(i[1])
2729 else:
2736 else:
2730 cmd = None
2737 cmd = None
2731 c = []
2738 c = []
2732
2739
2733 # combine global options into local
2740 # combine global options into local
2734 for o in globalopts:
2741 for o in globalopts:
2735 c.append((o[0], o[1], options[o[1]], o[3]))
2742 c.append((o[0], o[1], options[o[1]], o[3]))
2736
2743
2737 try:
2744 try:
2738 args = fancyopts.fancyopts(args, c, cmdoptions)
2745 args = fancyopts.fancyopts(args, c, cmdoptions)
2739 except fancyopts.getopt.GetoptError, inst:
2746 except fancyopts.getopt.GetoptError, inst:
2740 raise ParseError(cmd, inst)
2747 raise ParseError(cmd, inst)
2741
2748
2742 # separate global options back out
2749 # separate global options back out
2743 for o in globalopts:
2750 for o in globalopts:
2744 n = o[1]
2751 n = o[1]
2745 options[n] = cmdoptions[n]
2752 options[n] = cmdoptions[n]
2746 del cmdoptions[n]
2753 del cmdoptions[n]
2747
2754
2748 return (cmd, cmd and i[0] or None, args, options, cmdoptions)
2755 return (cmd, cmd and i[0] or None, args, options, cmdoptions)
2749
2756
2750 def dispatch(args):
2757 def dispatch(args):
2751 signal.signal(signal.SIGTERM, catchterm)
2758 signal.signal(signal.SIGTERM, catchterm)
2752 try:
2759 try:
2753 signal.signal(signal.SIGHUP, catchterm)
2760 signal.signal(signal.SIGHUP, catchterm)
2754 except AttributeError:
2761 except AttributeError:
2755 pass
2762 pass
2756
2763
2757 try:
2764 try:
2758 u = ui.ui()
2765 u = ui.ui()
2759 except util.Abort, inst:
2766 except util.Abort, inst:
2760 sys.stderr.write(_("abort: %s\n") % inst)
2767 sys.stderr.write(_("abort: %s\n") % inst)
2761 sys.exit(1)
2768 sys.exit(1)
2762
2769
2763 external = []
2770 external = []
2764 for x in u.extensions():
2771 for x in u.extensions():
2765 def on_exception(exc, inst):
2772 def on_exception(exc, inst):
2766 u.warn(_("*** failed to import extension %s\n") % x[1])
2773 u.warn(_("*** failed to import extension %s\n") % x[1])
2767 u.warn("%s\n" % inst)
2774 u.warn("%s\n" % inst)
2768 if "--traceback" in sys.argv[1:]:
2775 if "--traceback" in sys.argv[1:]:
2769 traceback.print_exc()
2776 traceback.print_exc()
2770 if x[1]:
2777 if x[1]:
2771 try:
2778 try:
2772 mod = imp.load_source(x[0], x[1])
2779 mod = imp.load_source(x[0], x[1])
2773 except Exception, inst:
2780 except Exception, inst:
2774 on_exception(Exception, inst)
2781 on_exception(Exception, inst)
2775 continue
2782 continue
2776 else:
2783 else:
2777 def importh(name):
2784 def importh(name):
2778 mod = __import__(name)
2785 mod = __import__(name)
2779 components = name.split('.')
2786 components = name.split('.')
2780 for comp in components[1:]:
2787 for comp in components[1:]:
2781 mod = getattr(mod, comp)
2788 mod = getattr(mod, comp)
2782 return mod
2789 return mod
2783 try:
2790 try:
2784 mod = importh(x[0])
2791 mod = importh(x[0])
2785 except Exception, inst:
2792 except Exception, inst:
2786 on_exception(Exception, inst)
2793 on_exception(Exception, inst)
2787 continue
2794 continue
2788
2795
2789 external.append(mod)
2796 external.append(mod)
2790 for x in external:
2797 for x in external:
2791 cmdtable = getattr(x, 'cmdtable', {})
2798 cmdtable = getattr(x, 'cmdtable', {})
2792 for t in cmdtable:
2799 for t in cmdtable:
2793 if t in table:
2800 if t in table:
2794 u.warn(_("module %s overrides %s\n") % (x.__name__, t))
2801 u.warn(_("module %s overrides %s\n") % (x.__name__, t))
2795 table.update(cmdtable)
2802 table.update(cmdtable)
2796
2803
2797 try:
2804 try:
2798 cmd, func, args, options, cmdoptions = parse(u, args)
2805 cmd, func, args, options, cmdoptions = parse(u, args)
2799 except ParseError, inst:
2806 except ParseError, inst:
2800 if inst.args[0]:
2807 if inst.args[0]:
2801 u.warn(_("hg %s: %s\n") % (inst.args[0], inst.args[1]))
2808 u.warn(_("hg %s: %s\n") % (inst.args[0], inst.args[1]))
2802 help_(u, inst.args[0])
2809 help_(u, inst.args[0])
2803 else:
2810 else:
2804 u.warn(_("hg: %s\n") % inst.args[1])
2811 u.warn(_("hg: %s\n") % inst.args[1])
2805 help_(u, 'shortlist')
2812 help_(u, 'shortlist')
2806 sys.exit(-1)
2813 sys.exit(-1)
2807 except AmbiguousCommand, inst:
2814 except AmbiguousCommand, inst:
2808 u.warn(_("hg: command '%s' is ambiguous:\n %s\n") %
2815 u.warn(_("hg: command '%s' is ambiguous:\n %s\n") %
2809 (inst.args[0], " ".join(inst.args[1])))
2816 (inst.args[0], " ".join(inst.args[1])))
2810 sys.exit(1)
2817 sys.exit(1)
2811 except UnknownCommand, inst:
2818 except UnknownCommand, inst:
2812 u.warn(_("hg: unknown command '%s'\n") % inst.args[0])
2819 u.warn(_("hg: unknown command '%s'\n") % inst.args[0])
2813 help_(u, 'shortlist')
2820 help_(u, 'shortlist')
2814 sys.exit(1)
2821 sys.exit(1)
2815
2822
2816 if options["time"]:
2823 if options["time"]:
2817 def get_times():
2824 def get_times():
2818 t = os.times()
2825 t = os.times()
2819 if t[4] == 0.0: # Windows leaves this as zero, so use time.clock()
2826 if t[4] == 0.0: # Windows leaves this as zero, so use time.clock()
2820 t = (t[0], t[1], t[2], t[3], time.clock())
2827 t = (t[0], t[1], t[2], t[3], time.clock())
2821 return t
2828 return t
2822 s = get_times()
2829 s = get_times()
2823 def print_time():
2830 def print_time():
2824 t = get_times()
2831 t = get_times()
2825 u.warn(_("Time: real %.3f secs (user %.3f+%.3f sys %.3f+%.3f)\n") %
2832 u.warn(_("Time: real %.3f secs (user %.3f+%.3f sys %.3f+%.3f)\n") %
2826 (t[4]-s[4], t[0]-s[0], t[2]-s[2], t[1]-s[1], t[3]-s[3]))
2833 (t[4]-s[4], t[0]-s[0], t[2]-s[2], t[1]-s[1], t[3]-s[3]))
2827 atexit.register(print_time)
2834 atexit.register(print_time)
2828
2835
2829 u.updateopts(options["verbose"], options["debug"], options["quiet"],
2836 u.updateopts(options["verbose"], options["debug"], options["quiet"],
2830 not options["noninteractive"])
2837 not options["noninteractive"])
2831
2838
2832 # enter the debugger before command execution
2839 # enter the debugger before command execution
2833 if options['debugger']:
2840 if options['debugger']:
2834 pdb.set_trace()
2841 pdb.set_trace()
2835
2842
2836 try:
2843 try:
2837 try:
2844 try:
2838 if options['help']:
2845 if options['help']:
2839 help_(u, cmd, options['version'])
2846 help_(u, cmd, options['version'])
2840 sys.exit(0)
2847 sys.exit(0)
2841 elif options['version']:
2848 elif options['version']:
2842 show_version(u)
2849 show_version(u)
2843 sys.exit(0)
2850 sys.exit(0)
2844 elif not cmd:
2851 elif not cmd:
2845 help_(u, 'shortlist')
2852 help_(u, 'shortlist')
2846 sys.exit(0)
2853 sys.exit(0)
2847
2854
2848 if options['cwd']:
2855 if options['cwd']:
2849 try:
2856 try:
2850 os.chdir(options['cwd'])
2857 os.chdir(options['cwd'])
2851 except OSError, inst:
2858 except OSError, inst:
2852 raise util.Abort('%s: %s' %
2859 raise util.Abort('%s: %s' %
2853 (options['cwd'], inst.strerror))
2860 (options['cwd'], inst.strerror))
2854
2861
2855 if cmd not in norepo.split():
2862 if cmd not in norepo.split():
2856 path = options["repository"] or ""
2863 path = options["repository"] or ""
2857 repo = hg.repository(u, path=path)
2864 repo = hg.repository(u, path=path)
2858 u = repo.ui
2865 u = repo.ui
2859 for x in external:
2866 for x in external:
2860 if hasattr(x, 'reposetup'):
2867 if hasattr(x, 'reposetup'):
2861 x.reposetup(u, repo)
2868 x.reposetup(u, repo)
2862 d = lambda: func(u, repo, *args, **cmdoptions)
2869 d = lambda: func(u, repo, *args, **cmdoptions)
2863 else:
2870 else:
2864 d = lambda: func(u, *args, **cmdoptions)
2871 d = lambda: func(u, *args, **cmdoptions)
2865
2872
2866 try:
2873 try:
2867 if options['profile']:
2874 if options['profile']:
2868 import hotshot, hotshot.stats
2875 import hotshot, hotshot.stats
2869 prof = hotshot.Profile("hg.prof")
2876 prof = hotshot.Profile("hg.prof")
2870 try:
2877 try:
2871 try:
2878 try:
2872 return prof.runcall(d)
2879 return prof.runcall(d)
2873 except:
2880 except:
2874 try:
2881 try:
2875 u.warn(_('exception raised - generating '
2882 u.warn(_('exception raised - generating '
2876 'profile anyway\n'))
2883 'profile anyway\n'))
2877 except:
2884 except:
2878 pass
2885 pass
2879 raise
2886 raise
2880 finally:
2887 finally:
2881 prof.close()
2888 prof.close()
2882 stats = hotshot.stats.load("hg.prof")
2889 stats = hotshot.stats.load("hg.prof")
2883 stats.strip_dirs()
2890 stats.strip_dirs()
2884 stats.sort_stats('time', 'calls')
2891 stats.sort_stats('time', 'calls')
2885 stats.print_stats(40)
2892 stats.print_stats(40)
2886 else:
2893 else:
2887 return d()
2894 return d()
2888 finally:
2895 finally:
2889 u.flush()
2896 u.flush()
2890 except:
2897 except:
2891 # enter the debugger when we hit an exception
2898 # enter the debugger when we hit an exception
2892 if options['debugger']:
2899 if options['debugger']:
2893 pdb.post_mortem(sys.exc_info()[2])
2900 pdb.post_mortem(sys.exc_info()[2])
2894 if options['traceback']:
2901 if options['traceback']:
2895 traceback.print_exc()
2902 traceback.print_exc()
2896 raise
2903 raise
2897 except hg.RepoError, inst:
2904 except hg.RepoError, inst:
2898 u.warn(_("abort: "), inst, "!\n")
2905 u.warn(_("abort: "), inst, "!\n")
2899 except revlog.RevlogError, inst:
2906 except revlog.RevlogError, inst:
2900 u.warn(_("abort: "), inst, "!\n")
2907 u.warn(_("abort: "), inst, "!\n")
2901 except SignalInterrupt:
2908 except SignalInterrupt:
2902 u.warn(_("killed!\n"))
2909 u.warn(_("killed!\n"))
2903 except KeyboardInterrupt:
2910 except KeyboardInterrupt:
2904 try:
2911 try:
2905 u.warn(_("interrupted!\n"))
2912 u.warn(_("interrupted!\n"))
2906 except IOError, inst:
2913 except IOError, inst:
2907 if inst.errno == errno.EPIPE:
2914 if inst.errno == errno.EPIPE:
2908 if u.debugflag:
2915 if u.debugflag:
2909 u.warn(_("\nbroken pipe\n"))
2916 u.warn(_("\nbroken pipe\n"))
2910 else:
2917 else:
2911 raise
2918 raise
2912 except IOError, inst:
2919 except IOError, inst:
2913 if hasattr(inst, "code"):
2920 if hasattr(inst, "code"):
2914 u.warn(_("abort: %s\n") % inst)
2921 u.warn(_("abort: %s\n") % inst)
2915 elif hasattr(inst, "reason"):
2922 elif hasattr(inst, "reason"):
2916 u.warn(_("abort: error: %s\n") % inst.reason[1])
2923 u.warn(_("abort: error: %s\n") % inst.reason[1])
2917 elif hasattr(inst, "args") and inst[0] == errno.EPIPE:
2924 elif hasattr(inst, "args") and inst[0] == errno.EPIPE:
2918 if u.debugflag:
2925 if u.debugflag:
2919 u.warn(_("broken pipe\n"))
2926 u.warn(_("broken pipe\n"))
2920 elif getattr(inst, "strerror", None):
2927 elif getattr(inst, "strerror", None):
2921 if getattr(inst, "filename", None):
2928 if getattr(inst, "filename", None):
2922 u.warn(_("abort: %s - %s\n") % (inst.strerror, inst.filename))
2929 u.warn(_("abort: %s - %s\n") % (inst.strerror, inst.filename))
2923 else:
2930 else:
2924 u.warn(_("abort: %s\n") % inst.strerror)
2931 u.warn(_("abort: %s\n") % inst.strerror)
2925 else:
2932 else:
2926 raise
2933 raise
2927 except OSError, inst:
2934 except OSError, inst:
2928 if hasattr(inst, "filename"):
2935 if hasattr(inst, "filename"):
2929 u.warn(_("abort: %s: %s\n") % (inst.strerror, inst.filename))
2936 u.warn(_("abort: %s: %s\n") % (inst.strerror, inst.filename))
2930 else:
2937 else:
2931 u.warn(_("abort: %s\n") % inst.strerror)
2938 u.warn(_("abort: %s\n") % inst.strerror)
2932 except util.Abort, inst:
2939 except util.Abort, inst:
2933 u.warn(_('abort: '), inst.args[0] % inst.args[1:], '\n')
2940 u.warn(_('abort: '), inst.args[0] % inst.args[1:], '\n')
2934 sys.exit(1)
2941 sys.exit(1)
2935 except TypeError, inst:
2942 except TypeError, inst:
2936 # was this an argument error?
2943 # was this an argument error?
2937 tb = traceback.extract_tb(sys.exc_info()[2])
2944 tb = traceback.extract_tb(sys.exc_info()[2])
2938 if len(tb) > 2: # no
2945 if len(tb) > 2: # no
2939 raise
2946 raise
2940 u.debug(inst, "\n")
2947 u.debug(inst, "\n")
2941 u.warn(_("%s: invalid arguments\n") % cmd)
2948 u.warn(_("%s: invalid arguments\n") % cmd)
2942 help_(u, cmd)
2949 help_(u, cmd)
2943 except AmbiguousCommand, inst:
2950 except AmbiguousCommand, inst:
2944 u.warn(_("hg: command '%s' is ambiguous:\n %s\n") %
2951 u.warn(_("hg: command '%s' is ambiguous:\n %s\n") %
2945 (inst.args[0], " ".join(inst.args[1])))
2952 (inst.args[0], " ".join(inst.args[1])))
2946 help_(u, 'shortlist')
2953 help_(u, 'shortlist')
2947 except UnknownCommand, inst:
2954 except UnknownCommand, inst:
2948 u.warn(_("hg: unknown command '%s'\n") % inst.args[0])
2955 u.warn(_("hg: unknown command '%s'\n") % inst.args[0])
2949 help_(u, 'shortlist')
2956 help_(u, 'shortlist')
2950 except SystemExit:
2957 except SystemExit:
2951 # don't catch this in the catch-all below
2958 # don't catch this in the catch-all below
2952 raise
2959 raise
2953 except:
2960 except:
2954 u.warn(_("** unknown exception encountered, details follow\n"))
2961 u.warn(_("** unknown exception encountered, details follow\n"))
2955 u.warn(_("** report bug details to mercurial@selenic.com\n"))
2962 u.warn(_("** report bug details to mercurial@selenic.com\n"))
2956 u.warn(_("** Mercurial Distributed SCM (version %s)\n")
2963 u.warn(_("** Mercurial Distributed SCM (version %s)\n")
2957 % version.get_version())
2964 % version.get_version())
2958 raise
2965 raise
2959
2966
2960 sys.exit(-1)
2967 sys.exit(-1)
General Comments 0
You need to be logged in to leave comments. Login now