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