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