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