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