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