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