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