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