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