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