##// END OF EJS Templates
fix incorrect date when committing a tag...
Benoit Boissinot -
r6243:437eef39 default
parent child Browse files
Show More
@@ -1,3180 +1,3184
1 # commands.py - command processing for mercurial
1 # commands.py - command processing for mercurial
2 #
2 #
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms
5 # This software may be used and distributed according to the terms
6 # of the GNU General Public License, incorporated herein by reference.
6 # of the GNU General Public License, incorporated herein by reference.
7
7
8 from node import hex, nullid, nullrev, short
8 from node import hex, nullid, nullrev, short
9 from repo import RepoError
9 from repo import RepoError
10 from i18n import _
10 from i18n import _
11 import os, re, sys, urllib
11 import os, re, sys, urllib
12 import hg, util, revlog, bundlerepo, extensions
12 import hg, util, revlog, bundlerepo, extensions
13 import difflib, patch, time, help, mdiff, tempfile
13 import difflib, patch, time, help, mdiff, tempfile
14 import version, socket
14 import version, socket
15 import archival, changegroup, cmdutil, hgweb.server, sshserver, hbisect
15 import archival, changegroup, cmdutil, hgweb.server, sshserver, hbisect
16
16
17 # Commands start here, listed alphabetically
17 # Commands start here, listed alphabetically
18
18
19 def add(ui, repo, *pats, **opts):
19 def add(ui, repo, *pats, **opts):
20 """add the specified files on the next commit
20 """add the specified files on the next commit
21
21
22 Schedule files to be version controlled and added to the repository.
22 Schedule files to be version controlled and added to the repository.
23
23
24 The files will be added to the repository at the next commit. To
24 The files will be added to the repository at the next commit. To
25 undo an add before that, see hg revert.
25 undo an add before that, see hg revert.
26
26
27 If no names are given, add all files in the repository.
27 If no names are given, add all files in the repository.
28 """
28 """
29
29
30 rejected = None
30 rejected = None
31 exacts = {}
31 exacts = {}
32 names = []
32 names = []
33 for src, abs, rel, exact in cmdutil.walk(repo, pats, opts,
33 for src, abs, rel, exact in cmdutil.walk(repo, pats, opts,
34 badmatch=util.always):
34 badmatch=util.always):
35 if exact:
35 if exact:
36 if ui.verbose:
36 if ui.verbose:
37 ui.status(_('adding %s\n') % rel)
37 ui.status(_('adding %s\n') % rel)
38 names.append(abs)
38 names.append(abs)
39 exacts[abs] = 1
39 exacts[abs] = 1
40 elif abs not in repo.dirstate:
40 elif abs not in repo.dirstate:
41 ui.status(_('adding %s\n') % rel)
41 ui.status(_('adding %s\n') % rel)
42 names.append(abs)
42 names.append(abs)
43 if not opts.get('dry_run'):
43 if not opts.get('dry_run'):
44 rejected = repo.add(names)
44 rejected = repo.add(names)
45 rejected = [p for p in rejected if p in exacts]
45 rejected = [p for p in rejected if p in exacts]
46 return rejected and 1 or 0
46 return rejected and 1 or 0
47
47
48 def addremove(ui, repo, *pats, **opts):
48 def addremove(ui, repo, *pats, **opts):
49 """add all new files, delete all missing files
49 """add all new files, delete all missing files
50
50
51 Add all new files and remove all missing files from the repository.
51 Add all new files and remove all missing files from the repository.
52
52
53 New files are ignored if they match any of the patterns in .hgignore. As
53 New files are ignored if they match any of the patterns in .hgignore. As
54 with add, these changes take effect at the next commit.
54 with add, these changes take effect at the next commit.
55
55
56 Use the -s option to detect renamed files. With a parameter > 0,
56 Use the -s option to detect renamed files. With a parameter > 0,
57 this compares every removed file with every added file and records
57 this compares every removed file with every added file and records
58 those similar enough as renames. This option takes a percentage
58 those similar enough as renames. This option takes a percentage
59 between 0 (disabled) and 100 (files must be identical) as its
59 between 0 (disabled) and 100 (files must be identical) as its
60 parameter. Detecting renamed files this way can be expensive.
60 parameter. Detecting renamed files this way can be expensive.
61 """
61 """
62 try:
62 try:
63 sim = float(opts.get('similarity') or 0)
63 sim = float(opts.get('similarity') or 0)
64 except ValueError:
64 except ValueError:
65 raise util.Abort(_('similarity must be a number'))
65 raise util.Abort(_('similarity must be a number'))
66 if sim < 0 or sim > 100:
66 if sim < 0 or sim > 100:
67 raise util.Abort(_('similarity must be between 0 and 100'))
67 raise util.Abort(_('similarity must be between 0 and 100'))
68 return cmdutil.addremove(repo, pats, opts, similarity=sim/100.)
68 return cmdutil.addremove(repo, pats, opts, similarity=sim/100.)
69
69
70 def annotate(ui, repo, *pats, **opts):
70 def annotate(ui, repo, *pats, **opts):
71 """show changeset information per file line
71 """show changeset information per file line
72
72
73 List changes in files, showing the revision id responsible for each line
73 List changes in files, showing the revision id responsible for each line
74
74
75 This command is useful to discover who did a change or when a change took
75 This command is useful to discover who did a change or when a change took
76 place.
76 place.
77
77
78 Without the -a option, annotate will avoid processing files it
78 Without the -a option, annotate will avoid processing files it
79 detects as binary. With -a, annotate will generate an annotation
79 detects as binary. With -a, annotate will generate an annotation
80 anyway, probably with undesirable results.
80 anyway, probably with undesirable results.
81 """
81 """
82 datefunc = ui.quiet and util.shortdate or util.datestr
82 datefunc = ui.quiet and util.shortdate or util.datestr
83 getdate = util.cachefunc(lambda x: datefunc(x[0].date()))
83 getdate = util.cachefunc(lambda x: datefunc(x[0].date()))
84
84
85 if not pats:
85 if not pats:
86 raise util.Abort(_('at least one file name or pattern required'))
86 raise util.Abort(_('at least one file name or pattern required'))
87
87
88 opmap = [('user', lambda x: ui.shortuser(x[0].user())),
88 opmap = [('user', lambda x: ui.shortuser(x[0].user())),
89 ('number', lambda x: str(x[0].rev())),
89 ('number', lambda x: str(x[0].rev())),
90 ('changeset', lambda x: short(x[0].node())),
90 ('changeset', lambda x: short(x[0].node())),
91 ('date', getdate),
91 ('date', getdate),
92 ('follow', lambda x: x[0].path()),
92 ('follow', lambda x: x[0].path()),
93 ]
93 ]
94
94
95 if (not opts['user'] and not opts['changeset'] and not opts['date']
95 if (not opts['user'] and not opts['changeset'] and not opts['date']
96 and not opts['follow']):
96 and not opts['follow']):
97 opts['number'] = 1
97 opts['number'] = 1
98
98
99 linenumber = opts.get('line_number') is not None
99 linenumber = opts.get('line_number') is not None
100 if (linenumber and (not opts['changeset']) and (not opts['number'])):
100 if (linenumber and (not opts['changeset']) and (not opts['number'])):
101 raise util.Abort(_('at least one of -n/-c is required for -l'))
101 raise util.Abort(_('at least one of -n/-c is required for -l'))
102
102
103 funcmap = [func for op, func in opmap if opts.get(op)]
103 funcmap = [func for op, func in opmap if opts.get(op)]
104 if linenumber:
104 if linenumber:
105 lastfunc = funcmap[-1]
105 lastfunc = funcmap[-1]
106 funcmap[-1] = lambda x: "%s:%s" % (lastfunc(x), x[1])
106 funcmap[-1] = lambda x: "%s:%s" % (lastfunc(x), x[1])
107
107
108 ctx = repo.changectx(opts['rev'])
108 ctx = repo.changectx(opts['rev'])
109
109
110 for src, abs, rel, exact in cmdutil.walk(repo, pats, opts,
110 for src, abs, rel, exact in cmdutil.walk(repo, pats, opts,
111 node=ctx.node()):
111 node=ctx.node()):
112 fctx = ctx.filectx(abs)
112 fctx = ctx.filectx(abs)
113 if not opts['text'] and util.binary(fctx.data()):
113 if not opts['text'] and util.binary(fctx.data()):
114 ui.write(_("%s: binary file\n") % ((pats and rel) or abs))
114 ui.write(_("%s: binary file\n") % ((pats and rel) or abs))
115 continue
115 continue
116
116
117 lines = fctx.annotate(follow=opts.get('follow'),
117 lines = fctx.annotate(follow=opts.get('follow'),
118 linenumber=linenumber)
118 linenumber=linenumber)
119 pieces = []
119 pieces = []
120
120
121 for f in funcmap:
121 for f in funcmap:
122 l = [f(n) for n, dummy in lines]
122 l = [f(n) for n, dummy in lines]
123 if l:
123 if l:
124 m = max(map(len, l))
124 m = max(map(len, l))
125 pieces.append(["%*s" % (m, x) for x in l])
125 pieces.append(["%*s" % (m, x) for x in l])
126
126
127 if pieces:
127 if pieces:
128 for p, l in zip(zip(*pieces), lines):
128 for p, l in zip(zip(*pieces), lines):
129 ui.write("%s: %s" % (" ".join(p), l[1]))
129 ui.write("%s: %s" % (" ".join(p), l[1]))
130
130
131 def archive(ui, repo, dest, **opts):
131 def archive(ui, repo, dest, **opts):
132 '''create unversioned archive of a repository revision
132 '''create unversioned archive of a repository revision
133
133
134 By default, the revision used is the parent of the working
134 By default, the revision used is the parent of the working
135 directory; use "-r" to specify a different revision.
135 directory; use "-r" to specify a different revision.
136
136
137 To specify the type of archive to create, use "-t". Valid
137 To specify the type of archive to create, use "-t". Valid
138 types are:
138 types are:
139
139
140 "files" (default): a directory full of files
140 "files" (default): a directory full of files
141 "tar": tar archive, uncompressed
141 "tar": tar archive, uncompressed
142 "tbz2": tar archive, compressed using bzip2
142 "tbz2": tar archive, compressed using bzip2
143 "tgz": tar archive, compressed using gzip
143 "tgz": tar archive, compressed using gzip
144 "uzip": zip archive, uncompressed
144 "uzip": zip archive, uncompressed
145 "zip": zip archive, compressed using deflate
145 "zip": zip archive, compressed using deflate
146
146
147 The exact name of the destination archive or directory is given
147 The exact name of the destination archive or directory is given
148 using a format string; see "hg help export" for details.
148 using a format string; see "hg help export" for details.
149
149
150 Each member added to an archive file has a directory prefix
150 Each member added to an archive file has a directory prefix
151 prepended. Use "-p" to specify a format string for the prefix.
151 prepended. Use "-p" to specify a format string for the prefix.
152 The default is the basename of the archive, with suffixes removed.
152 The default is the basename of the archive, with suffixes removed.
153 '''
153 '''
154
154
155 ctx = repo.changectx(opts['rev'])
155 ctx = repo.changectx(opts['rev'])
156 if not ctx:
156 if not ctx:
157 raise util.Abort(_('repository has no revisions'))
157 raise util.Abort(_('repository has no revisions'))
158 node = ctx.node()
158 node = ctx.node()
159 dest = cmdutil.make_filename(repo, dest, node)
159 dest = cmdutil.make_filename(repo, dest, node)
160 if os.path.realpath(dest) == repo.root:
160 if os.path.realpath(dest) == repo.root:
161 raise util.Abort(_('repository root cannot be destination'))
161 raise util.Abort(_('repository root cannot be destination'))
162 dummy, matchfn, dummy = cmdutil.matchpats(repo, [], opts)
162 dummy, matchfn, dummy = cmdutil.matchpats(repo, [], opts)
163 kind = opts.get('type') or 'files'
163 kind = opts.get('type') or 'files'
164 prefix = opts['prefix']
164 prefix = opts['prefix']
165 if dest == '-':
165 if dest == '-':
166 if kind == 'files':
166 if kind == 'files':
167 raise util.Abort(_('cannot archive plain files to stdout'))
167 raise util.Abort(_('cannot archive plain files to stdout'))
168 dest = sys.stdout
168 dest = sys.stdout
169 if not prefix: prefix = os.path.basename(repo.root) + '-%h'
169 if not prefix: prefix = os.path.basename(repo.root) + '-%h'
170 prefix = cmdutil.make_filename(repo, prefix, node)
170 prefix = cmdutil.make_filename(repo, prefix, node)
171 archival.archive(repo, dest, node, kind, not opts['no_decode'],
171 archival.archive(repo, dest, node, kind, not opts['no_decode'],
172 matchfn, prefix)
172 matchfn, prefix)
173
173
174 def backout(ui, repo, node=None, rev=None, **opts):
174 def backout(ui, repo, node=None, rev=None, **opts):
175 '''reverse effect of earlier changeset
175 '''reverse effect of earlier changeset
176
176
177 Commit the backed out changes as a new changeset. The new
177 Commit the backed out changes as a new changeset. The new
178 changeset is a child of the backed out changeset.
178 changeset is a child of the backed out changeset.
179
179
180 If you back out a changeset other than the tip, a new head is
180 If you back out a changeset other than the tip, a new head is
181 created. This head will be the new tip and you should merge this
181 created. This head will be the new tip and you should merge this
182 backout changeset with another head (current one by default).
182 backout changeset with another head (current one by default).
183
183
184 The --merge option remembers the parent of the working directory
184 The --merge option remembers the parent of the working directory
185 before starting the backout, then merges the new head with that
185 before starting the backout, then merges the new head with that
186 changeset afterwards. This saves you from doing the merge by
186 changeset afterwards. This saves you from doing the merge by
187 hand. The result of this merge is not committed, as for a normal
187 hand. The result of this merge is not committed, as for a normal
188 merge.
188 merge.
189
189
190 See 'hg help dates' for a list of formats valid for -d/--date.
190 See 'hg help dates' for a list of formats valid for -d/--date.
191 '''
191 '''
192 if rev and node:
192 if rev and node:
193 raise util.Abort(_("please specify just one revision"))
193 raise util.Abort(_("please specify just one revision"))
194
194
195 if not rev:
195 if not rev:
196 rev = node
196 rev = node
197
197
198 if not rev:
198 if not rev:
199 raise util.Abort(_("please specify a revision to backout"))
199 raise util.Abort(_("please specify a revision to backout"))
200
200
201 date = opts.get('date')
201 date = opts.get('date')
202 if date:
202 if date:
203 opts['date'] = util.parsedate(date)
203 opts['date'] = util.parsedate(date)
204
204
205 cmdutil.bail_if_changed(repo)
205 cmdutil.bail_if_changed(repo)
206 node = repo.lookup(rev)
206 node = repo.lookup(rev)
207
207
208 op1, op2 = repo.dirstate.parents()
208 op1, op2 = repo.dirstate.parents()
209 a = repo.changelog.ancestor(op1, node)
209 a = repo.changelog.ancestor(op1, node)
210 if a != node:
210 if a != node:
211 raise util.Abort(_('cannot back out change on a different branch'))
211 raise util.Abort(_('cannot back out change on a different branch'))
212
212
213 p1, p2 = repo.changelog.parents(node)
213 p1, p2 = repo.changelog.parents(node)
214 if p1 == nullid:
214 if p1 == nullid:
215 raise util.Abort(_('cannot back out a change with no parents'))
215 raise util.Abort(_('cannot back out a change with no parents'))
216 if p2 != nullid:
216 if p2 != nullid:
217 if not opts['parent']:
217 if not opts['parent']:
218 raise util.Abort(_('cannot back out a merge changeset without '
218 raise util.Abort(_('cannot back out a merge changeset without '
219 '--parent'))
219 '--parent'))
220 p = repo.lookup(opts['parent'])
220 p = repo.lookup(opts['parent'])
221 if p not in (p1, p2):
221 if p not in (p1, p2):
222 raise util.Abort(_('%s is not a parent of %s') %
222 raise util.Abort(_('%s is not a parent of %s') %
223 (short(p), short(node)))
223 (short(p), short(node)))
224 parent = p
224 parent = p
225 else:
225 else:
226 if opts['parent']:
226 if opts['parent']:
227 raise util.Abort(_('cannot use --parent on non-merge changeset'))
227 raise util.Abort(_('cannot use --parent on non-merge changeset'))
228 parent = p1
228 parent = p1
229
229
230 hg.clean(repo, node, show_stats=False)
230 hg.clean(repo, node, show_stats=False)
231 revert_opts = opts.copy()
231 revert_opts = opts.copy()
232 revert_opts['date'] = None
232 revert_opts['date'] = None
233 revert_opts['all'] = True
233 revert_opts['all'] = True
234 revert_opts['rev'] = hex(parent)
234 revert_opts['rev'] = hex(parent)
235 revert_opts['no_backup'] = None
235 revert_opts['no_backup'] = None
236 revert(ui, repo, **revert_opts)
236 revert(ui, repo, **revert_opts)
237 commit_opts = opts.copy()
237 commit_opts = opts.copy()
238 commit_opts['addremove'] = False
238 commit_opts['addremove'] = False
239 if not commit_opts['message'] and not commit_opts['logfile']:
239 if not commit_opts['message'] and not commit_opts['logfile']:
240 commit_opts['message'] = _("Backed out changeset %s") % (short(node))
240 commit_opts['message'] = _("Backed out changeset %s") % (short(node))
241 commit_opts['force_editor'] = True
241 commit_opts['force_editor'] = True
242 commit(ui, repo, **commit_opts)
242 commit(ui, repo, **commit_opts)
243 def nice(node):
243 def nice(node):
244 return '%d:%s' % (repo.changelog.rev(node), short(node))
244 return '%d:%s' % (repo.changelog.rev(node), short(node))
245 ui.status(_('changeset %s backs out changeset %s\n') %
245 ui.status(_('changeset %s backs out changeset %s\n') %
246 (nice(repo.changelog.tip()), nice(node)))
246 (nice(repo.changelog.tip()), nice(node)))
247 if op1 != node:
247 if op1 != node:
248 hg.clean(repo, op1, show_stats=False)
248 hg.clean(repo, op1, show_stats=False)
249 if opts['merge']:
249 if opts['merge']:
250 ui.status(_('merging with changeset %s\n') % nice(repo.changelog.tip()))
250 ui.status(_('merging with changeset %s\n') % nice(repo.changelog.tip()))
251 hg.merge(repo, hex(repo.changelog.tip()))
251 hg.merge(repo, hex(repo.changelog.tip()))
252 else:
252 else:
253 ui.status(_('the backout changeset is a new head - '
253 ui.status(_('the backout changeset is a new head - '
254 'do not forget to merge\n'))
254 'do not forget to merge\n'))
255 ui.status(_('(use "backout --merge" '
255 ui.status(_('(use "backout --merge" '
256 'if you want to auto-merge)\n'))
256 'if you want to auto-merge)\n'))
257
257
258 def bisect(ui, repo, rev=None, extra=None,
258 def bisect(ui, repo, rev=None, extra=None,
259 reset=None, good=None, bad=None, skip=None, noupdate=None):
259 reset=None, good=None, bad=None, skip=None, noupdate=None):
260 """subdivision search of changesets
260 """subdivision search of changesets
261
261
262 This command helps to find changesets which introduce problems.
262 This command helps to find changesets which introduce problems.
263 To use, mark the earliest changeset you know exhibits the problem
263 To use, mark the earliest changeset you know exhibits the problem
264 as bad, then mark the latest changeset which is free from the
264 as bad, then mark the latest changeset which is free from the
265 problem as good. Bisect will update your working directory to a
265 problem as good. Bisect will update your working directory to a
266 revision for testing. Once you have performed tests, mark the
266 revision for testing. Once you have performed tests, mark the
267 working directory as bad or good and bisect will either update to
267 working directory as bad or good and bisect will either update to
268 another candidate changeset or announce that it has found the bad
268 another candidate changeset or announce that it has found the bad
269 revision.
269 revision.
270 """
270 """
271 # backward compatibility
271 # backward compatibility
272 if rev in "good bad reset init".split():
272 if rev in "good bad reset init".split():
273 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
273 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
274 cmd, rev, extra = rev, extra, None
274 cmd, rev, extra = rev, extra, None
275 if cmd == "good":
275 if cmd == "good":
276 good = True
276 good = True
277 elif cmd == "bad":
277 elif cmd == "bad":
278 bad = True
278 bad = True
279 else:
279 else:
280 reset = True
280 reset = True
281 elif extra or good + bad + skip + reset > 1:
281 elif extra or good + bad + skip + reset > 1:
282 raise util.Abort("Incompatible arguments")
282 raise util.Abort("Incompatible arguments")
283
283
284 if reset:
284 if reset:
285 p = repo.join("bisect.state")
285 p = repo.join("bisect.state")
286 if os.path.exists(p):
286 if os.path.exists(p):
287 os.unlink(p)
287 os.unlink(p)
288 return
288 return
289
289
290 # load state
290 # load state
291 state = {'good': [], 'bad': [], 'skip': []}
291 state = {'good': [], 'bad': [], 'skip': []}
292 if os.path.exists(repo.join("bisect.state")):
292 if os.path.exists(repo.join("bisect.state")):
293 for l in repo.opener("bisect.state"):
293 for l in repo.opener("bisect.state"):
294 kind, node = l[:-1].split()
294 kind, node = l[:-1].split()
295 node = repo.lookup(node)
295 node = repo.lookup(node)
296 if kind not in state:
296 if kind not in state:
297 raise util.Abort(_("unknown bisect kind %s") % kind)
297 raise util.Abort(_("unknown bisect kind %s") % kind)
298 state[kind].append(node)
298 state[kind].append(node)
299
299
300 # update state
300 # update state
301 node = repo.lookup(rev or '.')
301 node = repo.lookup(rev or '.')
302 if good:
302 if good:
303 state['good'].append(node)
303 state['good'].append(node)
304 elif bad:
304 elif bad:
305 state['bad'].append(node)
305 state['bad'].append(node)
306 elif skip:
306 elif skip:
307 state['skip'].append(node)
307 state['skip'].append(node)
308
308
309 # save state
309 # save state
310 f = repo.opener("bisect.state", "w", atomictemp=True)
310 f = repo.opener("bisect.state", "w", atomictemp=True)
311 wlock = repo.wlock()
311 wlock = repo.wlock()
312 try:
312 try:
313 for kind in state:
313 for kind in state:
314 for node in state[kind]:
314 for node in state[kind]:
315 f.write("%s %s\n" % (kind, hex(node)))
315 f.write("%s %s\n" % (kind, hex(node)))
316 f.rename()
316 f.rename()
317 finally:
317 finally:
318 del wlock
318 del wlock
319
319
320 if not state['good'] or not state['bad']:
320 if not state['good'] or not state['bad']:
321 return
321 return
322
322
323 # actually bisect
323 # actually bisect
324 node, changesets, good = hbisect.bisect(repo.changelog, state)
324 node, changesets, good = hbisect.bisect(repo.changelog, state)
325 if changesets == 0:
325 if changesets == 0:
326 ui.write(_("The first %s revision is:\n") % (good and "good" or "bad"))
326 ui.write(_("The first %s revision is:\n") % (good and "good" or "bad"))
327 displayer = cmdutil.show_changeset(ui, repo, {})
327 displayer = cmdutil.show_changeset(ui, repo, {})
328 displayer.show(changenode=node)
328 displayer.show(changenode=node)
329 elif node is not None:
329 elif node is not None:
330 # compute the approximate number of remaining tests
330 # compute the approximate number of remaining tests
331 tests, size = 0, 2
331 tests, size = 0, 2
332 while size <= changesets:
332 while size <= changesets:
333 tests, size = tests + 1, size * 2
333 tests, size = tests + 1, size * 2
334 rev = repo.changelog.rev(node)
334 rev = repo.changelog.rev(node)
335 ui.write(_("Testing changeset %s:%s "
335 ui.write(_("Testing changeset %s:%s "
336 "(%s changesets remaining, ~%s tests)\n")
336 "(%s changesets remaining, ~%s tests)\n")
337 % (rev, short(node), changesets, tests))
337 % (rev, short(node), changesets, tests))
338 if not noupdate:
338 if not noupdate:
339 cmdutil.bail_if_changed(repo)
339 cmdutil.bail_if_changed(repo)
340 return hg.clean(repo, node)
340 return hg.clean(repo, node)
341
341
342 def branch(ui, repo, label=None, **opts):
342 def branch(ui, repo, label=None, **opts):
343 """set or show the current branch name
343 """set or show the current branch name
344
344
345 With no argument, show the current branch name. With one argument,
345 With no argument, show the current branch name. With one argument,
346 set the working directory branch name (the branch does not exist in
346 set the working directory branch name (the branch does not exist in
347 the repository until the next commit).
347 the repository until the next commit).
348
348
349 Unless --force is specified, branch will not let you set a
349 Unless --force is specified, branch will not let you set a
350 branch name that shadows an existing branch.
350 branch name that shadows an existing branch.
351
351
352 Use the command 'hg update' to switch to an existing branch.
352 Use the command 'hg update' to switch to an existing branch.
353 """
353 """
354
354
355 if label:
355 if label:
356 if not opts.get('force') and label in repo.branchtags():
356 if not opts.get('force') and label in repo.branchtags():
357 if label not in [p.branch() for p in repo.workingctx().parents()]:
357 if label not in [p.branch() for p in repo.workingctx().parents()]:
358 raise util.Abort(_('a branch of the same name already exists'
358 raise util.Abort(_('a branch of the same name already exists'
359 ' (use --force to override)'))
359 ' (use --force to override)'))
360 repo.dirstate.setbranch(util.fromlocal(label))
360 repo.dirstate.setbranch(util.fromlocal(label))
361 ui.status(_('marked working directory as branch %s\n') % label)
361 ui.status(_('marked working directory as branch %s\n') % label)
362 else:
362 else:
363 ui.write("%s\n" % util.tolocal(repo.dirstate.branch()))
363 ui.write("%s\n" % util.tolocal(repo.dirstate.branch()))
364
364
365 def branches(ui, repo, active=False):
365 def branches(ui, repo, active=False):
366 """list repository named branches
366 """list repository named branches
367
367
368 List the repository's named branches, indicating which ones are
368 List the repository's named branches, indicating which ones are
369 inactive. If active is specified, only show active branches.
369 inactive. If active is specified, only show active branches.
370
370
371 A branch is considered active if it contains unmerged heads.
371 A branch is considered active if it contains unmerged heads.
372
372
373 Use the command 'hg update' to switch to an existing branch.
373 Use the command 'hg update' to switch to an existing branch.
374 """
374 """
375 b = repo.branchtags()
375 b = repo.branchtags()
376 heads = dict.fromkeys(repo.heads(), 1)
376 heads = dict.fromkeys(repo.heads(), 1)
377 l = [((n in heads), repo.changelog.rev(n), n, t) for t, n in b.items()]
377 l = [((n in heads), repo.changelog.rev(n), n, t) for t, n in b.items()]
378 l.sort()
378 l.sort()
379 l.reverse()
379 l.reverse()
380 for ishead, r, n, t in l:
380 for ishead, r, n, t in l:
381 if active and not ishead:
381 if active and not ishead:
382 # If we're only displaying active branches, abort the loop on
382 # If we're only displaying active branches, abort the loop on
383 # encountering the first inactive head
383 # encountering the first inactive head
384 break
384 break
385 else:
385 else:
386 hexfunc = ui.debugflag and hex or short
386 hexfunc = ui.debugflag and hex or short
387 if ui.quiet:
387 if ui.quiet:
388 ui.write("%s\n" % t)
388 ui.write("%s\n" % t)
389 else:
389 else:
390 spaces = " " * (30 - util.locallen(t))
390 spaces = " " * (30 - util.locallen(t))
391 # The code only gets here if inactive branches are being
391 # The code only gets here if inactive branches are being
392 # displayed or the branch is active.
392 # displayed or the branch is active.
393 isinactive = ((not ishead) and " (inactive)") or ''
393 isinactive = ((not ishead) and " (inactive)") or ''
394 ui.write("%s%s %s:%s%s\n" % (t, spaces, r, hexfunc(n), isinactive))
394 ui.write("%s%s %s:%s%s\n" % (t, spaces, r, hexfunc(n), isinactive))
395
395
396 def bundle(ui, repo, fname, dest=None, **opts):
396 def bundle(ui, repo, fname, dest=None, **opts):
397 """create a changegroup file
397 """create a changegroup file
398
398
399 Generate a compressed changegroup file collecting changesets not
399 Generate a compressed changegroup file collecting changesets not
400 found in the other repository.
400 found in the other repository.
401
401
402 If no destination repository is specified the destination is
402 If no destination repository is specified the destination is
403 assumed to have all the nodes specified by one or more --base
403 assumed to have all the nodes specified by one or more --base
404 parameters. To create a bundle containing all changesets, use
404 parameters. To create a bundle containing all changesets, use
405 --all (or --base null).
405 --all (or --base null).
406
406
407 The bundle file can then be transferred using conventional means and
407 The bundle file can then be transferred using conventional means and
408 applied to another repository with the unbundle or pull command.
408 applied to another repository with the unbundle or pull command.
409 This is useful when direct push and pull are not available or when
409 This is useful when direct push and pull are not available or when
410 exporting an entire repository is undesirable.
410 exporting an entire repository is undesirable.
411
411
412 Applying bundles preserves all changeset contents including
412 Applying bundles preserves all changeset contents including
413 permissions, copy/rename information, and revision history.
413 permissions, copy/rename information, and revision history.
414 """
414 """
415 revs = opts.get('rev') or None
415 revs = opts.get('rev') or None
416 if revs:
416 if revs:
417 revs = [repo.lookup(rev) for rev in revs]
417 revs = [repo.lookup(rev) for rev in revs]
418 if opts.get('all'):
418 if opts.get('all'):
419 base = ['null']
419 base = ['null']
420 else:
420 else:
421 base = opts.get('base')
421 base = opts.get('base')
422 if base:
422 if base:
423 if dest:
423 if dest:
424 raise util.Abort(_("--base is incompatible with specifiying "
424 raise util.Abort(_("--base is incompatible with specifiying "
425 "a destination"))
425 "a destination"))
426 base = [repo.lookup(rev) for rev in base]
426 base = [repo.lookup(rev) for rev in base]
427 # create the right base
427 # create the right base
428 # XXX: nodesbetween / changegroup* should be "fixed" instead
428 # XXX: nodesbetween / changegroup* should be "fixed" instead
429 o = []
429 o = []
430 has = {nullid: None}
430 has = {nullid: None}
431 for n in base:
431 for n in base:
432 has.update(repo.changelog.reachable(n))
432 has.update(repo.changelog.reachable(n))
433 if revs:
433 if revs:
434 visit = list(revs)
434 visit = list(revs)
435 else:
435 else:
436 visit = repo.changelog.heads()
436 visit = repo.changelog.heads()
437 seen = {}
437 seen = {}
438 while visit:
438 while visit:
439 n = visit.pop(0)
439 n = visit.pop(0)
440 parents = [p for p in repo.changelog.parents(n) if p not in has]
440 parents = [p for p in repo.changelog.parents(n) if p not in has]
441 if len(parents) == 0:
441 if len(parents) == 0:
442 o.insert(0, n)
442 o.insert(0, n)
443 else:
443 else:
444 for p in parents:
444 for p in parents:
445 if p not in seen:
445 if p not in seen:
446 seen[p] = 1
446 seen[p] = 1
447 visit.append(p)
447 visit.append(p)
448 else:
448 else:
449 cmdutil.setremoteconfig(ui, opts)
449 cmdutil.setremoteconfig(ui, opts)
450 dest, revs, checkout = hg.parseurl(
450 dest, revs, checkout = hg.parseurl(
451 ui.expandpath(dest or 'default-push', dest or 'default'), revs)
451 ui.expandpath(dest or 'default-push', dest or 'default'), revs)
452 other = hg.repository(ui, dest)
452 other = hg.repository(ui, dest)
453 o = repo.findoutgoing(other, force=opts['force'])
453 o = repo.findoutgoing(other, force=opts['force'])
454
454
455 if revs:
455 if revs:
456 cg = repo.changegroupsubset(o, revs, 'bundle')
456 cg = repo.changegroupsubset(o, revs, 'bundle')
457 else:
457 else:
458 cg = repo.changegroup(o, 'bundle')
458 cg = repo.changegroup(o, 'bundle')
459 changegroup.writebundle(cg, fname, "HG10BZ")
459 changegroup.writebundle(cg, fname, "HG10BZ")
460
460
461 def cat(ui, repo, file1, *pats, **opts):
461 def cat(ui, repo, file1, *pats, **opts):
462 """output the current or given revision of files
462 """output the current or given revision of files
463
463
464 Print the specified files as they were at the given revision.
464 Print the specified files as they were at the given revision.
465 If no revision is given, the parent of the working directory is used,
465 If no revision is given, the parent of the working directory is used,
466 or tip if no revision is checked out.
466 or tip if no revision is checked out.
467
467
468 Output may be to a file, in which case the name of the file is
468 Output may be to a file, in which case the name of the file is
469 given using a format string. The formatting rules are the same as
469 given using a format string. The formatting rules are the same as
470 for the export command, with the following additions:
470 for the export command, with the following additions:
471
471
472 %s basename of file being printed
472 %s basename of file being printed
473 %d dirname of file being printed, or '.' if in repo root
473 %d dirname of file being printed, or '.' if in repo root
474 %p root-relative path name of file being printed
474 %p root-relative path name of file being printed
475 """
475 """
476 ctx = repo.changectx(opts['rev'])
476 ctx = repo.changectx(opts['rev'])
477 err = 1
477 err = 1
478 for src, abs, rel, exact in cmdutil.walk(repo, (file1,) + pats, opts,
478 for src, abs, rel, exact in cmdutil.walk(repo, (file1,) + pats, opts,
479 ctx.node()):
479 ctx.node()):
480 fp = cmdutil.make_file(repo, opts['output'], ctx.node(), pathname=abs)
480 fp = cmdutil.make_file(repo, opts['output'], ctx.node(), pathname=abs)
481 data = ctx.filectx(abs).data()
481 data = ctx.filectx(abs).data()
482 if opts.get('decode'):
482 if opts.get('decode'):
483 data = repo.wwritedata(abs, data)
483 data = repo.wwritedata(abs, data)
484 fp.write(data)
484 fp.write(data)
485 err = 0
485 err = 0
486 return err
486 return err
487
487
488 def clone(ui, source, dest=None, **opts):
488 def clone(ui, source, dest=None, **opts):
489 """make a copy of an existing repository
489 """make a copy of an existing repository
490
490
491 Create a copy of an existing repository in a new directory.
491 Create a copy of an existing repository in a new directory.
492
492
493 If no destination directory name is specified, it defaults to the
493 If no destination directory name is specified, it defaults to the
494 basename of the source.
494 basename of the source.
495
495
496 The location of the source is added to the new repository's
496 The location of the source is added to the new repository's
497 .hg/hgrc file, as the default to be used for future pulls.
497 .hg/hgrc file, as the default to be used for future pulls.
498
498
499 For efficiency, hardlinks are used for cloning whenever the source
499 For efficiency, hardlinks are used for cloning whenever the source
500 and destination are on the same filesystem (note this applies only
500 and destination are on the same filesystem (note this applies only
501 to the repository data, not to the checked out files). Some
501 to the repository data, not to the checked out files). Some
502 filesystems, such as AFS, implement hardlinking incorrectly, but
502 filesystems, such as AFS, implement hardlinking incorrectly, but
503 do not report errors. In these cases, use the --pull option to
503 do not report errors. In these cases, use the --pull option to
504 avoid hardlinking.
504 avoid hardlinking.
505
505
506 You can safely clone repositories and checked out files using full
506 You can safely clone repositories and checked out files using full
507 hardlinks with
507 hardlinks with
508
508
509 $ cp -al REPO REPOCLONE
509 $ cp -al REPO REPOCLONE
510
510
511 which is the fastest way to clone. However, the operation is not
511 which is the fastest way to clone. However, the operation is not
512 atomic (making sure REPO is not modified during the operation is
512 atomic (making sure REPO is not modified during the operation is
513 up to you) and you have to make sure your editor breaks hardlinks
513 up to you) and you have to make sure your editor breaks hardlinks
514 (Emacs and most Linux Kernel tools do so).
514 (Emacs and most Linux Kernel tools do so).
515
515
516 If you use the -r option to clone up to a specific revision, no
516 If you use the -r option to clone up to a specific revision, no
517 subsequent revisions will be present in the cloned repository.
517 subsequent revisions will be present in the cloned repository.
518 This option implies --pull, even on local repositories.
518 This option implies --pull, even on local repositories.
519
519
520 See pull for valid source format details.
520 See pull for valid source format details.
521
521
522 It is possible to specify an ssh:// URL as the destination, but no
522 It is possible to specify an ssh:// URL as the destination, but no
523 .hg/hgrc and working directory will be created on the remote side.
523 .hg/hgrc and working directory will be created on the remote side.
524 Look at the help text for the pull command for important details
524 Look at the help text for the pull command for important details
525 about ssh:// URLs.
525 about ssh:// URLs.
526 """
526 """
527 cmdutil.setremoteconfig(ui, opts)
527 cmdutil.setremoteconfig(ui, opts)
528 hg.clone(ui, source, dest,
528 hg.clone(ui, source, dest,
529 pull=opts['pull'],
529 pull=opts['pull'],
530 stream=opts['uncompressed'],
530 stream=opts['uncompressed'],
531 rev=opts['rev'],
531 rev=opts['rev'],
532 update=not opts['noupdate'])
532 update=not opts['noupdate'])
533
533
534 def commit(ui, repo, *pats, **opts):
534 def commit(ui, repo, *pats, **opts):
535 """commit the specified files or all outstanding changes
535 """commit the specified files or all outstanding changes
536
536
537 Commit changes to the given files into the repository.
537 Commit changes to the given files into the repository.
538
538
539 If a list of files is omitted, all changes reported by "hg status"
539 If a list of files is omitted, all changes reported by "hg status"
540 will be committed.
540 will be committed.
541
541
542 If no commit message is specified, the configured editor is started to
542 If no commit message is specified, the configured editor is started to
543 enter a message.
543 enter a message.
544
544
545 See 'hg help dates' for a list of formats valid for -d/--date.
545 See 'hg help dates' for a list of formats valid for -d/--date.
546 """
546 """
547 def commitfunc(ui, repo, files, message, match, opts):
547 def commitfunc(ui, repo, files, message, match, opts):
548 return repo.commit(files, message, opts['user'], opts['date'], match,
548 return repo.commit(files, message, opts['user'], opts['date'], match,
549 force_editor=opts.get('force_editor'))
549 force_editor=opts.get('force_editor'))
550 cmdutil.commit(ui, repo, commitfunc, pats, opts)
550 cmdutil.commit(ui, repo, commitfunc, pats, opts)
551
551
552 def copy(ui, repo, *pats, **opts):
552 def copy(ui, repo, *pats, **opts):
553 """mark files as copied for the next commit
553 """mark files as copied for the next commit
554
554
555 Mark dest as having copies of source files. If dest is a
555 Mark dest as having copies of source files. If dest is a
556 directory, copies are put in that directory. If dest is a file,
556 directory, copies are put in that directory. If dest is a file,
557 there can only be one source.
557 there can only be one source.
558
558
559 By default, this command copies the contents of files as they
559 By default, this command copies the contents of files as they
560 stand in the working directory. If invoked with --after, the
560 stand in the working directory. If invoked with --after, the
561 operation is recorded, but no copying is performed.
561 operation is recorded, but no copying is performed.
562
562
563 This command takes effect in the next commit. To undo a copy
563 This command takes effect in the next commit. To undo a copy
564 before that, see hg revert.
564 before that, see hg revert.
565 """
565 """
566 wlock = repo.wlock(False)
566 wlock = repo.wlock(False)
567 try:
567 try:
568 return cmdutil.copy(ui, repo, pats, opts)
568 return cmdutil.copy(ui, repo, pats, opts)
569 finally:
569 finally:
570 del wlock
570 del wlock
571
571
572 def debugancestor(ui, repo, *args):
572 def debugancestor(ui, repo, *args):
573 """find the ancestor revision of two revisions in a given index"""
573 """find the ancestor revision of two revisions in a given index"""
574 if len(args) == 3:
574 if len(args) == 3:
575 index, rev1, rev2 = args
575 index, rev1, rev2 = args
576 r = revlog.revlog(util.opener(os.getcwd(), audit=False), index)
576 r = revlog.revlog(util.opener(os.getcwd(), audit=False), index)
577 elif len(args) == 2:
577 elif len(args) == 2:
578 if not repo:
578 if not repo:
579 raise util.Abort(_("There is no Mercurial repository here "
579 raise util.Abort(_("There is no Mercurial repository here "
580 "(.hg not found)"))
580 "(.hg not found)"))
581 rev1, rev2 = args
581 rev1, rev2 = args
582 r = repo.changelog
582 r = repo.changelog
583 else:
583 else:
584 raise util.Abort(_('either two or three arguments required'))
584 raise util.Abort(_('either two or three arguments required'))
585 a = r.ancestor(r.lookup(rev1), r.lookup(rev2))
585 a = r.ancestor(r.lookup(rev1), r.lookup(rev2))
586 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
586 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
587
587
588 def debugcomplete(ui, cmd='', **opts):
588 def debugcomplete(ui, cmd='', **opts):
589 """returns the completion list associated with the given command"""
589 """returns the completion list associated with the given command"""
590
590
591 if opts['options']:
591 if opts['options']:
592 options = []
592 options = []
593 otables = [globalopts]
593 otables = [globalopts]
594 if cmd:
594 if cmd:
595 aliases, entry = cmdutil.findcmd(ui, cmd, table)
595 aliases, entry = cmdutil.findcmd(ui, cmd, table)
596 otables.append(entry[1])
596 otables.append(entry[1])
597 for t in otables:
597 for t in otables:
598 for o in t:
598 for o in t:
599 if o[0]:
599 if o[0]:
600 options.append('-%s' % o[0])
600 options.append('-%s' % o[0])
601 options.append('--%s' % o[1])
601 options.append('--%s' % o[1])
602 ui.write("%s\n" % "\n".join(options))
602 ui.write("%s\n" % "\n".join(options))
603 return
603 return
604
604
605 clist = cmdutil.findpossible(ui, cmd, table).keys()
605 clist = cmdutil.findpossible(ui, cmd, table).keys()
606 clist.sort()
606 clist.sort()
607 ui.write("%s\n" % "\n".join(clist))
607 ui.write("%s\n" % "\n".join(clist))
608
608
609 def debugfsinfo(ui, path = "."):
609 def debugfsinfo(ui, path = "."):
610 file('.debugfsinfo', 'w').write('')
610 file('.debugfsinfo', 'w').write('')
611 ui.write('exec: %s\n' % (util.checkexec(path) and 'yes' or 'no'))
611 ui.write('exec: %s\n' % (util.checkexec(path) and 'yes' or 'no'))
612 ui.write('symlink: %s\n' % (util.checklink(path) and 'yes' or 'no'))
612 ui.write('symlink: %s\n' % (util.checklink(path) and 'yes' or 'no'))
613 ui.write('case-sensitive: %s\n' % (util.checkfolding('.debugfsinfo')
613 ui.write('case-sensitive: %s\n' % (util.checkfolding('.debugfsinfo')
614 and 'yes' or 'no'))
614 and 'yes' or 'no'))
615 os.unlink('.debugfsinfo')
615 os.unlink('.debugfsinfo')
616
616
617 def debugrebuildstate(ui, repo, rev=""):
617 def debugrebuildstate(ui, repo, rev=""):
618 """rebuild the dirstate as it would look like for the given revision"""
618 """rebuild the dirstate as it would look like for the given revision"""
619 if rev == "":
619 if rev == "":
620 rev = repo.changelog.tip()
620 rev = repo.changelog.tip()
621 ctx = repo.changectx(rev)
621 ctx = repo.changectx(rev)
622 files = ctx.manifest()
622 files = ctx.manifest()
623 wlock = repo.wlock()
623 wlock = repo.wlock()
624 try:
624 try:
625 repo.dirstate.rebuild(rev, files)
625 repo.dirstate.rebuild(rev, files)
626 finally:
626 finally:
627 del wlock
627 del wlock
628
628
629 def debugcheckstate(ui, repo):
629 def debugcheckstate(ui, repo):
630 """validate the correctness of the current dirstate"""
630 """validate the correctness of the current dirstate"""
631 parent1, parent2 = repo.dirstate.parents()
631 parent1, parent2 = repo.dirstate.parents()
632 m1 = repo.changectx(parent1).manifest()
632 m1 = repo.changectx(parent1).manifest()
633 m2 = repo.changectx(parent2).manifest()
633 m2 = repo.changectx(parent2).manifest()
634 errors = 0
634 errors = 0
635 for f in repo.dirstate:
635 for f in repo.dirstate:
636 state = repo.dirstate[f]
636 state = repo.dirstate[f]
637 if state in "nr" and f not in m1:
637 if state in "nr" and f not in m1:
638 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
638 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
639 errors += 1
639 errors += 1
640 if state in "a" and f in m1:
640 if state in "a" and f in m1:
641 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
641 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
642 errors += 1
642 errors += 1
643 if state in "m" and f not in m1 and f not in m2:
643 if state in "m" and f not in m1 and f not in m2:
644 ui.warn(_("%s in state %s, but not in either manifest\n") %
644 ui.warn(_("%s in state %s, but not in either manifest\n") %
645 (f, state))
645 (f, state))
646 errors += 1
646 errors += 1
647 for f in m1:
647 for f in m1:
648 state = repo.dirstate[f]
648 state = repo.dirstate[f]
649 if state not in "nrm":
649 if state not in "nrm":
650 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
650 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
651 errors += 1
651 errors += 1
652 if errors:
652 if errors:
653 error = _(".hg/dirstate inconsistent with current parent's manifest")
653 error = _(".hg/dirstate inconsistent with current parent's manifest")
654 raise util.Abort(error)
654 raise util.Abort(error)
655
655
656 def showconfig(ui, repo, *values, **opts):
656 def showconfig(ui, repo, *values, **opts):
657 """show combined config settings from all hgrc files
657 """show combined config settings from all hgrc files
658
658
659 With no args, print names and values of all config items.
659 With no args, print names and values of all config items.
660
660
661 With one arg of the form section.name, print just the value of
661 With one arg of the form section.name, print just the value of
662 that config item.
662 that config item.
663
663
664 With multiple args, print names and values of all config items
664 With multiple args, print names and values of all config items
665 with matching section names."""
665 with matching section names."""
666
666
667 untrusted = bool(opts.get('untrusted'))
667 untrusted = bool(opts.get('untrusted'))
668 if values:
668 if values:
669 if len([v for v in values if '.' in v]) > 1:
669 if len([v for v in values if '.' in v]) > 1:
670 raise util.Abort(_('only one config item permitted'))
670 raise util.Abort(_('only one config item permitted'))
671 for section, name, value in ui.walkconfig(untrusted=untrusted):
671 for section, name, value in ui.walkconfig(untrusted=untrusted):
672 sectname = section + '.' + name
672 sectname = section + '.' + name
673 if values:
673 if values:
674 for v in values:
674 for v in values:
675 if v == section:
675 if v == section:
676 ui.write('%s=%s\n' % (sectname, value))
676 ui.write('%s=%s\n' % (sectname, value))
677 elif v == sectname:
677 elif v == sectname:
678 ui.write(value, '\n')
678 ui.write(value, '\n')
679 else:
679 else:
680 ui.write('%s=%s\n' % (sectname, value))
680 ui.write('%s=%s\n' % (sectname, value))
681
681
682 def debugsetparents(ui, repo, rev1, rev2=None):
682 def debugsetparents(ui, repo, rev1, rev2=None):
683 """manually set the parents of the current working directory
683 """manually set the parents of the current working directory
684
684
685 This is useful for writing repository conversion tools, but should
685 This is useful for writing repository conversion tools, but should
686 be used with care.
686 be used with care.
687 """
687 """
688
688
689 if not rev2:
689 if not rev2:
690 rev2 = hex(nullid)
690 rev2 = hex(nullid)
691
691
692 wlock = repo.wlock()
692 wlock = repo.wlock()
693 try:
693 try:
694 repo.dirstate.setparents(repo.lookup(rev1), repo.lookup(rev2))
694 repo.dirstate.setparents(repo.lookup(rev1), repo.lookup(rev2))
695 finally:
695 finally:
696 del wlock
696 del wlock
697
697
698 def debugstate(ui, repo):
698 def debugstate(ui, repo):
699 """show the contents of the current dirstate"""
699 """show the contents of the current dirstate"""
700 k = repo.dirstate._map.items()
700 k = repo.dirstate._map.items()
701 k.sort()
701 k.sort()
702 for file_, ent in k:
702 for file_, ent in k:
703 if ent[3] == -1:
703 if ent[3] == -1:
704 # Pad or slice to locale representation
704 # Pad or slice to locale representation
705 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(0)))
705 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(0)))
706 timestr = 'unset'
706 timestr = 'unset'
707 timestr = timestr[:locale_len] + ' '*(locale_len - len(timestr))
707 timestr = timestr[:locale_len] + ' '*(locale_len - len(timestr))
708 else:
708 else:
709 timestr = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(ent[3]))
709 timestr = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(ent[3]))
710 if ent[1] & 020000:
710 if ent[1] & 020000:
711 mode = 'lnk'
711 mode = 'lnk'
712 else:
712 else:
713 mode = '%3o' % (ent[1] & 0777)
713 mode = '%3o' % (ent[1] & 0777)
714 ui.write("%c %s %10d %s %s\n" % (ent[0], mode, ent[2], timestr, file_))
714 ui.write("%c %s %10d %s %s\n" % (ent[0], mode, ent[2], timestr, file_))
715 for f in repo.dirstate.copies():
715 for f in repo.dirstate.copies():
716 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
716 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
717
717
718 def debugdata(ui, file_, rev):
718 def debugdata(ui, file_, rev):
719 """dump the contents of a data file revision"""
719 """dump the contents of a data file revision"""
720 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_[:-2] + ".i")
720 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_[:-2] + ".i")
721 try:
721 try:
722 ui.write(r.revision(r.lookup(rev)))
722 ui.write(r.revision(r.lookup(rev)))
723 except KeyError:
723 except KeyError:
724 raise util.Abort(_('invalid revision identifier %s') % rev)
724 raise util.Abort(_('invalid revision identifier %s') % rev)
725
725
726 def debugdate(ui, date, range=None, **opts):
726 def debugdate(ui, date, range=None, **opts):
727 """parse and display a date"""
727 """parse and display a date"""
728 if opts["extended"]:
728 if opts["extended"]:
729 d = util.parsedate(date, util.extendeddateformats)
729 d = util.parsedate(date, util.extendeddateformats)
730 else:
730 else:
731 d = util.parsedate(date)
731 d = util.parsedate(date)
732 ui.write("internal: %s %s\n" % d)
732 ui.write("internal: %s %s\n" % d)
733 ui.write("standard: %s\n" % util.datestr(d))
733 ui.write("standard: %s\n" % util.datestr(d))
734 if range:
734 if range:
735 m = util.matchdate(range)
735 m = util.matchdate(range)
736 ui.write("match: %s\n" % m(d[0]))
736 ui.write("match: %s\n" % m(d[0]))
737
737
738 def debugindex(ui, file_):
738 def debugindex(ui, file_):
739 """dump the contents of an index file"""
739 """dump the contents of an index file"""
740 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_)
740 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_)
741 ui.write(" rev offset length base linkrev" +
741 ui.write(" rev offset length base linkrev" +
742 " nodeid p1 p2\n")
742 " nodeid p1 p2\n")
743 for i in xrange(r.count()):
743 for i in xrange(r.count()):
744 node = r.node(i)
744 node = r.node(i)
745 try:
745 try:
746 pp = r.parents(node)
746 pp = r.parents(node)
747 except:
747 except:
748 pp = [nullid, nullid]
748 pp = [nullid, nullid]
749 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
749 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
750 i, r.start(i), r.length(i), r.base(i), r.linkrev(node),
750 i, r.start(i), r.length(i), r.base(i), r.linkrev(node),
751 short(node), short(pp[0]), short(pp[1])))
751 short(node), short(pp[0]), short(pp[1])))
752
752
753 def debugindexdot(ui, file_):
753 def debugindexdot(ui, file_):
754 """dump an index DAG as a .dot file"""
754 """dump an index DAG as a .dot file"""
755 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_)
755 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_)
756 ui.write("digraph G {\n")
756 ui.write("digraph G {\n")
757 for i in xrange(r.count()):
757 for i in xrange(r.count()):
758 node = r.node(i)
758 node = r.node(i)
759 pp = r.parents(node)
759 pp = r.parents(node)
760 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
760 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
761 if pp[1] != nullid:
761 if pp[1] != nullid:
762 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
762 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
763 ui.write("}\n")
763 ui.write("}\n")
764
764
765 def debuginstall(ui):
765 def debuginstall(ui):
766 '''test Mercurial installation'''
766 '''test Mercurial installation'''
767
767
768 def writetemp(contents):
768 def writetemp(contents):
769 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
769 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
770 f = os.fdopen(fd, "wb")
770 f = os.fdopen(fd, "wb")
771 f.write(contents)
771 f.write(contents)
772 f.close()
772 f.close()
773 return name
773 return name
774
774
775 problems = 0
775 problems = 0
776
776
777 # encoding
777 # encoding
778 ui.status(_("Checking encoding (%s)...\n") % util._encoding)
778 ui.status(_("Checking encoding (%s)...\n") % util._encoding)
779 try:
779 try:
780 util.fromlocal("test")
780 util.fromlocal("test")
781 except util.Abort, inst:
781 except util.Abort, inst:
782 ui.write(" %s\n" % inst)
782 ui.write(" %s\n" % inst)
783 ui.write(_(" (check that your locale is properly set)\n"))
783 ui.write(_(" (check that your locale is properly set)\n"))
784 problems += 1
784 problems += 1
785
785
786 # compiled modules
786 # compiled modules
787 ui.status(_("Checking extensions...\n"))
787 ui.status(_("Checking extensions...\n"))
788 try:
788 try:
789 import bdiff, mpatch, base85
789 import bdiff, mpatch, base85
790 except Exception, inst:
790 except Exception, inst:
791 ui.write(" %s\n" % inst)
791 ui.write(" %s\n" % inst)
792 ui.write(_(" One or more extensions could not be found"))
792 ui.write(_(" One or more extensions could not be found"))
793 ui.write(_(" (check that you compiled the extensions)\n"))
793 ui.write(_(" (check that you compiled the extensions)\n"))
794 problems += 1
794 problems += 1
795
795
796 # templates
796 # templates
797 ui.status(_("Checking templates...\n"))
797 ui.status(_("Checking templates...\n"))
798 try:
798 try:
799 import templater
799 import templater
800 t = templater.templater(templater.templatepath("map-cmdline.default"))
800 t = templater.templater(templater.templatepath("map-cmdline.default"))
801 except Exception, inst:
801 except Exception, inst:
802 ui.write(" %s\n" % inst)
802 ui.write(" %s\n" % inst)
803 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
803 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
804 problems += 1
804 problems += 1
805
805
806 # patch
806 # patch
807 ui.status(_("Checking patch...\n"))
807 ui.status(_("Checking patch...\n"))
808 patchproblems = 0
808 patchproblems = 0
809 a = "1\n2\n3\n4\n"
809 a = "1\n2\n3\n4\n"
810 b = "1\n2\n3\ninsert\n4\n"
810 b = "1\n2\n3\ninsert\n4\n"
811 fa = writetemp(a)
811 fa = writetemp(a)
812 d = mdiff.unidiff(a, None, b, None, os.path.basename(fa),
812 d = mdiff.unidiff(a, None, b, None, os.path.basename(fa),
813 os.path.basename(fa))
813 os.path.basename(fa))
814 fd = writetemp(d)
814 fd = writetemp(d)
815
815
816 files = {}
816 files = {}
817 try:
817 try:
818 patch.patch(fd, ui, cwd=os.path.dirname(fa), files=files)
818 patch.patch(fd, ui, cwd=os.path.dirname(fa), files=files)
819 except util.Abort, e:
819 except util.Abort, e:
820 ui.write(_(" patch call failed:\n"))
820 ui.write(_(" patch call failed:\n"))
821 ui.write(" " + str(e) + "\n")
821 ui.write(" " + str(e) + "\n")
822 patchproblems += 1
822 patchproblems += 1
823 else:
823 else:
824 if list(files) != [os.path.basename(fa)]:
824 if list(files) != [os.path.basename(fa)]:
825 ui.write(_(" unexpected patch output!\n"))
825 ui.write(_(" unexpected patch output!\n"))
826 patchproblems += 1
826 patchproblems += 1
827 a = file(fa).read()
827 a = file(fa).read()
828 if a != b:
828 if a != b:
829 ui.write(_(" patch test failed!\n"))
829 ui.write(_(" patch test failed!\n"))
830 patchproblems += 1
830 patchproblems += 1
831
831
832 if patchproblems:
832 if patchproblems:
833 if ui.config('ui', 'patch'):
833 if ui.config('ui', 'patch'):
834 ui.write(_(" (Current patch tool may be incompatible with patch,"
834 ui.write(_(" (Current patch tool may be incompatible with patch,"
835 " or misconfigured. Please check your .hgrc file)\n"))
835 " or misconfigured. Please check your .hgrc file)\n"))
836 else:
836 else:
837 ui.write(_(" Internal patcher failure, please report this error"
837 ui.write(_(" Internal patcher failure, please report this error"
838 " to http://www.selenic.com/mercurial/bts\n"))
838 " to http://www.selenic.com/mercurial/bts\n"))
839 problems += patchproblems
839 problems += patchproblems
840
840
841 os.unlink(fa)
841 os.unlink(fa)
842 os.unlink(fd)
842 os.unlink(fd)
843
843
844 # editor
844 # editor
845 ui.status(_("Checking commit editor...\n"))
845 ui.status(_("Checking commit editor...\n"))
846 editor = ui.geteditor()
846 editor = ui.geteditor()
847 cmdpath = util.find_exe(editor) or util.find_exe(editor.split()[0])
847 cmdpath = util.find_exe(editor) or util.find_exe(editor.split()[0])
848 if not cmdpath:
848 if not cmdpath:
849 if editor == 'vi':
849 if editor == 'vi':
850 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
850 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
851 ui.write(_(" (specify a commit editor in your .hgrc file)\n"))
851 ui.write(_(" (specify a commit editor in your .hgrc file)\n"))
852 else:
852 else:
853 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
853 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
854 ui.write(_(" (specify a commit editor in your .hgrc file)\n"))
854 ui.write(_(" (specify a commit editor in your .hgrc file)\n"))
855 problems += 1
855 problems += 1
856
856
857 # check username
857 # check username
858 ui.status(_("Checking username...\n"))
858 ui.status(_("Checking username...\n"))
859 user = os.environ.get("HGUSER")
859 user = os.environ.get("HGUSER")
860 if user is None:
860 if user is None:
861 user = ui.config("ui", "username")
861 user = ui.config("ui", "username")
862 if user is None:
862 if user is None:
863 user = os.environ.get("EMAIL")
863 user = os.environ.get("EMAIL")
864 if not user:
864 if not user:
865 ui.warn(" ")
865 ui.warn(" ")
866 ui.username()
866 ui.username()
867 ui.write(_(" (specify a username in your .hgrc file)\n"))
867 ui.write(_(" (specify a username in your .hgrc file)\n"))
868
868
869 if not problems:
869 if not problems:
870 ui.status(_("No problems detected\n"))
870 ui.status(_("No problems detected\n"))
871 else:
871 else:
872 ui.write(_("%s problems detected,"
872 ui.write(_("%s problems detected,"
873 " please check your install!\n") % problems)
873 " please check your install!\n") % problems)
874
874
875 return problems
875 return problems
876
876
877 def debugrename(ui, repo, file1, *pats, **opts):
877 def debugrename(ui, repo, file1, *pats, **opts):
878 """dump rename information"""
878 """dump rename information"""
879
879
880 ctx = repo.changectx(opts.get('rev', 'tip'))
880 ctx = repo.changectx(opts.get('rev', 'tip'))
881 for src, abs, rel, exact in cmdutil.walk(repo, (file1,) + pats, opts,
881 for src, abs, rel, exact in cmdutil.walk(repo, (file1,) + pats, opts,
882 ctx.node()):
882 ctx.node()):
883 fctx = ctx.filectx(abs)
883 fctx = ctx.filectx(abs)
884 m = fctx.filelog().renamed(fctx.filenode())
884 m = fctx.filelog().renamed(fctx.filenode())
885 if m:
885 if m:
886 ui.write(_("%s renamed from %s:%s\n") % (rel, m[0], hex(m[1])))
886 ui.write(_("%s renamed from %s:%s\n") % (rel, m[0], hex(m[1])))
887 else:
887 else:
888 ui.write(_("%s not renamed\n") % rel)
888 ui.write(_("%s not renamed\n") % rel)
889
889
890 def debugwalk(ui, repo, *pats, **opts):
890 def debugwalk(ui, repo, *pats, **opts):
891 """show how files match on given patterns"""
891 """show how files match on given patterns"""
892 items = list(cmdutil.walk(repo, pats, opts))
892 items = list(cmdutil.walk(repo, pats, opts))
893 if not items:
893 if not items:
894 return
894 return
895 fmt = '%%s %%-%ds %%-%ds %%s' % (
895 fmt = '%%s %%-%ds %%-%ds %%s' % (
896 max([len(abs) for (src, abs, rel, exact) in items]),
896 max([len(abs) for (src, abs, rel, exact) in items]),
897 max([len(rel) for (src, abs, rel, exact) in items]))
897 max([len(rel) for (src, abs, rel, exact) in items]))
898 for src, abs, rel, exact in items:
898 for src, abs, rel, exact in items:
899 line = fmt % (src, abs, rel, exact and 'exact' or '')
899 line = fmt % (src, abs, rel, exact and 'exact' or '')
900 ui.write("%s\n" % line.rstrip())
900 ui.write("%s\n" % line.rstrip())
901
901
902 def diff(ui, repo, *pats, **opts):
902 def diff(ui, repo, *pats, **opts):
903 """diff repository (or selected files)
903 """diff repository (or selected files)
904
904
905 Show differences between revisions for the specified files.
905 Show differences between revisions for the specified files.
906
906
907 Differences between files are shown using the unified diff format.
907 Differences between files are shown using the unified diff format.
908
908
909 NOTE: diff may generate unexpected results for merges, as it will
909 NOTE: diff may generate unexpected results for merges, as it will
910 default to comparing against the working directory's first parent
910 default to comparing against the working directory's first parent
911 changeset if no revisions are specified.
911 changeset if no revisions are specified.
912
912
913 When two revision arguments are given, then changes are shown
913 When two revision arguments are given, then changes are shown
914 between those revisions. If only one revision is specified then
914 between those revisions. If only one revision is specified then
915 that revision is compared to the working directory, and, when no
915 that revision is compared to the working directory, and, when no
916 revisions are specified, the working directory files are compared
916 revisions are specified, the working directory files are compared
917 to its parent.
917 to its parent.
918
918
919 Without the -a option, diff will avoid generating diffs of files
919 Without the -a option, diff will avoid generating diffs of files
920 it detects as binary. With -a, diff will generate a diff anyway,
920 it detects as binary. With -a, diff will generate a diff anyway,
921 probably with undesirable results.
921 probably with undesirable results.
922 """
922 """
923 node1, node2 = cmdutil.revpair(repo, opts['rev'])
923 node1, node2 = cmdutil.revpair(repo, opts['rev'])
924
924
925 fns, matchfn, anypats = cmdutil.matchpats(repo, pats, opts)
925 fns, matchfn, anypats = cmdutil.matchpats(repo, pats, opts)
926
926
927 patch.diff(repo, node1, node2, fns, match=matchfn,
927 patch.diff(repo, node1, node2, fns, match=matchfn,
928 opts=patch.diffopts(ui, opts))
928 opts=patch.diffopts(ui, opts))
929
929
930 def export(ui, repo, *changesets, **opts):
930 def export(ui, repo, *changesets, **opts):
931 """dump the header and diffs for one or more changesets
931 """dump the header and diffs for one or more changesets
932
932
933 Print the changeset header and diffs for one or more revisions.
933 Print the changeset header and diffs for one or more revisions.
934
934
935 The information shown in the changeset header is: author,
935 The information shown in the changeset header is: author,
936 changeset hash, parent(s) and commit comment.
936 changeset hash, parent(s) and commit comment.
937
937
938 NOTE: export may generate unexpected diff output for merge changesets,
938 NOTE: export may generate unexpected diff output for merge changesets,
939 as it will compare the merge changeset against its first parent only.
939 as it will compare the merge changeset against its first parent only.
940
940
941 Output may be to a file, in which case the name of the file is
941 Output may be to a file, in which case the name of the file is
942 given using a format string. The formatting rules are as follows:
942 given using a format string. The formatting rules are as follows:
943
943
944 %% literal "%" character
944 %% literal "%" character
945 %H changeset hash (40 bytes of hexadecimal)
945 %H changeset hash (40 bytes of hexadecimal)
946 %N number of patches being generated
946 %N number of patches being generated
947 %R changeset revision number
947 %R changeset revision number
948 %b basename of the exporting repository
948 %b basename of the exporting repository
949 %h short-form changeset hash (12 bytes of hexadecimal)
949 %h short-form changeset hash (12 bytes of hexadecimal)
950 %n zero-padded sequence number, starting at 1
950 %n zero-padded sequence number, starting at 1
951 %r zero-padded changeset revision number
951 %r zero-padded changeset revision number
952
952
953 Without the -a option, export will avoid generating diffs of files
953 Without the -a option, export will avoid generating diffs of files
954 it detects as binary. With -a, export will generate a diff anyway,
954 it detects as binary. With -a, export will generate a diff anyway,
955 probably with undesirable results.
955 probably with undesirable results.
956
956
957 With the --switch-parent option, the diff will be against the second
957 With the --switch-parent option, the diff will be against the second
958 parent. It can be useful to review a merge.
958 parent. It can be useful to review a merge.
959 """
959 """
960 if not changesets:
960 if not changesets:
961 raise util.Abort(_("export requires at least one changeset"))
961 raise util.Abort(_("export requires at least one changeset"))
962 revs = cmdutil.revrange(repo, changesets)
962 revs = cmdutil.revrange(repo, changesets)
963 if len(revs) > 1:
963 if len(revs) > 1:
964 ui.note(_('exporting patches:\n'))
964 ui.note(_('exporting patches:\n'))
965 else:
965 else:
966 ui.note(_('exporting patch:\n'))
966 ui.note(_('exporting patch:\n'))
967 patch.export(repo, revs, template=opts['output'],
967 patch.export(repo, revs, template=opts['output'],
968 switch_parent=opts['switch_parent'],
968 switch_parent=opts['switch_parent'],
969 opts=patch.diffopts(ui, opts))
969 opts=patch.diffopts(ui, opts))
970
970
971 def grep(ui, repo, pattern, *pats, **opts):
971 def grep(ui, repo, pattern, *pats, **opts):
972 """search for a pattern in specified files and revisions
972 """search for a pattern in specified files and revisions
973
973
974 Search revisions of files for a regular expression.
974 Search revisions of files for a regular expression.
975
975
976 This command behaves differently than Unix grep. It only accepts
976 This command behaves differently than Unix grep. It only accepts
977 Python/Perl regexps. It searches repository history, not the
977 Python/Perl regexps. It searches repository history, not the
978 working directory. It always prints the revision number in which
978 working directory. It always prints the revision number in which
979 a match appears.
979 a match appears.
980
980
981 By default, grep only prints output for the first revision of a
981 By default, grep only prints output for the first revision of a
982 file in which it finds a match. To get it to print every revision
982 file in which it finds a match. To get it to print every revision
983 that contains a change in match status ("-" for a match that
983 that contains a change in match status ("-" for a match that
984 becomes a non-match, or "+" for a non-match that becomes a match),
984 becomes a non-match, or "+" for a non-match that becomes a match),
985 use the --all flag.
985 use the --all flag.
986 """
986 """
987 reflags = 0
987 reflags = 0
988 if opts['ignore_case']:
988 if opts['ignore_case']:
989 reflags |= re.I
989 reflags |= re.I
990 try:
990 try:
991 regexp = re.compile(pattern, reflags)
991 regexp = re.compile(pattern, reflags)
992 except Exception, inst:
992 except Exception, inst:
993 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
993 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
994 return None
994 return None
995 sep, eol = ':', '\n'
995 sep, eol = ':', '\n'
996 if opts['print0']:
996 if opts['print0']:
997 sep = eol = '\0'
997 sep = eol = '\0'
998
998
999 fcache = {}
999 fcache = {}
1000 def getfile(fn):
1000 def getfile(fn):
1001 if fn not in fcache:
1001 if fn not in fcache:
1002 fcache[fn] = repo.file(fn)
1002 fcache[fn] = repo.file(fn)
1003 return fcache[fn]
1003 return fcache[fn]
1004
1004
1005 def matchlines(body):
1005 def matchlines(body):
1006 begin = 0
1006 begin = 0
1007 linenum = 0
1007 linenum = 0
1008 while True:
1008 while True:
1009 match = regexp.search(body, begin)
1009 match = regexp.search(body, begin)
1010 if not match:
1010 if not match:
1011 break
1011 break
1012 mstart, mend = match.span()
1012 mstart, mend = match.span()
1013 linenum += body.count('\n', begin, mstart) + 1
1013 linenum += body.count('\n', begin, mstart) + 1
1014 lstart = body.rfind('\n', begin, mstart) + 1 or begin
1014 lstart = body.rfind('\n', begin, mstart) + 1 or begin
1015 lend = body.find('\n', mend)
1015 lend = body.find('\n', mend)
1016 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
1016 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
1017 begin = lend + 1
1017 begin = lend + 1
1018
1018
1019 class linestate(object):
1019 class linestate(object):
1020 def __init__(self, line, linenum, colstart, colend):
1020 def __init__(self, line, linenum, colstart, colend):
1021 self.line = line
1021 self.line = line
1022 self.linenum = linenum
1022 self.linenum = linenum
1023 self.colstart = colstart
1023 self.colstart = colstart
1024 self.colend = colend
1024 self.colend = colend
1025
1025
1026 def __eq__(self, other):
1026 def __eq__(self, other):
1027 return self.line == other.line
1027 return self.line == other.line
1028
1028
1029 matches = {}
1029 matches = {}
1030 copies = {}
1030 copies = {}
1031 def grepbody(fn, rev, body):
1031 def grepbody(fn, rev, body):
1032 matches[rev].setdefault(fn, [])
1032 matches[rev].setdefault(fn, [])
1033 m = matches[rev][fn]
1033 m = matches[rev][fn]
1034 for lnum, cstart, cend, line in matchlines(body):
1034 for lnum, cstart, cend, line in matchlines(body):
1035 s = linestate(line, lnum, cstart, cend)
1035 s = linestate(line, lnum, cstart, cend)
1036 m.append(s)
1036 m.append(s)
1037
1037
1038 def difflinestates(a, b):
1038 def difflinestates(a, b):
1039 sm = difflib.SequenceMatcher(None, a, b)
1039 sm = difflib.SequenceMatcher(None, a, b)
1040 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
1040 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
1041 if tag == 'insert':
1041 if tag == 'insert':
1042 for i in xrange(blo, bhi):
1042 for i in xrange(blo, bhi):
1043 yield ('+', b[i])
1043 yield ('+', b[i])
1044 elif tag == 'delete':
1044 elif tag == 'delete':
1045 for i in xrange(alo, ahi):
1045 for i in xrange(alo, ahi):
1046 yield ('-', a[i])
1046 yield ('-', a[i])
1047 elif tag == 'replace':
1047 elif tag == 'replace':
1048 for i in xrange(alo, ahi):
1048 for i in xrange(alo, ahi):
1049 yield ('-', a[i])
1049 yield ('-', a[i])
1050 for i in xrange(blo, bhi):
1050 for i in xrange(blo, bhi):
1051 yield ('+', b[i])
1051 yield ('+', b[i])
1052
1052
1053 prev = {}
1053 prev = {}
1054 def display(fn, rev, states, prevstates):
1054 def display(fn, rev, states, prevstates):
1055 datefunc = ui.quiet and util.shortdate or util.datestr
1055 datefunc = ui.quiet and util.shortdate or util.datestr
1056 found = False
1056 found = False
1057 filerevmatches = {}
1057 filerevmatches = {}
1058 r = prev.get(fn, -1)
1058 r = prev.get(fn, -1)
1059 if opts['all']:
1059 if opts['all']:
1060 iter = difflinestates(states, prevstates)
1060 iter = difflinestates(states, prevstates)
1061 else:
1061 else:
1062 iter = [('', l) for l in prevstates]
1062 iter = [('', l) for l in prevstates]
1063 for change, l in iter:
1063 for change, l in iter:
1064 cols = [fn, str(r)]
1064 cols = [fn, str(r)]
1065 if opts['line_number']:
1065 if opts['line_number']:
1066 cols.append(str(l.linenum))
1066 cols.append(str(l.linenum))
1067 if opts['all']:
1067 if opts['all']:
1068 cols.append(change)
1068 cols.append(change)
1069 if opts['user']:
1069 if opts['user']:
1070 cols.append(ui.shortuser(get(r)[1]))
1070 cols.append(ui.shortuser(get(r)[1]))
1071 if opts.get('date'):
1071 if opts.get('date'):
1072 cols.append(datefunc(get(r)[2]))
1072 cols.append(datefunc(get(r)[2]))
1073 if opts['files_with_matches']:
1073 if opts['files_with_matches']:
1074 c = (fn, r)
1074 c = (fn, r)
1075 if c in filerevmatches:
1075 if c in filerevmatches:
1076 continue
1076 continue
1077 filerevmatches[c] = 1
1077 filerevmatches[c] = 1
1078 else:
1078 else:
1079 cols.append(l.line)
1079 cols.append(l.line)
1080 ui.write(sep.join(cols), eol)
1080 ui.write(sep.join(cols), eol)
1081 found = True
1081 found = True
1082 return found
1082 return found
1083
1083
1084 fstate = {}
1084 fstate = {}
1085 skip = {}
1085 skip = {}
1086 get = util.cachefunc(lambda r: repo.changectx(r).changeset())
1086 get = util.cachefunc(lambda r: repo.changectx(r).changeset())
1087 changeiter, matchfn = cmdutil.walkchangerevs(ui, repo, pats, get, opts)
1087 changeiter, matchfn = cmdutil.walkchangerevs(ui, repo, pats, get, opts)
1088 found = False
1088 found = False
1089 follow = opts.get('follow')
1089 follow = opts.get('follow')
1090 for st, rev, fns in changeiter:
1090 for st, rev, fns in changeiter:
1091 if st == 'window':
1091 if st == 'window':
1092 matches.clear()
1092 matches.clear()
1093 elif st == 'add':
1093 elif st == 'add':
1094 ctx = repo.changectx(rev)
1094 ctx = repo.changectx(rev)
1095 matches[rev] = {}
1095 matches[rev] = {}
1096 for fn in fns:
1096 for fn in fns:
1097 if fn in skip:
1097 if fn in skip:
1098 continue
1098 continue
1099 try:
1099 try:
1100 grepbody(fn, rev, getfile(fn).read(ctx.filenode(fn)))
1100 grepbody(fn, rev, getfile(fn).read(ctx.filenode(fn)))
1101 fstate.setdefault(fn, [])
1101 fstate.setdefault(fn, [])
1102 if follow:
1102 if follow:
1103 copied = getfile(fn).renamed(ctx.filenode(fn))
1103 copied = getfile(fn).renamed(ctx.filenode(fn))
1104 if copied:
1104 if copied:
1105 copies.setdefault(rev, {})[fn] = copied[0]
1105 copies.setdefault(rev, {})[fn] = copied[0]
1106 except revlog.LookupError:
1106 except revlog.LookupError:
1107 pass
1107 pass
1108 elif st == 'iter':
1108 elif st == 'iter':
1109 states = matches[rev].items()
1109 states = matches[rev].items()
1110 states.sort()
1110 states.sort()
1111 for fn, m in states:
1111 for fn, m in states:
1112 copy = copies.get(rev, {}).get(fn)
1112 copy = copies.get(rev, {}).get(fn)
1113 if fn in skip:
1113 if fn in skip:
1114 if copy:
1114 if copy:
1115 skip[copy] = True
1115 skip[copy] = True
1116 continue
1116 continue
1117 if fn in prev or fstate[fn]:
1117 if fn in prev or fstate[fn]:
1118 r = display(fn, rev, m, fstate[fn])
1118 r = display(fn, rev, m, fstate[fn])
1119 found = found or r
1119 found = found or r
1120 if r and not opts['all']:
1120 if r and not opts['all']:
1121 skip[fn] = True
1121 skip[fn] = True
1122 if copy:
1122 if copy:
1123 skip[copy] = True
1123 skip[copy] = True
1124 fstate[fn] = m
1124 fstate[fn] = m
1125 if copy:
1125 if copy:
1126 fstate[copy] = m
1126 fstate[copy] = m
1127 prev[fn] = rev
1127 prev[fn] = rev
1128
1128
1129 fstate = fstate.items()
1129 fstate = fstate.items()
1130 fstate.sort()
1130 fstate.sort()
1131 for fn, state in fstate:
1131 for fn, state in fstate:
1132 if fn in skip:
1132 if fn in skip:
1133 continue
1133 continue
1134 if fn not in copies.get(prev[fn], {}):
1134 if fn not in copies.get(prev[fn], {}):
1135 found = display(fn, rev, {}, state) or found
1135 found = display(fn, rev, {}, state) or found
1136 return (not found and 1) or 0
1136 return (not found and 1) or 0
1137
1137
1138 def heads(ui, repo, *branchrevs, **opts):
1138 def heads(ui, repo, *branchrevs, **opts):
1139 """show current repository heads or show branch heads
1139 """show current repository heads or show branch heads
1140
1140
1141 With no arguments, show all repository head changesets.
1141 With no arguments, show all repository head changesets.
1142
1142
1143 If branch or revisions names are given this will show the heads of
1143 If branch or revisions names are given this will show the heads of
1144 the specified branches or the branches those revisions are tagged
1144 the specified branches or the branches those revisions are tagged
1145 with.
1145 with.
1146
1146
1147 Repository "heads" are changesets that don't have child
1147 Repository "heads" are changesets that don't have child
1148 changesets. They are where development generally takes place and
1148 changesets. They are where development generally takes place and
1149 are the usual targets for update and merge operations.
1149 are the usual targets for update and merge operations.
1150
1150
1151 Branch heads are changesets that have a given branch tag, but have
1151 Branch heads are changesets that have a given branch tag, but have
1152 no child changesets with that tag. They are usually where
1152 no child changesets with that tag. They are usually where
1153 development on the given branch takes place.
1153 development on the given branch takes place.
1154 """
1154 """
1155 if opts['rev']:
1155 if opts['rev']:
1156 start = repo.lookup(opts['rev'])
1156 start = repo.lookup(opts['rev'])
1157 else:
1157 else:
1158 start = None
1158 start = None
1159 if not branchrevs:
1159 if not branchrevs:
1160 # Assume we're looking repo-wide heads if no revs were specified.
1160 # Assume we're looking repo-wide heads if no revs were specified.
1161 heads = repo.heads(start)
1161 heads = repo.heads(start)
1162 else:
1162 else:
1163 heads = []
1163 heads = []
1164 visitedset = util.set()
1164 visitedset = util.set()
1165 for branchrev in branchrevs:
1165 for branchrev in branchrevs:
1166 branch = repo.changectx(branchrev).branch()
1166 branch = repo.changectx(branchrev).branch()
1167 if branch in visitedset:
1167 if branch in visitedset:
1168 continue
1168 continue
1169 visitedset.add(branch)
1169 visitedset.add(branch)
1170 bheads = repo.branchheads(branch, start)
1170 bheads = repo.branchheads(branch, start)
1171 if not bheads:
1171 if not bheads:
1172 if branch != branchrev:
1172 if branch != branchrev:
1173 ui.warn(_("no changes on branch %s containing %s are "
1173 ui.warn(_("no changes on branch %s containing %s are "
1174 "reachable from %s\n")
1174 "reachable from %s\n")
1175 % (branch, branchrev, opts['rev']))
1175 % (branch, branchrev, opts['rev']))
1176 else:
1176 else:
1177 ui.warn(_("no changes on branch %s are reachable from %s\n")
1177 ui.warn(_("no changes on branch %s are reachable from %s\n")
1178 % (branch, opts['rev']))
1178 % (branch, opts['rev']))
1179 heads.extend(bheads)
1179 heads.extend(bheads)
1180 if not heads:
1180 if not heads:
1181 return 1
1181 return 1
1182 displayer = cmdutil.show_changeset(ui, repo, opts)
1182 displayer = cmdutil.show_changeset(ui, repo, opts)
1183 for n in heads:
1183 for n in heads:
1184 displayer.show(changenode=n)
1184 displayer.show(changenode=n)
1185
1185
1186 def help_(ui, name=None, with_version=False):
1186 def help_(ui, name=None, with_version=False):
1187 """show help for a command, extension, or list of commands
1187 """show help for a command, extension, or list of commands
1188
1188
1189 With no arguments, print a list of commands and short help.
1189 With no arguments, print a list of commands and short help.
1190
1190
1191 Given a command name, print help for that command.
1191 Given a command name, print help for that command.
1192
1192
1193 Given an extension name, print help for that extension, and the
1193 Given an extension name, print help for that extension, and the
1194 commands it provides."""
1194 commands it provides."""
1195 option_lists = []
1195 option_lists = []
1196
1196
1197 def addglobalopts(aliases):
1197 def addglobalopts(aliases):
1198 if ui.verbose:
1198 if ui.verbose:
1199 option_lists.append((_("global options:"), globalopts))
1199 option_lists.append((_("global options:"), globalopts))
1200 if name == 'shortlist':
1200 if name == 'shortlist':
1201 option_lists.append((_('use "hg help" for the full list '
1201 option_lists.append((_('use "hg help" for the full list '
1202 'of commands'), ()))
1202 'of commands'), ()))
1203 else:
1203 else:
1204 if name == 'shortlist':
1204 if name == 'shortlist':
1205 msg = _('use "hg help" for the full list of commands '
1205 msg = _('use "hg help" for the full list of commands '
1206 'or "hg -v" for details')
1206 'or "hg -v" for details')
1207 elif aliases:
1207 elif aliases:
1208 msg = _('use "hg -v help%s" to show aliases and '
1208 msg = _('use "hg -v help%s" to show aliases and '
1209 'global options') % (name and " " + name or "")
1209 'global options') % (name and " " + name or "")
1210 else:
1210 else:
1211 msg = _('use "hg -v help %s" to show global options') % name
1211 msg = _('use "hg -v help %s" to show global options') % name
1212 option_lists.append((msg, ()))
1212 option_lists.append((msg, ()))
1213
1213
1214 def helpcmd(name):
1214 def helpcmd(name):
1215 if with_version:
1215 if with_version:
1216 version_(ui)
1216 version_(ui)
1217 ui.write('\n')
1217 ui.write('\n')
1218 aliases, i = cmdutil.findcmd(ui, name, table)
1218 aliases, i = cmdutil.findcmd(ui, name, table)
1219 # synopsis
1219 # synopsis
1220 ui.write("%s\n" % i[2])
1220 ui.write("%s\n" % i[2])
1221
1221
1222 # aliases
1222 # aliases
1223 if not ui.quiet and len(aliases) > 1:
1223 if not ui.quiet and len(aliases) > 1:
1224 ui.write(_("\naliases: %s\n") % ', '.join(aliases[1:]))
1224 ui.write(_("\naliases: %s\n") % ', '.join(aliases[1:]))
1225
1225
1226 # description
1226 # description
1227 doc = i[0].__doc__
1227 doc = i[0].__doc__
1228 if not doc:
1228 if not doc:
1229 doc = _("(No help text available)")
1229 doc = _("(No help text available)")
1230 if ui.quiet:
1230 if ui.quiet:
1231 doc = doc.splitlines(0)[0]
1231 doc = doc.splitlines(0)[0]
1232 ui.write("\n%s\n" % doc.rstrip())
1232 ui.write("\n%s\n" % doc.rstrip())
1233
1233
1234 if not ui.quiet:
1234 if not ui.quiet:
1235 # options
1235 # options
1236 if i[1]:
1236 if i[1]:
1237 option_lists.append((_("options:\n"), i[1]))
1237 option_lists.append((_("options:\n"), i[1]))
1238
1238
1239 addglobalopts(False)
1239 addglobalopts(False)
1240
1240
1241 def helplist(header, select=None):
1241 def helplist(header, select=None):
1242 h = {}
1242 h = {}
1243 cmds = {}
1243 cmds = {}
1244 for c, e in table.items():
1244 for c, e in table.items():
1245 f = c.split("|", 1)[0]
1245 f = c.split("|", 1)[0]
1246 if select and not select(f):
1246 if select and not select(f):
1247 continue
1247 continue
1248 if name == "shortlist" and not f.startswith("^"):
1248 if name == "shortlist" and not f.startswith("^"):
1249 continue
1249 continue
1250 f = f.lstrip("^")
1250 f = f.lstrip("^")
1251 if not ui.debugflag and f.startswith("debug"):
1251 if not ui.debugflag and f.startswith("debug"):
1252 continue
1252 continue
1253 doc = e[0].__doc__
1253 doc = e[0].__doc__
1254 if not doc:
1254 if not doc:
1255 doc = _("(No help text available)")
1255 doc = _("(No help text available)")
1256 h[f] = doc.splitlines(0)[0].rstrip()
1256 h[f] = doc.splitlines(0)[0].rstrip()
1257 cmds[f] = c.lstrip("^")
1257 cmds[f] = c.lstrip("^")
1258
1258
1259 if not h:
1259 if not h:
1260 ui.status(_('no commands defined\n'))
1260 ui.status(_('no commands defined\n'))
1261 return
1261 return
1262
1262
1263 ui.status(header)
1263 ui.status(header)
1264 fns = h.keys()
1264 fns = h.keys()
1265 fns.sort()
1265 fns.sort()
1266 m = max(map(len, fns))
1266 m = max(map(len, fns))
1267 for f in fns:
1267 for f in fns:
1268 if ui.verbose:
1268 if ui.verbose:
1269 commands = cmds[f].replace("|",", ")
1269 commands = cmds[f].replace("|",", ")
1270 ui.write(" %s:\n %s\n"%(commands, h[f]))
1270 ui.write(" %s:\n %s\n"%(commands, h[f]))
1271 else:
1271 else:
1272 ui.write(' %-*s %s\n' % (m, f, h[f]))
1272 ui.write(' %-*s %s\n' % (m, f, h[f]))
1273
1273
1274 if not ui.quiet:
1274 if not ui.quiet:
1275 addglobalopts(True)
1275 addglobalopts(True)
1276
1276
1277 def helptopic(name):
1277 def helptopic(name):
1278 v = None
1278 v = None
1279 for i in help.helptable:
1279 for i in help.helptable:
1280 l = i.split('|')
1280 l = i.split('|')
1281 if name in l:
1281 if name in l:
1282 v = i
1282 v = i
1283 header = l[-1]
1283 header = l[-1]
1284 if not v:
1284 if not v:
1285 raise cmdutil.UnknownCommand(name)
1285 raise cmdutil.UnknownCommand(name)
1286
1286
1287 # description
1287 # description
1288 doc = help.helptable[v]
1288 doc = help.helptable[v]
1289 if not doc:
1289 if not doc:
1290 doc = _("(No help text available)")
1290 doc = _("(No help text available)")
1291 if callable(doc):
1291 if callable(doc):
1292 doc = doc()
1292 doc = doc()
1293
1293
1294 ui.write("%s\n" % header)
1294 ui.write("%s\n" % header)
1295 ui.write("%s\n" % doc.rstrip())
1295 ui.write("%s\n" % doc.rstrip())
1296
1296
1297 def helpext(name):
1297 def helpext(name):
1298 try:
1298 try:
1299 mod = extensions.find(name)
1299 mod = extensions.find(name)
1300 except KeyError:
1300 except KeyError:
1301 raise cmdutil.UnknownCommand(name)
1301 raise cmdutil.UnknownCommand(name)
1302
1302
1303 doc = (mod.__doc__ or _('No help text available')).splitlines(0)
1303 doc = (mod.__doc__ or _('No help text available')).splitlines(0)
1304 ui.write(_('%s extension - %s\n') % (name.split('.')[-1], doc[0]))
1304 ui.write(_('%s extension - %s\n') % (name.split('.')[-1], doc[0]))
1305 for d in doc[1:]:
1305 for d in doc[1:]:
1306 ui.write(d, '\n')
1306 ui.write(d, '\n')
1307
1307
1308 ui.status('\n')
1308 ui.status('\n')
1309
1309
1310 try:
1310 try:
1311 ct = mod.cmdtable
1311 ct = mod.cmdtable
1312 except AttributeError:
1312 except AttributeError:
1313 ct = {}
1313 ct = {}
1314
1314
1315 modcmds = dict.fromkeys([c.split('|', 1)[0] for c in ct])
1315 modcmds = dict.fromkeys([c.split('|', 1)[0] for c in ct])
1316 helplist(_('list of commands:\n\n'), modcmds.has_key)
1316 helplist(_('list of commands:\n\n'), modcmds.has_key)
1317
1317
1318 if name and name != 'shortlist':
1318 if name and name != 'shortlist':
1319 i = None
1319 i = None
1320 for f in (helpcmd, helptopic, helpext):
1320 for f in (helpcmd, helptopic, helpext):
1321 try:
1321 try:
1322 f(name)
1322 f(name)
1323 i = None
1323 i = None
1324 break
1324 break
1325 except cmdutil.UnknownCommand, inst:
1325 except cmdutil.UnknownCommand, inst:
1326 i = inst
1326 i = inst
1327 if i:
1327 if i:
1328 raise i
1328 raise i
1329
1329
1330 else:
1330 else:
1331 # program name
1331 # program name
1332 if ui.verbose or with_version:
1332 if ui.verbose or with_version:
1333 version_(ui)
1333 version_(ui)
1334 else:
1334 else:
1335 ui.status(_("Mercurial Distributed SCM\n"))
1335 ui.status(_("Mercurial Distributed SCM\n"))
1336 ui.status('\n')
1336 ui.status('\n')
1337
1337
1338 # list of commands
1338 # list of commands
1339 if name == "shortlist":
1339 if name == "shortlist":
1340 header = _('basic commands:\n\n')
1340 header = _('basic commands:\n\n')
1341 else:
1341 else:
1342 header = _('list of commands:\n\n')
1342 header = _('list of commands:\n\n')
1343
1343
1344 helplist(header)
1344 helplist(header)
1345
1345
1346 # list all option lists
1346 # list all option lists
1347 opt_output = []
1347 opt_output = []
1348 for title, options in option_lists:
1348 for title, options in option_lists:
1349 opt_output.append(("\n%s" % title, None))
1349 opt_output.append(("\n%s" % title, None))
1350 for shortopt, longopt, default, desc in options:
1350 for shortopt, longopt, default, desc in options:
1351 if "DEPRECATED" in desc and not ui.verbose: continue
1351 if "DEPRECATED" in desc and not ui.verbose: continue
1352 opt_output.append(("%2s%s" % (shortopt and "-%s" % shortopt,
1352 opt_output.append(("%2s%s" % (shortopt and "-%s" % shortopt,
1353 longopt and " --%s" % longopt),
1353 longopt and " --%s" % longopt),
1354 "%s%s" % (desc,
1354 "%s%s" % (desc,
1355 default
1355 default
1356 and _(" (default: %s)") % default
1356 and _(" (default: %s)") % default
1357 or "")))
1357 or "")))
1358
1358
1359 if opt_output:
1359 if opt_output:
1360 opts_len = max([len(line[0]) for line in opt_output if line[1]] or [0])
1360 opts_len = max([len(line[0]) for line in opt_output if line[1]] or [0])
1361 for first, second in opt_output:
1361 for first, second in opt_output:
1362 if second:
1362 if second:
1363 ui.write(" %-*s %s\n" % (opts_len, first, second))
1363 ui.write(" %-*s %s\n" % (opts_len, first, second))
1364 else:
1364 else:
1365 ui.write("%s\n" % first)
1365 ui.write("%s\n" % first)
1366
1366
1367 def identify(ui, repo, source=None,
1367 def identify(ui, repo, source=None,
1368 rev=None, num=None, id=None, branch=None, tags=None):
1368 rev=None, num=None, id=None, branch=None, tags=None):
1369 """identify the working copy or specified revision
1369 """identify the working copy or specified revision
1370
1370
1371 With no revision, print a summary of the current state of the repo.
1371 With no revision, print a summary of the current state of the repo.
1372
1372
1373 With a path, do a lookup in another repository.
1373 With a path, do a lookup in another repository.
1374
1374
1375 This summary identifies the repository state using one or two parent
1375 This summary identifies the repository state using one or two parent
1376 hash identifiers, followed by a "+" if there are uncommitted changes
1376 hash identifiers, followed by a "+" if there are uncommitted changes
1377 in the working directory, a list of tags for this revision and a branch
1377 in the working directory, a list of tags for this revision and a branch
1378 name for non-default branches.
1378 name for non-default branches.
1379 """
1379 """
1380
1380
1381 if not repo and not source:
1381 if not repo and not source:
1382 raise util.Abort(_("There is no Mercurial repository here "
1382 raise util.Abort(_("There is no Mercurial repository here "
1383 "(.hg not found)"))
1383 "(.hg not found)"))
1384
1384
1385 hexfunc = ui.debugflag and hex or short
1385 hexfunc = ui.debugflag and hex or short
1386 default = not (num or id or branch or tags)
1386 default = not (num or id or branch or tags)
1387 output = []
1387 output = []
1388
1388
1389 if source:
1389 if source:
1390 source, revs, checkout = hg.parseurl(ui.expandpath(source), [])
1390 source, revs, checkout = hg.parseurl(ui.expandpath(source), [])
1391 srepo = hg.repository(ui, source)
1391 srepo = hg.repository(ui, source)
1392 if not rev and revs:
1392 if not rev and revs:
1393 rev = revs[0]
1393 rev = revs[0]
1394 if not rev:
1394 if not rev:
1395 rev = "tip"
1395 rev = "tip"
1396 if num or branch or tags:
1396 if num or branch or tags:
1397 raise util.Abort(
1397 raise util.Abort(
1398 "can't query remote revision number, branch, or tags")
1398 "can't query remote revision number, branch, or tags")
1399 output = [hexfunc(srepo.lookup(rev))]
1399 output = [hexfunc(srepo.lookup(rev))]
1400 elif not rev:
1400 elif not rev:
1401 ctx = repo.workingctx()
1401 ctx = repo.workingctx()
1402 parents = ctx.parents()
1402 parents = ctx.parents()
1403 changed = False
1403 changed = False
1404 if default or id or num:
1404 if default or id or num:
1405 changed = ctx.files() + ctx.deleted()
1405 changed = ctx.files() + ctx.deleted()
1406 if default or id:
1406 if default or id:
1407 output = ["%s%s" % ('+'.join([hexfunc(p.node()) for p in parents]),
1407 output = ["%s%s" % ('+'.join([hexfunc(p.node()) for p in parents]),
1408 (changed) and "+" or "")]
1408 (changed) and "+" or "")]
1409 if num:
1409 if num:
1410 output.append("%s%s" % ('+'.join([str(p.rev()) for p in parents]),
1410 output.append("%s%s" % ('+'.join([str(p.rev()) for p in parents]),
1411 (changed) and "+" or ""))
1411 (changed) and "+" or ""))
1412 else:
1412 else:
1413 ctx = repo.changectx(rev)
1413 ctx = repo.changectx(rev)
1414 if default or id:
1414 if default or id:
1415 output = [hexfunc(ctx.node())]
1415 output = [hexfunc(ctx.node())]
1416 if num:
1416 if num:
1417 output.append(str(ctx.rev()))
1417 output.append(str(ctx.rev()))
1418
1418
1419 if not source and default and not ui.quiet:
1419 if not source and default and not ui.quiet:
1420 b = util.tolocal(ctx.branch())
1420 b = util.tolocal(ctx.branch())
1421 if b != 'default':
1421 if b != 'default':
1422 output.append("(%s)" % b)
1422 output.append("(%s)" % b)
1423
1423
1424 # multiple tags for a single parent separated by '/'
1424 # multiple tags for a single parent separated by '/'
1425 t = "/".join(ctx.tags())
1425 t = "/".join(ctx.tags())
1426 if t:
1426 if t:
1427 output.append(t)
1427 output.append(t)
1428
1428
1429 if branch:
1429 if branch:
1430 output.append(util.tolocal(ctx.branch()))
1430 output.append(util.tolocal(ctx.branch()))
1431
1431
1432 if tags:
1432 if tags:
1433 output.extend(ctx.tags())
1433 output.extend(ctx.tags())
1434
1434
1435 ui.write("%s\n" % ' '.join(output))
1435 ui.write("%s\n" % ' '.join(output))
1436
1436
1437 def import_(ui, repo, patch1, *patches, **opts):
1437 def import_(ui, repo, patch1, *patches, **opts):
1438 """import an ordered set of patches
1438 """import an ordered set of patches
1439
1439
1440 Import a list of patches and commit them individually.
1440 Import a list of patches and commit them individually.
1441
1441
1442 If there are outstanding changes in the working directory, import
1442 If there are outstanding changes in the working directory, import
1443 will abort unless given the -f flag.
1443 will abort unless given the -f flag.
1444
1444
1445 You can import a patch straight from a mail message. Even patches
1445 You can import a patch straight from a mail message. Even patches
1446 as attachments work (body part must be type text/plain or
1446 as attachments work (body part must be type text/plain or
1447 text/x-patch to be used). From and Subject headers of email
1447 text/x-patch to be used). From and Subject headers of email
1448 message are used as default committer and commit message. All
1448 message are used as default committer and commit message. All
1449 text/plain body parts before first diff are added to commit
1449 text/plain body parts before first diff are added to commit
1450 message.
1450 message.
1451
1451
1452 If the imported patch was generated by hg export, user and description
1452 If the imported patch was generated by hg export, user and description
1453 from patch override values from message headers and body. Values
1453 from patch override values from message headers and body. Values
1454 given on command line with -m and -u override these.
1454 given on command line with -m and -u override these.
1455
1455
1456 If --exact is specified, import will set the working directory
1456 If --exact is specified, import will set the working directory
1457 to the parent of each patch before applying it, and will abort
1457 to the parent of each patch before applying it, and will abort
1458 if the resulting changeset has a different ID than the one
1458 if the resulting changeset has a different ID than the one
1459 recorded in the patch. This may happen due to character set
1459 recorded in the patch. This may happen due to character set
1460 problems or other deficiencies in the text patch format.
1460 problems or other deficiencies in the text patch format.
1461
1461
1462 To read a patch from standard input, use patch name "-".
1462 To read a patch from standard input, use patch name "-".
1463 See 'hg help dates' for a list of formats valid for -d/--date.
1463 See 'hg help dates' for a list of formats valid for -d/--date.
1464 """
1464 """
1465 patches = (patch1,) + patches
1465 patches = (patch1,) + patches
1466
1466
1467 date = opts.get('date')
1467 date = opts.get('date')
1468 if date:
1468 if date:
1469 opts['date'] = util.parsedate(date)
1469 opts['date'] = util.parsedate(date)
1470
1470
1471 if opts.get('exact') or not opts['force']:
1471 if opts.get('exact') or not opts['force']:
1472 cmdutil.bail_if_changed(repo)
1472 cmdutil.bail_if_changed(repo)
1473
1473
1474 d = opts["base"]
1474 d = opts["base"]
1475 strip = opts["strip"]
1475 strip = opts["strip"]
1476 wlock = lock = None
1476 wlock = lock = None
1477 try:
1477 try:
1478 wlock = repo.wlock()
1478 wlock = repo.wlock()
1479 lock = repo.lock()
1479 lock = repo.lock()
1480 for p in patches:
1480 for p in patches:
1481 pf = os.path.join(d, p)
1481 pf = os.path.join(d, p)
1482
1482
1483 if pf == '-':
1483 if pf == '-':
1484 ui.status(_("applying patch from stdin\n"))
1484 ui.status(_("applying patch from stdin\n"))
1485 data = patch.extract(ui, sys.stdin)
1485 data = patch.extract(ui, sys.stdin)
1486 else:
1486 else:
1487 ui.status(_("applying %s\n") % p)
1487 ui.status(_("applying %s\n") % p)
1488 if os.path.exists(pf):
1488 if os.path.exists(pf):
1489 data = patch.extract(ui, file(pf, 'rb'))
1489 data = patch.extract(ui, file(pf, 'rb'))
1490 else:
1490 else:
1491 data = patch.extract(ui, urllib.urlopen(pf))
1491 data = patch.extract(ui, urllib.urlopen(pf))
1492 tmpname, message, user, date, branch, nodeid, p1, p2 = data
1492 tmpname, message, user, date, branch, nodeid, p1, p2 = data
1493
1493
1494 if tmpname is None:
1494 if tmpname is None:
1495 raise util.Abort(_('no diffs found'))
1495 raise util.Abort(_('no diffs found'))
1496
1496
1497 try:
1497 try:
1498 cmdline_message = cmdutil.logmessage(opts)
1498 cmdline_message = cmdutil.logmessage(opts)
1499 if cmdline_message:
1499 if cmdline_message:
1500 # pickup the cmdline msg
1500 # pickup the cmdline msg
1501 message = cmdline_message
1501 message = cmdline_message
1502 elif message:
1502 elif message:
1503 # pickup the patch msg
1503 # pickup the patch msg
1504 message = message.strip()
1504 message = message.strip()
1505 else:
1505 else:
1506 # launch the editor
1506 # launch the editor
1507 message = None
1507 message = None
1508 ui.debug(_('message:\n%s\n') % message)
1508 ui.debug(_('message:\n%s\n') % message)
1509
1509
1510 wp = repo.workingctx().parents()
1510 wp = repo.workingctx().parents()
1511 if opts.get('exact'):
1511 if opts.get('exact'):
1512 if not nodeid or not p1:
1512 if not nodeid or not p1:
1513 raise util.Abort(_('not a mercurial patch'))
1513 raise util.Abort(_('not a mercurial patch'))
1514 p1 = repo.lookup(p1)
1514 p1 = repo.lookup(p1)
1515 p2 = repo.lookup(p2 or hex(nullid))
1515 p2 = repo.lookup(p2 or hex(nullid))
1516
1516
1517 if p1 != wp[0].node():
1517 if p1 != wp[0].node():
1518 hg.clean(repo, p1)
1518 hg.clean(repo, p1)
1519 repo.dirstate.setparents(p1, p2)
1519 repo.dirstate.setparents(p1, p2)
1520 elif p2:
1520 elif p2:
1521 try:
1521 try:
1522 p1 = repo.lookup(p1)
1522 p1 = repo.lookup(p1)
1523 p2 = repo.lookup(p2)
1523 p2 = repo.lookup(p2)
1524 if p1 == wp[0].node():
1524 if p1 == wp[0].node():
1525 repo.dirstate.setparents(p1, p2)
1525 repo.dirstate.setparents(p1, p2)
1526 except RepoError:
1526 except RepoError:
1527 pass
1527 pass
1528 if opts.get('exact') or opts.get('import_branch'):
1528 if opts.get('exact') or opts.get('import_branch'):
1529 repo.dirstate.setbranch(branch or 'default')
1529 repo.dirstate.setbranch(branch or 'default')
1530
1530
1531 files = {}
1531 files = {}
1532 try:
1532 try:
1533 fuzz = patch.patch(tmpname, ui, strip=strip, cwd=repo.root,
1533 fuzz = patch.patch(tmpname, ui, strip=strip, cwd=repo.root,
1534 files=files)
1534 files=files)
1535 finally:
1535 finally:
1536 files = patch.updatedir(ui, repo, files)
1536 files = patch.updatedir(ui, repo, files)
1537 if not opts.get('no_commit'):
1537 if not opts.get('no_commit'):
1538 n = repo.commit(files, message, opts.get('user') or user,
1538 n = repo.commit(files, message, opts.get('user') or user,
1539 opts.get('date') or date)
1539 opts.get('date') or date)
1540 if opts.get('exact'):
1540 if opts.get('exact'):
1541 if hex(n) != nodeid:
1541 if hex(n) != nodeid:
1542 repo.rollback()
1542 repo.rollback()
1543 raise util.Abort(_('patch is damaged'
1543 raise util.Abort(_('patch is damaged'
1544 ' or loses information'))
1544 ' or loses information'))
1545 # Force a dirstate write so that the next transaction
1545 # Force a dirstate write so that the next transaction
1546 # backups an up-do-date file.
1546 # backups an up-do-date file.
1547 repo.dirstate.write()
1547 repo.dirstate.write()
1548 finally:
1548 finally:
1549 os.unlink(tmpname)
1549 os.unlink(tmpname)
1550 finally:
1550 finally:
1551 del lock, wlock
1551 del lock, wlock
1552
1552
1553 def incoming(ui, repo, source="default", **opts):
1553 def incoming(ui, repo, source="default", **opts):
1554 """show new changesets found in source
1554 """show new changesets found in source
1555
1555
1556 Show new changesets found in the specified path/URL or the default
1556 Show new changesets found in the specified path/URL or the default
1557 pull location. These are the changesets that would be pulled if a pull
1557 pull location. These are the changesets that would be pulled if a pull
1558 was requested.
1558 was requested.
1559
1559
1560 For remote repository, using --bundle avoids downloading the changesets
1560 For remote repository, using --bundle avoids downloading the changesets
1561 twice if the incoming is followed by a pull.
1561 twice if the incoming is followed by a pull.
1562
1562
1563 See pull for valid source format details.
1563 See pull for valid source format details.
1564 """
1564 """
1565 limit = cmdutil.loglimit(opts)
1565 limit = cmdutil.loglimit(opts)
1566 source, revs, checkout = hg.parseurl(ui.expandpath(source), opts['rev'])
1566 source, revs, checkout = hg.parseurl(ui.expandpath(source), opts['rev'])
1567 cmdutil.setremoteconfig(ui, opts)
1567 cmdutil.setremoteconfig(ui, opts)
1568
1568
1569 other = hg.repository(ui, source)
1569 other = hg.repository(ui, source)
1570 ui.status(_('comparing with %s\n') % util.hidepassword(source))
1570 ui.status(_('comparing with %s\n') % util.hidepassword(source))
1571 if revs:
1571 if revs:
1572 revs = [other.lookup(rev) for rev in revs]
1572 revs = [other.lookup(rev) for rev in revs]
1573 incoming = repo.findincoming(other, heads=revs, force=opts["force"])
1573 incoming = repo.findincoming(other, heads=revs, force=opts["force"])
1574 if not incoming:
1574 if not incoming:
1575 try:
1575 try:
1576 os.unlink(opts["bundle"])
1576 os.unlink(opts["bundle"])
1577 except:
1577 except:
1578 pass
1578 pass
1579 ui.status(_("no changes found\n"))
1579 ui.status(_("no changes found\n"))
1580 return 1
1580 return 1
1581
1581
1582 cleanup = None
1582 cleanup = None
1583 try:
1583 try:
1584 fname = opts["bundle"]
1584 fname = opts["bundle"]
1585 if fname or not other.local():
1585 if fname or not other.local():
1586 # create a bundle (uncompressed if other repo is not local)
1586 # create a bundle (uncompressed if other repo is not local)
1587 if revs is None:
1587 if revs is None:
1588 cg = other.changegroup(incoming, "incoming")
1588 cg = other.changegroup(incoming, "incoming")
1589 else:
1589 else:
1590 cg = other.changegroupsubset(incoming, revs, 'incoming')
1590 cg = other.changegroupsubset(incoming, revs, 'incoming')
1591 bundletype = other.local() and "HG10BZ" or "HG10UN"
1591 bundletype = other.local() and "HG10BZ" or "HG10UN"
1592 fname = cleanup = changegroup.writebundle(cg, fname, bundletype)
1592 fname = cleanup = changegroup.writebundle(cg, fname, bundletype)
1593 # keep written bundle?
1593 # keep written bundle?
1594 if opts["bundle"]:
1594 if opts["bundle"]:
1595 cleanup = None
1595 cleanup = None
1596 if not other.local():
1596 if not other.local():
1597 # use the created uncompressed bundlerepo
1597 # use the created uncompressed bundlerepo
1598 other = bundlerepo.bundlerepository(ui, repo.root, fname)
1598 other = bundlerepo.bundlerepository(ui, repo.root, fname)
1599
1599
1600 o = other.changelog.nodesbetween(incoming, revs)[0]
1600 o = other.changelog.nodesbetween(incoming, revs)[0]
1601 if opts['newest_first']:
1601 if opts['newest_first']:
1602 o.reverse()
1602 o.reverse()
1603 displayer = cmdutil.show_changeset(ui, other, opts)
1603 displayer = cmdutil.show_changeset(ui, other, opts)
1604 count = 0
1604 count = 0
1605 for n in o:
1605 for n in o:
1606 if count >= limit:
1606 if count >= limit:
1607 break
1607 break
1608 parents = [p for p in other.changelog.parents(n) if p != nullid]
1608 parents = [p for p in other.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 count += 1
1611 count += 1
1612 displayer.show(changenode=n)
1612 displayer.show(changenode=n)
1613 finally:
1613 finally:
1614 if hasattr(other, 'close'):
1614 if hasattr(other, 'close'):
1615 other.close()
1615 other.close()
1616 if cleanup:
1616 if cleanup:
1617 os.unlink(cleanup)
1617 os.unlink(cleanup)
1618
1618
1619 def init(ui, dest=".", **opts):
1619 def init(ui, dest=".", **opts):
1620 """create a new repository in the given directory
1620 """create a new repository in the given directory
1621
1621
1622 Initialize a new repository in the given directory. If the given
1622 Initialize a new repository in the given directory. If the given
1623 directory does not exist, it is created.
1623 directory does not exist, it is created.
1624
1624
1625 If no directory is given, the current directory is used.
1625 If no directory is given, the current directory is used.
1626
1626
1627 It is possible to specify an ssh:// URL as the destination.
1627 It is possible to specify an ssh:// URL as the destination.
1628 Look at the help text for the pull command for important details
1628 Look at the help text for the pull command for important details
1629 about ssh:// URLs.
1629 about ssh:// URLs.
1630 """
1630 """
1631 cmdutil.setremoteconfig(ui, opts)
1631 cmdutil.setremoteconfig(ui, opts)
1632 hg.repository(ui, dest, create=1)
1632 hg.repository(ui, dest, create=1)
1633
1633
1634 def locate(ui, repo, *pats, **opts):
1634 def locate(ui, repo, *pats, **opts):
1635 """locate files matching specific patterns
1635 """locate files matching specific patterns
1636
1636
1637 Print all files under Mercurial control whose names match the
1637 Print all files under Mercurial control whose names match the
1638 given patterns.
1638 given patterns.
1639
1639
1640 This command searches the entire repository by default. To search
1640 This command searches the entire repository by default. To search
1641 just the current directory and its subdirectories, use
1641 just the current directory and its subdirectories, use
1642 "--include .".
1642 "--include .".
1643
1643
1644 If no patterns are given to match, this command prints all file
1644 If no patterns are given to match, this command prints all file
1645 names.
1645 names.
1646
1646
1647 If you want to feed the output of this command into the "xargs"
1647 If you want to feed the output of this command into the "xargs"
1648 command, use the "-0" option to both this command and "xargs".
1648 command, use the "-0" option to both this command and "xargs".
1649 This will avoid the problem of "xargs" treating single filenames
1649 This will avoid the problem of "xargs" treating single filenames
1650 that contain white space as multiple filenames.
1650 that contain white space as multiple filenames.
1651 """
1651 """
1652 end = opts['print0'] and '\0' or '\n'
1652 end = opts['print0'] and '\0' or '\n'
1653 rev = opts['rev']
1653 rev = opts['rev']
1654 if rev:
1654 if rev:
1655 node = repo.lookup(rev)
1655 node = repo.lookup(rev)
1656 else:
1656 else:
1657 node = None
1657 node = None
1658
1658
1659 ret = 1
1659 ret = 1
1660 for src, abs, rel, exact in cmdutil.walk(repo, pats, opts, node=node,
1660 for src, abs, rel, exact in cmdutil.walk(repo, pats, opts, node=node,
1661 badmatch=util.always,
1661 badmatch=util.always,
1662 default='relglob'):
1662 default='relglob'):
1663 if src == 'b':
1663 if src == 'b':
1664 continue
1664 continue
1665 if not node and abs not in repo.dirstate:
1665 if not node and abs not in repo.dirstate:
1666 continue
1666 continue
1667 if opts['fullpath']:
1667 if opts['fullpath']:
1668 ui.write(os.path.join(repo.root, abs), end)
1668 ui.write(os.path.join(repo.root, abs), end)
1669 else:
1669 else:
1670 ui.write(((pats and rel) or abs), end)
1670 ui.write(((pats and rel) or abs), end)
1671 ret = 0
1671 ret = 0
1672
1672
1673 return ret
1673 return ret
1674
1674
1675 def log(ui, repo, *pats, **opts):
1675 def log(ui, repo, *pats, **opts):
1676 """show revision history of entire repository or files
1676 """show revision history of entire repository or files
1677
1677
1678 Print the revision history of the specified files or the entire
1678 Print the revision history of the specified files or the entire
1679 project.
1679 project.
1680
1680
1681 File history is shown without following rename or copy history of
1681 File history is shown without following rename or copy history of
1682 files. Use -f/--follow with a file name to follow history across
1682 files. Use -f/--follow with a file name to follow history across
1683 renames and copies. --follow without a file name will only show
1683 renames and copies. --follow without a file name will only show
1684 ancestors or descendants of the starting revision. --follow-first
1684 ancestors or descendants of the starting revision. --follow-first
1685 only follows the first parent of merge revisions.
1685 only follows the first parent of merge revisions.
1686
1686
1687 If no revision range is specified, the default is tip:0 unless
1687 If no revision range is specified, the default is tip:0 unless
1688 --follow is set, in which case the working directory parent is
1688 --follow is set, in which case the working directory parent is
1689 used as the starting revision.
1689 used as the starting revision.
1690
1690
1691 See 'hg help dates' for a list of formats valid for -d/--date.
1691 See 'hg help dates' for a list of formats valid for -d/--date.
1692
1692
1693 By default this command outputs: changeset id and hash, tags,
1693 By default this command outputs: changeset id and hash, tags,
1694 non-trivial parents, user, date and time, and a summary for each
1694 non-trivial parents, user, date and time, and a summary for each
1695 commit. When the -v/--verbose switch is used, the list of changed
1695 commit. When the -v/--verbose switch is used, the list of changed
1696 files and full commit message is shown.
1696 files and full commit message is shown.
1697
1697
1698 NOTE: log -p may generate unexpected diff output for merge
1698 NOTE: log -p may generate unexpected diff output for merge
1699 changesets, as it will compare the merge changeset against its
1699 changesets, as it will compare the merge changeset against its
1700 first parent only. Also, the files: list will only reflect files
1700 first parent only. Also, the files: list will only reflect files
1701 that are different from BOTH parents.
1701 that are different from BOTH parents.
1702
1702
1703 """
1703 """
1704
1704
1705 get = util.cachefunc(lambda r: repo.changectx(r).changeset())
1705 get = util.cachefunc(lambda r: repo.changectx(r).changeset())
1706 changeiter, matchfn = cmdutil.walkchangerevs(ui, repo, pats, get, opts)
1706 changeiter, matchfn = cmdutil.walkchangerevs(ui, repo, pats, get, opts)
1707
1707
1708 limit = cmdutil.loglimit(opts)
1708 limit = cmdutil.loglimit(opts)
1709 count = 0
1709 count = 0
1710
1710
1711 if opts['copies'] and opts['rev']:
1711 if opts['copies'] and opts['rev']:
1712 endrev = max(cmdutil.revrange(repo, opts['rev'])) + 1
1712 endrev = max(cmdutil.revrange(repo, opts['rev'])) + 1
1713 else:
1713 else:
1714 endrev = repo.changelog.count()
1714 endrev = repo.changelog.count()
1715 rcache = {}
1715 rcache = {}
1716 ncache = {}
1716 ncache = {}
1717 def getrenamed(fn, rev):
1717 def getrenamed(fn, rev):
1718 '''looks up all renames for a file (up to endrev) the first
1718 '''looks up all renames for a file (up to endrev) the first
1719 time the file is given. It indexes on the changerev and only
1719 time the file is given. It indexes on the changerev and only
1720 parses the manifest if linkrev != changerev.
1720 parses the manifest if linkrev != changerev.
1721 Returns rename info for fn at changerev rev.'''
1721 Returns rename info for fn at changerev rev.'''
1722 if fn not in rcache:
1722 if fn not in rcache:
1723 rcache[fn] = {}
1723 rcache[fn] = {}
1724 ncache[fn] = {}
1724 ncache[fn] = {}
1725 fl = repo.file(fn)
1725 fl = repo.file(fn)
1726 for i in xrange(fl.count()):
1726 for i in xrange(fl.count()):
1727 node = fl.node(i)
1727 node = fl.node(i)
1728 lr = fl.linkrev(node)
1728 lr = fl.linkrev(node)
1729 renamed = fl.renamed(node)
1729 renamed = fl.renamed(node)
1730 rcache[fn][lr] = renamed
1730 rcache[fn][lr] = renamed
1731 if renamed:
1731 if renamed:
1732 ncache[fn][node] = renamed
1732 ncache[fn][node] = renamed
1733 if lr >= endrev:
1733 if lr >= endrev:
1734 break
1734 break
1735 if rev in rcache[fn]:
1735 if rev in rcache[fn]:
1736 return rcache[fn][rev]
1736 return rcache[fn][rev]
1737
1737
1738 # If linkrev != rev (i.e. rev not found in rcache) fallback to
1738 # If linkrev != rev (i.e. rev not found in rcache) fallback to
1739 # filectx logic.
1739 # filectx logic.
1740
1740
1741 try:
1741 try:
1742 return repo.changectx(rev).filectx(fn).renamed()
1742 return repo.changectx(rev).filectx(fn).renamed()
1743 except revlog.LookupError:
1743 except revlog.LookupError:
1744 pass
1744 pass
1745 return None
1745 return None
1746
1746
1747 df = False
1747 df = False
1748 if opts["date"]:
1748 if opts["date"]:
1749 df = util.matchdate(opts["date"])
1749 df = util.matchdate(opts["date"])
1750
1750
1751 only_branches = opts['only_branch']
1751 only_branches = opts['only_branch']
1752
1752
1753 displayer = cmdutil.show_changeset(ui, repo, opts, True, matchfn)
1753 displayer = cmdutil.show_changeset(ui, repo, opts, True, matchfn)
1754 for st, rev, fns in changeiter:
1754 for st, rev, fns in changeiter:
1755 if st == 'add':
1755 if st == 'add':
1756 changenode = repo.changelog.node(rev)
1756 changenode = repo.changelog.node(rev)
1757 parents = [p for p in repo.changelog.parentrevs(rev)
1757 parents = [p for p in repo.changelog.parentrevs(rev)
1758 if p != nullrev]
1758 if p != nullrev]
1759 if opts['no_merges'] and len(parents) == 2:
1759 if opts['no_merges'] and len(parents) == 2:
1760 continue
1760 continue
1761 if opts['only_merges'] and len(parents) != 2:
1761 if opts['only_merges'] and len(parents) != 2:
1762 continue
1762 continue
1763
1763
1764 if only_branches:
1764 if only_branches:
1765 revbranch = get(rev)[5]['branch']
1765 revbranch = get(rev)[5]['branch']
1766 if revbranch not in only_branches:
1766 if revbranch not in only_branches:
1767 continue
1767 continue
1768
1768
1769 if df:
1769 if df:
1770 changes = get(rev)
1770 changes = get(rev)
1771 if not df(changes[2][0]):
1771 if not df(changes[2][0]):
1772 continue
1772 continue
1773
1773
1774 if opts['keyword']:
1774 if opts['keyword']:
1775 changes = get(rev)
1775 changes = get(rev)
1776 miss = 0
1776 miss = 0
1777 for k in [kw.lower() for kw in opts['keyword']]:
1777 for k in [kw.lower() for kw in opts['keyword']]:
1778 if not (k in changes[1].lower() or
1778 if not (k in changes[1].lower() or
1779 k in changes[4].lower() or
1779 k in changes[4].lower() or
1780 k in " ".join(changes[3]).lower()):
1780 k in " ".join(changes[3]).lower()):
1781 miss = 1
1781 miss = 1
1782 break
1782 break
1783 if miss:
1783 if miss:
1784 continue
1784 continue
1785
1785
1786 copies = []
1786 copies = []
1787 if opts.get('copies') and rev:
1787 if opts.get('copies') and rev:
1788 for fn in get(rev)[3]:
1788 for fn in get(rev)[3]:
1789 rename = getrenamed(fn, rev)
1789 rename = getrenamed(fn, rev)
1790 if rename:
1790 if rename:
1791 copies.append((fn, rename[0]))
1791 copies.append((fn, rename[0]))
1792 displayer.show(rev, changenode, copies=copies)
1792 displayer.show(rev, changenode, copies=copies)
1793 elif st == 'iter':
1793 elif st == 'iter':
1794 if count == limit: break
1794 if count == limit: break
1795 if displayer.flush(rev):
1795 if displayer.flush(rev):
1796 count += 1
1796 count += 1
1797
1797
1798 def manifest(ui, repo, node=None, rev=None):
1798 def manifest(ui, repo, node=None, rev=None):
1799 """output the current or given revision of the project manifest
1799 """output the current or given revision of the project manifest
1800
1800
1801 Print a list of version controlled files for the given revision.
1801 Print a list of version controlled files for the given revision.
1802 If no revision is given, the parent of the working directory is used,
1802 If no revision is given, the parent of the working directory is used,
1803 or tip if no revision is checked out.
1803 or tip if no revision is checked out.
1804
1804
1805 The manifest is the list of files being version controlled. If no revision
1805 The manifest is the list of files being version controlled. If no revision
1806 is given then the first parent of the working directory is used.
1806 is given then the first parent of the working directory is used.
1807
1807
1808 With -v flag, print file permissions, symlink and executable bits. With
1808 With -v flag, print file permissions, symlink and executable bits. With
1809 --debug flag, print file revision hashes.
1809 --debug flag, print file revision hashes.
1810 """
1810 """
1811
1811
1812 if rev and node:
1812 if rev and node:
1813 raise util.Abort(_("please specify just one revision"))
1813 raise util.Abort(_("please specify just one revision"))
1814
1814
1815 if not node:
1815 if not node:
1816 node = rev
1816 node = rev
1817
1817
1818 m = repo.changectx(node).manifest()
1818 m = repo.changectx(node).manifest()
1819 files = m.keys()
1819 files = m.keys()
1820 files.sort()
1820 files.sort()
1821
1821
1822 for f in files:
1822 for f in files:
1823 if ui.debugflag:
1823 if ui.debugflag:
1824 ui.write("%40s " % hex(m[f]))
1824 ui.write("%40s " % hex(m[f]))
1825 if ui.verbose:
1825 if ui.verbose:
1826 type = m.execf(f) and "*" or m.linkf(f) and "@" or " "
1826 type = m.execf(f) and "*" or m.linkf(f) and "@" or " "
1827 perm = m.execf(f) and "755" or "644"
1827 perm = m.execf(f) and "755" or "644"
1828 ui.write("%3s %1s " % (perm, type))
1828 ui.write("%3s %1s " % (perm, type))
1829 ui.write("%s\n" % f)
1829 ui.write("%s\n" % f)
1830
1830
1831 def merge(ui, repo, node=None, force=None, rev=None):
1831 def merge(ui, repo, node=None, force=None, rev=None):
1832 """merge working directory with another revision
1832 """merge working directory with another revision
1833
1833
1834 Merge the contents of the current working directory and the
1834 Merge the contents of the current working directory and the
1835 requested revision. Files that changed between either parent are
1835 requested revision. Files that changed between either parent are
1836 marked as changed for the next commit and a commit must be
1836 marked as changed for the next commit and a commit must be
1837 performed before any further updates are allowed.
1837 performed before any further updates are allowed.
1838
1838
1839 If no revision is specified, the working directory's parent is a
1839 If no revision is specified, the working directory's parent is a
1840 head revision, and the repository contains exactly one other head,
1840 head revision, and the repository contains exactly one other head,
1841 the other head is merged with by default. Otherwise, an explicit
1841 the other head is merged with by default. Otherwise, an explicit
1842 revision to merge with must be provided.
1842 revision to merge with must be provided.
1843 """
1843 """
1844
1844
1845 if rev and node:
1845 if rev and node:
1846 raise util.Abort(_("please specify just one revision"))
1846 raise util.Abort(_("please specify just one revision"))
1847 if not node:
1847 if not node:
1848 node = rev
1848 node = rev
1849
1849
1850 if not node:
1850 if not node:
1851 heads = repo.heads()
1851 heads = repo.heads()
1852 if len(heads) > 2:
1852 if len(heads) > 2:
1853 raise util.Abort(_('repo has %d heads - '
1853 raise util.Abort(_('repo has %d heads - '
1854 'please merge with an explicit rev') %
1854 'please merge with an explicit rev') %
1855 len(heads))
1855 len(heads))
1856 parent = repo.dirstate.parents()[0]
1856 parent = repo.dirstate.parents()[0]
1857 if len(heads) == 1:
1857 if len(heads) == 1:
1858 msg = _('there is nothing to merge')
1858 msg = _('there is nothing to merge')
1859 if parent != repo.lookup(repo.workingctx().branch()):
1859 if parent != repo.lookup(repo.workingctx().branch()):
1860 msg = _('%s - use "hg update" instead') % msg
1860 msg = _('%s - use "hg update" instead') % msg
1861 raise util.Abort(msg)
1861 raise util.Abort(msg)
1862
1862
1863 if parent not in heads:
1863 if parent not in heads:
1864 raise util.Abort(_('working dir not at a head rev - '
1864 raise util.Abort(_('working dir not at a head rev - '
1865 'use "hg update" or merge with an explicit rev'))
1865 'use "hg update" or merge with an explicit rev'))
1866 node = parent == heads[0] and heads[-1] or heads[0]
1866 node = parent == heads[0] and heads[-1] or heads[0]
1867 return hg.merge(repo, node, force=force)
1867 return hg.merge(repo, node, force=force)
1868
1868
1869 def outgoing(ui, repo, dest=None, **opts):
1869 def outgoing(ui, repo, dest=None, **opts):
1870 """show changesets not found in destination
1870 """show changesets not found in destination
1871
1871
1872 Show changesets not found in the specified destination repository or
1872 Show changesets not found in the specified destination repository or
1873 the default push location. These are the changesets that would be pushed
1873 the default push location. These are the changesets that would be pushed
1874 if a push was requested.
1874 if a push was requested.
1875
1875
1876 See pull for valid destination format details.
1876 See pull for valid destination format details.
1877 """
1877 """
1878 limit = cmdutil.loglimit(opts)
1878 limit = cmdutil.loglimit(opts)
1879 dest, revs, checkout = hg.parseurl(
1879 dest, revs, checkout = hg.parseurl(
1880 ui.expandpath(dest or 'default-push', dest or 'default'), opts['rev'])
1880 ui.expandpath(dest or 'default-push', dest or 'default'), opts['rev'])
1881 cmdutil.setremoteconfig(ui, opts)
1881 cmdutil.setremoteconfig(ui, opts)
1882 if revs:
1882 if revs:
1883 revs = [repo.lookup(rev) for rev in revs]
1883 revs = [repo.lookup(rev) for rev in revs]
1884
1884
1885 other = hg.repository(ui, dest)
1885 other = hg.repository(ui, dest)
1886 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
1886 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
1887 o = repo.findoutgoing(other, force=opts['force'])
1887 o = repo.findoutgoing(other, force=opts['force'])
1888 if not o:
1888 if not o:
1889 ui.status(_("no changes found\n"))
1889 ui.status(_("no changes found\n"))
1890 return 1
1890 return 1
1891 o = repo.changelog.nodesbetween(o, revs)[0]
1891 o = repo.changelog.nodesbetween(o, revs)[0]
1892 if opts['newest_first']:
1892 if opts['newest_first']:
1893 o.reverse()
1893 o.reverse()
1894 displayer = cmdutil.show_changeset(ui, repo, opts)
1894 displayer = cmdutil.show_changeset(ui, repo, opts)
1895 count = 0
1895 count = 0
1896 for n in o:
1896 for n in o:
1897 if count >= limit:
1897 if count >= limit:
1898 break
1898 break
1899 parents = [p for p in repo.changelog.parents(n) if p != nullid]
1899 parents = [p for p in repo.changelog.parents(n) if p != nullid]
1900 if opts['no_merges'] and len(parents) == 2:
1900 if opts['no_merges'] and len(parents) == 2:
1901 continue
1901 continue
1902 count += 1
1902 count += 1
1903 displayer.show(changenode=n)
1903 displayer.show(changenode=n)
1904
1904
1905 def parents(ui, repo, file_=None, **opts):
1905 def parents(ui, repo, file_=None, **opts):
1906 """show the parents of the working dir or revision
1906 """show the parents of the working dir or revision
1907
1907
1908 Print the working directory's parent revisions. If a
1908 Print the working directory's parent revisions. If a
1909 revision is given via --rev, the parent of that revision
1909 revision is given via --rev, the parent of that revision
1910 will be printed. If a file argument is given, revision in
1910 will be printed. If a file argument is given, revision in
1911 which the file was last changed (before the working directory
1911 which the file was last changed (before the working directory
1912 revision or the argument to --rev if given) is printed.
1912 revision or the argument to --rev if given) is printed.
1913 """
1913 """
1914 rev = opts.get('rev')
1914 rev = opts.get('rev')
1915 if rev:
1915 if rev:
1916 ctx = repo.changectx(rev)
1916 ctx = repo.changectx(rev)
1917 else:
1917 else:
1918 ctx = repo.workingctx()
1918 ctx = repo.workingctx()
1919
1919
1920 if file_:
1920 if file_:
1921 files, match, anypats = cmdutil.matchpats(repo, (file_,), opts)
1921 files, match, anypats = cmdutil.matchpats(repo, (file_,), opts)
1922 if anypats or len(files) != 1:
1922 if anypats or len(files) != 1:
1923 raise util.Abort(_('can only specify an explicit file name'))
1923 raise util.Abort(_('can only specify an explicit file name'))
1924 file_ = files[0]
1924 file_ = files[0]
1925 filenodes = []
1925 filenodes = []
1926 for cp in ctx.parents():
1926 for cp in ctx.parents():
1927 if not cp:
1927 if not cp:
1928 continue
1928 continue
1929 try:
1929 try:
1930 filenodes.append(cp.filenode(file_))
1930 filenodes.append(cp.filenode(file_))
1931 except revlog.LookupError:
1931 except revlog.LookupError:
1932 pass
1932 pass
1933 if not filenodes:
1933 if not filenodes:
1934 raise util.Abort(_("'%s' not found in manifest!") % file_)
1934 raise util.Abort(_("'%s' not found in manifest!") % file_)
1935 fl = repo.file(file_)
1935 fl = repo.file(file_)
1936 p = [repo.lookup(fl.linkrev(fn)) for fn in filenodes]
1936 p = [repo.lookup(fl.linkrev(fn)) for fn in filenodes]
1937 else:
1937 else:
1938 p = [cp.node() for cp in ctx.parents()]
1938 p = [cp.node() for cp in ctx.parents()]
1939
1939
1940 displayer = cmdutil.show_changeset(ui, repo, opts)
1940 displayer = cmdutil.show_changeset(ui, repo, opts)
1941 for n in p:
1941 for n in p:
1942 if n != nullid:
1942 if n != nullid:
1943 displayer.show(changenode=n)
1943 displayer.show(changenode=n)
1944
1944
1945 def paths(ui, repo, search=None):
1945 def paths(ui, repo, search=None):
1946 """show definition of symbolic path names
1946 """show definition of symbolic path names
1947
1947
1948 Show definition of symbolic path name NAME. If no name is given, show
1948 Show definition of symbolic path name NAME. If no name is given, show
1949 definition of available names.
1949 definition of available names.
1950
1950
1951 Path names are defined in the [paths] section of /etc/mercurial/hgrc
1951 Path names are defined in the [paths] section of /etc/mercurial/hgrc
1952 and $HOME/.hgrc. If run inside a repository, .hg/hgrc is used, too.
1952 and $HOME/.hgrc. If run inside a repository, .hg/hgrc is used, too.
1953 """
1953 """
1954 if search:
1954 if search:
1955 for name, path in ui.configitems("paths"):
1955 for name, path in ui.configitems("paths"):
1956 if name == search:
1956 if name == search:
1957 ui.write("%s\n" % util.hidepassword(path))
1957 ui.write("%s\n" % util.hidepassword(path))
1958 return
1958 return
1959 ui.warn(_("not found!\n"))
1959 ui.warn(_("not found!\n"))
1960 return 1
1960 return 1
1961 else:
1961 else:
1962 for name, path in ui.configitems("paths"):
1962 for name, path in ui.configitems("paths"):
1963 ui.write("%s = %s\n" % (name, util.hidepassword(path)))
1963 ui.write("%s = %s\n" % (name, util.hidepassword(path)))
1964
1964
1965 def postincoming(ui, repo, modheads, optupdate, checkout):
1965 def postincoming(ui, repo, modheads, optupdate, checkout):
1966 if modheads == 0:
1966 if modheads == 0:
1967 return
1967 return
1968 if optupdate:
1968 if optupdate:
1969 if modheads <= 1 or checkout:
1969 if modheads <= 1 or checkout:
1970 return hg.update(repo, checkout)
1970 return hg.update(repo, checkout)
1971 else:
1971 else:
1972 ui.status(_("not updating, since new heads added\n"))
1972 ui.status(_("not updating, since new heads added\n"))
1973 if modheads > 1:
1973 if modheads > 1:
1974 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
1974 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
1975 else:
1975 else:
1976 ui.status(_("(run 'hg update' to get a working copy)\n"))
1976 ui.status(_("(run 'hg update' to get a working copy)\n"))
1977
1977
1978 def pull(ui, repo, source="default", **opts):
1978 def pull(ui, repo, source="default", **opts):
1979 """pull changes from the specified source
1979 """pull changes from the specified source
1980
1980
1981 Pull changes from a remote repository to a local one.
1981 Pull changes from a remote repository to a local one.
1982
1982
1983 This finds all changes from the repository at the specified path
1983 This finds all changes from the repository at the specified path
1984 or URL and adds them to the local repository. By default, this
1984 or URL and adds them to the local repository. By default, this
1985 does not update the copy of the project in the working directory.
1985 does not update the copy of the project in the working directory.
1986
1986
1987 Valid URLs are of the form:
1987 Valid URLs are of the form:
1988
1988
1989 local/filesystem/path (or file://local/filesystem/path)
1989 local/filesystem/path (or file://local/filesystem/path)
1990 http://[user@]host[:port]/[path]
1990 http://[user@]host[:port]/[path]
1991 https://[user@]host[:port]/[path]
1991 https://[user@]host[:port]/[path]
1992 ssh://[user@]host[:port]/[path]
1992 ssh://[user@]host[:port]/[path]
1993 static-http://host[:port]/[path]
1993 static-http://host[:port]/[path]
1994
1994
1995 Paths in the local filesystem can either point to Mercurial
1995 Paths in the local filesystem can either point to Mercurial
1996 repositories or to bundle files (as created by 'hg bundle' or
1996 repositories or to bundle files (as created by 'hg bundle' or
1997 'hg incoming --bundle'). The static-http:// protocol, albeit slow,
1997 'hg incoming --bundle'). The static-http:// protocol, albeit slow,
1998 allows access to a Mercurial repository where you simply use a web
1998 allows access to a Mercurial repository where you simply use a web
1999 server to publish the .hg directory as static content.
1999 server to publish the .hg directory as static content.
2000
2000
2001 An optional identifier after # indicates a particular branch, tag,
2001 An optional identifier after # indicates a particular branch, tag,
2002 or changeset to pull.
2002 or changeset to pull.
2003
2003
2004 Some notes about using SSH with Mercurial:
2004 Some notes about using SSH with Mercurial:
2005 - SSH requires an accessible shell account on the destination machine
2005 - SSH requires an accessible shell account on the destination machine
2006 and a copy of hg in the remote path or specified with as remotecmd.
2006 and a copy of hg in the remote path or specified with as remotecmd.
2007 - path is relative to the remote user's home directory by default.
2007 - path is relative to the remote user's home directory by default.
2008 Use an extra slash at the start of a path to specify an absolute path:
2008 Use an extra slash at the start of a path to specify an absolute path:
2009 ssh://example.com//tmp/repository
2009 ssh://example.com//tmp/repository
2010 - Mercurial doesn't use its own compression via SSH; the right thing
2010 - Mercurial doesn't use its own compression via SSH; the right thing
2011 to do is to configure it in your ~/.ssh/config, e.g.:
2011 to do is to configure it in your ~/.ssh/config, e.g.:
2012 Host *.mylocalnetwork.example.com
2012 Host *.mylocalnetwork.example.com
2013 Compression no
2013 Compression no
2014 Host *
2014 Host *
2015 Compression yes
2015 Compression yes
2016 Alternatively specify "ssh -C" as your ssh command in your hgrc or
2016 Alternatively specify "ssh -C" as your ssh command in your hgrc or
2017 with the --ssh command line option.
2017 with the --ssh command line option.
2018 """
2018 """
2019 source, revs, checkout = hg.parseurl(ui.expandpath(source), opts['rev'])
2019 source, revs, checkout = hg.parseurl(ui.expandpath(source), opts['rev'])
2020 cmdutil.setremoteconfig(ui, opts)
2020 cmdutil.setremoteconfig(ui, opts)
2021
2021
2022 other = hg.repository(ui, source)
2022 other = hg.repository(ui, source)
2023 ui.status(_('pulling from %s\n') % util.hidepassword(source))
2023 ui.status(_('pulling from %s\n') % util.hidepassword(source))
2024 if revs:
2024 if revs:
2025 try:
2025 try:
2026 revs = [other.lookup(rev) for rev in revs]
2026 revs = [other.lookup(rev) for rev in revs]
2027 except repo.NoCapability:
2027 except repo.NoCapability:
2028 error = _("Other repository doesn't support revision lookup, "
2028 error = _("Other repository doesn't support revision lookup, "
2029 "so a rev cannot be specified.")
2029 "so a rev cannot be specified.")
2030 raise util.Abort(error)
2030 raise util.Abort(error)
2031
2031
2032 modheads = repo.pull(other, heads=revs, force=opts['force'])
2032 modheads = repo.pull(other, heads=revs, force=opts['force'])
2033 return postincoming(ui, repo, modheads, opts['update'], checkout)
2033 return postincoming(ui, repo, modheads, opts['update'], checkout)
2034
2034
2035 def push(ui, repo, dest=None, **opts):
2035 def push(ui, repo, dest=None, **opts):
2036 """push changes to the specified destination
2036 """push changes to the specified destination
2037
2037
2038 Push changes from the local repository to the given destination.
2038 Push changes from the local repository to the given destination.
2039
2039
2040 This is the symmetrical operation for pull. It helps to move
2040 This is the symmetrical operation for pull. It helps to move
2041 changes from the current repository to a different one. If the
2041 changes from the current repository to a different one. If the
2042 destination is local this is identical to a pull in that directory
2042 destination is local this is identical to a pull in that directory
2043 from the current one.
2043 from the current one.
2044
2044
2045 By default, push will refuse to run if it detects the result would
2045 By default, push will refuse to run if it detects the result would
2046 increase the number of remote heads. This generally indicates the
2046 increase the number of remote heads. This generally indicates the
2047 the client has forgotten to sync and merge before pushing.
2047 the client has forgotten to sync and merge before pushing.
2048
2048
2049 Valid URLs are of the form:
2049 Valid URLs are of the form:
2050
2050
2051 local/filesystem/path (or file://local/filesystem/path)
2051 local/filesystem/path (or file://local/filesystem/path)
2052 ssh://[user@]host[:port]/[path]
2052 ssh://[user@]host[:port]/[path]
2053 http://[user@]host[:port]/[path]
2053 http://[user@]host[:port]/[path]
2054 https://[user@]host[:port]/[path]
2054 https://[user@]host[:port]/[path]
2055
2055
2056 An optional identifier after # indicates a particular branch, tag,
2056 An optional identifier after # indicates a particular branch, tag,
2057 or changeset to push.
2057 or changeset to push.
2058
2058
2059 Look at the help text for the pull command for important details
2059 Look at the help text for the pull command for important details
2060 about ssh:// URLs.
2060 about ssh:// URLs.
2061
2061
2062 Pushing to http:// and https:// URLs is only possible, if this
2062 Pushing to http:// and https:// URLs is only possible, if this
2063 feature is explicitly enabled on the remote Mercurial server.
2063 feature is explicitly enabled on the remote Mercurial server.
2064 """
2064 """
2065 dest, revs, checkout = hg.parseurl(
2065 dest, revs, checkout = hg.parseurl(
2066 ui.expandpath(dest or 'default-push', dest or 'default'), opts['rev'])
2066 ui.expandpath(dest or 'default-push', dest or 'default'), opts['rev'])
2067 cmdutil.setremoteconfig(ui, opts)
2067 cmdutil.setremoteconfig(ui, opts)
2068
2068
2069 other = hg.repository(ui, dest)
2069 other = hg.repository(ui, dest)
2070 ui.status('pushing to %s\n' % util.hidepassword(dest))
2070 ui.status('pushing to %s\n' % util.hidepassword(dest))
2071 if revs:
2071 if revs:
2072 revs = [repo.lookup(rev) for rev in revs]
2072 revs = [repo.lookup(rev) for rev in revs]
2073 r = repo.push(other, opts['force'], revs=revs)
2073 r = repo.push(other, opts['force'], revs=revs)
2074 return r == 0
2074 return r == 0
2075
2075
2076 def rawcommit(ui, repo, *pats, **opts):
2076 def rawcommit(ui, repo, *pats, **opts):
2077 """raw commit interface (DEPRECATED)
2077 """raw commit interface (DEPRECATED)
2078
2078
2079 (DEPRECATED)
2079 (DEPRECATED)
2080 Lowlevel commit, for use in helper scripts.
2080 Lowlevel commit, for use in helper scripts.
2081
2081
2082 This command is not intended to be used by normal users, as it is
2082 This command is not intended to be used by normal users, as it is
2083 primarily useful for importing from other SCMs.
2083 primarily useful for importing from other SCMs.
2084
2084
2085 This command is now deprecated and will be removed in a future
2085 This command is now deprecated and will be removed in a future
2086 release, please use debugsetparents and commit instead.
2086 release, please use debugsetparents and commit instead.
2087 """
2087 """
2088
2088
2089 ui.warn(_("(the rawcommit command is deprecated)\n"))
2089 ui.warn(_("(the rawcommit command is deprecated)\n"))
2090
2090
2091 message = cmdutil.logmessage(opts)
2091 message = cmdutil.logmessage(opts)
2092
2092
2093 files, match, anypats = cmdutil.matchpats(repo, pats, opts)
2093 files, match, anypats = cmdutil.matchpats(repo, pats, opts)
2094 if opts['files']:
2094 if opts['files']:
2095 files += open(opts['files']).read().splitlines()
2095 files += open(opts['files']).read().splitlines()
2096
2096
2097 parents = [repo.lookup(p) for p in opts['parent']]
2097 parents = [repo.lookup(p) for p in opts['parent']]
2098
2098
2099 try:
2099 try:
2100 repo.rawcommit(files, message, opts['user'], opts['date'], *parents)
2100 repo.rawcommit(files, message, opts['user'], opts['date'], *parents)
2101 except ValueError, inst:
2101 except ValueError, inst:
2102 raise util.Abort(str(inst))
2102 raise util.Abort(str(inst))
2103
2103
2104 def recover(ui, repo):
2104 def recover(ui, repo):
2105 """roll back an interrupted transaction
2105 """roll back an interrupted transaction
2106
2106
2107 Recover from an interrupted commit or pull.
2107 Recover from an interrupted commit or pull.
2108
2108
2109 This command tries to fix the repository status after an interrupted
2109 This command tries to fix the repository status after an interrupted
2110 operation. It should only be necessary when Mercurial suggests it.
2110 operation. It should only be necessary when Mercurial suggests it.
2111 """
2111 """
2112 if repo.recover():
2112 if repo.recover():
2113 return hg.verify(repo)
2113 return hg.verify(repo)
2114 return 1
2114 return 1
2115
2115
2116 def remove(ui, repo, *pats, **opts):
2116 def remove(ui, repo, *pats, **opts):
2117 """remove the specified files on the next commit
2117 """remove the specified files on the next commit
2118
2118
2119 Schedule the indicated files for removal from the repository.
2119 Schedule the indicated files for removal from the repository.
2120
2120
2121 This only removes files from the current branch, not from the
2121 This only removes files from the current branch, not from the
2122 entire project history. If the files still exist in the working
2122 entire project history. If the files still exist in the working
2123 directory, they will be deleted from it. If invoked with --after,
2123 directory, they will be deleted from it. If invoked with --after,
2124 files are marked as removed, but not actually unlinked unless --force
2124 files are marked as removed, but not actually unlinked unless --force
2125 is also given. Without exact file names, --after will only mark
2125 is also given. Without exact file names, --after will only mark
2126 files as removed if they are no longer in the working directory.
2126 files as removed if they are no longer in the working directory.
2127
2127
2128 This command schedules the files to be removed at the next commit.
2128 This command schedules the files to be removed at the next commit.
2129 To undo a remove before that, see hg revert.
2129 To undo a remove before that, see hg revert.
2130
2130
2131 Modified files and added files are not removed by default. To
2131 Modified files and added files are not removed by default. To
2132 remove them, use the -f/--force option.
2132 remove them, use the -f/--force option.
2133 """
2133 """
2134 if not opts['after'] and not pats:
2134 if not opts['after'] and not pats:
2135 raise util.Abort(_('no files specified'))
2135 raise util.Abort(_('no files specified'))
2136 files, matchfn, anypats = cmdutil.matchpats(repo, pats, opts)
2136 files, matchfn, anypats = cmdutil.matchpats(repo, pats, opts)
2137 exact = dict.fromkeys(files)
2137 exact = dict.fromkeys(files)
2138 mardu = map(dict.fromkeys, repo.status(files=files, match=matchfn))[:5]
2138 mardu = map(dict.fromkeys, repo.status(files=files, match=matchfn))[:5]
2139 modified, added, removed, deleted, unknown = mardu
2139 modified, added, removed, deleted, unknown = mardu
2140 remove, forget = [], []
2140 remove, forget = [], []
2141 for src, abs, rel, exact in cmdutil.walk(repo, pats, opts):
2141 for src, abs, rel, exact in cmdutil.walk(repo, pats, opts):
2142 reason = None
2142 reason = None
2143 if abs in modified and not opts['force']:
2143 if abs in modified and not opts['force']:
2144 reason = _('is modified (use -f to force removal)')
2144 reason = _('is modified (use -f to force removal)')
2145 elif abs in added:
2145 elif abs in added:
2146 if opts['force']:
2146 if opts['force']:
2147 forget.append(abs)
2147 forget.append(abs)
2148 continue
2148 continue
2149 reason = _('has been marked for add (use -f to force removal)')
2149 reason = _('has been marked for add (use -f to force removal)')
2150 exact = 1 # force the message
2150 exact = 1 # force the message
2151 elif abs not in repo.dirstate:
2151 elif abs not in repo.dirstate:
2152 reason = _('is not managed')
2152 reason = _('is not managed')
2153 elif opts['after'] and not exact and abs not in deleted:
2153 elif opts['after'] and not exact and abs not in deleted:
2154 continue
2154 continue
2155 elif abs in removed:
2155 elif abs in removed:
2156 continue
2156 continue
2157 if reason:
2157 if reason:
2158 if exact:
2158 if exact:
2159 ui.warn(_('not removing %s: file %s\n') % (rel, reason))
2159 ui.warn(_('not removing %s: file %s\n') % (rel, reason))
2160 else:
2160 else:
2161 if ui.verbose or not exact:
2161 if ui.verbose or not exact:
2162 ui.status(_('removing %s\n') % rel)
2162 ui.status(_('removing %s\n') % rel)
2163 remove.append(abs)
2163 remove.append(abs)
2164 repo.forget(forget)
2164 repo.forget(forget)
2165 repo.remove(remove, unlink=opts['force'] or not opts['after'])
2165 repo.remove(remove, unlink=opts['force'] or not opts['after'])
2166
2166
2167 def rename(ui, repo, *pats, **opts):
2167 def rename(ui, repo, *pats, **opts):
2168 """rename files; equivalent of copy + remove
2168 """rename files; equivalent of copy + remove
2169
2169
2170 Mark dest as copies of sources; mark sources for deletion. If
2170 Mark dest as copies of sources; mark sources for deletion. If
2171 dest is a directory, copies are put in that directory. If dest is
2171 dest is a directory, copies are put in that directory. If dest is
2172 a file, there can only be one source.
2172 a file, there can only be one source.
2173
2173
2174 By default, this command copies the contents of files as they
2174 By default, this command copies the contents of files as they
2175 stand in the working directory. If invoked with --after, the
2175 stand in the working directory. If invoked with --after, the
2176 operation is recorded, but no copying is performed.
2176 operation is recorded, but no copying is performed.
2177
2177
2178 This command takes effect in the next commit. To undo a rename
2178 This command takes effect in the next commit. To undo a rename
2179 before that, see hg revert.
2179 before that, see hg revert.
2180 """
2180 """
2181 wlock = repo.wlock(False)
2181 wlock = repo.wlock(False)
2182 try:
2182 try:
2183 return cmdutil.copy(ui, repo, pats, opts, rename=True)
2183 return cmdutil.copy(ui, repo, pats, opts, rename=True)
2184 finally:
2184 finally:
2185 del wlock
2185 del wlock
2186
2186
2187 def revert(ui, repo, *pats, **opts):
2187 def revert(ui, repo, *pats, **opts):
2188 """restore individual files or dirs to an earlier state
2188 """restore individual files or dirs to an earlier state
2189
2189
2190 (use update -r to check out earlier revisions, revert does not
2190 (use update -r to check out earlier revisions, revert does not
2191 change the working dir parents)
2191 change the working dir parents)
2192
2192
2193 With no revision specified, revert the named files or directories
2193 With no revision specified, revert the named files or directories
2194 to the contents they had in the parent of the working directory.
2194 to the contents they had in the parent of the working directory.
2195 This restores the contents of the affected files to an unmodified
2195 This restores the contents of the affected files to an unmodified
2196 state and unschedules adds, removes, copies, and renames. If the
2196 state and unschedules adds, removes, copies, and renames. If the
2197 working directory has two parents, you must explicitly specify the
2197 working directory has two parents, you must explicitly specify the
2198 revision to revert to.
2198 revision to revert to.
2199
2199
2200 Using the -r option, revert the given files or directories to their
2200 Using the -r option, revert the given files or directories to their
2201 contents as of a specific revision. This can be helpful to "roll
2201 contents as of a specific revision. This can be helpful to "roll
2202 back" some or all of an earlier change.
2202 back" some or all of an earlier change.
2203 See 'hg help dates' for a list of formats valid for -d/--date.
2203 See 'hg help dates' for a list of formats valid for -d/--date.
2204
2204
2205 Revert modifies the working directory. It does not commit any
2205 Revert modifies the working directory. It does not commit any
2206 changes, or change the parent of the working directory. If you
2206 changes, or change the parent of the working directory. If you
2207 revert to a revision other than the parent of the working
2207 revert to a revision other than the parent of the working
2208 directory, the reverted files will thus appear modified
2208 directory, the reverted files will thus appear modified
2209 afterwards.
2209 afterwards.
2210
2210
2211 If a file has been deleted, it is restored. If the executable
2211 If a file has been deleted, it is restored. If the executable
2212 mode of a file was changed, it is reset.
2212 mode of a file was changed, it is reset.
2213
2213
2214 If names are given, all files matching the names are reverted.
2214 If names are given, all files matching the names are reverted.
2215 If no arguments are given, no files are reverted.
2215 If no arguments are given, no files are reverted.
2216
2216
2217 Modified files are saved with a .orig suffix before reverting.
2217 Modified files are saved with a .orig suffix before reverting.
2218 To disable these backups, use --no-backup.
2218 To disable these backups, use --no-backup.
2219 """
2219 """
2220
2220
2221 if opts["date"]:
2221 if opts["date"]:
2222 if opts["rev"]:
2222 if opts["rev"]:
2223 raise util.Abort(_("you can't specify a revision and a date"))
2223 raise util.Abort(_("you can't specify a revision and a date"))
2224 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
2224 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
2225
2225
2226 if not pats and not opts['all']:
2226 if not pats and not opts['all']:
2227 raise util.Abort(_('no files or directories specified; '
2227 raise util.Abort(_('no files or directories specified; '
2228 'use --all to revert the whole repo'))
2228 'use --all to revert the whole repo'))
2229
2229
2230 parent, p2 = repo.dirstate.parents()
2230 parent, p2 = repo.dirstate.parents()
2231 if not opts['rev'] and p2 != nullid:
2231 if not opts['rev'] and p2 != nullid:
2232 raise util.Abort(_('uncommitted merge - please provide a '
2232 raise util.Abort(_('uncommitted merge - please provide a '
2233 'specific revision'))
2233 'specific revision'))
2234 ctx = repo.changectx(opts['rev'])
2234 ctx = repo.changectx(opts['rev'])
2235 node = ctx.node()
2235 node = ctx.node()
2236 mf = ctx.manifest()
2236 mf = ctx.manifest()
2237 if node == parent:
2237 if node == parent:
2238 pmf = mf
2238 pmf = mf
2239 else:
2239 else:
2240 pmf = None
2240 pmf = None
2241
2241
2242 # need all matching names in dirstate and manifest of target rev,
2242 # need all matching names in dirstate and manifest of target rev,
2243 # so have to walk both. do not print errors if files exist in one
2243 # so have to walk both. do not print errors if files exist in one
2244 # but not other.
2244 # but not other.
2245
2245
2246 names = {}
2246 names = {}
2247
2247
2248 wlock = repo.wlock()
2248 wlock = repo.wlock()
2249 try:
2249 try:
2250 # walk dirstate.
2250 # walk dirstate.
2251 files = []
2251 files = []
2252 for src, abs, rel, exact in cmdutil.walk(repo, pats, opts,
2252 for src, abs, rel, exact in cmdutil.walk(repo, pats, opts,
2253 badmatch=mf.has_key):
2253 badmatch=mf.has_key):
2254 names[abs] = (rel, exact)
2254 names[abs] = (rel, exact)
2255 if src != 'b':
2255 if src != 'b':
2256 files.append(abs)
2256 files.append(abs)
2257
2257
2258 # walk target manifest.
2258 # walk target manifest.
2259
2259
2260 def badmatch(path):
2260 def badmatch(path):
2261 if path in names:
2261 if path in names:
2262 return True
2262 return True
2263 path_ = path + '/'
2263 path_ = path + '/'
2264 for f in names:
2264 for f in names:
2265 if f.startswith(path_):
2265 if f.startswith(path_):
2266 return True
2266 return True
2267 return False
2267 return False
2268
2268
2269 for src, abs, rel, exact in cmdutil.walk(repo, pats, opts, node=node,
2269 for src, abs, rel, exact in cmdutil.walk(repo, pats, opts, node=node,
2270 badmatch=badmatch):
2270 badmatch=badmatch):
2271 if abs in names or src == 'b':
2271 if abs in names or src == 'b':
2272 continue
2272 continue
2273 names[abs] = (rel, exact)
2273 names[abs] = (rel, exact)
2274
2274
2275 changes = repo.status(files=files, match=names.has_key)[:4]
2275 changes = repo.status(files=files, match=names.has_key)[:4]
2276 modified, added, removed, deleted = map(dict.fromkeys, changes)
2276 modified, added, removed, deleted = map(dict.fromkeys, changes)
2277
2277
2278 # if f is a rename, also revert the source
2278 # if f is a rename, also revert the source
2279 cwd = repo.getcwd()
2279 cwd = repo.getcwd()
2280 for f in added:
2280 for f in added:
2281 src = repo.dirstate.copied(f)
2281 src = repo.dirstate.copied(f)
2282 if src and src not in names and repo.dirstate[src] == 'r':
2282 if src and src not in names and repo.dirstate[src] == 'r':
2283 removed[src] = None
2283 removed[src] = None
2284 names[src] = (repo.pathto(src, cwd), True)
2284 names[src] = (repo.pathto(src, cwd), True)
2285
2285
2286 def removeforget(abs):
2286 def removeforget(abs):
2287 if repo.dirstate[abs] == 'a':
2287 if repo.dirstate[abs] == 'a':
2288 return _('forgetting %s\n')
2288 return _('forgetting %s\n')
2289 return _('removing %s\n')
2289 return _('removing %s\n')
2290
2290
2291 revert = ([], _('reverting %s\n'))
2291 revert = ([], _('reverting %s\n'))
2292 add = ([], _('adding %s\n'))
2292 add = ([], _('adding %s\n'))
2293 remove = ([], removeforget)
2293 remove = ([], removeforget)
2294 undelete = ([], _('undeleting %s\n'))
2294 undelete = ([], _('undeleting %s\n'))
2295
2295
2296 disptable = (
2296 disptable = (
2297 # dispatch table:
2297 # dispatch table:
2298 # file state
2298 # file state
2299 # action if in target manifest
2299 # action if in target manifest
2300 # action if not in target manifest
2300 # action if not in target manifest
2301 # make backup if in target manifest
2301 # make backup if in target manifest
2302 # make backup if not in target manifest
2302 # make backup if not in target manifest
2303 (modified, revert, remove, True, True),
2303 (modified, revert, remove, True, True),
2304 (added, revert, remove, True, False),
2304 (added, revert, remove, True, False),
2305 (removed, undelete, None, False, False),
2305 (removed, undelete, None, False, False),
2306 (deleted, revert, remove, False, False),
2306 (deleted, revert, remove, False, False),
2307 )
2307 )
2308
2308
2309 entries = names.items()
2309 entries = names.items()
2310 entries.sort()
2310 entries.sort()
2311
2311
2312 for abs, (rel, exact) in entries:
2312 for abs, (rel, exact) in entries:
2313 mfentry = mf.get(abs)
2313 mfentry = mf.get(abs)
2314 target = repo.wjoin(abs)
2314 target = repo.wjoin(abs)
2315 def handle(xlist, dobackup):
2315 def handle(xlist, dobackup):
2316 xlist[0].append(abs)
2316 xlist[0].append(abs)
2317 if dobackup and not opts['no_backup'] and util.lexists(target):
2317 if dobackup and not opts['no_backup'] and util.lexists(target):
2318 bakname = "%s.orig" % rel
2318 bakname = "%s.orig" % rel
2319 ui.note(_('saving current version of %s as %s\n') %
2319 ui.note(_('saving current version of %s as %s\n') %
2320 (rel, bakname))
2320 (rel, bakname))
2321 if not opts.get('dry_run'):
2321 if not opts.get('dry_run'):
2322 util.copyfile(target, bakname)
2322 util.copyfile(target, bakname)
2323 if ui.verbose or not exact:
2323 if ui.verbose or not exact:
2324 msg = xlist[1]
2324 msg = xlist[1]
2325 if not isinstance(msg, basestring):
2325 if not isinstance(msg, basestring):
2326 msg = msg(abs)
2326 msg = msg(abs)
2327 ui.status(msg % rel)
2327 ui.status(msg % rel)
2328 for table, hitlist, misslist, backuphit, backupmiss in disptable:
2328 for table, hitlist, misslist, backuphit, backupmiss in disptable:
2329 if abs not in table: continue
2329 if abs not in table: continue
2330 # file has changed in dirstate
2330 # file has changed in dirstate
2331 if mfentry:
2331 if mfentry:
2332 handle(hitlist, backuphit)
2332 handle(hitlist, backuphit)
2333 elif misslist is not None:
2333 elif misslist is not None:
2334 handle(misslist, backupmiss)
2334 handle(misslist, backupmiss)
2335 break
2335 break
2336 else:
2336 else:
2337 if abs not in repo.dirstate:
2337 if abs not in repo.dirstate:
2338 if mfentry:
2338 if mfentry:
2339 handle(add, True)
2339 handle(add, True)
2340 elif exact:
2340 elif exact:
2341 ui.warn(_('file not managed: %s\n') % rel)
2341 ui.warn(_('file not managed: %s\n') % rel)
2342 continue
2342 continue
2343 # file has not changed in dirstate
2343 # file has not changed in dirstate
2344 if node == parent:
2344 if node == parent:
2345 if exact: ui.warn(_('no changes needed to %s\n') % rel)
2345 if exact: ui.warn(_('no changes needed to %s\n') % rel)
2346 continue
2346 continue
2347 if pmf is None:
2347 if pmf is None:
2348 # only need parent manifest in this unlikely case,
2348 # only need parent manifest in this unlikely case,
2349 # so do not read by default
2349 # so do not read by default
2350 pmf = repo.changectx(parent).manifest()
2350 pmf = repo.changectx(parent).manifest()
2351 if abs in pmf:
2351 if abs in pmf:
2352 if mfentry:
2352 if mfentry:
2353 # if version of file is same in parent and target
2353 # if version of file is same in parent and target
2354 # manifests, do nothing
2354 # manifests, do nothing
2355 if (pmf[abs] != mfentry or
2355 if (pmf[abs] != mfentry or
2356 pmf.flags(abs) != mf.flags(abs)):
2356 pmf.flags(abs) != mf.flags(abs)):
2357 handle(revert, False)
2357 handle(revert, False)
2358 else:
2358 else:
2359 handle(remove, False)
2359 handle(remove, False)
2360
2360
2361 if not opts.get('dry_run'):
2361 if not opts.get('dry_run'):
2362 def checkout(f):
2362 def checkout(f):
2363 fc = ctx[f]
2363 fc = ctx[f]
2364 repo.wwrite(f, fc.data(), fc.fileflags())
2364 repo.wwrite(f, fc.data(), fc.fileflags())
2365
2365
2366 audit_path = util.path_auditor(repo.root)
2366 audit_path = util.path_auditor(repo.root)
2367 for f in remove[0]:
2367 for f in remove[0]:
2368 if repo.dirstate[f] == 'a':
2368 if repo.dirstate[f] == 'a':
2369 repo.dirstate.forget(f)
2369 repo.dirstate.forget(f)
2370 continue
2370 continue
2371 audit_path(f)
2371 audit_path(f)
2372 try:
2372 try:
2373 util.unlink(repo.wjoin(f))
2373 util.unlink(repo.wjoin(f))
2374 except OSError:
2374 except OSError:
2375 pass
2375 pass
2376 repo.dirstate.remove(f)
2376 repo.dirstate.remove(f)
2377
2377
2378 for f in revert[0]:
2378 for f in revert[0]:
2379 checkout(f)
2379 checkout(f)
2380
2380
2381 for f in add[0]:
2381 for f in add[0]:
2382 checkout(f)
2382 checkout(f)
2383 repo.dirstate.add(f)
2383 repo.dirstate.add(f)
2384
2384
2385 normal = repo.dirstate.normallookup
2385 normal = repo.dirstate.normallookup
2386 if node == parent and p2 == nullid:
2386 if node == parent and p2 == nullid:
2387 normal = repo.dirstate.normal
2387 normal = repo.dirstate.normal
2388 for f in undelete[0]:
2388 for f in undelete[0]:
2389 checkout(f)
2389 checkout(f)
2390 normal(f)
2390 normal(f)
2391
2391
2392 finally:
2392 finally:
2393 del wlock
2393 del wlock
2394
2394
2395 def rollback(ui, repo):
2395 def rollback(ui, repo):
2396 """roll back the last transaction
2396 """roll back the last transaction
2397
2397
2398 This command should be used with care. There is only one level of
2398 This command should be used with care. There is only one level of
2399 rollback, and there is no way to undo a rollback. It will also
2399 rollback, and there is no way to undo a rollback. It will also
2400 restore the dirstate at the time of the last transaction, losing
2400 restore the dirstate at the time of the last transaction, losing
2401 any dirstate changes since that time.
2401 any dirstate changes since that time.
2402
2402
2403 Transactions are used to encapsulate the effects of all commands
2403 Transactions are used to encapsulate the effects of all commands
2404 that create new changesets or propagate existing changesets into a
2404 that create new changesets or propagate existing changesets into a
2405 repository. For example, the following commands are transactional,
2405 repository. For example, the following commands are transactional,
2406 and their effects can be rolled back:
2406 and their effects can be rolled back:
2407
2407
2408 commit
2408 commit
2409 import
2409 import
2410 pull
2410 pull
2411 push (with this repository as destination)
2411 push (with this repository as destination)
2412 unbundle
2412 unbundle
2413
2413
2414 This command is not intended for use on public repositories. Once
2414 This command is not intended for use on public repositories. Once
2415 changes are visible for pull by other users, rolling a transaction
2415 changes are visible for pull by other users, rolling a transaction
2416 back locally is ineffective (someone else may already have pulled
2416 back locally is ineffective (someone else may already have pulled
2417 the changes). Furthermore, a race is possible with readers of the
2417 the changes). Furthermore, a race is possible with readers of the
2418 repository; for example an in-progress pull from the repository
2418 repository; for example an in-progress pull from the repository
2419 may fail if a rollback is performed.
2419 may fail if a rollback is performed.
2420 """
2420 """
2421 repo.rollback()
2421 repo.rollback()
2422
2422
2423 def root(ui, repo):
2423 def root(ui, repo):
2424 """print the root (top) of the current working dir
2424 """print the root (top) of the current working dir
2425
2425
2426 Print the root directory of the current repository.
2426 Print the root directory of the current repository.
2427 """
2427 """
2428 ui.write(repo.root + "\n")
2428 ui.write(repo.root + "\n")
2429
2429
2430 def serve(ui, repo, **opts):
2430 def serve(ui, repo, **opts):
2431 """export the repository via HTTP
2431 """export the repository via HTTP
2432
2432
2433 Start a local HTTP repository browser and pull server.
2433 Start a local HTTP repository browser and pull server.
2434
2434
2435 By default, the server logs accesses to stdout and errors to
2435 By default, the server logs accesses to stdout and errors to
2436 stderr. Use the "-A" and "-E" options to log to files.
2436 stderr. Use the "-A" and "-E" options to log to files.
2437 """
2437 """
2438
2438
2439 if opts["stdio"]:
2439 if opts["stdio"]:
2440 if repo is None:
2440 if repo is None:
2441 raise RepoError(_("There is no Mercurial repository here"
2441 raise RepoError(_("There is no Mercurial repository here"
2442 " (.hg not found)"))
2442 " (.hg not found)"))
2443 s = sshserver.sshserver(ui, repo)
2443 s = sshserver.sshserver(ui, repo)
2444 s.serve_forever()
2444 s.serve_forever()
2445
2445
2446 parentui = ui.parentui or ui
2446 parentui = ui.parentui or ui
2447 optlist = ("name templates style address port prefix ipv6"
2447 optlist = ("name templates style address port prefix ipv6"
2448 " accesslog errorlog webdir_conf certificate")
2448 " accesslog errorlog webdir_conf certificate")
2449 for o in optlist.split():
2449 for o in optlist.split():
2450 if opts[o]:
2450 if opts[o]:
2451 parentui.setconfig("web", o, str(opts[o]))
2451 parentui.setconfig("web", o, str(opts[o]))
2452 if (repo is not None) and (repo.ui != parentui):
2452 if (repo is not None) and (repo.ui != parentui):
2453 repo.ui.setconfig("web", o, str(opts[o]))
2453 repo.ui.setconfig("web", o, str(opts[o]))
2454
2454
2455 if repo is None and not ui.config("web", "webdir_conf"):
2455 if repo is None and not ui.config("web", "webdir_conf"):
2456 raise RepoError(_("There is no Mercurial repository here"
2456 raise RepoError(_("There is no Mercurial repository here"
2457 " (.hg not found)"))
2457 " (.hg not found)"))
2458
2458
2459 class service:
2459 class service:
2460 def init(self):
2460 def init(self):
2461 util.set_signal_handler()
2461 util.set_signal_handler()
2462 try:
2462 try:
2463 self.httpd = hgweb.server.create_server(parentui, repo)
2463 self.httpd = hgweb.server.create_server(parentui, repo)
2464 except socket.error, inst:
2464 except socket.error, inst:
2465 raise util.Abort(_('cannot start server: ') + inst.args[1])
2465 raise util.Abort(_('cannot start server: ') + inst.args[1])
2466
2466
2467 if not ui.verbose: return
2467 if not ui.verbose: return
2468
2468
2469 if self.httpd.prefix:
2469 if self.httpd.prefix:
2470 prefix = self.httpd.prefix.strip('/') + '/'
2470 prefix = self.httpd.prefix.strip('/') + '/'
2471 else:
2471 else:
2472 prefix = ''
2472 prefix = ''
2473
2473
2474 if self.httpd.port != 80:
2474 if self.httpd.port != 80:
2475 ui.status(_('listening at http://%s:%d/%s\n') %
2475 ui.status(_('listening at http://%s:%d/%s\n') %
2476 (self.httpd.addr, self.httpd.port, prefix))
2476 (self.httpd.addr, self.httpd.port, prefix))
2477 else:
2477 else:
2478 ui.status(_('listening at http://%s/%s\n') %
2478 ui.status(_('listening at http://%s/%s\n') %
2479 (self.httpd.addr, prefix))
2479 (self.httpd.addr, prefix))
2480
2480
2481 def run(self):
2481 def run(self):
2482 self.httpd.serve_forever()
2482 self.httpd.serve_forever()
2483
2483
2484 service = service()
2484 service = service()
2485
2485
2486 cmdutil.service(opts, initfn=service.init, runfn=service.run)
2486 cmdutil.service(opts, initfn=service.init, runfn=service.run)
2487
2487
2488 def status(ui, repo, *pats, **opts):
2488 def status(ui, repo, *pats, **opts):
2489 """show changed files in the working directory
2489 """show changed files in the working directory
2490
2490
2491 Show status of files in the repository. If names are given, only
2491 Show status of files in the repository. If names are given, only
2492 files that match are shown. Files that are clean or ignored or
2492 files that match are shown. Files that are clean or ignored or
2493 source of a copy/move operation, are not listed unless -c (clean),
2493 source of a copy/move operation, are not listed unless -c (clean),
2494 -i (ignored), -C (copies) or -A is given. Unless options described
2494 -i (ignored), -C (copies) or -A is given. Unless options described
2495 with "show only ..." are given, the options -mardu are used.
2495 with "show only ..." are given, the options -mardu are used.
2496
2496
2497 Option -q/--quiet hides untracked (unknown and ignored) files
2497 Option -q/--quiet hides untracked (unknown and ignored) files
2498 unless explicitly requested with -u/--unknown or -i/-ignored.
2498 unless explicitly requested with -u/--unknown or -i/-ignored.
2499
2499
2500 NOTE: status may appear to disagree with diff if permissions have
2500 NOTE: status may appear to disagree with diff if permissions have
2501 changed or a merge has occurred. The standard diff format does not
2501 changed or a merge has occurred. The standard diff format does not
2502 report permission changes and diff only reports changes relative
2502 report permission changes and diff only reports changes relative
2503 to one merge parent.
2503 to one merge parent.
2504
2504
2505 If one revision is given, it is used as the base revision.
2505 If one revision is given, it is used as the base revision.
2506 If two revisions are given, the difference between them is shown.
2506 If two revisions are given, the difference between them is shown.
2507
2507
2508 The codes used to show the status of files are:
2508 The codes used to show the status of files are:
2509 M = modified
2509 M = modified
2510 A = added
2510 A = added
2511 R = removed
2511 R = removed
2512 C = clean
2512 C = clean
2513 ! = deleted, but still tracked
2513 ! = deleted, but still tracked
2514 ? = not tracked
2514 ? = not tracked
2515 I = ignored
2515 I = ignored
2516 = the previous added file was copied from here
2516 = the previous added file was copied from here
2517 """
2517 """
2518
2518
2519 all = opts['all']
2519 all = opts['all']
2520 node1, node2 = cmdutil.revpair(repo, opts.get('rev'))
2520 node1, node2 = cmdutil.revpair(repo, opts.get('rev'))
2521
2521
2522 files, matchfn, anypats = cmdutil.matchpats(repo, pats, opts)
2522 files, matchfn, anypats = cmdutil.matchpats(repo, pats, opts)
2523 cwd = (pats and repo.getcwd()) or ''
2523 cwd = (pats and repo.getcwd()) or ''
2524 modified, added, removed, deleted, unknown, ignored, clean = [
2524 modified, added, removed, deleted, unknown, ignored, clean = [
2525 n for n in repo.status(node1=node1, node2=node2, files=files,
2525 n for n in repo.status(node1=node1, node2=node2, files=files,
2526 match=matchfn,
2526 match=matchfn,
2527 list_ignored=opts['ignored']
2527 list_ignored=opts['ignored']
2528 or all and not ui.quiet,
2528 or all and not ui.quiet,
2529 list_clean=opts['clean'] or all,
2529 list_clean=opts['clean'] or all,
2530 list_unknown=opts['unknown']
2530 list_unknown=opts['unknown']
2531 or not (ui.quiet or
2531 or not (ui.quiet or
2532 opts['modified'] or
2532 opts['modified'] or
2533 opts['added'] or
2533 opts['added'] or
2534 opts['removed'] or
2534 opts['removed'] or
2535 opts['deleted'] or
2535 opts['deleted'] or
2536 opts['ignored']))]
2536 opts['ignored']))]
2537
2537
2538 changetypes = (('modified', 'M', modified),
2538 changetypes = (('modified', 'M', modified),
2539 ('added', 'A', added),
2539 ('added', 'A', added),
2540 ('removed', 'R', removed),
2540 ('removed', 'R', removed),
2541 ('deleted', '!', deleted),
2541 ('deleted', '!', deleted),
2542 ('unknown', '?', unknown),
2542 ('unknown', '?', unknown),
2543 ('ignored', 'I', ignored))
2543 ('ignored', 'I', ignored))
2544
2544
2545 explicit_changetypes = changetypes + (('clean', 'C', clean),)
2545 explicit_changetypes = changetypes + (('clean', 'C', clean),)
2546
2546
2547 end = opts['print0'] and '\0' or '\n'
2547 end = opts['print0'] and '\0' or '\n'
2548
2548
2549 for opt, char, changes in ([ct for ct in explicit_changetypes
2549 for opt, char, changes in ([ct for ct in explicit_changetypes
2550 if all or opts[ct[0]]]
2550 if all or opts[ct[0]]]
2551 or changetypes):
2551 or changetypes):
2552
2552
2553 if opts['no_status']:
2553 if opts['no_status']:
2554 format = "%%s%s" % end
2554 format = "%%s%s" % end
2555 else:
2555 else:
2556 format = "%s %%s%s" % (char, end)
2556 format = "%s %%s%s" % (char, end)
2557
2557
2558 for f in changes:
2558 for f in changes:
2559 ui.write(format % repo.pathto(f, cwd))
2559 ui.write(format % repo.pathto(f, cwd))
2560 if ((all or opts.get('copies')) and not opts.get('no_status')):
2560 if ((all or opts.get('copies')) and not opts.get('no_status')):
2561 copied = repo.dirstate.copied(f)
2561 copied = repo.dirstate.copied(f)
2562 if copied:
2562 if copied:
2563 ui.write(' %s%s' % (repo.pathto(copied, cwd), end))
2563 ui.write(' %s%s' % (repo.pathto(copied, cwd), end))
2564
2564
2565 def tag(ui, repo, name, rev_=None, **opts):
2565 def tag(ui, repo, name, rev_=None, **opts):
2566 """add a tag for the current or given revision
2566 """add a tag for the current or given revision
2567
2567
2568 Name a particular revision using <name>.
2568 Name a particular revision using <name>.
2569
2569
2570 Tags are used to name particular revisions of the repository and are
2570 Tags are used to name particular revisions of the repository and are
2571 very useful to compare different revisions, to go back to significant
2571 very useful to compare different revisions, to go back to significant
2572 earlier versions or to mark branch points as releases, etc.
2572 earlier versions or to mark branch points as releases, etc.
2573
2573
2574 If no revision is given, the parent of the working directory is used,
2574 If no revision is given, the parent of the working directory is used,
2575 or tip if no revision is checked out.
2575 or tip if no revision is checked out.
2576
2576
2577 To facilitate version control, distribution, and merging of tags,
2577 To facilitate version control, distribution, and merging of tags,
2578 they are stored as a file named ".hgtags" which is managed
2578 they are stored as a file named ".hgtags" which is managed
2579 similarly to other project files and can be hand-edited if
2579 similarly to other project files and can be hand-edited if
2580 necessary. The file '.hg/localtags' is used for local tags (not
2580 necessary. The file '.hg/localtags' is used for local tags (not
2581 shared among repositories).
2581 shared among repositories).
2582
2582
2583 See 'hg help dates' for a list of formats valid for -d/--date.
2583 See 'hg help dates' for a list of formats valid for -d/--date.
2584 """
2584 """
2585 if name in ['tip', '.', 'null']:
2585 if name in ['tip', '.', 'null']:
2586 raise util.Abort(_("the name '%s' is reserved") % name)
2586 raise util.Abort(_("the name '%s' is reserved") % name)
2587 if rev_ is not None:
2587 if rev_ is not None:
2588 ui.warn(_("use of 'hg tag NAME [REV]' is deprecated, "
2588 ui.warn(_("use of 'hg tag NAME [REV]' is deprecated, "
2589 "please use 'hg tag [-r REV] NAME' instead\n"))
2589 "please use 'hg tag [-r REV] NAME' instead\n"))
2590 if opts['rev']:
2590 if opts['rev']:
2591 raise util.Abort(_("use only one form to specify the revision"))
2591 raise util.Abort(_("use only one form to specify the revision"))
2592 if opts['rev'] and opts['remove']:
2592 if opts['rev'] and opts['remove']:
2593 raise util.Abort(_("--rev and --remove are incompatible"))
2593 raise util.Abort(_("--rev and --remove are incompatible"))
2594 if opts['rev']:
2594 if opts['rev']:
2595 rev_ = opts['rev']
2595 rev_ = opts['rev']
2596 message = opts['message']
2596 message = opts['message']
2597 if opts['remove']:
2597 if opts['remove']:
2598 tagtype = repo.tagtype(name)
2598 tagtype = repo.tagtype(name)
2599
2599
2600 if not tagtype:
2600 if not tagtype:
2601 raise util.Abort(_('tag %s does not exist') % name)
2601 raise util.Abort(_('tag %s does not exist') % name)
2602 if opts['local'] and tagtype == 'global':
2602 if opts['local'] and tagtype == 'global':
2603 raise util.Abort(_('%s tag is global') % name)
2603 raise util.Abort(_('%s tag is global') % name)
2604 if not opts['local'] and tagtype == 'local':
2604 if not opts['local'] and tagtype == 'local':
2605 raise util.Abort(_('%s tag is local') % name)
2605 raise util.Abort(_('%s tag is local') % name)
2606
2606
2607 rev_ = nullid
2607 rev_ = nullid
2608 if not message:
2608 if not message:
2609 message = _('Removed tag %s') % name
2609 message = _('Removed tag %s') % name
2610 elif name in repo.tags() and not opts['force']:
2610 elif name in repo.tags() and not opts['force']:
2611 raise util.Abort(_('a tag named %s already exists (use -f to force)')
2611 raise util.Abort(_('a tag named %s already exists (use -f to force)')
2612 % name)
2612 % name)
2613 if not rev_ and repo.dirstate.parents()[1] != nullid:
2613 if not rev_ and repo.dirstate.parents()[1] != nullid:
2614 raise util.Abort(_('uncommitted merge - please provide a '
2614 raise util.Abort(_('uncommitted merge - please provide a '
2615 'specific revision'))
2615 'specific revision'))
2616 r = repo.changectx(rev_).node()
2616 r = repo.changectx(rev_).node()
2617
2617
2618 if not message:
2618 if not message:
2619 message = _('Added tag %s for changeset %s') % (name, short(r))
2619 message = _('Added tag %s for changeset %s') % (name, short(r))
2620
2620
2621 repo.tag(name, r, message, opts['local'], opts['user'], opts['date'])
2621 date = opts.get('date')
2622 if date:
2623 date = util.parsedate(date)
2624
2625 repo.tag(name, r, message, opts['local'], opts['user'], date)
2622
2626
2623 def tags(ui, repo):
2627 def tags(ui, repo):
2624 """list repository tags
2628 """list repository tags
2625
2629
2626 List the repository tags.
2630 List the repository tags.
2627
2631
2628 This lists both regular and local tags. When the -v/--verbose switch
2632 This lists both regular and local tags. When the -v/--verbose switch
2629 is used, a third column "local" is printed for local tags.
2633 is used, a third column "local" is printed for local tags.
2630 """
2634 """
2631
2635
2632 l = repo.tagslist()
2636 l = repo.tagslist()
2633 l.reverse()
2637 l.reverse()
2634 hexfunc = ui.debugflag and hex or short
2638 hexfunc = ui.debugflag and hex or short
2635 tagtype = ""
2639 tagtype = ""
2636
2640
2637 for t, n in l:
2641 for t, n in l:
2638 if ui.quiet:
2642 if ui.quiet:
2639 ui.write("%s\n" % t)
2643 ui.write("%s\n" % t)
2640 continue
2644 continue
2641
2645
2642 try:
2646 try:
2643 hn = hexfunc(n)
2647 hn = hexfunc(n)
2644 r = "%5d:%s" % (repo.changelog.rev(n), hn)
2648 r = "%5d:%s" % (repo.changelog.rev(n), hn)
2645 except revlog.LookupError:
2649 except revlog.LookupError:
2646 r = " ?:%s" % hn
2650 r = " ?:%s" % hn
2647 else:
2651 else:
2648 spaces = " " * (30 - util.locallen(t))
2652 spaces = " " * (30 - util.locallen(t))
2649 if ui.verbose:
2653 if ui.verbose:
2650 if repo.tagtype(t) == 'local':
2654 if repo.tagtype(t) == 'local':
2651 tagtype = " local"
2655 tagtype = " local"
2652 else:
2656 else:
2653 tagtype = ""
2657 tagtype = ""
2654 ui.write("%s%s %s%s\n" % (t, spaces, r, tagtype))
2658 ui.write("%s%s %s%s\n" % (t, spaces, r, tagtype))
2655
2659
2656 def tip(ui, repo, **opts):
2660 def tip(ui, repo, **opts):
2657 """show the tip revision
2661 """show the tip revision
2658
2662
2659 Show the tip revision.
2663 Show the tip revision.
2660 """
2664 """
2661 cmdutil.show_changeset(ui, repo, opts).show(nullrev+repo.changelog.count())
2665 cmdutil.show_changeset(ui, repo, opts).show(nullrev+repo.changelog.count())
2662
2666
2663 def unbundle(ui, repo, fname1, *fnames, **opts):
2667 def unbundle(ui, repo, fname1, *fnames, **opts):
2664 """apply one or more changegroup files
2668 """apply one or more changegroup files
2665
2669
2666 Apply one or more compressed changegroup files generated by the
2670 Apply one or more compressed changegroup files generated by the
2667 bundle command.
2671 bundle command.
2668 """
2672 """
2669 fnames = (fname1,) + fnames
2673 fnames = (fname1,) + fnames
2670
2674
2671 lock = None
2675 lock = None
2672 try:
2676 try:
2673 lock = repo.lock()
2677 lock = repo.lock()
2674 for fname in fnames:
2678 for fname in fnames:
2675 if os.path.exists(fname):
2679 if os.path.exists(fname):
2676 f = open(fname, "rb")
2680 f = open(fname, "rb")
2677 else:
2681 else:
2678 f = urllib.urlopen(fname)
2682 f = urllib.urlopen(fname)
2679 gen = changegroup.readbundle(f, fname)
2683 gen = changegroup.readbundle(f, fname)
2680 modheads = repo.addchangegroup(gen, 'unbundle', 'bundle:' + fname)
2684 modheads = repo.addchangegroup(gen, 'unbundle', 'bundle:' + fname)
2681 finally:
2685 finally:
2682 del lock
2686 del lock
2683
2687
2684 return postincoming(ui, repo, modheads, opts['update'], None)
2688 return postincoming(ui, repo, modheads, opts['update'], None)
2685
2689
2686 def update(ui, repo, node=None, rev=None, clean=False, date=None):
2690 def update(ui, repo, node=None, rev=None, clean=False, date=None):
2687 """update working directory
2691 """update working directory
2688
2692
2689 Update the working directory to the specified revision, or the
2693 Update the working directory to the specified revision, or the
2690 tip of the current branch if none is specified.
2694 tip of the current branch if none is specified.
2691 See 'hg help dates' for a list of formats valid for -d/--date.
2695 See 'hg help dates' for a list of formats valid for -d/--date.
2692
2696
2693 If there are no outstanding changes in the working directory and
2697 If there are no outstanding changes in the working directory and
2694 there is a linear relationship between the current version and the
2698 there is a linear relationship between the current version and the
2695 requested version, the result is the requested version.
2699 requested version, the result is the requested version.
2696
2700
2697 To merge the working directory with another revision, use the
2701 To merge the working directory with another revision, use the
2698 merge command.
2702 merge command.
2699
2703
2700 By default, update will refuse to run if doing so would require
2704 By default, update will refuse to run if doing so would require
2701 discarding local changes.
2705 discarding local changes.
2702 """
2706 """
2703 if rev and node:
2707 if rev and node:
2704 raise util.Abort(_("please specify just one revision"))
2708 raise util.Abort(_("please specify just one revision"))
2705
2709
2706 if not rev:
2710 if not rev:
2707 rev = node
2711 rev = node
2708
2712
2709 if date:
2713 if date:
2710 if rev:
2714 if rev:
2711 raise util.Abort(_("you can't specify a revision and a date"))
2715 raise util.Abort(_("you can't specify a revision and a date"))
2712 rev = cmdutil.finddate(ui, repo, date)
2716 rev = cmdutil.finddate(ui, repo, date)
2713
2717
2714 if clean:
2718 if clean:
2715 return hg.clean(repo, rev)
2719 return hg.clean(repo, rev)
2716 else:
2720 else:
2717 return hg.update(repo, rev)
2721 return hg.update(repo, rev)
2718
2722
2719 def verify(ui, repo):
2723 def verify(ui, repo):
2720 """verify the integrity of the repository
2724 """verify the integrity of the repository
2721
2725
2722 Verify the integrity of the current repository.
2726 Verify the integrity of the current repository.
2723
2727
2724 This will perform an extensive check of the repository's
2728 This will perform an extensive check of the repository's
2725 integrity, validating the hashes and checksums of each entry in
2729 integrity, validating the hashes and checksums of each entry in
2726 the changelog, manifest, and tracked files, as well as the
2730 the changelog, manifest, and tracked files, as well as the
2727 integrity of their crosslinks and indices.
2731 integrity of their crosslinks and indices.
2728 """
2732 """
2729 return hg.verify(repo)
2733 return hg.verify(repo)
2730
2734
2731 def version_(ui):
2735 def version_(ui):
2732 """output version and copyright information"""
2736 """output version and copyright information"""
2733 ui.write(_("Mercurial Distributed SCM (version %s)\n")
2737 ui.write(_("Mercurial Distributed SCM (version %s)\n")
2734 % version.get_version())
2738 % version.get_version())
2735 ui.status(_(
2739 ui.status(_(
2736 "\nCopyright (C) 2005-2008 Matt Mackall <mpm@selenic.com> and others\n"
2740 "\nCopyright (C) 2005-2008 Matt Mackall <mpm@selenic.com> and others\n"
2737 "This is free software; see the source for copying conditions. "
2741 "This is free software; see the source for copying conditions. "
2738 "There is NO\nwarranty; "
2742 "There is NO\nwarranty; "
2739 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
2743 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
2740 ))
2744 ))
2741
2745
2742 # Command options and aliases are listed here, alphabetically
2746 # Command options and aliases are listed here, alphabetically
2743
2747
2744 globalopts = [
2748 globalopts = [
2745 ('R', 'repository', '',
2749 ('R', 'repository', '',
2746 _('repository root directory or symbolic path name')),
2750 _('repository root directory or symbolic path name')),
2747 ('', 'cwd', '', _('change working directory')),
2751 ('', 'cwd', '', _('change working directory')),
2748 ('y', 'noninteractive', None,
2752 ('y', 'noninteractive', None,
2749 _('do not prompt, assume \'yes\' for any required answers')),
2753 _('do not prompt, assume \'yes\' for any required answers')),
2750 ('q', 'quiet', None, _('suppress output')),
2754 ('q', 'quiet', None, _('suppress output')),
2751 ('v', 'verbose', None, _('enable additional output')),
2755 ('v', 'verbose', None, _('enable additional output')),
2752 ('', 'config', [], _('set/override config option')),
2756 ('', 'config', [], _('set/override config option')),
2753 ('', 'debug', None, _('enable debugging output')),
2757 ('', 'debug', None, _('enable debugging output')),
2754 ('', 'debugger', None, _('start debugger')),
2758 ('', 'debugger', None, _('start debugger')),
2755 ('', 'encoding', util._encoding, _('set the charset encoding')),
2759 ('', 'encoding', util._encoding, _('set the charset encoding')),
2756 ('', 'encodingmode', util._encodingmode, _('set the charset encoding mode')),
2760 ('', 'encodingmode', util._encodingmode, _('set the charset encoding mode')),
2757 ('', 'lsprof', None, _('print improved command execution profile')),
2761 ('', 'lsprof', None, _('print improved command execution profile')),
2758 ('', 'traceback', None, _('print traceback on exception')),
2762 ('', 'traceback', None, _('print traceback on exception')),
2759 ('', 'time', None, _('time how long the command takes')),
2763 ('', 'time', None, _('time how long the command takes')),
2760 ('', 'profile', None, _('print command execution profile')),
2764 ('', 'profile', None, _('print command execution profile')),
2761 ('', 'version', None, _('output version information and exit')),
2765 ('', 'version', None, _('output version information and exit')),
2762 ('h', 'help', None, _('display help and exit')),
2766 ('h', 'help', None, _('display help and exit')),
2763 ]
2767 ]
2764
2768
2765 dryrunopts = [('n', 'dry-run', None,
2769 dryrunopts = [('n', 'dry-run', None,
2766 _('do not perform actions, just print output'))]
2770 _('do not perform actions, just print output'))]
2767
2771
2768 remoteopts = [
2772 remoteopts = [
2769 ('e', 'ssh', '', _('specify ssh command to use')),
2773 ('e', 'ssh', '', _('specify ssh command to use')),
2770 ('', 'remotecmd', '', _('specify hg command to run on the remote side')),
2774 ('', 'remotecmd', '', _('specify hg command to run on the remote side')),
2771 ]
2775 ]
2772
2776
2773 walkopts = [
2777 walkopts = [
2774 ('I', 'include', [], _('include names matching the given patterns')),
2778 ('I', 'include', [], _('include names matching the given patterns')),
2775 ('X', 'exclude', [], _('exclude names matching the given patterns')),
2779 ('X', 'exclude', [], _('exclude names matching the given patterns')),
2776 ]
2780 ]
2777
2781
2778 commitopts = [
2782 commitopts = [
2779 ('m', 'message', '', _('use <text> as commit message')),
2783 ('m', 'message', '', _('use <text> as commit message')),
2780 ('l', 'logfile', '', _('read commit message from <file>')),
2784 ('l', 'logfile', '', _('read commit message from <file>')),
2781 ]
2785 ]
2782
2786
2783 commitopts2 = [
2787 commitopts2 = [
2784 ('d', 'date', '', _('record datecode as commit date')),
2788 ('d', 'date', '', _('record datecode as commit date')),
2785 ('u', 'user', '', _('record user as committer')),
2789 ('u', 'user', '', _('record user as committer')),
2786 ]
2790 ]
2787
2791
2788 templateopts = [
2792 templateopts = [
2789 ('', 'style', '', _('display using template map file')),
2793 ('', 'style', '', _('display using template map file')),
2790 ('', 'template', '', _('display with template')),
2794 ('', 'template', '', _('display with template')),
2791 ]
2795 ]
2792
2796
2793 logopts = [
2797 logopts = [
2794 ('p', 'patch', None, _('show patch')),
2798 ('p', 'patch', None, _('show patch')),
2795 ('l', 'limit', '', _('limit number of changes displayed')),
2799 ('l', 'limit', '', _('limit number of changes displayed')),
2796 ('M', 'no-merges', None, _('do not show merges')),
2800 ('M', 'no-merges', None, _('do not show merges')),
2797 ] + templateopts
2801 ] + templateopts
2798
2802
2799 table = {
2803 table = {
2800 "^add": (add, walkopts + dryrunopts, _('hg add [OPTION]... [FILE]...')),
2804 "^add": (add, walkopts + dryrunopts, _('hg add [OPTION]... [FILE]...')),
2801 "addremove":
2805 "addremove":
2802 (addremove,
2806 (addremove,
2803 [('s', 'similarity', '',
2807 [('s', 'similarity', '',
2804 _('guess renamed files by similarity (0<=s<=100)')),
2808 _('guess renamed files by similarity (0<=s<=100)')),
2805 ] + walkopts + dryrunopts,
2809 ] + walkopts + dryrunopts,
2806 _('hg addremove [OPTION]... [FILE]...')),
2810 _('hg addremove [OPTION]... [FILE]...')),
2807 "^annotate|blame":
2811 "^annotate|blame":
2808 (annotate,
2812 (annotate,
2809 [('r', 'rev', '', _('annotate the specified revision')),
2813 [('r', 'rev', '', _('annotate the specified revision')),
2810 ('f', 'follow', None, _('follow file copies and renames')),
2814 ('f', 'follow', None, _('follow file copies and renames')),
2811 ('a', 'text', None, _('treat all files as text')),
2815 ('a', 'text', None, _('treat all files as text')),
2812 ('u', 'user', None, _('list the author (long with -v)')),
2816 ('u', 'user', None, _('list the author (long with -v)')),
2813 ('d', 'date', None, _('list the date (short with -q)')),
2817 ('d', 'date', None, _('list the date (short with -q)')),
2814 ('n', 'number', None, _('list the revision number (default)')),
2818 ('n', 'number', None, _('list the revision number (default)')),
2815 ('c', 'changeset', None, _('list the changeset')),
2819 ('c', 'changeset', None, _('list the changeset')),
2816 ('l', 'line-number', None,
2820 ('l', 'line-number', None,
2817 _('show line number at the first appearance'))
2821 _('show line number at the first appearance'))
2818 ] + walkopts,
2822 ] + walkopts,
2819 _('hg annotate [-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...')),
2823 _('hg annotate [-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...')),
2820 "archive":
2824 "archive":
2821 (archive,
2825 (archive,
2822 [('', 'no-decode', None, _('do not pass files through decoders')),
2826 [('', 'no-decode', None, _('do not pass files through decoders')),
2823 ('p', 'prefix', '', _('directory prefix for files in archive')),
2827 ('p', 'prefix', '', _('directory prefix for files in archive')),
2824 ('r', 'rev', '', _('revision to distribute')),
2828 ('r', 'rev', '', _('revision to distribute')),
2825 ('t', 'type', '', _('type of distribution to create')),
2829 ('t', 'type', '', _('type of distribution to create')),
2826 ] + walkopts,
2830 ] + walkopts,
2827 _('hg archive [OPTION]... DEST')),
2831 _('hg archive [OPTION]... DEST')),
2828 "backout":
2832 "backout":
2829 (backout,
2833 (backout,
2830 [('', 'merge', None,
2834 [('', 'merge', None,
2831 _('merge with old dirstate parent after backout')),
2835 _('merge with old dirstate parent after backout')),
2832 ('', 'parent', '', _('parent to choose when backing out merge')),
2836 ('', 'parent', '', _('parent to choose when backing out merge')),
2833 ('r', 'rev', '', _('revision to backout')),
2837 ('r', 'rev', '', _('revision to backout')),
2834 ] + walkopts + commitopts + commitopts2,
2838 ] + walkopts + commitopts + commitopts2,
2835 _('hg backout [OPTION]... [-r] REV')),
2839 _('hg backout [OPTION]... [-r] REV')),
2836 "bisect":
2840 "bisect":
2837 (bisect,
2841 (bisect,
2838 [('r', 'reset', False, _('reset bisect state')),
2842 [('r', 'reset', False, _('reset bisect state')),
2839 ('g', 'good', False, _('mark changeset good')),
2843 ('g', 'good', False, _('mark changeset good')),
2840 ('b', 'bad', False, _('mark changeset bad')),
2844 ('b', 'bad', False, _('mark changeset bad')),
2841 ('s', 'skip', False, _('skip testing changeset')),
2845 ('s', 'skip', False, _('skip testing changeset')),
2842 ('U', 'noupdate', False, _('do not update to target'))],
2846 ('U', 'noupdate', False, _('do not update to target'))],
2843 _("hg bisect [-gbsr] [REV]")),
2847 _("hg bisect [-gbsr] [REV]")),
2844 "branch":
2848 "branch":
2845 (branch,
2849 (branch,
2846 [('f', 'force', None,
2850 [('f', 'force', None,
2847 _('set branch name even if it shadows an existing branch'))],
2851 _('set branch name even if it shadows an existing branch'))],
2848 _('hg branch [-f] [NAME]')),
2852 _('hg branch [-f] [NAME]')),
2849 "branches":
2853 "branches":
2850 (branches,
2854 (branches,
2851 [('a', 'active', False,
2855 [('a', 'active', False,
2852 _('show only branches that have unmerged heads'))],
2856 _('show only branches that have unmerged heads'))],
2853 _('hg branches [-a]')),
2857 _('hg branches [-a]')),
2854 "bundle":
2858 "bundle":
2855 (bundle,
2859 (bundle,
2856 [('f', 'force', None,
2860 [('f', 'force', None,
2857 _('run even when remote repository is unrelated')),
2861 _('run even when remote repository is unrelated')),
2858 ('r', 'rev', [],
2862 ('r', 'rev', [],
2859 _('a changeset you would like to bundle')),
2863 _('a changeset you would like to bundle')),
2860 ('', 'base', [],
2864 ('', 'base', [],
2861 _('a base changeset to specify instead of a destination')),
2865 _('a base changeset to specify instead of a destination')),
2862 ('a', 'all', None,
2866 ('a', 'all', None,
2863 _('bundle all changesets in the repository')),
2867 _('bundle all changesets in the repository')),
2864 ] + remoteopts,
2868 ] + remoteopts,
2865 _('hg bundle [-f] [-a] [-r REV]... [--base REV]... FILE [DEST]')),
2869 _('hg bundle [-f] [-a] [-r REV]... [--base REV]... FILE [DEST]')),
2866 "cat":
2870 "cat":
2867 (cat,
2871 (cat,
2868 [('o', 'output', '', _('print output to file with formatted name')),
2872 [('o', 'output', '', _('print output to file with formatted name')),
2869 ('r', 'rev', '', _('print the given revision')),
2873 ('r', 'rev', '', _('print the given revision')),
2870 ('', 'decode', None, _('apply any matching decode filter')),
2874 ('', 'decode', None, _('apply any matching decode filter')),
2871 ] + walkopts,
2875 ] + walkopts,
2872 _('hg cat [OPTION]... FILE...')),
2876 _('hg cat [OPTION]... FILE...')),
2873 "^clone":
2877 "^clone":
2874 (clone,
2878 (clone,
2875 [('U', 'noupdate', None, _('do not update the new working directory')),
2879 [('U', 'noupdate', None, _('do not update the new working directory')),
2876 ('r', 'rev', [],
2880 ('r', 'rev', [],
2877 _('a changeset you would like to have after cloning')),
2881 _('a changeset you would like to have after cloning')),
2878 ('', 'pull', None, _('use pull protocol to copy metadata')),
2882 ('', 'pull', None, _('use pull protocol to copy metadata')),
2879 ('', 'uncompressed', None,
2883 ('', 'uncompressed', None,
2880 _('use uncompressed transfer (fast over LAN)')),
2884 _('use uncompressed transfer (fast over LAN)')),
2881 ] + remoteopts,
2885 ] + remoteopts,
2882 _('hg clone [OPTION]... SOURCE [DEST]')),
2886 _('hg clone [OPTION]... SOURCE [DEST]')),
2883 "^commit|ci":
2887 "^commit|ci":
2884 (commit,
2888 (commit,
2885 [('A', 'addremove', None,
2889 [('A', 'addremove', None,
2886 _('mark new/missing files as added/removed before committing')),
2890 _('mark new/missing files as added/removed before committing')),
2887 ] + walkopts + commitopts + commitopts2,
2891 ] + walkopts + commitopts + commitopts2,
2888 _('hg commit [OPTION]... [FILE]...')),
2892 _('hg commit [OPTION]... [FILE]...')),
2889 "copy|cp":
2893 "copy|cp":
2890 (copy,
2894 (copy,
2891 [('A', 'after', None, _('record a copy that has already occurred')),
2895 [('A', 'after', None, _('record a copy that has already occurred')),
2892 ('f', 'force', None,
2896 ('f', 'force', None,
2893 _('forcibly copy over an existing managed file')),
2897 _('forcibly copy over an existing managed file')),
2894 ] + walkopts + dryrunopts,
2898 ] + walkopts + dryrunopts,
2895 _('hg copy [OPTION]... [SOURCE]... DEST')),
2899 _('hg copy [OPTION]... [SOURCE]... DEST')),
2896 "debugancestor": (debugancestor, [],
2900 "debugancestor": (debugancestor, [],
2897 _('hg debugancestor [INDEX] REV1 REV2')),
2901 _('hg debugancestor [INDEX] REV1 REV2')),
2898 "debugcheckstate": (debugcheckstate, [], _('hg debugcheckstate')),
2902 "debugcheckstate": (debugcheckstate, [], _('hg debugcheckstate')),
2899 "debugcomplete":
2903 "debugcomplete":
2900 (debugcomplete,
2904 (debugcomplete,
2901 [('o', 'options', None, _('show the command options'))],
2905 [('o', 'options', None, _('show the command options'))],
2902 _('hg debugcomplete [-o] CMD')),
2906 _('hg debugcomplete [-o] CMD')),
2903 "debugdate":
2907 "debugdate":
2904 (debugdate,
2908 (debugdate,
2905 [('e', 'extended', None, _('try extended date formats'))],
2909 [('e', 'extended', None, _('try extended date formats'))],
2906 _('hg debugdate [-e] DATE [RANGE]')),
2910 _('hg debugdate [-e] DATE [RANGE]')),
2907 "debugdata": (debugdata, [], _('hg debugdata FILE REV')),
2911 "debugdata": (debugdata, [], _('hg debugdata FILE REV')),
2908 "debugfsinfo": (debugfsinfo, [], _('hg debugfsinfo [PATH]')),
2912 "debugfsinfo": (debugfsinfo, [], _('hg debugfsinfo [PATH]')),
2909 "debugindex": (debugindex, [], _('hg debugindex FILE')),
2913 "debugindex": (debugindex, [], _('hg debugindex FILE')),
2910 "debugindexdot": (debugindexdot, [], _('hg debugindexdot FILE')),
2914 "debugindexdot": (debugindexdot, [], _('hg debugindexdot FILE')),
2911 "debuginstall": (debuginstall, [], _('hg debuginstall')),
2915 "debuginstall": (debuginstall, [], _('hg debuginstall')),
2912 "debugrawcommit|rawcommit":
2916 "debugrawcommit|rawcommit":
2913 (rawcommit,
2917 (rawcommit,
2914 [('p', 'parent', [], _('parent')),
2918 [('p', 'parent', [], _('parent')),
2915 ('F', 'files', '', _('file list'))
2919 ('F', 'files', '', _('file list'))
2916 ] + commitopts + commitopts2,
2920 ] + commitopts + commitopts2,
2917 _('hg debugrawcommit [OPTION]... [FILE]...')),
2921 _('hg debugrawcommit [OPTION]... [FILE]...')),
2918 "debugrebuildstate":
2922 "debugrebuildstate":
2919 (debugrebuildstate,
2923 (debugrebuildstate,
2920 [('r', 'rev', '', _('revision to rebuild to'))],
2924 [('r', 'rev', '', _('revision to rebuild to'))],
2921 _('hg debugrebuildstate [-r REV] [REV]')),
2925 _('hg debugrebuildstate [-r REV] [REV]')),
2922 "debugrename":
2926 "debugrename":
2923 (debugrename,
2927 (debugrename,
2924 [('r', 'rev', '', _('revision to debug'))],
2928 [('r', 'rev', '', _('revision to debug'))],
2925 _('hg debugrename [-r REV] FILE')),
2929 _('hg debugrename [-r REV] FILE')),
2926 "debugsetparents":
2930 "debugsetparents":
2927 (debugsetparents,
2931 (debugsetparents,
2928 [],
2932 [],
2929 _('hg debugsetparents REV1 [REV2]')),
2933 _('hg debugsetparents REV1 [REV2]')),
2930 "debugstate": (debugstate, [], _('hg debugstate')),
2934 "debugstate": (debugstate, [], _('hg debugstate')),
2931 "debugwalk": (debugwalk, walkopts, _('hg debugwalk [OPTION]... [FILE]...')),
2935 "debugwalk": (debugwalk, walkopts, _('hg debugwalk [OPTION]... [FILE]...')),
2932 "^diff":
2936 "^diff":
2933 (diff,
2937 (diff,
2934 [('r', 'rev', [], _('revision')),
2938 [('r', 'rev', [], _('revision')),
2935 ('a', 'text', None, _('treat all files as text')),
2939 ('a', 'text', None, _('treat all files as text')),
2936 ('p', 'show-function', None,
2940 ('p', 'show-function', None,
2937 _('show which function each change is in')),
2941 _('show which function each change is in')),
2938 ('g', 'git', None, _('use git extended diff format')),
2942 ('g', 'git', None, _('use git extended diff format')),
2939 ('', 'nodates', None, _("don't include dates in diff headers")),
2943 ('', 'nodates', None, _("don't include dates in diff headers")),
2940 ('w', 'ignore-all-space', None,
2944 ('w', 'ignore-all-space', None,
2941 _('ignore white space when comparing lines')),
2945 _('ignore white space when comparing lines')),
2942 ('b', 'ignore-space-change', None,
2946 ('b', 'ignore-space-change', None,
2943 _('ignore changes in the amount of white space')),
2947 _('ignore changes in the amount of white space')),
2944 ('B', 'ignore-blank-lines', None,
2948 ('B', 'ignore-blank-lines', None,
2945 _('ignore changes whose lines are all blank')),
2949 _('ignore changes whose lines are all blank')),
2946 ('U', 'unified', 3,
2950 ('U', 'unified', 3,
2947 _('number of lines of context to show'))
2951 _('number of lines of context to show'))
2948 ] + walkopts,
2952 ] + walkopts,
2949 _('hg diff [OPTION]... [-r REV1 [-r REV2]] [FILE]...')),
2953 _('hg diff [OPTION]... [-r REV1 [-r REV2]] [FILE]...')),
2950 "^export":
2954 "^export":
2951 (export,
2955 (export,
2952 [('o', 'output', '', _('print output to file with formatted name')),
2956 [('o', 'output', '', _('print output to file with formatted name')),
2953 ('a', 'text', None, _('treat all files as text')),
2957 ('a', 'text', None, _('treat all files as text')),
2954 ('g', 'git', None, _('use git extended diff format')),
2958 ('g', 'git', None, _('use git extended diff format')),
2955 ('', 'nodates', None, _("don't include dates in diff headers")),
2959 ('', 'nodates', None, _("don't include dates in diff headers")),
2956 ('', 'switch-parent', None, _('diff against the second parent'))],
2960 ('', 'switch-parent', None, _('diff against the second parent'))],
2957 _('hg export [OPTION]... [-o OUTFILESPEC] REV...')),
2961 _('hg export [OPTION]... [-o OUTFILESPEC] REV...')),
2958 "grep":
2962 "grep":
2959 (grep,
2963 (grep,
2960 [('0', 'print0', None, _('end fields with NUL')),
2964 [('0', 'print0', None, _('end fields with NUL')),
2961 ('', 'all', None, _('print all revisions that match')),
2965 ('', 'all', None, _('print all revisions that match')),
2962 ('f', 'follow', None,
2966 ('f', 'follow', None,
2963 _('follow changeset history, or file history across copies and renames')),
2967 _('follow changeset history, or file history across copies and renames')),
2964 ('i', 'ignore-case', None, _('ignore case when matching')),
2968 ('i', 'ignore-case', None, _('ignore case when matching')),
2965 ('l', 'files-with-matches', None,
2969 ('l', 'files-with-matches', None,
2966 _('print only filenames and revs that match')),
2970 _('print only filenames and revs that match')),
2967 ('n', 'line-number', None, _('print matching line numbers')),
2971 ('n', 'line-number', None, _('print matching line numbers')),
2968 ('r', 'rev', [], _('search in given revision range')),
2972 ('r', 'rev', [], _('search in given revision range')),
2969 ('u', 'user', None, _('list the author (long with -v)')),
2973 ('u', 'user', None, _('list the author (long with -v)')),
2970 ('d', 'date', None, _('list the date (short with -q)')),
2974 ('d', 'date', None, _('list the date (short with -q)')),
2971 ] + walkopts,
2975 ] + walkopts,
2972 _('hg grep [OPTION]... PATTERN [FILE]...')),
2976 _('hg grep [OPTION]... PATTERN [FILE]...')),
2973 "heads":
2977 "heads":
2974 (heads,
2978 (heads,
2975 [('r', 'rev', '', _('show only heads which are descendants of rev')),
2979 [('r', 'rev', '', _('show only heads which are descendants of rev')),
2976 ] + templateopts,
2980 ] + templateopts,
2977 _('hg heads [-r REV] [REV]...')),
2981 _('hg heads [-r REV] [REV]...')),
2978 "help": (help_, [], _('hg help [COMMAND]')),
2982 "help": (help_, [], _('hg help [COMMAND]')),
2979 "identify|id":
2983 "identify|id":
2980 (identify,
2984 (identify,
2981 [('r', 'rev', '', _('identify the specified rev')),
2985 [('r', 'rev', '', _('identify the specified rev')),
2982 ('n', 'num', None, _('show local revision number')),
2986 ('n', 'num', None, _('show local revision number')),
2983 ('i', 'id', None, _('show global revision id')),
2987 ('i', 'id', None, _('show global revision id')),
2984 ('b', 'branch', None, _('show branch')),
2988 ('b', 'branch', None, _('show branch')),
2985 ('t', 'tags', None, _('show tags'))],
2989 ('t', 'tags', None, _('show tags'))],
2986 _('hg identify [-nibt] [-r REV] [SOURCE]')),
2990 _('hg identify [-nibt] [-r REV] [SOURCE]')),
2987 "import|patch":
2991 "import|patch":
2988 (import_,
2992 (import_,
2989 [('p', 'strip', 1,
2993 [('p', 'strip', 1,
2990 _('directory strip option for patch. This has the same\n'
2994 _('directory strip option for patch. This has the same\n'
2991 'meaning as the corresponding patch option')),
2995 'meaning as the corresponding patch option')),
2992 ('b', 'base', '', _('base path')),
2996 ('b', 'base', '', _('base path')),
2993 ('f', 'force', None,
2997 ('f', 'force', None,
2994 _('skip check for outstanding uncommitted changes')),
2998 _('skip check for outstanding uncommitted changes')),
2995 ('', 'no-commit', None, _("don't commit, just update the working directory")),
2999 ('', 'no-commit', None, _("don't commit, just update the working directory")),
2996 ('', 'exact', None,
3000 ('', 'exact', None,
2997 _('apply patch to the nodes from which it was generated')),
3001 _('apply patch to the nodes from which it was generated')),
2998 ('', 'import-branch', None,
3002 ('', 'import-branch', None,
2999 _('Use any branch information in patch (implied by --exact)'))] +
3003 _('Use any branch information in patch (implied by --exact)'))] +
3000 commitopts + commitopts2,
3004 commitopts + commitopts2,
3001 _('hg import [OPTION]... PATCH...')),
3005 _('hg import [OPTION]... PATCH...')),
3002 "incoming|in":
3006 "incoming|in":
3003 (incoming,
3007 (incoming,
3004 [('f', 'force', None,
3008 [('f', 'force', None,
3005 _('run even when remote repository is unrelated')),
3009 _('run even when remote repository is unrelated')),
3006 ('n', 'newest-first', None, _('show newest record first')),
3010 ('n', 'newest-first', None, _('show newest record first')),
3007 ('', 'bundle', '', _('file to store the bundles into')),
3011 ('', 'bundle', '', _('file to store the bundles into')),
3008 ('r', 'rev', [], _('a specific revision up to which you would like to pull')),
3012 ('r', 'rev', [], _('a specific revision up to which you would like to pull')),
3009 ] + logopts + remoteopts,
3013 ] + logopts + remoteopts,
3010 _('hg incoming [-p] [-n] [-M] [-f] [-r REV]...'
3014 _('hg incoming [-p] [-n] [-M] [-f] [-r REV]...'
3011 ' [--bundle FILENAME] [SOURCE]')),
3015 ' [--bundle FILENAME] [SOURCE]')),
3012 "^init":
3016 "^init":
3013 (init,
3017 (init,
3014 remoteopts,
3018 remoteopts,
3015 _('hg init [-e CMD] [--remotecmd CMD] [DEST]')),
3019 _('hg init [-e CMD] [--remotecmd CMD] [DEST]')),
3016 "locate":
3020 "locate":
3017 (locate,
3021 (locate,
3018 [('r', 'rev', '', _('search the repository as it stood at rev')),
3022 [('r', 'rev', '', _('search the repository as it stood at rev')),
3019 ('0', 'print0', None,
3023 ('0', 'print0', None,
3020 _('end filenames with NUL, for use with xargs')),
3024 _('end filenames with NUL, for use with xargs')),
3021 ('f', 'fullpath', None,
3025 ('f', 'fullpath', None,
3022 _('print complete paths from the filesystem root')),
3026 _('print complete paths from the filesystem root')),
3023 ] + walkopts,
3027 ] + walkopts,
3024 _('hg locate [OPTION]... [PATTERN]...')),
3028 _('hg locate [OPTION]... [PATTERN]...')),
3025 "^log|history":
3029 "^log|history":
3026 (log,
3030 (log,
3027 [('f', 'follow', None,
3031 [('f', 'follow', None,
3028 _('follow changeset history, or file history across copies and renames')),
3032 _('follow changeset history, or file history across copies and renames')),
3029 ('', 'follow-first', None,
3033 ('', 'follow-first', None,
3030 _('only follow the first parent of merge changesets')),
3034 _('only follow the first parent of merge changesets')),
3031 ('d', 'date', '', _('show revs matching date spec')),
3035 ('d', 'date', '', _('show revs matching date spec')),
3032 ('C', 'copies', None, _('show copied files')),
3036 ('C', 'copies', None, _('show copied files')),
3033 ('k', 'keyword', [], _('do case-insensitive search for a keyword')),
3037 ('k', 'keyword', [], _('do case-insensitive search for a keyword')),
3034 ('r', 'rev', [], _('show the specified revision or range')),
3038 ('r', 'rev', [], _('show the specified revision or range')),
3035 ('', 'removed', None, _('include revs where files were removed')),
3039 ('', 'removed', None, _('include revs where files were removed')),
3036 ('m', 'only-merges', None, _('show only merges')),
3040 ('m', 'only-merges', None, _('show only merges')),
3037 ('b', 'only-branch', [],
3041 ('b', 'only-branch', [],
3038 _('show only changesets within the given named branch')),
3042 _('show only changesets within the given named branch')),
3039 ('P', 'prune', [], _('do not display revision or any of its ancestors')),
3043 ('P', 'prune', [], _('do not display revision or any of its ancestors')),
3040 ] + logopts + walkopts,
3044 ] + logopts + walkopts,
3041 _('hg log [OPTION]... [FILE]')),
3045 _('hg log [OPTION]... [FILE]')),
3042 "manifest":
3046 "manifest":
3043 (manifest,
3047 (manifest,
3044 [('r', 'rev', '', _('revision to display'))],
3048 [('r', 'rev', '', _('revision to display'))],
3045 _('hg manifest [-r REV]')),
3049 _('hg manifest [-r REV]')),
3046 "^merge":
3050 "^merge":
3047 (merge,
3051 (merge,
3048 [('f', 'force', None, _('force a merge with outstanding changes')),
3052 [('f', 'force', None, _('force a merge with outstanding changes')),
3049 ('r', 'rev', '', _('revision to merge')),
3053 ('r', 'rev', '', _('revision to merge')),
3050 ],
3054 ],
3051 _('hg merge [-f] [[-r] REV]')),
3055 _('hg merge [-f] [[-r] REV]')),
3052 "outgoing|out":
3056 "outgoing|out":
3053 (outgoing,
3057 (outgoing,
3054 [('f', 'force', None,
3058 [('f', 'force', None,
3055 _('run even when remote repository is unrelated')),
3059 _('run even when remote repository is unrelated')),
3056 ('r', 'rev', [], _('a specific revision you would like to push')),
3060 ('r', 'rev', [], _('a specific revision you would like to push')),
3057 ('n', 'newest-first', None, _('show newest record first')),
3061 ('n', 'newest-first', None, _('show newest record first')),
3058 ] + logopts + remoteopts,
3062 ] + logopts + remoteopts,
3059 _('hg outgoing [-M] [-p] [-n] [-f] [-r REV]... [DEST]')),
3063 _('hg outgoing [-M] [-p] [-n] [-f] [-r REV]... [DEST]')),
3060 "^parents":
3064 "^parents":
3061 (parents,
3065 (parents,
3062 [('r', 'rev', '', _('show parents from the specified rev')),
3066 [('r', 'rev', '', _('show parents from the specified rev')),
3063 ] + templateopts,
3067 ] + templateopts,
3064 _('hg parents [-r REV] [FILE]')),
3068 _('hg parents [-r REV] [FILE]')),
3065 "paths": (paths, [], _('hg paths [NAME]')),
3069 "paths": (paths, [], _('hg paths [NAME]')),
3066 "^pull":
3070 "^pull":
3067 (pull,
3071 (pull,
3068 [('u', 'update', None,
3072 [('u', 'update', None,
3069 _('update to new tip if changesets were pulled')),
3073 _('update to new tip if changesets were pulled')),
3070 ('f', 'force', None,
3074 ('f', 'force', None,
3071 _('run even when remote repository is unrelated')),
3075 _('run even when remote repository is unrelated')),
3072 ('r', 'rev', [],
3076 ('r', 'rev', [],
3073 _('a specific revision up to which you would like to pull')),
3077 _('a specific revision up to which you would like to pull')),
3074 ] + remoteopts,
3078 ] + remoteopts,
3075 _('hg pull [-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]')),
3079 _('hg pull [-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]')),
3076 "^push":
3080 "^push":
3077 (push,
3081 (push,
3078 [('f', 'force', None, _('force push')),
3082 [('f', 'force', None, _('force push')),
3079 ('r', 'rev', [], _('a specific revision you would like to push')),
3083 ('r', 'rev', [], _('a specific revision you would like to push')),
3080 ] + remoteopts,
3084 ] + remoteopts,
3081 _('hg push [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]')),
3085 _('hg push [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]')),
3082 "recover": (recover, [], _('hg recover')),
3086 "recover": (recover, [], _('hg recover')),
3083 "^remove|rm":
3087 "^remove|rm":
3084 (remove,
3088 (remove,
3085 [('A', 'after', None, _('record remove without deleting')),
3089 [('A', 'after', None, _('record remove without deleting')),
3086 ('f', 'force', None, _('remove file even if modified')),
3090 ('f', 'force', None, _('remove file even if modified')),
3087 ] + walkopts,
3091 ] + walkopts,
3088 _('hg remove [OPTION]... FILE...')),
3092 _('hg remove [OPTION]... FILE...')),
3089 "rename|mv":
3093 "rename|mv":
3090 (rename,
3094 (rename,
3091 [('A', 'after', None, _('record a rename that has already occurred')),
3095 [('A', 'after', None, _('record a rename that has already occurred')),
3092 ('f', 'force', None,
3096 ('f', 'force', None,
3093 _('forcibly copy over an existing managed file')),
3097 _('forcibly copy over an existing managed file')),
3094 ] + walkopts + dryrunopts,
3098 ] + walkopts + dryrunopts,
3095 _('hg rename [OPTION]... SOURCE... DEST')),
3099 _('hg rename [OPTION]... SOURCE... DEST')),
3096 "revert":
3100 "revert":
3097 (revert,
3101 (revert,
3098 [('a', 'all', None, _('revert all changes when no arguments given')),
3102 [('a', 'all', None, _('revert all changes when no arguments given')),
3099 ('d', 'date', '', _('tipmost revision matching date')),
3103 ('d', 'date', '', _('tipmost revision matching date')),
3100 ('r', 'rev', '', _('revision to revert to')),
3104 ('r', 'rev', '', _('revision to revert to')),
3101 ('', 'no-backup', None, _('do not save backup copies of files')),
3105 ('', 'no-backup', None, _('do not save backup copies of files')),
3102 ] + walkopts + dryrunopts,
3106 ] + walkopts + dryrunopts,
3103 _('hg revert [OPTION]... [-r REV] [NAME]...')),
3107 _('hg revert [OPTION]... [-r REV] [NAME]...')),
3104 "rollback": (rollback, [], _('hg rollback')),
3108 "rollback": (rollback, [], _('hg rollback')),
3105 "root": (root, [], _('hg root')),
3109 "root": (root, [], _('hg root')),
3106 "^serve":
3110 "^serve":
3107 (serve,
3111 (serve,
3108 [('A', 'accesslog', '', _('name of access log file to write to')),
3112 [('A', 'accesslog', '', _('name of access log file to write to')),
3109 ('d', 'daemon', None, _('run server in background')),
3113 ('d', 'daemon', None, _('run server in background')),
3110 ('', 'daemon-pipefds', '', _('used internally by daemon mode')),
3114 ('', 'daemon-pipefds', '', _('used internally by daemon mode')),
3111 ('E', 'errorlog', '', _('name of error log file to write to')),
3115 ('E', 'errorlog', '', _('name of error log file to write to')),
3112 ('p', 'port', 0, _('port to use (default: 8000)')),
3116 ('p', 'port', 0, _('port to use (default: 8000)')),
3113 ('a', 'address', '', _('address to use')),
3117 ('a', 'address', '', _('address to use')),
3114 ('', 'prefix', '', _('prefix path to serve from (default: server root)')),
3118 ('', 'prefix', '', _('prefix path to serve from (default: server root)')),
3115 ('n', 'name', '',
3119 ('n', 'name', '',
3116 _('name to show in web pages (default: working dir)')),
3120 _('name to show in web pages (default: working dir)')),
3117 ('', 'webdir-conf', '', _('name of the webdir config file'
3121 ('', 'webdir-conf', '', _('name of the webdir config file'
3118 ' (serve more than one repo)')),
3122 ' (serve more than one repo)')),
3119 ('', 'pid-file', '', _('name of file to write process ID to')),
3123 ('', 'pid-file', '', _('name of file to write process ID to')),
3120 ('', 'stdio', None, _('for remote clients')),
3124 ('', 'stdio', None, _('for remote clients')),
3121 ('t', 'templates', '', _('web templates to use')),
3125 ('t', 'templates', '', _('web templates to use')),
3122 ('', 'style', '', _('template style to use')),
3126 ('', 'style', '', _('template style to use')),
3123 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
3127 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
3124 ('', 'certificate', '', _('SSL certificate file'))],
3128 ('', 'certificate', '', _('SSL certificate file'))],
3125 _('hg serve [OPTION]...')),
3129 _('hg serve [OPTION]...')),
3126 "showconfig|debugconfig":
3130 "showconfig|debugconfig":
3127 (showconfig,
3131 (showconfig,
3128 [('u', 'untrusted', None, _('show untrusted configuration options'))],
3132 [('u', 'untrusted', None, _('show untrusted configuration options'))],
3129 _('hg showconfig [-u] [NAME]...')),
3133 _('hg showconfig [-u] [NAME]...')),
3130 "^status|st":
3134 "^status|st":
3131 (status,
3135 (status,
3132 [('A', 'all', None, _('show status of all files')),
3136 [('A', 'all', None, _('show status of all files')),
3133 ('m', 'modified', None, _('show only modified files')),
3137 ('m', 'modified', None, _('show only modified files')),
3134 ('a', 'added', None, _('show only added files')),
3138 ('a', 'added', None, _('show only added files')),
3135 ('r', 'removed', None, _('show only removed files')),
3139 ('r', 'removed', None, _('show only removed files')),
3136 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
3140 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
3137 ('c', 'clean', None, _('show only files without changes')),
3141 ('c', 'clean', None, _('show only files without changes')),
3138 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
3142 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
3139 ('i', 'ignored', None, _('show only ignored files')),
3143 ('i', 'ignored', None, _('show only ignored files')),
3140 ('n', 'no-status', None, _('hide status prefix')),
3144 ('n', 'no-status', None, _('hide status prefix')),
3141 ('C', 'copies', None, _('show source of copied files')),
3145 ('C', 'copies', None, _('show source of copied files')),
3142 ('0', 'print0', None,
3146 ('0', 'print0', None,
3143 _('end filenames with NUL, for use with xargs')),
3147 _('end filenames with NUL, for use with xargs')),
3144 ('', 'rev', [], _('show difference from revision')),
3148 ('', 'rev', [], _('show difference from revision')),
3145 ] + walkopts,
3149 ] + walkopts,
3146 _('hg status [OPTION]... [FILE]...')),
3150 _('hg status [OPTION]... [FILE]...')),
3147 "tag":
3151 "tag":
3148 (tag,
3152 (tag,
3149 [('f', 'force', None, _('replace existing tag')),
3153 [('f', 'force', None, _('replace existing tag')),
3150 ('l', 'local', None, _('make the tag local')),
3154 ('l', 'local', None, _('make the tag local')),
3151 ('r', 'rev', '', _('revision to tag')),
3155 ('r', 'rev', '', _('revision to tag')),
3152 ('', 'remove', None, _('remove a tag')),
3156 ('', 'remove', None, _('remove a tag')),
3153 # -l/--local is already there, commitopts cannot be used
3157 # -l/--local is already there, commitopts cannot be used
3154 ('m', 'message', '', _('use <text> as commit message')),
3158 ('m', 'message', '', _('use <text> as commit message')),
3155 ] + commitopts2,
3159 ] + commitopts2,
3156 _('hg tag [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME')),
3160 _('hg tag [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME')),
3157 "tags": (tags, [], _('hg tags')),
3161 "tags": (tags, [], _('hg tags')),
3158 "tip":
3162 "tip":
3159 (tip,
3163 (tip,
3160 [('p', 'patch', None, _('show patch')),
3164 [('p', 'patch', None, _('show patch')),
3161 ] + templateopts,
3165 ] + templateopts,
3162 _('hg tip [-p]')),
3166 _('hg tip [-p]')),
3163 "unbundle":
3167 "unbundle":
3164 (unbundle,
3168 (unbundle,
3165 [('u', 'update', None,
3169 [('u', 'update', None,
3166 _('update to new tip if changesets were unbundled'))],
3170 _('update to new tip if changesets were unbundled'))],
3167 _('hg unbundle [-u] FILE...')),
3171 _('hg unbundle [-u] FILE...')),
3168 "^update|up|checkout|co":
3172 "^update|up|checkout|co":
3169 (update,
3173 (update,
3170 [('C', 'clean', None, _('overwrite locally modified files')),
3174 [('C', 'clean', None, _('overwrite locally modified files')),
3171 ('d', 'date', '', _('tipmost revision matching date')),
3175 ('d', 'date', '', _('tipmost revision matching date')),
3172 ('r', 'rev', '', _('revision'))],
3176 ('r', 'rev', '', _('revision'))],
3173 _('hg update [-C] [-d DATE] [[-r] REV]')),
3177 _('hg update [-C] [-d DATE] [[-r] REV]')),
3174 "verify": (verify, [], _('hg verify')),
3178 "verify": (verify, [], _('hg verify')),
3175 "version": (version_, [], _('hg version')),
3179 "version": (version_, [], _('hg version')),
3176 }
3180 }
3177
3181
3178 norepo = ("clone init version help debugcomplete debugdata"
3182 norepo = ("clone init version help debugcomplete debugdata"
3179 " debugindex debugindexdot debugdate debuginstall debugfsinfo")
3183 " debugindex debugindexdot debugdate debuginstall debugfsinfo")
3180 optionalrepo = ("identify paths serve showconfig debugancestor")
3184 optionalrepo = ("identify paths serve showconfig debugancestor")
@@ -1,2126 +1,2124
1 # localrepo.py - read/write repository class for mercurial
1 # localrepo.py - read/write repository class for mercurial
2 #
2 #
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms
5 # This software may be used and distributed according to the terms
6 # of the GNU General Public License, incorporated herein by reference.
6 # of the GNU General Public License, incorporated herein by reference.
7
7
8 from node import bin, hex, nullid, nullrev, short
8 from node import bin, hex, nullid, nullrev, short
9 from i18n import _
9 from i18n import _
10 import repo, changegroup
10 import repo, changegroup
11 import changelog, dirstate, filelog, manifest, context, weakref
11 import changelog, dirstate, filelog, manifest, context, weakref
12 import lock, transaction, stat, errno, ui
12 import lock, transaction, stat, errno, ui
13 import os, revlog, time, util, extensions, hook, inspect
13 import os, revlog, time, util, extensions, hook, inspect
14
14
15 class localrepository(repo.repository):
15 class localrepository(repo.repository):
16 capabilities = util.set(('lookup', 'changegroupsubset'))
16 capabilities = util.set(('lookup', 'changegroupsubset'))
17 supported = ('revlogv1', 'store')
17 supported = ('revlogv1', 'store')
18
18
19 def __init__(self, parentui, path=None, create=0):
19 def __init__(self, parentui, path=None, create=0):
20 repo.repository.__init__(self)
20 repo.repository.__init__(self)
21 self.root = os.path.realpath(path)
21 self.root = os.path.realpath(path)
22 self.path = os.path.join(self.root, ".hg")
22 self.path = os.path.join(self.root, ".hg")
23 self.origroot = path
23 self.origroot = path
24 self.opener = util.opener(self.path)
24 self.opener = util.opener(self.path)
25 self.wopener = util.opener(self.root)
25 self.wopener = util.opener(self.root)
26
26
27 if not os.path.isdir(self.path):
27 if not os.path.isdir(self.path):
28 if create:
28 if create:
29 if not os.path.exists(path):
29 if not os.path.exists(path):
30 os.mkdir(path)
30 os.mkdir(path)
31 os.mkdir(self.path)
31 os.mkdir(self.path)
32 requirements = ["revlogv1"]
32 requirements = ["revlogv1"]
33 if parentui.configbool('format', 'usestore', True):
33 if parentui.configbool('format', 'usestore', True):
34 os.mkdir(os.path.join(self.path, "store"))
34 os.mkdir(os.path.join(self.path, "store"))
35 requirements.append("store")
35 requirements.append("store")
36 # create an invalid changelog
36 # create an invalid changelog
37 self.opener("00changelog.i", "a").write(
37 self.opener("00changelog.i", "a").write(
38 '\0\0\0\2' # represents revlogv2
38 '\0\0\0\2' # represents revlogv2
39 ' dummy changelog to prevent using the old repo layout'
39 ' dummy changelog to prevent using the old repo layout'
40 )
40 )
41 reqfile = self.opener("requires", "w")
41 reqfile = self.opener("requires", "w")
42 for r in requirements:
42 for r in requirements:
43 reqfile.write("%s\n" % r)
43 reqfile.write("%s\n" % r)
44 reqfile.close()
44 reqfile.close()
45 else:
45 else:
46 raise repo.RepoError(_("repository %s not found") % path)
46 raise repo.RepoError(_("repository %s not found") % path)
47 elif create:
47 elif create:
48 raise repo.RepoError(_("repository %s already exists") % path)
48 raise repo.RepoError(_("repository %s already exists") % path)
49 else:
49 else:
50 # find requirements
50 # find requirements
51 try:
51 try:
52 requirements = self.opener("requires").read().splitlines()
52 requirements = self.opener("requires").read().splitlines()
53 except IOError, inst:
53 except IOError, inst:
54 if inst.errno != errno.ENOENT:
54 if inst.errno != errno.ENOENT:
55 raise
55 raise
56 requirements = []
56 requirements = []
57 # check them
57 # check them
58 for r in requirements:
58 for r in requirements:
59 if r not in self.supported:
59 if r not in self.supported:
60 raise repo.RepoError(_("requirement '%s' not supported") % r)
60 raise repo.RepoError(_("requirement '%s' not supported") % r)
61
61
62 # setup store
62 # setup store
63 if "store" in requirements:
63 if "store" in requirements:
64 self.encodefn = util.encodefilename
64 self.encodefn = util.encodefilename
65 self.decodefn = util.decodefilename
65 self.decodefn = util.decodefilename
66 self.spath = os.path.join(self.path, "store")
66 self.spath = os.path.join(self.path, "store")
67 else:
67 else:
68 self.encodefn = lambda x: x
68 self.encodefn = lambda x: x
69 self.decodefn = lambda x: x
69 self.decodefn = lambda x: x
70 self.spath = self.path
70 self.spath = self.path
71
71
72 try:
72 try:
73 # files in .hg/ will be created using this mode
73 # files in .hg/ will be created using this mode
74 mode = os.stat(self.spath).st_mode
74 mode = os.stat(self.spath).st_mode
75 # avoid some useless chmods
75 # avoid some useless chmods
76 if (0777 & ~util._umask) == (0777 & mode):
76 if (0777 & ~util._umask) == (0777 & mode):
77 mode = None
77 mode = None
78 except OSError:
78 except OSError:
79 mode = None
79 mode = None
80
80
81 self._createmode = mode
81 self._createmode = mode
82 self.opener.createmode = mode
82 self.opener.createmode = mode
83 sopener = util.opener(self.spath)
83 sopener = util.opener(self.spath)
84 sopener.createmode = mode
84 sopener.createmode = mode
85 self.sopener = util.encodedopener(sopener, self.encodefn)
85 self.sopener = util.encodedopener(sopener, self.encodefn)
86
86
87 self.ui = ui.ui(parentui=parentui)
87 self.ui = ui.ui(parentui=parentui)
88 try:
88 try:
89 self.ui.readconfig(self.join("hgrc"), self.root)
89 self.ui.readconfig(self.join("hgrc"), self.root)
90 extensions.loadall(self.ui)
90 extensions.loadall(self.ui)
91 except IOError:
91 except IOError:
92 pass
92 pass
93
93
94 self.tagscache = None
94 self.tagscache = None
95 self._tagstypecache = None
95 self._tagstypecache = None
96 self.branchcache = None
96 self.branchcache = None
97 self._ubranchcache = None # UTF-8 version of branchcache
97 self._ubranchcache = None # UTF-8 version of branchcache
98 self._branchcachetip = None
98 self._branchcachetip = None
99 self.nodetagscache = None
99 self.nodetagscache = None
100 self.filterpats = {}
100 self.filterpats = {}
101 self._datafilters = {}
101 self._datafilters = {}
102 self._transref = self._lockref = self._wlockref = None
102 self._transref = self._lockref = self._wlockref = None
103
103
104 def __getattr__(self, name):
104 def __getattr__(self, name):
105 if name == 'changelog':
105 if name == 'changelog':
106 self.changelog = changelog.changelog(self.sopener)
106 self.changelog = changelog.changelog(self.sopener)
107 self.sopener.defversion = self.changelog.version
107 self.sopener.defversion = self.changelog.version
108 return self.changelog
108 return self.changelog
109 if name == 'manifest':
109 if name == 'manifest':
110 self.changelog
110 self.changelog
111 self.manifest = manifest.manifest(self.sopener)
111 self.manifest = manifest.manifest(self.sopener)
112 return self.manifest
112 return self.manifest
113 if name == 'dirstate':
113 if name == 'dirstate':
114 self.dirstate = dirstate.dirstate(self.opener, self.ui, self.root)
114 self.dirstate = dirstate.dirstate(self.opener, self.ui, self.root)
115 return self.dirstate
115 return self.dirstate
116 else:
116 else:
117 raise AttributeError, name
117 raise AttributeError, name
118
118
119 def url(self):
119 def url(self):
120 return 'file:' + self.root
120 return 'file:' + self.root
121
121
122 def hook(self, name, throw=False, **args):
122 def hook(self, name, throw=False, **args):
123 return hook.hook(self.ui, self, name, throw, **args)
123 return hook.hook(self.ui, self, name, throw, **args)
124
124
125 tag_disallowed = ':\r\n'
125 tag_disallowed = ':\r\n'
126
126
127 def _tag(self, name, node, message, local, user, date, parent=None,
127 def _tag(self, name, node, message, local, user, date, parent=None,
128 extra={}):
128 extra={}):
129 use_dirstate = parent is None
129 use_dirstate = parent is None
130
130
131 for c in self.tag_disallowed:
131 for c in self.tag_disallowed:
132 if c in name:
132 if c in name:
133 raise util.Abort(_('%r cannot be used in a tag name') % c)
133 raise util.Abort(_('%r cannot be used in a tag name') % c)
134
134
135 self.hook('pretag', throw=True, node=hex(node), tag=name, local=local)
135 self.hook('pretag', throw=True, node=hex(node), tag=name, local=local)
136
136
137 def writetag(fp, name, munge, prevtags):
137 def writetag(fp, name, munge, prevtags):
138 fp.seek(0, 2)
138 fp.seek(0, 2)
139 if prevtags and prevtags[-1] != '\n':
139 if prevtags and prevtags[-1] != '\n':
140 fp.write('\n')
140 fp.write('\n')
141 fp.write('%s %s\n' % (hex(node), munge and munge(name) or name))
141 fp.write('%s %s\n' % (hex(node), munge and munge(name) or name))
142 fp.close()
142 fp.close()
143
143
144 prevtags = ''
144 prevtags = ''
145 if local:
145 if local:
146 try:
146 try:
147 fp = self.opener('localtags', 'r+')
147 fp = self.opener('localtags', 'r+')
148 except IOError, err:
148 except IOError, err:
149 fp = self.opener('localtags', 'a')
149 fp = self.opener('localtags', 'a')
150 else:
150 else:
151 prevtags = fp.read()
151 prevtags = fp.read()
152
152
153 # local tags are stored in the current charset
153 # local tags are stored in the current charset
154 writetag(fp, name, None, prevtags)
154 writetag(fp, name, None, prevtags)
155 self.hook('tag', node=hex(node), tag=name, local=local)
155 self.hook('tag', node=hex(node), tag=name, local=local)
156 return
156 return
157
157
158 if use_dirstate:
158 if use_dirstate:
159 try:
159 try:
160 fp = self.wfile('.hgtags', 'rb+')
160 fp = self.wfile('.hgtags', 'rb+')
161 except IOError, err:
161 except IOError, err:
162 fp = self.wfile('.hgtags', 'ab')
162 fp = self.wfile('.hgtags', 'ab')
163 else:
163 else:
164 prevtags = fp.read()
164 prevtags = fp.read()
165 else:
165 else:
166 try:
166 try:
167 prevtags = self.filectx('.hgtags', parent).data()
167 prevtags = self.filectx('.hgtags', parent).data()
168 except revlog.LookupError:
168 except revlog.LookupError:
169 pass
169 pass
170 fp = self.wfile('.hgtags', 'wb')
170 fp = self.wfile('.hgtags', 'wb')
171 if prevtags:
171 if prevtags:
172 fp.write(prevtags)
172 fp.write(prevtags)
173
173
174 # committed tags are stored in UTF-8
174 # committed tags are stored in UTF-8
175 writetag(fp, name, util.fromlocal, prevtags)
175 writetag(fp, name, util.fromlocal, prevtags)
176
176
177 if use_dirstate and '.hgtags' not in self.dirstate:
177 if use_dirstate and '.hgtags' not in self.dirstate:
178 self.add(['.hgtags'])
178 self.add(['.hgtags'])
179
179
180 tagnode = self.commit(['.hgtags'], message, user, date, p1=parent,
180 tagnode = self.commit(['.hgtags'], message, user, date, p1=parent,
181 extra=extra)
181 extra=extra)
182
182
183 self.hook('tag', node=hex(node), tag=name, local=local)
183 self.hook('tag', node=hex(node), tag=name, local=local)
184
184
185 return tagnode
185 return tagnode
186
186
187 def tag(self, name, node, message, local, user, date):
187 def tag(self, name, node, message, local, user, date):
188 '''tag a revision with a symbolic name.
188 '''tag a revision with a symbolic name.
189
189
190 if local is True, the tag is stored in a per-repository file.
190 if local is True, the tag is stored in a per-repository file.
191 otherwise, it is stored in the .hgtags file, and a new
191 otherwise, it is stored in the .hgtags file, and a new
192 changeset is committed with the change.
192 changeset is committed with the change.
193
193
194 keyword arguments:
194 keyword arguments:
195
195
196 local: whether to store tag in non-version-controlled file
196 local: whether to store tag in non-version-controlled file
197 (default False)
197 (default False)
198
198
199 message: commit message to use if committing
199 message: commit message to use if committing
200
200
201 user: name of user to use if committing
201 user: name of user to use if committing
202
202
203 date: date tuple to use if committing'''
203 date: date tuple to use if committing'''
204
204
205 date = util.parsedate(date)
206 for x in self.status()[:5]:
205 for x in self.status()[:5]:
207 if '.hgtags' in x:
206 if '.hgtags' in x:
208 raise util.Abort(_('working copy of .hgtags is changed '
207 raise util.Abort(_('working copy of .hgtags is changed '
209 '(please commit .hgtags manually)'))
208 '(please commit .hgtags manually)'))
210
209
211
212 self._tag(name, node, message, local, user, date)
210 self._tag(name, node, message, local, user, date)
213
211
214 def tags(self):
212 def tags(self):
215 '''return a mapping of tag to node'''
213 '''return a mapping of tag to node'''
216 if self.tagscache:
214 if self.tagscache:
217 return self.tagscache
215 return self.tagscache
218
216
219 globaltags = {}
217 globaltags = {}
220 tagtypes = {}
218 tagtypes = {}
221
219
222 def readtags(lines, fn, tagtype):
220 def readtags(lines, fn, tagtype):
223 filetags = {}
221 filetags = {}
224 count = 0
222 count = 0
225
223
226 def warn(msg):
224 def warn(msg):
227 self.ui.warn(_("%s, line %s: %s\n") % (fn, count, msg))
225 self.ui.warn(_("%s, line %s: %s\n") % (fn, count, msg))
228
226
229 for l in lines:
227 for l in lines:
230 count += 1
228 count += 1
231 if not l:
229 if not l:
232 continue
230 continue
233 s = l.split(" ", 1)
231 s = l.split(" ", 1)
234 if len(s) != 2:
232 if len(s) != 2:
235 warn(_("cannot parse entry"))
233 warn(_("cannot parse entry"))
236 continue
234 continue
237 node, key = s
235 node, key = s
238 key = util.tolocal(key.strip()) # stored in UTF-8
236 key = util.tolocal(key.strip()) # stored in UTF-8
239 try:
237 try:
240 bin_n = bin(node)
238 bin_n = bin(node)
241 except TypeError:
239 except TypeError:
242 warn(_("node '%s' is not well formed") % node)
240 warn(_("node '%s' is not well formed") % node)
243 continue
241 continue
244 if bin_n not in self.changelog.nodemap:
242 if bin_n not in self.changelog.nodemap:
245 warn(_("tag '%s' refers to unknown node") % key)
243 warn(_("tag '%s' refers to unknown node") % key)
246 continue
244 continue
247
245
248 h = []
246 h = []
249 if key in filetags:
247 if key in filetags:
250 n, h = filetags[key]
248 n, h = filetags[key]
251 h.append(n)
249 h.append(n)
252 filetags[key] = (bin_n, h)
250 filetags[key] = (bin_n, h)
253
251
254 for k, nh in filetags.items():
252 for k, nh in filetags.items():
255 if k not in globaltags:
253 if k not in globaltags:
256 globaltags[k] = nh
254 globaltags[k] = nh
257 tagtypes[k] = tagtype
255 tagtypes[k] = tagtype
258 continue
256 continue
259
257
260 # we prefer the global tag if:
258 # we prefer the global tag if:
261 # it supercedes us OR
259 # it supercedes us OR
262 # mutual supercedes and it has a higher rank
260 # mutual supercedes and it has a higher rank
263 # otherwise we win because we're tip-most
261 # otherwise we win because we're tip-most
264 an, ah = nh
262 an, ah = nh
265 bn, bh = globaltags[k]
263 bn, bh = globaltags[k]
266 if (bn != an and an in bh and
264 if (bn != an and an in bh and
267 (bn not in ah or len(bh) > len(ah))):
265 (bn not in ah or len(bh) > len(ah))):
268 an = bn
266 an = bn
269 ah.extend([n for n in bh if n not in ah])
267 ah.extend([n for n in bh if n not in ah])
270 globaltags[k] = an, ah
268 globaltags[k] = an, ah
271 tagtypes[k] = tagtype
269 tagtypes[k] = tagtype
272
270
273 # read the tags file from each head, ending with the tip
271 # read the tags file from each head, ending with the tip
274 f = None
272 f = None
275 for rev, node, fnode in self._hgtagsnodes():
273 for rev, node, fnode in self._hgtagsnodes():
276 f = (f and f.filectx(fnode) or
274 f = (f and f.filectx(fnode) or
277 self.filectx('.hgtags', fileid=fnode))
275 self.filectx('.hgtags', fileid=fnode))
278 readtags(f.data().splitlines(), f, "global")
276 readtags(f.data().splitlines(), f, "global")
279
277
280 try:
278 try:
281 data = util.fromlocal(self.opener("localtags").read())
279 data = util.fromlocal(self.opener("localtags").read())
282 # localtags are stored in the local character set
280 # localtags are stored in the local character set
283 # while the internal tag table is stored in UTF-8
281 # while the internal tag table is stored in UTF-8
284 readtags(data.splitlines(), "localtags", "local")
282 readtags(data.splitlines(), "localtags", "local")
285 except IOError:
283 except IOError:
286 pass
284 pass
287
285
288 self.tagscache = {}
286 self.tagscache = {}
289 self._tagstypecache = {}
287 self._tagstypecache = {}
290 for k,nh in globaltags.items():
288 for k,nh in globaltags.items():
291 n = nh[0]
289 n = nh[0]
292 if n != nullid:
290 if n != nullid:
293 self.tagscache[k] = n
291 self.tagscache[k] = n
294 self._tagstypecache[k] = tagtypes[k]
292 self._tagstypecache[k] = tagtypes[k]
295 self.tagscache['tip'] = self.changelog.tip()
293 self.tagscache['tip'] = self.changelog.tip()
296
294
297 return self.tagscache
295 return self.tagscache
298
296
299 def tagtype(self, tagname):
297 def tagtype(self, tagname):
300 '''
298 '''
301 return the type of the given tag. result can be:
299 return the type of the given tag. result can be:
302
300
303 'local' : a local tag
301 'local' : a local tag
304 'global' : a global tag
302 'global' : a global tag
305 None : tag does not exist
303 None : tag does not exist
306 '''
304 '''
307
305
308 self.tags()
306 self.tags()
309
307
310 return self._tagstypecache.get(tagname)
308 return self._tagstypecache.get(tagname)
311
309
312 def _hgtagsnodes(self):
310 def _hgtagsnodes(self):
313 heads = self.heads()
311 heads = self.heads()
314 heads.reverse()
312 heads.reverse()
315 last = {}
313 last = {}
316 ret = []
314 ret = []
317 for node in heads:
315 for node in heads:
318 c = self.changectx(node)
316 c = self.changectx(node)
319 rev = c.rev()
317 rev = c.rev()
320 try:
318 try:
321 fnode = c.filenode('.hgtags')
319 fnode = c.filenode('.hgtags')
322 except revlog.LookupError:
320 except revlog.LookupError:
323 continue
321 continue
324 ret.append((rev, node, fnode))
322 ret.append((rev, node, fnode))
325 if fnode in last:
323 if fnode in last:
326 ret[last[fnode]] = None
324 ret[last[fnode]] = None
327 last[fnode] = len(ret) - 1
325 last[fnode] = len(ret) - 1
328 return [item for item in ret if item]
326 return [item for item in ret if item]
329
327
330 def tagslist(self):
328 def tagslist(self):
331 '''return a list of tags ordered by revision'''
329 '''return a list of tags ordered by revision'''
332 l = []
330 l = []
333 for t, n in self.tags().items():
331 for t, n in self.tags().items():
334 try:
332 try:
335 r = self.changelog.rev(n)
333 r = self.changelog.rev(n)
336 except:
334 except:
337 r = -2 # sort to the beginning of the list if unknown
335 r = -2 # sort to the beginning of the list if unknown
338 l.append((r, t, n))
336 l.append((r, t, n))
339 l.sort()
337 l.sort()
340 return [(t, n) for r, t, n in l]
338 return [(t, n) for r, t, n in l]
341
339
342 def nodetags(self, node):
340 def nodetags(self, node):
343 '''return the tags associated with a node'''
341 '''return the tags associated with a node'''
344 if not self.nodetagscache:
342 if not self.nodetagscache:
345 self.nodetagscache = {}
343 self.nodetagscache = {}
346 for t, n in self.tags().items():
344 for t, n in self.tags().items():
347 self.nodetagscache.setdefault(n, []).append(t)
345 self.nodetagscache.setdefault(n, []).append(t)
348 return self.nodetagscache.get(node, [])
346 return self.nodetagscache.get(node, [])
349
347
350 def _branchtags(self, partial, lrev):
348 def _branchtags(self, partial, lrev):
351 tiprev = self.changelog.count() - 1
349 tiprev = self.changelog.count() - 1
352 if lrev != tiprev:
350 if lrev != tiprev:
353 self._updatebranchcache(partial, lrev+1, tiprev+1)
351 self._updatebranchcache(partial, lrev+1, tiprev+1)
354 self._writebranchcache(partial, self.changelog.tip(), tiprev)
352 self._writebranchcache(partial, self.changelog.tip(), tiprev)
355
353
356 return partial
354 return partial
357
355
358 def branchtags(self):
356 def branchtags(self):
359 tip = self.changelog.tip()
357 tip = self.changelog.tip()
360 if self.branchcache is not None and self._branchcachetip == tip:
358 if self.branchcache is not None and self._branchcachetip == tip:
361 return self.branchcache
359 return self.branchcache
362
360
363 oldtip = self._branchcachetip
361 oldtip = self._branchcachetip
364 self._branchcachetip = tip
362 self._branchcachetip = tip
365 if self.branchcache is None:
363 if self.branchcache is None:
366 self.branchcache = {} # avoid recursion in changectx
364 self.branchcache = {} # avoid recursion in changectx
367 else:
365 else:
368 self.branchcache.clear() # keep using the same dict
366 self.branchcache.clear() # keep using the same dict
369 if oldtip is None or oldtip not in self.changelog.nodemap:
367 if oldtip is None or oldtip not in self.changelog.nodemap:
370 partial, last, lrev = self._readbranchcache()
368 partial, last, lrev = self._readbranchcache()
371 else:
369 else:
372 lrev = self.changelog.rev(oldtip)
370 lrev = self.changelog.rev(oldtip)
373 partial = self._ubranchcache
371 partial = self._ubranchcache
374
372
375 self._branchtags(partial, lrev)
373 self._branchtags(partial, lrev)
376
374
377 # the branch cache is stored on disk as UTF-8, but in the local
375 # the branch cache is stored on disk as UTF-8, but in the local
378 # charset internally
376 # charset internally
379 for k, v in partial.items():
377 for k, v in partial.items():
380 self.branchcache[util.tolocal(k)] = v
378 self.branchcache[util.tolocal(k)] = v
381 self._ubranchcache = partial
379 self._ubranchcache = partial
382 return self.branchcache
380 return self.branchcache
383
381
384 def _readbranchcache(self):
382 def _readbranchcache(self):
385 partial = {}
383 partial = {}
386 try:
384 try:
387 f = self.opener("branch.cache")
385 f = self.opener("branch.cache")
388 lines = f.read().split('\n')
386 lines = f.read().split('\n')
389 f.close()
387 f.close()
390 except (IOError, OSError):
388 except (IOError, OSError):
391 return {}, nullid, nullrev
389 return {}, nullid, nullrev
392
390
393 try:
391 try:
394 last, lrev = lines.pop(0).split(" ", 1)
392 last, lrev = lines.pop(0).split(" ", 1)
395 last, lrev = bin(last), int(lrev)
393 last, lrev = bin(last), int(lrev)
396 if not (lrev < self.changelog.count() and
394 if not (lrev < self.changelog.count() and
397 self.changelog.node(lrev) == last): # sanity check
395 self.changelog.node(lrev) == last): # sanity check
398 # invalidate the cache
396 # invalidate the cache
399 raise ValueError('invalidating branch cache (tip differs)')
397 raise ValueError('invalidating branch cache (tip differs)')
400 for l in lines:
398 for l in lines:
401 if not l: continue
399 if not l: continue
402 node, label = l.split(" ", 1)
400 node, label = l.split(" ", 1)
403 partial[label.strip()] = bin(node)
401 partial[label.strip()] = bin(node)
404 except (KeyboardInterrupt, util.SignalInterrupt):
402 except (KeyboardInterrupt, util.SignalInterrupt):
405 raise
403 raise
406 except Exception, inst:
404 except Exception, inst:
407 if self.ui.debugflag:
405 if self.ui.debugflag:
408 self.ui.warn(str(inst), '\n')
406 self.ui.warn(str(inst), '\n')
409 partial, last, lrev = {}, nullid, nullrev
407 partial, last, lrev = {}, nullid, nullrev
410 return partial, last, lrev
408 return partial, last, lrev
411
409
412 def _writebranchcache(self, branches, tip, tiprev):
410 def _writebranchcache(self, branches, tip, tiprev):
413 try:
411 try:
414 f = self.opener("branch.cache", "w", atomictemp=True)
412 f = self.opener("branch.cache", "w", atomictemp=True)
415 f.write("%s %s\n" % (hex(tip), tiprev))
413 f.write("%s %s\n" % (hex(tip), tiprev))
416 for label, node in branches.iteritems():
414 for label, node in branches.iteritems():
417 f.write("%s %s\n" % (hex(node), label))
415 f.write("%s %s\n" % (hex(node), label))
418 f.rename()
416 f.rename()
419 except (IOError, OSError):
417 except (IOError, OSError):
420 pass
418 pass
421
419
422 def _updatebranchcache(self, partial, start, end):
420 def _updatebranchcache(self, partial, start, end):
423 for r in xrange(start, end):
421 for r in xrange(start, end):
424 c = self.changectx(r)
422 c = self.changectx(r)
425 b = c.branch()
423 b = c.branch()
426 partial[b] = c.node()
424 partial[b] = c.node()
427
425
428 def lookup(self, key):
426 def lookup(self, key):
429 if key == '.':
427 if key == '.':
430 key, second = self.dirstate.parents()
428 key, second = self.dirstate.parents()
431 if key == nullid:
429 if key == nullid:
432 raise repo.RepoError(_("no revision checked out"))
430 raise repo.RepoError(_("no revision checked out"))
433 if second != nullid:
431 if second != nullid:
434 self.ui.warn(_("warning: working directory has two parents, "
432 self.ui.warn(_("warning: working directory has two parents, "
435 "tag '.' uses the first\n"))
433 "tag '.' uses the first\n"))
436 elif key == 'null':
434 elif key == 'null':
437 return nullid
435 return nullid
438 n = self.changelog._match(key)
436 n = self.changelog._match(key)
439 if n:
437 if n:
440 return n
438 return n
441 if key in self.tags():
439 if key in self.tags():
442 return self.tags()[key]
440 return self.tags()[key]
443 if key in self.branchtags():
441 if key in self.branchtags():
444 return self.branchtags()[key]
442 return self.branchtags()[key]
445 n = self.changelog._partialmatch(key)
443 n = self.changelog._partialmatch(key)
446 if n:
444 if n:
447 return n
445 return n
448 try:
446 try:
449 if len(key) == 20:
447 if len(key) == 20:
450 key = hex(key)
448 key = hex(key)
451 except:
449 except:
452 pass
450 pass
453 raise repo.RepoError(_("unknown revision '%s'") % key)
451 raise repo.RepoError(_("unknown revision '%s'") % key)
454
452
455 def dev(self):
453 def dev(self):
456 return os.lstat(self.path).st_dev
454 return os.lstat(self.path).st_dev
457
455
458 def local(self):
456 def local(self):
459 return True
457 return True
460
458
461 def join(self, f):
459 def join(self, f):
462 return os.path.join(self.path, f)
460 return os.path.join(self.path, f)
463
461
464 def sjoin(self, f):
462 def sjoin(self, f):
465 f = self.encodefn(f)
463 f = self.encodefn(f)
466 return os.path.join(self.spath, f)
464 return os.path.join(self.spath, f)
467
465
468 def wjoin(self, f):
466 def wjoin(self, f):
469 return os.path.join(self.root, f)
467 return os.path.join(self.root, f)
470
468
471 def file(self, f):
469 def file(self, f):
472 if f[0] == '/':
470 if f[0] == '/':
473 f = f[1:]
471 f = f[1:]
474 return filelog.filelog(self.sopener, f)
472 return filelog.filelog(self.sopener, f)
475
473
476 def changectx(self, changeid=None):
474 def changectx(self, changeid=None):
477 return context.changectx(self, changeid)
475 return context.changectx(self, changeid)
478
476
479 def workingctx(self):
477 def workingctx(self):
480 return context.workingctx(self)
478 return context.workingctx(self)
481
479
482 def parents(self, changeid=None):
480 def parents(self, changeid=None):
483 '''
481 '''
484 get list of changectxs for parents of changeid or working directory
482 get list of changectxs for parents of changeid or working directory
485 '''
483 '''
486 if changeid is None:
484 if changeid is None:
487 pl = self.dirstate.parents()
485 pl = self.dirstate.parents()
488 else:
486 else:
489 n = self.changelog.lookup(changeid)
487 n = self.changelog.lookup(changeid)
490 pl = self.changelog.parents(n)
488 pl = self.changelog.parents(n)
491 if pl[1] == nullid:
489 if pl[1] == nullid:
492 return [self.changectx(pl[0])]
490 return [self.changectx(pl[0])]
493 return [self.changectx(pl[0]), self.changectx(pl[1])]
491 return [self.changectx(pl[0]), self.changectx(pl[1])]
494
492
495 def filectx(self, path, changeid=None, fileid=None):
493 def filectx(self, path, changeid=None, fileid=None):
496 """changeid can be a changeset revision, node, or tag.
494 """changeid can be a changeset revision, node, or tag.
497 fileid can be a file revision or node."""
495 fileid can be a file revision or node."""
498 return context.filectx(self, path, changeid, fileid)
496 return context.filectx(self, path, changeid, fileid)
499
497
500 def getcwd(self):
498 def getcwd(self):
501 return self.dirstate.getcwd()
499 return self.dirstate.getcwd()
502
500
503 def pathto(self, f, cwd=None):
501 def pathto(self, f, cwd=None):
504 return self.dirstate.pathto(f, cwd)
502 return self.dirstate.pathto(f, cwd)
505
503
506 def wfile(self, f, mode='r'):
504 def wfile(self, f, mode='r'):
507 return self.wopener(f, mode)
505 return self.wopener(f, mode)
508
506
509 def _link(self, f):
507 def _link(self, f):
510 return os.path.islink(self.wjoin(f))
508 return os.path.islink(self.wjoin(f))
511
509
512 def _filter(self, filter, filename, data):
510 def _filter(self, filter, filename, data):
513 if filter not in self.filterpats:
511 if filter not in self.filterpats:
514 l = []
512 l = []
515 for pat, cmd in self.ui.configitems(filter):
513 for pat, cmd in self.ui.configitems(filter):
516 mf = util.matcher(self.root, "", [pat], [], [])[1]
514 mf = util.matcher(self.root, "", [pat], [], [])[1]
517 fn = None
515 fn = None
518 params = cmd
516 params = cmd
519 for name, filterfn in self._datafilters.iteritems():
517 for name, filterfn in self._datafilters.iteritems():
520 if cmd.startswith(name):
518 if cmd.startswith(name):
521 fn = filterfn
519 fn = filterfn
522 params = cmd[len(name):].lstrip()
520 params = cmd[len(name):].lstrip()
523 break
521 break
524 if not fn:
522 if not fn:
525 fn = lambda s, c, **kwargs: util.filter(s, c)
523 fn = lambda s, c, **kwargs: util.filter(s, c)
526 # Wrap old filters not supporting keyword arguments
524 # Wrap old filters not supporting keyword arguments
527 if not inspect.getargspec(fn)[2]:
525 if not inspect.getargspec(fn)[2]:
528 oldfn = fn
526 oldfn = fn
529 fn = lambda s, c, **kwargs: oldfn(s, c)
527 fn = lambda s, c, **kwargs: oldfn(s, c)
530 l.append((mf, fn, params))
528 l.append((mf, fn, params))
531 self.filterpats[filter] = l
529 self.filterpats[filter] = l
532
530
533 for mf, fn, cmd in self.filterpats[filter]:
531 for mf, fn, cmd in self.filterpats[filter]:
534 if mf(filename):
532 if mf(filename):
535 self.ui.debug(_("filtering %s through %s\n") % (filename, cmd))
533 self.ui.debug(_("filtering %s through %s\n") % (filename, cmd))
536 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
534 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
537 break
535 break
538
536
539 return data
537 return data
540
538
541 def adddatafilter(self, name, filter):
539 def adddatafilter(self, name, filter):
542 self._datafilters[name] = filter
540 self._datafilters[name] = filter
543
541
544 def wread(self, filename):
542 def wread(self, filename):
545 if self._link(filename):
543 if self._link(filename):
546 data = os.readlink(self.wjoin(filename))
544 data = os.readlink(self.wjoin(filename))
547 else:
545 else:
548 data = self.wopener(filename, 'r').read()
546 data = self.wopener(filename, 'r').read()
549 return self._filter("encode", filename, data)
547 return self._filter("encode", filename, data)
550
548
551 def wwrite(self, filename, data, flags):
549 def wwrite(self, filename, data, flags):
552 data = self._filter("decode", filename, data)
550 data = self._filter("decode", filename, data)
553 try:
551 try:
554 os.unlink(self.wjoin(filename))
552 os.unlink(self.wjoin(filename))
555 except OSError:
553 except OSError:
556 pass
554 pass
557 self.wopener(filename, 'w').write(data)
555 self.wopener(filename, 'w').write(data)
558 util.set_flags(self.wjoin(filename), flags)
556 util.set_flags(self.wjoin(filename), flags)
559
557
560 def wwritedata(self, filename, data):
558 def wwritedata(self, filename, data):
561 return self._filter("decode", filename, data)
559 return self._filter("decode", filename, data)
562
560
563 def transaction(self):
561 def transaction(self):
564 if self._transref and self._transref():
562 if self._transref and self._transref():
565 return self._transref().nest()
563 return self._transref().nest()
566
564
567 # abort here if the journal already exists
565 # abort here if the journal already exists
568 if os.path.exists(self.sjoin("journal")):
566 if os.path.exists(self.sjoin("journal")):
569 raise repo.RepoError(_("journal already exists - run hg recover"))
567 raise repo.RepoError(_("journal already exists - run hg recover"))
570
568
571 # save dirstate for rollback
569 # save dirstate for rollback
572 try:
570 try:
573 ds = self.opener("dirstate").read()
571 ds = self.opener("dirstate").read()
574 except IOError:
572 except IOError:
575 ds = ""
573 ds = ""
576 self.opener("journal.dirstate", "w").write(ds)
574 self.opener("journal.dirstate", "w").write(ds)
577 self.opener("journal.branch", "w").write(self.dirstate.branch())
575 self.opener("journal.branch", "w").write(self.dirstate.branch())
578
576
579 renames = [(self.sjoin("journal"), self.sjoin("undo")),
577 renames = [(self.sjoin("journal"), self.sjoin("undo")),
580 (self.join("journal.dirstate"), self.join("undo.dirstate")),
578 (self.join("journal.dirstate"), self.join("undo.dirstate")),
581 (self.join("journal.branch"), self.join("undo.branch"))]
579 (self.join("journal.branch"), self.join("undo.branch"))]
582 tr = transaction.transaction(self.ui.warn, self.sopener,
580 tr = transaction.transaction(self.ui.warn, self.sopener,
583 self.sjoin("journal"),
581 self.sjoin("journal"),
584 aftertrans(renames),
582 aftertrans(renames),
585 self._createmode)
583 self._createmode)
586 self._transref = weakref.ref(tr)
584 self._transref = weakref.ref(tr)
587 return tr
585 return tr
588
586
589 def recover(self):
587 def recover(self):
590 l = self.lock()
588 l = self.lock()
591 try:
589 try:
592 if os.path.exists(self.sjoin("journal")):
590 if os.path.exists(self.sjoin("journal")):
593 self.ui.status(_("rolling back interrupted transaction\n"))
591 self.ui.status(_("rolling back interrupted transaction\n"))
594 transaction.rollback(self.sopener, self.sjoin("journal"))
592 transaction.rollback(self.sopener, self.sjoin("journal"))
595 self.invalidate()
593 self.invalidate()
596 return True
594 return True
597 else:
595 else:
598 self.ui.warn(_("no interrupted transaction available\n"))
596 self.ui.warn(_("no interrupted transaction available\n"))
599 return False
597 return False
600 finally:
598 finally:
601 del l
599 del l
602
600
603 def rollback(self):
601 def rollback(self):
604 wlock = lock = None
602 wlock = lock = None
605 try:
603 try:
606 wlock = self.wlock()
604 wlock = self.wlock()
607 lock = self.lock()
605 lock = self.lock()
608 if os.path.exists(self.sjoin("undo")):
606 if os.path.exists(self.sjoin("undo")):
609 self.ui.status(_("rolling back last transaction\n"))
607 self.ui.status(_("rolling back last transaction\n"))
610 transaction.rollback(self.sopener, self.sjoin("undo"))
608 transaction.rollback(self.sopener, self.sjoin("undo"))
611 util.rename(self.join("undo.dirstate"), self.join("dirstate"))
609 util.rename(self.join("undo.dirstate"), self.join("dirstate"))
612 try:
610 try:
613 branch = self.opener("undo.branch").read()
611 branch = self.opener("undo.branch").read()
614 self.dirstate.setbranch(branch)
612 self.dirstate.setbranch(branch)
615 except IOError:
613 except IOError:
616 self.ui.warn(_("Named branch could not be reset, "
614 self.ui.warn(_("Named branch could not be reset, "
617 "current branch still is: %s\n")
615 "current branch still is: %s\n")
618 % util.tolocal(self.dirstate.branch()))
616 % util.tolocal(self.dirstate.branch()))
619 self.invalidate()
617 self.invalidate()
620 self.dirstate.invalidate()
618 self.dirstate.invalidate()
621 else:
619 else:
622 self.ui.warn(_("no rollback information available\n"))
620 self.ui.warn(_("no rollback information available\n"))
623 finally:
621 finally:
624 del lock, wlock
622 del lock, wlock
625
623
626 def invalidate(self):
624 def invalidate(self):
627 for a in "changelog manifest".split():
625 for a in "changelog manifest".split():
628 if hasattr(self, a):
626 if hasattr(self, a):
629 self.__delattr__(a)
627 self.__delattr__(a)
630 self.tagscache = None
628 self.tagscache = None
631 self._tagstypecache = None
629 self._tagstypecache = None
632 self.nodetagscache = None
630 self.nodetagscache = None
633 self.branchcache = None
631 self.branchcache = None
634 self._ubranchcache = None
632 self._ubranchcache = None
635 self._branchcachetip = None
633 self._branchcachetip = None
636
634
637 def _lock(self, lockname, wait, releasefn, acquirefn, desc):
635 def _lock(self, lockname, wait, releasefn, acquirefn, desc):
638 try:
636 try:
639 l = lock.lock(lockname, 0, releasefn, desc=desc)
637 l = lock.lock(lockname, 0, releasefn, desc=desc)
640 except lock.LockHeld, inst:
638 except lock.LockHeld, inst:
641 if not wait:
639 if not wait:
642 raise
640 raise
643 self.ui.warn(_("waiting for lock on %s held by %r\n") %
641 self.ui.warn(_("waiting for lock on %s held by %r\n") %
644 (desc, inst.locker))
642 (desc, inst.locker))
645 # default to 600 seconds timeout
643 # default to 600 seconds timeout
646 l = lock.lock(lockname, int(self.ui.config("ui", "timeout", "600")),
644 l = lock.lock(lockname, int(self.ui.config("ui", "timeout", "600")),
647 releasefn, desc=desc)
645 releasefn, desc=desc)
648 if acquirefn:
646 if acquirefn:
649 acquirefn()
647 acquirefn()
650 return l
648 return l
651
649
652 def lock(self, wait=True):
650 def lock(self, wait=True):
653 if self._lockref and self._lockref():
651 if self._lockref and self._lockref():
654 return self._lockref()
652 return self._lockref()
655
653
656 l = self._lock(self.sjoin("lock"), wait, None, self.invalidate,
654 l = self._lock(self.sjoin("lock"), wait, None, self.invalidate,
657 _('repository %s') % self.origroot)
655 _('repository %s') % self.origroot)
658 self._lockref = weakref.ref(l)
656 self._lockref = weakref.ref(l)
659 return l
657 return l
660
658
661 def wlock(self, wait=True):
659 def wlock(self, wait=True):
662 if self._wlockref and self._wlockref():
660 if self._wlockref and self._wlockref():
663 return self._wlockref()
661 return self._wlockref()
664
662
665 l = self._lock(self.join("wlock"), wait, self.dirstate.write,
663 l = self._lock(self.join("wlock"), wait, self.dirstate.write,
666 self.dirstate.invalidate, _('working directory of %s') %
664 self.dirstate.invalidate, _('working directory of %s') %
667 self.origroot)
665 self.origroot)
668 self._wlockref = weakref.ref(l)
666 self._wlockref = weakref.ref(l)
669 return l
667 return l
670
668
671 def filecommit(self, fn, manifest1, manifest2, linkrev, tr, changelist):
669 def filecommit(self, fn, manifest1, manifest2, linkrev, tr, changelist):
672 """
670 """
673 commit an individual file as part of a larger transaction
671 commit an individual file as part of a larger transaction
674 """
672 """
675
673
676 t = self.wread(fn)
674 t = self.wread(fn)
677 fl = self.file(fn)
675 fl = self.file(fn)
678 fp1 = manifest1.get(fn, nullid)
676 fp1 = manifest1.get(fn, nullid)
679 fp2 = manifest2.get(fn, nullid)
677 fp2 = manifest2.get(fn, nullid)
680
678
681 meta = {}
679 meta = {}
682 cp = self.dirstate.copied(fn)
680 cp = self.dirstate.copied(fn)
683 if cp:
681 if cp:
684 # Mark the new revision of this file as a copy of another
682 # Mark the new revision of this file as a copy of another
685 # file. This copy data will effectively act as a parent
683 # file. This copy data will effectively act as a parent
686 # of this new revision. If this is a merge, the first
684 # of this new revision. If this is a merge, the first
687 # parent will be the nullid (meaning "look up the copy data")
685 # parent will be the nullid (meaning "look up the copy data")
688 # and the second one will be the other parent. For example:
686 # and the second one will be the other parent. For example:
689 #
687 #
690 # 0 --- 1 --- 3 rev1 changes file foo
688 # 0 --- 1 --- 3 rev1 changes file foo
691 # \ / rev2 renames foo to bar and changes it
689 # \ / rev2 renames foo to bar and changes it
692 # \- 2 -/ rev3 should have bar with all changes and
690 # \- 2 -/ rev3 should have bar with all changes and
693 # should record that bar descends from
691 # should record that bar descends from
694 # bar in rev2 and foo in rev1
692 # bar in rev2 and foo in rev1
695 #
693 #
696 # this allows this merge to succeed:
694 # this allows this merge to succeed:
697 #
695 #
698 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
696 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
699 # \ / merging rev3 and rev4 should use bar@rev2
697 # \ / merging rev3 and rev4 should use bar@rev2
700 # \- 2 --- 4 as the merge base
698 # \- 2 --- 4 as the merge base
701 #
699 #
702 meta["copy"] = cp
700 meta["copy"] = cp
703 if not manifest2: # not a branch merge
701 if not manifest2: # not a branch merge
704 meta["copyrev"] = hex(manifest1.get(cp, nullid))
702 meta["copyrev"] = hex(manifest1.get(cp, nullid))
705 fp2 = nullid
703 fp2 = nullid
706 elif fp2 != nullid: # copied on remote side
704 elif fp2 != nullid: # copied on remote side
707 meta["copyrev"] = hex(manifest1.get(cp, nullid))
705 meta["copyrev"] = hex(manifest1.get(cp, nullid))
708 elif fp1 != nullid: # copied on local side, reversed
706 elif fp1 != nullid: # copied on local side, reversed
709 meta["copyrev"] = hex(manifest2.get(cp))
707 meta["copyrev"] = hex(manifest2.get(cp))
710 fp2 = fp1
708 fp2 = fp1
711 elif cp in manifest2: # directory rename on local side
709 elif cp in manifest2: # directory rename on local side
712 meta["copyrev"] = hex(manifest2[cp])
710 meta["copyrev"] = hex(manifest2[cp])
713 else: # directory rename on remote side
711 else: # directory rename on remote side
714 meta["copyrev"] = hex(manifest1.get(cp, nullid))
712 meta["copyrev"] = hex(manifest1.get(cp, nullid))
715 self.ui.debug(_(" %s: copy %s:%s\n") %
713 self.ui.debug(_(" %s: copy %s:%s\n") %
716 (fn, cp, meta["copyrev"]))
714 (fn, cp, meta["copyrev"]))
717 fp1 = nullid
715 fp1 = nullid
718 elif fp2 != nullid:
716 elif fp2 != nullid:
719 # is one parent an ancestor of the other?
717 # is one parent an ancestor of the other?
720 fpa = fl.ancestor(fp1, fp2)
718 fpa = fl.ancestor(fp1, fp2)
721 if fpa == fp1:
719 if fpa == fp1:
722 fp1, fp2 = fp2, nullid
720 fp1, fp2 = fp2, nullid
723 elif fpa == fp2:
721 elif fpa == fp2:
724 fp2 = nullid
722 fp2 = nullid
725
723
726 # is the file unmodified from the parent? report existing entry
724 # is the file unmodified from the parent? report existing entry
727 if fp2 == nullid and not fl.cmp(fp1, t) and not meta:
725 if fp2 == nullid and not fl.cmp(fp1, t) and not meta:
728 return fp1
726 return fp1
729
727
730 changelist.append(fn)
728 changelist.append(fn)
731 return fl.add(t, meta, tr, linkrev, fp1, fp2)
729 return fl.add(t, meta, tr, linkrev, fp1, fp2)
732
730
733 def rawcommit(self, files, text, user, date, p1=None, p2=None, extra={}):
731 def rawcommit(self, files, text, user, date, p1=None, p2=None, extra={}):
734 if p1 is None:
732 if p1 is None:
735 p1, p2 = self.dirstate.parents()
733 p1, p2 = self.dirstate.parents()
736 return self.commit(files=files, text=text, user=user, date=date,
734 return self.commit(files=files, text=text, user=user, date=date,
737 p1=p1, p2=p2, extra=extra, empty_ok=True)
735 p1=p1, p2=p2, extra=extra, empty_ok=True)
738
736
739 def commit(self, files=None, text="", user=None, date=None,
737 def commit(self, files=None, text="", user=None, date=None,
740 match=util.always, force=False, force_editor=False,
738 match=util.always, force=False, force_editor=False,
741 p1=None, p2=None, extra={}, empty_ok=False):
739 p1=None, p2=None, extra={}, empty_ok=False):
742 wlock = lock = tr = None
740 wlock = lock = tr = None
743 valid = 0 # don't save the dirstate if this isn't set
741 valid = 0 # don't save the dirstate if this isn't set
744 if files:
742 if files:
745 files = util.unique(files)
743 files = util.unique(files)
746 try:
744 try:
747 commit = []
745 commit = []
748 remove = []
746 remove = []
749 changed = []
747 changed = []
750 use_dirstate = (p1 is None) # not rawcommit
748 use_dirstate = (p1 is None) # not rawcommit
751 extra = extra.copy()
749 extra = extra.copy()
752
750
753 if use_dirstate:
751 if use_dirstate:
754 if files:
752 if files:
755 for f in files:
753 for f in files:
756 s = self.dirstate[f]
754 s = self.dirstate[f]
757 if s in 'nma':
755 if s in 'nma':
758 commit.append(f)
756 commit.append(f)
759 elif s == 'r':
757 elif s == 'r':
760 remove.append(f)
758 remove.append(f)
761 else:
759 else:
762 self.ui.warn(_("%s not tracked!\n") % f)
760 self.ui.warn(_("%s not tracked!\n") % f)
763 else:
761 else:
764 changes = self.status(match=match)[:5]
762 changes = self.status(match=match)[:5]
765 modified, added, removed, deleted, unknown = changes
763 modified, added, removed, deleted, unknown = changes
766 commit = modified + added
764 commit = modified + added
767 remove = removed
765 remove = removed
768 else:
766 else:
769 commit = files
767 commit = files
770
768
771 if use_dirstate:
769 if use_dirstate:
772 p1, p2 = self.dirstate.parents()
770 p1, p2 = self.dirstate.parents()
773 update_dirstate = True
771 update_dirstate = True
774 else:
772 else:
775 p1, p2 = p1, p2 or nullid
773 p1, p2 = p1, p2 or nullid
776 update_dirstate = (self.dirstate.parents()[0] == p1)
774 update_dirstate = (self.dirstate.parents()[0] == p1)
777
775
778 c1 = self.changelog.read(p1)
776 c1 = self.changelog.read(p1)
779 c2 = self.changelog.read(p2)
777 c2 = self.changelog.read(p2)
780 m1 = self.manifest.read(c1[0]).copy()
778 m1 = self.manifest.read(c1[0]).copy()
781 m2 = self.manifest.read(c2[0])
779 m2 = self.manifest.read(c2[0])
782
780
783 if use_dirstate:
781 if use_dirstate:
784 branchname = self.workingctx().branch()
782 branchname = self.workingctx().branch()
785 try:
783 try:
786 branchname = branchname.decode('UTF-8').encode('UTF-8')
784 branchname = branchname.decode('UTF-8').encode('UTF-8')
787 except UnicodeDecodeError:
785 except UnicodeDecodeError:
788 raise util.Abort(_('branch name not in UTF-8!'))
786 raise util.Abort(_('branch name not in UTF-8!'))
789 else:
787 else:
790 branchname = ""
788 branchname = ""
791
789
792 if use_dirstate:
790 if use_dirstate:
793 oldname = c1[5].get("branch") # stored in UTF-8
791 oldname = c1[5].get("branch") # stored in UTF-8
794 if (not commit and not remove and not force and p2 == nullid
792 if (not commit and not remove and not force and p2 == nullid
795 and branchname == oldname):
793 and branchname == oldname):
796 self.ui.status(_("nothing changed\n"))
794 self.ui.status(_("nothing changed\n"))
797 return None
795 return None
798
796
799 xp1 = hex(p1)
797 xp1 = hex(p1)
800 if p2 == nullid: xp2 = ''
798 if p2 == nullid: xp2 = ''
801 else: xp2 = hex(p2)
799 else: xp2 = hex(p2)
802
800
803 self.hook("precommit", throw=True, parent1=xp1, parent2=xp2)
801 self.hook("precommit", throw=True, parent1=xp1, parent2=xp2)
804
802
805 wlock = self.wlock()
803 wlock = self.wlock()
806 lock = self.lock()
804 lock = self.lock()
807 tr = self.transaction()
805 tr = self.transaction()
808 trp = weakref.proxy(tr)
806 trp = weakref.proxy(tr)
809
807
810 # check in files
808 # check in files
811 new = {}
809 new = {}
812 linkrev = self.changelog.count()
810 linkrev = self.changelog.count()
813 commit.sort()
811 commit.sort()
814 is_exec = util.execfunc(self.root, m1.execf)
812 is_exec = util.execfunc(self.root, m1.execf)
815 is_link = util.linkfunc(self.root, m1.linkf)
813 is_link = util.linkfunc(self.root, m1.linkf)
816 for f in commit:
814 for f in commit:
817 self.ui.note(f + "\n")
815 self.ui.note(f + "\n")
818 try:
816 try:
819 new[f] = self.filecommit(f, m1, m2, linkrev, trp, changed)
817 new[f] = self.filecommit(f, m1, m2, linkrev, trp, changed)
820 new_exec = is_exec(f)
818 new_exec = is_exec(f)
821 new_link = is_link(f)
819 new_link = is_link(f)
822 if ((not changed or changed[-1] != f) and
820 if ((not changed or changed[-1] != f) and
823 m2.get(f) != new[f]):
821 m2.get(f) != new[f]):
824 # mention the file in the changelog if some
822 # mention the file in the changelog if some
825 # flag changed, even if there was no content
823 # flag changed, even if there was no content
826 # change.
824 # change.
827 old_exec = m1.execf(f)
825 old_exec = m1.execf(f)
828 old_link = m1.linkf(f)
826 old_link = m1.linkf(f)
829 if old_exec != new_exec or old_link != new_link:
827 if old_exec != new_exec or old_link != new_link:
830 changed.append(f)
828 changed.append(f)
831 m1.set(f, new_exec, new_link)
829 m1.set(f, new_exec, new_link)
832 if use_dirstate:
830 if use_dirstate:
833 self.dirstate.normal(f)
831 self.dirstate.normal(f)
834
832
835 except (OSError, IOError):
833 except (OSError, IOError):
836 if use_dirstate:
834 if use_dirstate:
837 self.ui.warn(_("trouble committing %s!\n") % f)
835 self.ui.warn(_("trouble committing %s!\n") % f)
838 raise
836 raise
839 else:
837 else:
840 remove.append(f)
838 remove.append(f)
841
839
842 # update manifest
840 # update manifest
843 m1.update(new)
841 m1.update(new)
844 remove.sort()
842 remove.sort()
845 removed = []
843 removed = []
846
844
847 for f in remove:
845 for f in remove:
848 if f in m1:
846 if f in m1:
849 del m1[f]
847 del m1[f]
850 removed.append(f)
848 removed.append(f)
851 elif f in m2:
849 elif f in m2:
852 removed.append(f)
850 removed.append(f)
853 mn = self.manifest.add(m1, trp, linkrev, c1[0], c2[0],
851 mn = self.manifest.add(m1, trp, linkrev, c1[0], c2[0],
854 (new, removed))
852 (new, removed))
855
853
856 # add changeset
854 # add changeset
857 new = new.keys()
855 new = new.keys()
858 new.sort()
856 new.sort()
859
857
860 user = user or self.ui.username()
858 user = user or self.ui.username()
861 if (not empty_ok and not text) or force_editor:
859 if (not empty_ok and not text) or force_editor:
862 edittext = []
860 edittext = []
863 if text:
861 if text:
864 edittext.append(text)
862 edittext.append(text)
865 edittext.append("")
863 edittext.append("")
866 edittext.append(_("HG: Enter commit message."
864 edittext.append(_("HG: Enter commit message."
867 " Lines beginning with 'HG:' are removed."))
865 " Lines beginning with 'HG:' are removed."))
868 edittext.append("HG: --")
866 edittext.append("HG: --")
869 edittext.append("HG: user: %s" % user)
867 edittext.append("HG: user: %s" % user)
870 if p2 != nullid:
868 if p2 != nullid:
871 edittext.append("HG: branch merge")
869 edittext.append("HG: branch merge")
872 if branchname:
870 if branchname:
873 edittext.append("HG: branch '%s'" % util.tolocal(branchname))
871 edittext.append("HG: branch '%s'" % util.tolocal(branchname))
874 edittext.extend(["HG: changed %s" % f for f in changed])
872 edittext.extend(["HG: changed %s" % f for f in changed])
875 edittext.extend(["HG: removed %s" % f for f in removed])
873 edittext.extend(["HG: removed %s" % f for f in removed])
876 if not changed and not remove:
874 if not changed and not remove:
877 edittext.append("HG: no files changed")
875 edittext.append("HG: no files changed")
878 edittext.append("")
876 edittext.append("")
879 # run editor in the repository root
877 # run editor in the repository root
880 olddir = os.getcwd()
878 olddir = os.getcwd()
881 os.chdir(self.root)
879 os.chdir(self.root)
882 text = self.ui.edit("\n".join(edittext), user)
880 text = self.ui.edit("\n".join(edittext), user)
883 os.chdir(olddir)
881 os.chdir(olddir)
884
882
885 if branchname:
883 if branchname:
886 extra["branch"] = branchname
884 extra["branch"] = branchname
887
885
888 if use_dirstate:
886 if use_dirstate:
889 lines = [line.rstrip() for line in text.rstrip().splitlines()]
887 lines = [line.rstrip() for line in text.rstrip().splitlines()]
890 while lines and not lines[0]:
888 while lines and not lines[0]:
891 del lines[0]
889 del lines[0]
892 if not lines:
890 if not lines:
893 raise util.Abort(_("empty commit message"))
891 raise util.Abort(_("empty commit message"))
894 text = '\n'.join(lines)
892 text = '\n'.join(lines)
895
893
896 n = self.changelog.add(mn, changed + removed, text, trp, p1, p2,
894 n = self.changelog.add(mn, changed + removed, text, trp, p1, p2,
897 user, date, extra)
895 user, date, extra)
898 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
896 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
899 parent2=xp2)
897 parent2=xp2)
900 tr.close()
898 tr.close()
901
899
902 if self.branchcache:
900 if self.branchcache:
903 self.branchtags()
901 self.branchtags()
904
902
905 if use_dirstate or update_dirstate:
903 if use_dirstate or update_dirstate:
906 self.dirstate.setparents(n)
904 self.dirstate.setparents(n)
907 if use_dirstate:
905 if use_dirstate:
908 for f in removed:
906 for f in removed:
909 self.dirstate.forget(f)
907 self.dirstate.forget(f)
910 valid = 1 # our dirstate updates are complete
908 valid = 1 # our dirstate updates are complete
911
909
912 self.hook("commit", node=hex(n), parent1=xp1, parent2=xp2)
910 self.hook("commit", node=hex(n), parent1=xp1, parent2=xp2)
913 return n
911 return n
914 finally:
912 finally:
915 if not valid: # don't save our updated dirstate
913 if not valid: # don't save our updated dirstate
916 self.dirstate.invalidate()
914 self.dirstate.invalidate()
917 del tr, lock, wlock
915 del tr, lock, wlock
918
916
919 def walk(self, node=None, files=[], match=util.always, badmatch=None):
917 def walk(self, node=None, files=[], match=util.always, badmatch=None):
920 '''
918 '''
921 walk recursively through the directory tree or a given
919 walk recursively through the directory tree or a given
922 changeset, finding all files matched by the match
920 changeset, finding all files matched by the match
923 function
921 function
924
922
925 results are yielded in a tuple (src, filename), where src
923 results are yielded in a tuple (src, filename), where src
926 is one of:
924 is one of:
927 'f' the file was found in the directory tree
925 'f' the file was found in the directory tree
928 'm' the file was only in the dirstate and not in the tree
926 'm' the file was only in the dirstate and not in the tree
929 'b' file was not found and matched badmatch
927 'b' file was not found and matched badmatch
930 '''
928 '''
931
929
932 if node:
930 if node:
933 fdict = dict.fromkeys(files)
931 fdict = dict.fromkeys(files)
934 # for dirstate.walk, files=['.'] means "walk the whole tree".
932 # for dirstate.walk, files=['.'] means "walk the whole tree".
935 # follow that here, too
933 # follow that here, too
936 fdict.pop('.', None)
934 fdict.pop('.', None)
937 mdict = self.manifest.read(self.changelog.read(node)[0])
935 mdict = self.manifest.read(self.changelog.read(node)[0])
938 mfiles = mdict.keys()
936 mfiles = mdict.keys()
939 mfiles.sort()
937 mfiles.sort()
940 for fn in mfiles:
938 for fn in mfiles:
941 for ffn in fdict:
939 for ffn in fdict:
942 # match if the file is the exact name or a directory
940 # match if the file is the exact name or a directory
943 if ffn == fn or fn.startswith("%s/" % ffn):
941 if ffn == fn or fn.startswith("%s/" % ffn):
944 del fdict[ffn]
942 del fdict[ffn]
945 break
943 break
946 if match(fn):
944 if match(fn):
947 yield 'm', fn
945 yield 'm', fn
948 ffiles = fdict.keys()
946 ffiles = fdict.keys()
949 ffiles.sort()
947 ffiles.sort()
950 for fn in ffiles:
948 for fn in ffiles:
951 if badmatch and badmatch(fn):
949 if badmatch and badmatch(fn):
952 if match(fn):
950 if match(fn):
953 yield 'b', fn
951 yield 'b', fn
954 else:
952 else:
955 self.ui.warn(_('%s: No such file in rev %s\n')
953 self.ui.warn(_('%s: No such file in rev %s\n')
956 % (self.pathto(fn), short(node)))
954 % (self.pathto(fn), short(node)))
957 else:
955 else:
958 for src, fn in self.dirstate.walk(files, match, badmatch=badmatch):
956 for src, fn in self.dirstate.walk(files, match, badmatch=badmatch):
959 yield src, fn
957 yield src, fn
960
958
961 def status(self, node1=None, node2=None, files=[], match=util.always,
959 def status(self, node1=None, node2=None, files=[], match=util.always,
962 list_ignored=False, list_clean=False, list_unknown=True):
960 list_ignored=False, list_clean=False, list_unknown=True):
963 """return status of files between two nodes or node and working directory
961 """return status of files between two nodes or node and working directory
964
962
965 If node1 is None, use the first dirstate parent instead.
963 If node1 is None, use the first dirstate parent instead.
966 If node2 is None, compare node1 with working directory.
964 If node2 is None, compare node1 with working directory.
967 """
965 """
968
966
969 def fcmp(fn, getnode):
967 def fcmp(fn, getnode):
970 t1 = self.wread(fn)
968 t1 = self.wread(fn)
971 return self.file(fn).cmp(getnode(fn), t1)
969 return self.file(fn).cmp(getnode(fn), t1)
972
970
973 def mfmatches(node):
971 def mfmatches(node):
974 change = self.changelog.read(node)
972 change = self.changelog.read(node)
975 mf = self.manifest.read(change[0]).copy()
973 mf = self.manifest.read(change[0]).copy()
976 for fn in mf.keys():
974 for fn in mf.keys():
977 if not match(fn):
975 if not match(fn):
978 del mf[fn]
976 del mf[fn]
979 return mf
977 return mf
980
978
981 modified, added, removed, deleted, unknown = [], [], [], [], []
979 modified, added, removed, deleted, unknown = [], [], [], [], []
982 ignored, clean = [], []
980 ignored, clean = [], []
983
981
984 compareworking = False
982 compareworking = False
985 if not node1 or (not node2 and node1 == self.dirstate.parents()[0]):
983 if not node1 or (not node2 and node1 == self.dirstate.parents()[0]):
986 compareworking = True
984 compareworking = True
987
985
988 if not compareworking:
986 if not compareworking:
989 # read the manifest from node1 before the manifest from node2,
987 # read the manifest from node1 before the manifest from node2,
990 # so that we'll hit the manifest cache if we're going through
988 # so that we'll hit the manifest cache if we're going through
991 # all the revisions in parent->child order.
989 # all the revisions in parent->child order.
992 mf1 = mfmatches(node1)
990 mf1 = mfmatches(node1)
993
991
994 # are we comparing the working directory?
992 # are we comparing the working directory?
995 if not node2:
993 if not node2:
996 (lookup, modified, added, removed, deleted, unknown,
994 (lookup, modified, added, removed, deleted, unknown,
997 ignored, clean) = self.dirstate.status(files, match,
995 ignored, clean) = self.dirstate.status(files, match,
998 list_ignored, list_clean,
996 list_ignored, list_clean,
999 list_unknown)
997 list_unknown)
1000
998
1001 # are we comparing working dir against its parent?
999 # are we comparing working dir against its parent?
1002 if compareworking:
1000 if compareworking:
1003 if lookup:
1001 if lookup:
1004 fixup = []
1002 fixup = []
1005 # do a full compare of any files that might have changed
1003 # do a full compare of any files that might have changed
1006 ctx = self.changectx()
1004 ctx = self.changectx()
1007 mexec = lambda f: 'x' in ctx.fileflags(f)
1005 mexec = lambda f: 'x' in ctx.fileflags(f)
1008 mlink = lambda f: 'l' in ctx.fileflags(f)
1006 mlink = lambda f: 'l' in ctx.fileflags(f)
1009 is_exec = util.execfunc(self.root, mexec)
1007 is_exec = util.execfunc(self.root, mexec)
1010 is_link = util.linkfunc(self.root, mlink)
1008 is_link = util.linkfunc(self.root, mlink)
1011 def flags(f):
1009 def flags(f):
1012 return is_link(f) and 'l' or is_exec(f) and 'x' or ''
1010 return is_link(f) and 'l' or is_exec(f) and 'x' or ''
1013 for f in lookup:
1011 for f in lookup:
1014 if (f not in ctx or flags(f) != ctx.fileflags(f)
1012 if (f not in ctx or flags(f) != ctx.fileflags(f)
1015 or ctx[f].cmp(self.wread(f))):
1013 or ctx[f].cmp(self.wread(f))):
1016 modified.append(f)
1014 modified.append(f)
1017 else:
1015 else:
1018 fixup.append(f)
1016 fixup.append(f)
1019 if list_clean:
1017 if list_clean:
1020 clean.append(f)
1018 clean.append(f)
1021
1019
1022 # update dirstate for files that are actually clean
1020 # update dirstate for files that are actually clean
1023 if fixup:
1021 if fixup:
1024 wlock = None
1022 wlock = None
1025 try:
1023 try:
1026 try:
1024 try:
1027 wlock = self.wlock(False)
1025 wlock = self.wlock(False)
1028 except lock.LockException:
1026 except lock.LockException:
1029 pass
1027 pass
1030 if wlock:
1028 if wlock:
1031 for f in fixup:
1029 for f in fixup:
1032 self.dirstate.normal(f)
1030 self.dirstate.normal(f)
1033 finally:
1031 finally:
1034 del wlock
1032 del wlock
1035 else:
1033 else:
1036 # we are comparing working dir against non-parent
1034 # we are comparing working dir against non-parent
1037 # generate a pseudo-manifest for the working dir
1035 # generate a pseudo-manifest for the working dir
1038 # XXX: create it in dirstate.py ?
1036 # XXX: create it in dirstate.py ?
1039 mf2 = mfmatches(self.dirstate.parents()[0])
1037 mf2 = mfmatches(self.dirstate.parents()[0])
1040 is_exec = util.execfunc(self.root, mf2.execf)
1038 is_exec = util.execfunc(self.root, mf2.execf)
1041 is_link = util.linkfunc(self.root, mf2.linkf)
1039 is_link = util.linkfunc(self.root, mf2.linkf)
1042 for f in lookup + modified + added:
1040 for f in lookup + modified + added:
1043 mf2[f] = ""
1041 mf2[f] = ""
1044 mf2.set(f, is_exec(f), is_link(f))
1042 mf2.set(f, is_exec(f), is_link(f))
1045 for f in removed:
1043 for f in removed:
1046 if f in mf2:
1044 if f in mf2:
1047 del mf2[f]
1045 del mf2[f]
1048
1046
1049 else:
1047 else:
1050 # we are comparing two revisions
1048 # we are comparing two revisions
1051 mf2 = mfmatches(node2)
1049 mf2 = mfmatches(node2)
1052
1050
1053 if not compareworking:
1051 if not compareworking:
1054 # flush lists from dirstate before comparing manifests
1052 # flush lists from dirstate before comparing manifests
1055 modified, added, clean = [], [], []
1053 modified, added, clean = [], [], []
1056
1054
1057 # make sure to sort the files so we talk to the disk in a
1055 # make sure to sort the files so we talk to the disk in a
1058 # reasonable order
1056 # reasonable order
1059 mf2keys = mf2.keys()
1057 mf2keys = mf2.keys()
1060 mf2keys.sort()
1058 mf2keys.sort()
1061 getnode = lambda fn: mf1.get(fn, nullid)
1059 getnode = lambda fn: mf1.get(fn, nullid)
1062 for fn in mf2keys:
1060 for fn in mf2keys:
1063 if fn in mf1:
1061 if fn in mf1:
1064 if (mf1.flags(fn) != mf2.flags(fn) or
1062 if (mf1.flags(fn) != mf2.flags(fn) or
1065 (mf1[fn] != mf2[fn] and
1063 (mf1[fn] != mf2[fn] and
1066 (mf2[fn] != "" or fcmp(fn, getnode)))):
1064 (mf2[fn] != "" or fcmp(fn, getnode)))):
1067 modified.append(fn)
1065 modified.append(fn)
1068 elif list_clean:
1066 elif list_clean:
1069 clean.append(fn)
1067 clean.append(fn)
1070 del mf1[fn]
1068 del mf1[fn]
1071 else:
1069 else:
1072 added.append(fn)
1070 added.append(fn)
1073
1071
1074 removed = mf1.keys()
1072 removed = mf1.keys()
1075
1073
1076 # sort and return results:
1074 # sort and return results:
1077 for l in modified, added, removed, deleted, unknown, ignored, clean:
1075 for l in modified, added, removed, deleted, unknown, ignored, clean:
1078 l.sort()
1076 l.sort()
1079 return (modified, added, removed, deleted, unknown, ignored, clean)
1077 return (modified, added, removed, deleted, unknown, ignored, clean)
1080
1078
1081 def add(self, list):
1079 def add(self, list):
1082 wlock = self.wlock()
1080 wlock = self.wlock()
1083 try:
1081 try:
1084 rejected = []
1082 rejected = []
1085 for f in list:
1083 for f in list:
1086 p = self.wjoin(f)
1084 p = self.wjoin(f)
1087 try:
1085 try:
1088 st = os.lstat(p)
1086 st = os.lstat(p)
1089 except:
1087 except:
1090 self.ui.warn(_("%s does not exist!\n") % f)
1088 self.ui.warn(_("%s does not exist!\n") % f)
1091 rejected.append(f)
1089 rejected.append(f)
1092 continue
1090 continue
1093 if st.st_size > 10000000:
1091 if st.st_size > 10000000:
1094 self.ui.warn(_("%s: files over 10MB may cause memory and"
1092 self.ui.warn(_("%s: files over 10MB may cause memory and"
1095 " performance problems\n"
1093 " performance problems\n"
1096 "(use 'hg revert %s' to unadd the file)\n")
1094 "(use 'hg revert %s' to unadd the file)\n")
1097 % (f, f))
1095 % (f, f))
1098 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1096 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1099 self.ui.warn(_("%s not added: only files and symlinks "
1097 self.ui.warn(_("%s not added: only files and symlinks "
1100 "supported currently\n") % f)
1098 "supported currently\n") % f)
1101 rejected.append(p)
1099 rejected.append(p)
1102 elif self.dirstate[f] in 'amn':
1100 elif self.dirstate[f] in 'amn':
1103 self.ui.warn(_("%s already tracked!\n") % f)
1101 self.ui.warn(_("%s already tracked!\n") % f)
1104 elif self.dirstate[f] == 'r':
1102 elif self.dirstate[f] == 'r':
1105 self.dirstate.normallookup(f)
1103 self.dirstate.normallookup(f)
1106 else:
1104 else:
1107 self.dirstate.add(f)
1105 self.dirstate.add(f)
1108 return rejected
1106 return rejected
1109 finally:
1107 finally:
1110 del wlock
1108 del wlock
1111
1109
1112 def forget(self, list):
1110 def forget(self, list):
1113 wlock = self.wlock()
1111 wlock = self.wlock()
1114 try:
1112 try:
1115 for f in list:
1113 for f in list:
1116 if self.dirstate[f] != 'a':
1114 if self.dirstate[f] != 'a':
1117 self.ui.warn(_("%s not added!\n") % f)
1115 self.ui.warn(_("%s not added!\n") % f)
1118 else:
1116 else:
1119 self.dirstate.forget(f)
1117 self.dirstate.forget(f)
1120 finally:
1118 finally:
1121 del wlock
1119 del wlock
1122
1120
1123 def remove(self, list, unlink=False):
1121 def remove(self, list, unlink=False):
1124 wlock = None
1122 wlock = None
1125 try:
1123 try:
1126 if unlink:
1124 if unlink:
1127 for f in list:
1125 for f in list:
1128 try:
1126 try:
1129 util.unlink(self.wjoin(f))
1127 util.unlink(self.wjoin(f))
1130 except OSError, inst:
1128 except OSError, inst:
1131 if inst.errno != errno.ENOENT:
1129 if inst.errno != errno.ENOENT:
1132 raise
1130 raise
1133 wlock = self.wlock()
1131 wlock = self.wlock()
1134 for f in list:
1132 for f in list:
1135 if unlink and os.path.exists(self.wjoin(f)):
1133 if unlink and os.path.exists(self.wjoin(f)):
1136 self.ui.warn(_("%s still exists!\n") % f)
1134 self.ui.warn(_("%s still exists!\n") % f)
1137 elif self.dirstate[f] == 'a':
1135 elif self.dirstate[f] == 'a':
1138 self.dirstate.forget(f)
1136 self.dirstate.forget(f)
1139 elif f not in self.dirstate:
1137 elif f not in self.dirstate:
1140 self.ui.warn(_("%s not tracked!\n") % f)
1138 self.ui.warn(_("%s not tracked!\n") % f)
1141 else:
1139 else:
1142 self.dirstate.remove(f)
1140 self.dirstate.remove(f)
1143 finally:
1141 finally:
1144 del wlock
1142 del wlock
1145
1143
1146 def undelete(self, list):
1144 def undelete(self, list):
1147 wlock = None
1145 wlock = None
1148 try:
1146 try:
1149 manifests = [self.manifest.read(self.changelog.read(p)[0])
1147 manifests = [self.manifest.read(self.changelog.read(p)[0])
1150 for p in self.dirstate.parents() if p != nullid]
1148 for p in self.dirstate.parents() if p != nullid]
1151 wlock = self.wlock()
1149 wlock = self.wlock()
1152 for f in list:
1150 for f in list:
1153 if self.dirstate[f] != 'r':
1151 if self.dirstate[f] != 'r':
1154 self.ui.warn("%s not removed!\n" % f)
1152 self.ui.warn("%s not removed!\n" % f)
1155 else:
1153 else:
1156 m = f in manifests[0] and manifests[0] or manifests[1]
1154 m = f in manifests[0] and manifests[0] or manifests[1]
1157 t = self.file(f).read(m[f])
1155 t = self.file(f).read(m[f])
1158 self.wwrite(f, t, m.flags(f))
1156 self.wwrite(f, t, m.flags(f))
1159 self.dirstate.normal(f)
1157 self.dirstate.normal(f)
1160 finally:
1158 finally:
1161 del wlock
1159 del wlock
1162
1160
1163 def copy(self, source, dest):
1161 def copy(self, source, dest):
1164 wlock = None
1162 wlock = None
1165 try:
1163 try:
1166 p = self.wjoin(dest)
1164 p = self.wjoin(dest)
1167 if not (os.path.exists(p) or os.path.islink(p)):
1165 if not (os.path.exists(p) or os.path.islink(p)):
1168 self.ui.warn(_("%s does not exist!\n") % dest)
1166 self.ui.warn(_("%s does not exist!\n") % dest)
1169 elif not (os.path.isfile(p) or os.path.islink(p)):
1167 elif not (os.path.isfile(p) or os.path.islink(p)):
1170 self.ui.warn(_("copy failed: %s is not a file or a "
1168 self.ui.warn(_("copy failed: %s is not a file or a "
1171 "symbolic link\n") % dest)
1169 "symbolic link\n") % dest)
1172 else:
1170 else:
1173 wlock = self.wlock()
1171 wlock = self.wlock()
1174 if dest not in self.dirstate:
1172 if dest not in self.dirstate:
1175 self.dirstate.add(dest)
1173 self.dirstate.add(dest)
1176 self.dirstate.copy(source, dest)
1174 self.dirstate.copy(source, dest)
1177 finally:
1175 finally:
1178 del wlock
1176 del wlock
1179
1177
1180 def heads(self, start=None):
1178 def heads(self, start=None):
1181 heads = self.changelog.heads(start)
1179 heads = self.changelog.heads(start)
1182 # sort the output in rev descending order
1180 # sort the output in rev descending order
1183 heads = [(-self.changelog.rev(h), h) for h in heads]
1181 heads = [(-self.changelog.rev(h), h) for h in heads]
1184 heads.sort()
1182 heads.sort()
1185 return [n for (r, n) in heads]
1183 return [n for (r, n) in heads]
1186
1184
1187 def branchheads(self, branch, start=None):
1185 def branchheads(self, branch, start=None):
1188 branches = self.branchtags()
1186 branches = self.branchtags()
1189 if branch not in branches:
1187 if branch not in branches:
1190 return []
1188 return []
1191 # The basic algorithm is this:
1189 # The basic algorithm is this:
1192 #
1190 #
1193 # Start from the branch tip since there are no later revisions that can
1191 # Start from the branch tip since there are no later revisions that can
1194 # possibly be in this branch, and the tip is a guaranteed head.
1192 # possibly be in this branch, and the tip is a guaranteed head.
1195 #
1193 #
1196 # Remember the tip's parents as the first ancestors, since these by
1194 # Remember the tip's parents as the first ancestors, since these by
1197 # definition are not heads.
1195 # definition are not heads.
1198 #
1196 #
1199 # Step backwards from the brach tip through all the revisions. We are
1197 # Step backwards from the brach tip through all the revisions. We are
1200 # guaranteed by the rules of Mercurial that we will now be visiting the
1198 # guaranteed by the rules of Mercurial that we will now be visiting the
1201 # nodes in reverse topological order (children before parents).
1199 # nodes in reverse topological order (children before parents).
1202 #
1200 #
1203 # If a revision is one of the ancestors of a head then we can toss it
1201 # If a revision is one of the ancestors of a head then we can toss it
1204 # out of the ancestors set (we've already found it and won't be
1202 # out of the ancestors set (we've already found it and won't be
1205 # visiting it again) and put its parents in the ancestors set.
1203 # visiting it again) and put its parents in the ancestors set.
1206 #
1204 #
1207 # Otherwise, if a revision is in the branch it's another head, since it
1205 # Otherwise, if a revision is in the branch it's another head, since it
1208 # wasn't in the ancestor list of an existing head. So add it to the
1206 # wasn't in the ancestor list of an existing head. So add it to the
1209 # head list, and add its parents to the ancestor list.
1207 # head list, and add its parents to the ancestor list.
1210 #
1208 #
1211 # If it is not in the branch ignore it.
1209 # If it is not in the branch ignore it.
1212 #
1210 #
1213 # Once we have a list of heads, use nodesbetween to filter out all the
1211 # Once we have a list of heads, use nodesbetween to filter out all the
1214 # heads that cannot be reached from startrev. There may be a more
1212 # heads that cannot be reached from startrev. There may be a more
1215 # efficient way to do this as part of the previous algorithm.
1213 # efficient way to do this as part of the previous algorithm.
1216
1214
1217 set = util.set
1215 set = util.set
1218 heads = [self.changelog.rev(branches[branch])]
1216 heads = [self.changelog.rev(branches[branch])]
1219 # Don't care if ancestors contains nullrev or not.
1217 # Don't care if ancestors contains nullrev or not.
1220 ancestors = set(self.changelog.parentrevs(heads[0]))
1218 ancestors = set(self.changelog.parentrevs(heads[0]))
1221 for rev in xrange(heads[0] - 1, nullrev, -1):
1219 for rev in xrange(heads[0] - 1, nullrev, -1):
1222 if rev in ancestors:
1220 if rev in ancestors:
1223 ancestors.update(self.changelog.parentrevs(rev))
1221 ancestors.update(self.changelog.parentrevs(rev))
1224 ancestors.remove(rev)
1222 ancestors.remove(rev)
1225 elif self.changectx(rev).branch() == branch:
1223 elif self.changectx(rev).branch() == branch:
1226 heads.append(rev)
1224 heads.append(rev)
1227 ancestors.update(self.changelog.parentrevs(rev))
1225 ancestors.update(self.changelog.parentrevs(rev))
1228 heads = [self.changelog.node(rev) for rev in heads]
1226 heads = [self.changelog.node(rev) for rev in heads]
1229 if start is not None:
1227 if start is not None:
1230 heads = self.changelog.nodesbetween([start], heads)[2]
1228 heads = self.changelog.nodesbetween([start], heads)[2]
1231 return heads
1229 return heads
1232
1230
1233 def branches(self, nodes):
1231 def branches(self, nodes):
1234 if not nodes:
1232 if not nodes:
1235 nodes = [self.changelog.tip()]
1233 nodes = [self.changelog.tip()]
1236 b = []
1234 b = []
1237 for n in nodes:
1235 for n in nodes:
1238 t = n
1236 t = n
1239 while 1:
1237 while 1:
1240 p = self.changelog.parents(n)
1238 p = self.changelog.parents(n)
1241 if p[1] != nullid or p[0] == nullid:
1239 if p[1] != nullid or p[0] == nullid:
1242 b.append((t, n, p[0], p[1]))
1240 b.append((t, n, p[0], p[1]))
1243 break
1241 break
1244 n = p[0]
1242 n = p[0]
1245 return b
1243 return b
1246
1244
1247 def between(self, pairs):
1245 def between(self, pairs):
1248 r = []
1246 r = []
1249
1247
1250 for top, bottom in pairs:
1248 for top, bottom in pairs:
1251 n, l, i = top, [], 0
1249 n, l, i = top, [], 0
1252 f = 1
1250 f = 1
1253
1251
1254 while n != bottom:
1252 while n != bottom:
1255 p = self.changelog.parents(n)[0]
1253 p = self.changelog.parents(n)[0]
1256 if i == f:
1254 if i == f:
1257 l.append(n)
1255 l.append(n)
1258 f = f * 2
1256 f = f * 2
1259 n = p
1257 n = p
1260 i += 1
1258 i += 1
1261
1259
1262 r.append(l)
1260 r.append(l)
1263
1261
1264 return r
1262 return r
1265
1263
1266 def findincoming(self, remote, base=None, heads=None, force=False):
1264 def findincoming(self, remote, base=None, heads=None, force=False):
1267 """Return list of roots of the subsets of missing nodes from remote
1265 """Return list of roots of the subsets of missing nodes from remote
1268
1266
1269 If base dict is specified, assume that these nodes and their parents
1267 If base dict is specified, assume that these nodes and their parents
1270 exist on the remote side and that no child of a node of base exists
1268 exist on the remote side and that no child of a node of base exists
1271 in both remote and self.
1269 in both remote and self.
1272 Furthermore base will be updated to include the nodes that exists
1270 Furthermore base will be updated to include the nodes that exists
1273 in self and remote but no children exists in self and remote.
1271 in self and remote but no children exists in self and remote.
1274 If a list of heads is specified, return only nodes which are heads
1272 If a list of heads is specified, return only nodes which are heads
1275 or ancestors of these heads.
1273 or ancestors of these heads.
1276
1274
1277 All the ancestors of base are in self and in remote.
1275 All the ancestors of base are in self and in remote.
1278 All the descendants of the list returned are missing in self.
1276 All the descendants of the list returned are missing in self.
1279 (and so we know that the rest of the nodes are missing in remote, see
1277 (and so we know that the rest of the nodes are missing in remote, see
1280 outgoing)
1278 outgoing)
1281 """
1279 """
1282 m = self.changelog.nodemap
1280 m = self.changelog.nodemap
1283 search = []
1281 search = []
1284 fetch = {}
1282 fetch = {}
1285 seen = {}
1283 seen = {}
1286 seenbranch = {}
1284 seenbranch = {}
1287 if base == None:
1285 if base == None:
1288 base = {}
1286 base = {}
1289
1287
1290 if not heads:
1288 if not heads:
1291 heads = remote.heads()
1289 heads = remote.heads()
1292
1290
1293 if self.changelog.tip() == nullid:
1291 if self.changelog.tip() == nullid:
1294 base[nullid] = 1
1292 base[nullid] = 1
1295 if heads != [nullid]:
1293 if heads != [nullid]:
1296 return [nullid]
1294 return [nullid]
1297 return []
1295 return []
1298
1296
1299 # assume we're closer to the tip than the root
1297 # assume we're closer to the tip than the root
1300 # and start by examining the heads
1298 # and start by examining the heads
1301 self.ui.status(_("searching for changes\n"))
1299 self.ui.status(_("searching for changes\n"))
1302
1300
1303 unknown = []
1301 unknown = []
1304 for h in heads:
1302 for h in heads:
1305 if h not in m:
1303 if h not in m:
1306 unknown.append(h)
1304 unknown.append(h)
1307 else:
1305 else:
1308 base[h] = 1
1306 base[h] = 1
1309
1307
1310 if not unknown:
1308 if not unknown:
1311 return []
1309 return []
1312
1310
1313 req = dict.fromkeys(unknown)
1311 req = dict.fromkeys(unknown)
1314 reqcnt = 0
1312 reqcnt = 0
1315
1313
1316 # search through remote branches
1314 # search through remote branches
1317 # a 'branch' here is a linear segment of history, with four parts:
1315 # a 'branch' here is a linear segment of history, with four parts:
1318 # head, root, first parent, second parent
1316 # head, root, first parent, second parent
1319 # (a branch always has two parents (or none) by definition)
1317 # (a branch always has two parents (or none) by definition)
1320 unknown = remote.branches(unknown)
1318 unknown = remote.branches(unknown)
1321 while unknown:
1319 while unknown:
1322 r = []
1320 r = []
1323 while unknown:
1321 while unknown:
1324 n = unknown.pop(0)
1322 n = unknown.pop(0)
1325 if n[0] in seen:
1323 if n[0] in seen:
1326 continue
1324 continue
1327
1325
1328 self.ui.debug(_("examining %s:%s\n")
1326 self.ui.debug(_("examining %s:%s\n")
1329 % (short(n[0]), short(n[1])))
1327 % (short(n[0]), short(n[1])))
1330 if n[0] == nullid: # found the end of the branch
1328 if n[0] == nullid: # found the end of the branch
1331 pass
1329 pass
1332 elif n in seenbranch:
1330 elif n in seenbranch:
1333 self.ui.debug(_("branch already found\n"))
1331 self.ui.debug(_("branch already found\n"))
1334 continue
1332 continue
1335 elif n[1] and n[1] in m: # do we know the base?
1333 elif n[1] and n[1] in m: # do we know the base?
1336 self.ui.debug(_("found incomplete branch %s:%s\n")
1334 self.ui.debug(_("found incomplete branch %s:%s\n")
1337 % (short(n[0]), short(n[1])))
1335 % (short(n[0]), short(n[1])))
1338 search.append(n) # schedule branch range for scanning
1336 search.append(n) # schedule branch range for scanning
1339 seenbranch[n] = 1
1337 seenbranch[n] = 1
1340 else:
1338 else:
1341 if n[1] not in seen and n[1] not in fetch:
1339 if n[1] not in seen and n[1] not in fetch:
1342 if n[2] in m and n[3] in m:
1340 if n[2] in m and n[3] in m:
1343 self.ui.debug(_("found new changeset %s\n") %
1341 self.ui.debug(_("found new changeset %s\n") %
1344 short(n[1]))
1342 short(n[1]))
1345 fetch[n[1]] = 1 # earliest unknown
1343 fetch[n[1]] = 1 # earliest unknown
1346 for p in n[2:4]:
1344 for p in n[2:4]:
1347 if p in m:
1345 if p in m:
1348 base[p] = 1 # latest known
1346 base[p] = 1 # latest known
1349
1347
1350 for p in n[2:4]:
1348 for p in n[2:4]:
1351 if p not in req and p not in m:
1349 if p not in req and p not in m:
1352 r.append(p)
1350 r.append(p)
1353 req[p] = 1
1351 req[p] = 1
1354 seen[n[0]] = 1
1352 seen[n[0]] = 1
1355
1353
1356 if r:
1354 if r:
1357 reqcnt += 1
1355 reqcnt += 1
1358 self.ui.debug(_("request %d: %s\n") %
1356 self.ui.debug(_("request %d: %s\n") %
1359 (reqcnt, " ".join(map(short, r))))
1357 (reqcnt, " ".join(map(short, r))))
1360 for p in xrange(0, len(r), 10):
1358 for p in xrange(0, len(r), 10):
1361 for b in remote.branches(r[p:p+10]):
1359 for b in remote.branches(r[p:p+10]):
1362 self.ui.debug(_("received %s:%s\n") %
1360 self.ui.debug(_("received %s:%s\n") %
1363 (short(b[0]), short(b[1])))
1361 (short(b[0]), short(b[1])))
1364 unknown.append(b)
1362 unknown.append(b)
1365
1363
1366 # do binary search on the branches we found
1364 # do binary search on the branches we found
1367 while search:
1365 while search:
1368 n = search.pop(0)
1366 n = search.pop(0)
1369 reqcnt += 1
1367 reqcnt += 1
1370 l = remote.between([(n[0], n[1])])[0]
1368 l = remote.between([(n[0], n[1])])[0]
1371 l.append(n[1])
1369 l.append(n[1])
1372 p = n[0]
1370 p = n[0]
1373 f = 1
1371 f = 1
1374 for i in l:
1372 for i in l:
1375 self.ui.debug(_("narrowing %d:%d %s\n") % (f, len(l), short(i)))
1373 self.ui.debug(_("narrowing %d:%d %s\n") % (f, len(l), short(i)))
1376 if i in m:
1374 if i in m:
1377 if f <= 2:
1375 if f <= 2:
1378 self.ui.debug(_("found new branch changeset %s\n") %
1376 self.ui.debug(_("found new branch changeset %s\n") %
1379 short(p))
1377 short(p))
1380 fetch[p] = 1
1378 fetch[p] = 1
1381 base[i] = 1
1379 base[i] = 1
1382 else:
1380 else:
1383 self.ui.debug(_("narrowed branch search to %s:%s\n")
1381 self.ui.debug(_("narrowed branch search to %s:%s\n")
1384 % (short(p), short(i)))
1382 % (short(p), short(i)))
1385 search.append((p, i))
1383 search.append((p, i))
1386 break
1384 break
1387 p, f = i, f * 2
1385 p, f = i, f * 2
1388
1386
1389 # sanity check our fetch list
1387 # sanity check our fetch list
1390 for f in fetch.keys():
1388 for f in fetch.keys():
1391 if f in m:
1389 if f in m:
1392 raise repo.RepoError(_("already have changeset ") + short(f[:4]))
1390 raise repo.RepoError(_("already have changeset ") + short(f[:4]))
1393
1391
1394 if base.keys() == [nullid]:
1392 if base.keys() == [nullid]:
1395 if force:
1393 if force:
1396 self.ui.warn(_("warning: repository is unrelated\n"))
1394 self.ui.warn(_("warning: repository is unrelated\n"))
1397 else:
1395 else:
1398 raise util.Abort(_("repository is unrelated"))
1396 raise util.Abort(_("repository is unrelated"))
1399
1397
1400 self.ui.debug(_("found new changesets starting at ") +
1398 self.ui.debug(_("found new changesets starting at ") +
1401 " ".join([short(f) for f in fetch]) + "\n")
1399 " ".join([short(f) for f in fetch]) + "\n")
1402
1400
1403 self.ui.debug(_("%d total queries\n") % reqcnt)
1401 self.ui.debug(_("%d total queries\n") % reqcnt)
1404
1402
1405 return fetch.keys()
1403 return fetch.keys()
1406
1404
1407 def findoutgoing(self, remote, base=None, heads=None, force=False):
1405 def findoutgoing(self, remote, base=None, heads=None, force=False):
1408 """Return list of nodes that are roots of subsets not in remote
1406 """Return list of nodes that are roots of subsets not in remote
1409
1407
1410 If base dict is specified, assume that these nodes and their parents
1408 If base dict is specified, assume that these nodes and their parents
1411 exist on the remote side.
1409 exist on the remote side.
1412 If a list of heads is specified, return only nodes which are heads
1410 If a list of heads is specified, return only nodes which are heads
1413 or ancestors of these heads, and return a second element which
1411 or ancestors of these heads, and return a second element which
1414 contains all remote heads which get new children.
1412 contains all remote heads which get new children.
1415 """
1413 """
1416 if base == None:
1414 if base == None:
1417 base = {}
1415 base = {}
1418 self.findincoming(remote, base, heads, force=force)
1416 self.findincoming(remote, base, heads, force=force)
1419
1417
1420 self.ui.debug(_("common changesets up to ")
1418 self.ui.debug(_("common changesets up to ")
1421 + " ".join(map(short, base.keys())) + "\n")
1419 + " ".join(map(short, base.keys())) + "\n")
1422
1420
1423 remain = dict.fromkeys(self.changelog.nodemap)
1421 remain = dict.fromkeys(self.changelog.nodemap)
1424
1422
1425 # prune everything remote has from the tree
1423 # prune everything remote has from the tree
1426 del remain[nullid]
1424 del remain[nullid]
1427 remove = base.keys()
1425 remove = base.keys()
1428 while remove:
1426 while remove:
1429 n = remove.pop(0)
1427 n = remove.pop(0)
1430 if n in remain:
1428 if n in remain:
1431 del remain[n]
1429 del remain[n]
1432 for p in self.changelog.parents(n):
1430 for p in self.changelog.parents(n):
1433 remove.append(p)
1431 remove.append(p)
1434
1432
1435 # find every node whose parents have been pruned
1433 # find every node whose parents have been pruned
1436 subset = []
1434 subset = []
1437 # find every remote head that will get new children
1435 # find every remote head that will get new children
1438 updated_heads = {}
1436 updated_heads = {}
1439 for n in remain:
1437 for n in remain:
1440 p1, p2 = self.changelog.parents(n)
1438 p1, p2 = self.changelog.parents(n)
1441 if p1 not in remain and p2 not in remain:
1439 if p1 not in remain and p2 not in remain:
1442 subset.append(n)
1440 subset.append(n)
1443 if heads:
1441 if heads:
1444 if p1 in heads:
1442 if p1 in heads:
1445 updated_heads[p1] = True
1443 updated_heads[p1] = True
1446 if p2 in heads:
1444 if p2 in heads:
1447 updated_heads[p2] = True
1445 updated_heads[p2] = True
1448
1446
1449 # this is the set of all roots we have to push
1447 # this is the set of all roots we have to push
1450 if heads:
1448 if heads:
1451 return subset, updated_heads.keys()
1449 return subset, updated_heads.keys()
1452 else:
1450 else:
1453 return subset
1451 return subset
1454
1452
1455 def pull(self, remote, heads=None, force=False):
1453 def pull(self, remote, heads=None, force=False):
1456 lock = self.lock()
1454 lock = self.lock()
1457 try:
1455 try:
1458 fetch = self.findincoming(remote, heads=heads, force=force)
1456 fetch = self.findincoming(remote, heads=heads, force=force)
1459 if fetch == [nullid]:
1457 if fetch == [nullid]:
1460 self.ui.status(_("requesting all changes\n"))
1458 self.ui.status(_("requesting all changes\n"))
1461
1459
1462 if not fetch:
1460 if not fetch:
1463 self.ui.status(_("no changes found\n"))
1461 self.ui.status(_("no changes found\n"))
1464 return 0
1462 return 0
1465
1463
1466 if heads is None:
1464 if heads is None:
1467 cg = remote.changegroup(fetch, 'pull')
1465 cg = remote.changegroup(fetch, 'pull')
1468 else:
1466 else:
1469 if 'changegroupsubset' not in remote.capabilities:
1467 if 'changegroupsubset' not in remote.capabilities:
1470 raise util.Abort(_("Partial pull cannot be done because other repository doesn't support changegroupsubset."))
1468 raise util.Abort(_("Partial pull cannot be done because other repository doesn't support changegroupsubset."))
1471 cg = remote.changegroupsubset(fetch, heads, 'pull')
1469 cg = remote.changegroupsubset(fetch, heads, 'pull')
1472 return self.addchangegroup(cg, 'pull', remote.url())
1470 return self.addchangegroup(cg, 'pull', remote.url())
1473 finally:
1471 finally:
1474 del lock
1472 del lock
1475
1473
1476 def push(self, remote, force=False, revs=None):
1474 def push(self, remote, force=False, revs=None):
1477 # there are two ways to push to remote repo:
1475 # there are two ways to push to remote repo:
1478 #
1476 #
1479 # addchangegroup assumes local user can lock remote
1477 # addchangegroup assumes local user can lock remote
1480 # repo (local filesystem, old ssh servers).
1478 # repo (local filesystem, old ssh servers).
1481 #
1479 #
1482 # unbundle assumes local user cannot lock remote repo (new ssh
1480 # unbundle assumes local user cannot lock remote repo (new ssh
1483 # servers, http servers).
1481 # servers, http servers).
1484
1482
1485 if remote.capable('unbundle'):
1483 if remote.capable('unbundle'):
1486 return self.push_unbundle(remote, force, revs)
1484 return self.push_unbundle(remote, force, revs)
1487 return self.push_addchangegroup(remote, force, revs)
1485 return self.push_addchangegroup(remote, force, revs)
1488
1486
1489 def prepush(self, remote, force, revs):
1487 def prepush(self, remote, force, revs):
1490 base = {}
1488 base = {}
1491 remote_heads = remote.heads()
1489 remote_heads = remote.heads()
1492 inc = self.findincoming(remote, base, remote_heads, force=force)
1490 inc = self.findincoming(remote, base, remote_heads, force=force)
1493
1491
1494 update, updated_heads = self.findoutgoing(remote, base, remote_heads)
1492 update, updated_heads = self.findoutgoing(remote, base, remote_heads)
1495 if revs is not None:
1493 if revs is not None:
1496 msng_cl, bases, heads = self.changelog.nodesbetween(update, revs)
1494 msng_cl, bases, heads = self.changelog.nodesbetween(update, revs)
1497 else:
1495 else:
1498 bases, heads = update, self.changelog.heads()
1496 bases, heads = update, self.changelog.heads()
1499
1497
1500 if not bases:
1498 if not bases:
1501 self.ui.status(_("no changes found\n"))
1499 self.ui.status(_("no changes found\n"))
1502 return None, 1
1500 return None, 1
1503 elif not force:
1501 elif not force:
1504 # check if we're creating new remote heads
1502 # check if we're creating new remote heads
1505 # to be a remote head after push, node must be either
1503 # to be a remote head after push, node must be either
1506 # - unknown locally
1504 # - unknown locally
1507 # - a local outgoing head descended from update
1505 # - a local outgoing head descended from update
1508 # - a remote head that's known locally and not
1506 # - a remote head that's known locally and not
1509 # ancestral to an outgoing head
1507 # ancestral to an outgoing head
1510
1508
1511 warn = 0
1509 warn = 0
1512
1510
1513 if remote_heads == [nullid]:
1511 if remote_heads == [nullid]:
1514 warn = 0
1512 warn = 0
1515 elif not revs and len(heads) > len(remote_heads):
1513 elif not revs and len(heads) > len(remote_heads):
1516 warn = 1
1514 warn = 1
1517 else:
1515 else:
1518 newheads = list(heads)
1516 newheads = list(heads)
1519 for r in remote_heads:
1517 for r in remote_heads:
1520 if r in self.changelog.nodemap:
1518 if r in self.changelog.nodemap:
1521 desc = self.changelog.heads(r, heads)
1519 desc = self.changelog.heads(r, heads)
1522 l = [h for h in heads if h in desc]
1520 l = [h for h in heads if h in desc]
1523 if not l:
1521 if not l:
1524 newheads.append(r)
1522 newheads.append(r)
1525 else:
1523 else:
1526 newheads.append(r)
1524 newheads.append(r)
1527 if len(newheads) > len(remote_heads):
1525 if len(newheads) > len(remote_heads):
1528 warn = 1
1526 warn = 1
1529
1527
1530 if warn:
1528 if warn:
1531 self.ui.warn(_("abort: push creates new remote heads!\n"))
1529 self.ui.warn(_("abort: push creates new remote heads!\n"))
1532 self.ui.status(_("(did you forget to merge?"
1530 self.ui.status(_("(did you forget to merge?"
1533 " use push -f to force)\n"))
1531 " use push -f to force)\n"))
1534 return None, 0
1532 return None, 0
1535 elif inc:
1533 elif inc:
1536 self.ui.warn(_("note: unsynced remote changes!\n"))
1534 self.ui.warn(_("note: unsynced remote changes!\n"))
1537
1535
1538
1536
1539 if revs is None:
1537 if revs is None:
1540 cg = self.changegroup(update, 'push')
1538 cg = self.changegroup(update, 'push')
1541 else:
1539 else:
1542 cg = self.changegroupsubset(update, revs, 'push')
1540 cg = self.changegroupsubset(update, revs, 'push')
1543 return cg, remote_heads
1541 return cg, remote_heads
1544
1542
1545 def push_addchangegroup(self, remote, force, revs):
1543 def push_addchangegroup(self, remote, force, revs):
1546 lock = remote.lock()
1544 lock = remote.lock()
1547 try:
1545 try:
1548 ret = self.prepush(remote, force, revs)
1546 ret = self.prepush(remote, force, revs)
1549 if ret[0] is not None:
1547 if ret[0] is not None:
1550 cg, remote_heads = ret
1548 cg, remote_heads = ret
1551 return remote.addchangegroup(cg, 'push', self.url())
1549 return remote.addchangegroup(cg, 'push', self.url())
1552 return ret[1]
1550 return ret[1]
1553 finally:
1551 finally:
1554 del lock
1552 del lock
1555
1553
1556 def push_unbundle(self, remote, force, revs):
1554 def push_unbundle(self, remote, force, revs):
1557 # local repo finds heads on server, finds out what revs it
1555 # local repo finds heads on server, finds out what revs it
1558 # must push. once revs transferred, if server finds it has
1556 # must push. once revs transferred, if server finds it has
1559 # different heads (someone else won commit/push race), server
1557 # different heads (someone else won commit/push race), server
1560 # aborts.
1558 # aborts.
1561
1559
1562 ret = self.prepush(remote, force, revs)
1560 ret = self.prepush(remote, force, revs)
1563 if ret[0] is not None:
1561 if ret[0] is not None:
1564 cg, remote_heads = ret
1562 cg, remote_heads = ret
1565 if force: remote_heads = ['force']
1563 if force: remote_heads = ['force']
1566 return remote.unbundle(cg, remote_heads, 'push')
1564 return remote.unbundle(cg, remote_heads, 'push')
1567 return ret[1]
1565 return ret[1]
1568
1566
1569 def changegroupinfo(self, nodes, source):
1567 def changegroupinfo(self, nodes, source):
1570 if self.ui.verbose or source == 'bundle':
1568 if self.ui.verbose or source == 'bundle':
1571 self.ui.status(_("%d changesets found\n") % len(nodes))
1569 self.ui.status(_("%d changesets found\n") % len(nodes))
1572 if self.ui.debugflag:
1570 if self.ui.debugflag:
1573 self.ui.debug(_("List of changesets:\n"))
1571 self.ui.debug(_("List of changesets:\n"))
1574 for node in nodes:
1572 for node in nodes:
1575 self.ui.debug("%s\n" % hex(node))
1573 self.ui.debug("%s\n" % hex(node))
1576
1574
1577 def changegroupsubset(self, bases, heads, source, extranodes=None):
1575 def changegroupsubset(self, bases, heads, source, extranodes=None):
1578 """This function generates a changegroup consisting of all the nodes
1576 """This function generates a changegroup consisting of all the nodes
1579 that are descendents of any of the bases, and ancestors of any of
1577 that are descendents of any of the bases, and ancestors of any of
1580 the heads.
1578 the heads.
1581
1579
1582 It is fairly complex as determining which filenodes and which
1580 It is fairly complex as determining which filenodes and which
1583 manifest nodes need to be included for the changeset to be complete
1581 manifest nodes need to be included for the changeset to be complete
1584 is non-trivial.
1582 is non-trivial.
1585
1583
1586 Another wrinkle is doing the reverse, figuring out which changeset in
1584 Another wrinkle is doing the reverse, figuring out which changeset in
1587 the changegroup a particular filenode or manifestnode belongs to.
1585 the changegroup a particular filenode or manifestnode belongs to.
1588
1586
1589 The caller can specify some nodes that must be included in the
1587 The caller can specify some nodes that must be included in the
1590 changegroup using the extranodes argument. It should be a dict
1588 changegroup using the extranodes argument. It should be a dict
1591 where the keys are the filenames (or 1 for the manifest), and the
1589 where the keys are the filenames (or 1 for the manifest), and the
1592 values are lists of (node, linknode) tuples, where node is a wanted
1590 values are lists of (node, linknode) tuples, where node is a wanted
1593 node and linknode is the changelog node that should be transmitted as
1591 node and linknode is the changelog node that should be transmitted as
1594 the linkrev.
1592 the linkrev.
1595 """
1593 """
1596
1594
1597 self.hook('preoutgoing', throw=True, source=source)
1595 self.hook('preoutgoing', throw=True, source=source)
1598
1596
1599 # Set up some initial variables
1597 # Set up some initial variables
1600 # Make it easy to refer to self.changelog
1598 # Make it easy to refer to self.changelog
1601 cl = self.changelog
1599 cl = self.changelog
1602 # msng is short for missing - compute the list of changesets in this
1600 # msng is short for missing - compute the list of changesets in this
1603 # changegroup.
1601 # changegroup.
1604 msng_cl_lst, bases, heads = cl.nodesbetween(bases, heads)
1602 msng_cl_lst, bases, heads = cl.nodesbetween(bases, heads)
1605 self.changegroupinfo(msng_cl_lst, source)
1603 self.changegroupinfo(msng_cl_lst, source)
1606 # Some bases may turn out to be superfluous, and some heads may be
1604 # Some bases may turn out to be superfluous, and some heads may be
1607 # too. nodesbetween will return the minimal set of bases and heads
1605 # too. nodesbetween will return the minimal set of bases and heads
1608 # necessary to re-create the changegroup.
1606 # necessary to re-create the changegroup.
1609
1607
1610 # Known heads are the list of heads that it is assumed the recipient
1608 # Known heads are the list of heads that it is assumed the recipient
1611 # of this changegroup will know about.
1609 # of this changegroup will know about.
1612 knownheads = {}
1610 knownheads = {}
1613 # We assume that all parents of bases are known heads.
1611 # We assume that all parents of bases are known heads.
1614 for n in bases:
1612 for n in bases:
1615 for p in cl.parents(n):
1613 for p in cl.parents(n):
1616 if p != nullid:
1614 if p != nullid:
1617 knownheads[p] = 1
1615 knownheads[p] = 1
1618 knownheads = knownheads.keys()
1616 knownheads = knownheads.keys()
1619 if knownheads:
1617 if knownheads:
1620 # Now that we know what heads are known, we can compute which
1618 # Now that we know what heads are known, we can compute which
1621 # changesets are known. The recipient must know about all
1619 # changesets are known. The recipient must know about all
1622 # changesets required to reach the known heads from the null
1620 # changesets required to reach the known heads from the null
1623 # changeset.
1621 # changeset.
1624 has_cl_set, junk, junk = cl.nodesbetween(None, knownheads)
1622 has_cl_set, junk, junk = cl.nodesbetween(None, knownheads)
1625 junk = None
1623 junk = None
1626 # Transform the list into an ersatz set.
1624 # Transform the list into an ersatz set.
1627 has_cl_set = dict.fromkeys(has_cl_set)
1625 has_cl_set = dict.fromkeys(has_cl_set)
1628 else:
1626 else:
1629 # If there were no known heads, the recipient cannot be assumed to
1627 # If there were no known heads, the recipient cannot be assumed to
1630 # know about any changesets.
1628 # know about any changesets.
1631 has_cl_set = {}
1629 has_cl_set = {}
1632
1630
1633 # Make it easy to refer to self.manifest
1631 # Make it easy to refer to self.manifest
1634 mnfst = self.manifest
1632 mnfst = self.manifest
1635 # We don't know which manifests are missing yet
1633 # We don't know which manifests are missing yet
1636 msng_mnfst_set = {}
1634 msng_mnfst_set = {}
1637 # Nor do we know which filenodes are missing.
1635 # Nor do we know which filenodes are missing.
1638 msng_filenode_set = {}
1636 msng_filenode_set = {}
1639
1637
1640 junk = mnfst.index[mnfst.count() - 1] # Get around a bug in lazyindex
1638 junk = mnfst.index[mnfst.count() - 1] # Get around a bug in lazyindex
1641 junk = None
1639 junk = None
1642
1640
1643 # A changeset always belongs to itself, so the changenode lookup
1641 # A changeset always belongs to itself, so the changenode lookup
1644 # function for a changenode is identity.
1642 # function for a changenode is identity.
1645 def identity(x):
1643 def identity(x):
1646 return x
1644 return x
1647
1645
1648 # A function generating function. Sets up an environment for the
1646 # A function generating function. Sets up an environment for the
1649 # inner function.
1647 # inner function.
1650 def cmp_by_rev_func(revlog):
1648 def cmp_by_rev_func(revlog):
1651 # Compare two nodes by their revision number in the environment's
1649 # Compare two nodes by their revision number in the environment's
1652 # revision history. Since the revision number both represents the
1650 # revision history. Since the revision number both represents the
1653 # most efficient order to read the nodes in, and represents a
1651 # most efficient order to read the nodes in, and represents a
1654 # topological sorting of the nodes, this function is often useful.
1652 # topological sorting of the nodes, this function is often useful.
1655 def cmp_by_rev(a, b):
1653 def cmp_by_rev(a, b):
1656 return cmp(revlog.rev(a), revlog.rev(b))
1654 return cmp(revlog.rev(a), revlog.rev(b))
1657 return cmp_by_rev
1655 return cmp_by_rev
1658
1656
1659 # If we determine that a particular file or manifest node must be a
1657 # If we determine that a particular file or manifest node must be a
1660 # node that the recipient of the changegroup will already have, we can
1658 # node that the recipient of the changegroup will already have, we can
1661 # also assume the recipient will have all the parents. This function
1659 # also assume the recipient will have all the parents. This function
1662 # prunes them from the set of missing nodes.
1660 # prunes them from the set of missing nodes.
1663 def prune_parents(revlog, hasset, msngset):
1661 def prune_parents(revlog, hasset, msngset):
1664 haslst = hasset.keys()
1662 haslst = hasset.keys()
1665 haslst.sort(cmp_by_rev_func(revlog))
1663 haslst.sort(cmp_by_rev_func(revlog))
1666 for node in haslst:
1664 for node in haslst:
1667 parentlst = [p for p in revlog.parents(node) if p != nullid]
1665 parentlst = [p for p in revlog.parents(node) if p != nullid]
1668 while parentlst:
1666 while parentlst:
1669 n = parentlst.pop()
1667 n = parentlst.pop()
1670 if n not in hasset:
1668 if n not in hasset:
1671 hasset[n] = 1
1669 hasset[n] = 1
1672 p = [p for p in revlog.parents(n) if p != nullid]
1670 p = [p for p in revlog.parents(n) if p != nullid]
1673 parentlst.extend(p)
1671 parentlst.extend(p)
1674 for n in hasset:
1672 for n in hasset:
1675 msngset.pop(n, None)
1673 msngset.pop(n, None)
1676
1674
1677 # This is a function generating function used to set up an environment
1675 # This is a function generating function used to set up an environment
1678 # for the inner function to execute in.
1676 # for the inner function to execute in.
1679 def manifest_and_file_collector(changedfileset):
1677 def manifest_and_file_collector(changedfileset):
1680 # This is an information gathering function that gathers
1678 # This is an information gathering function that gathers
1681 # information from each changeset node that goes out as part of
1679 # information from each changeset node that goes out as part of
1682 # the changegroup. The information gathered is a list of which
1680 # the changegroup. The information gathered is a list of which
1683 # manifest nodes are potentially required (the recipient may
1681 # manifest nodes are potentially required (the recipient may
1684 # already have them) and total list of all files which were
1682 # already have them) and total list of all files which were
1685 # changed in any changeset in the changegroup.
1683 # changed in any changeset in the changegroup.
1686 #
1684 #
1687 # We also remember the first changenode we saw any manifest
1685 # We also remember the first changenode we saw any manifest
1688 # referenced by so we can later determine which changenode 'owns'
1686 # referenced by so we can later determine which changenode 'owns'
1689 # the manifest.
1687 # the manifest.
1690 def collect_manifests_and_files(clnode):
1688 def collect_manifests_and_files(clnode):
1691 c = cl.read(clnode)
1689 c = cl.read(clnode)
1692 for f in c[3]:
1690 for f in c[3]:
1693 # This is to make sure we only have one instance of each
1691 # This is to make sure we only have one instance of each
1694 # filename string for each filename.
1692 # filename string for each filename.
1695 changedfileset.setdefault(f, f)
1693 changedfileset.setdefault(f, f)
1696 msng_mnfst_set.setdefault(c[0], clnode)
1694 msng_mnfst_set.setdefault(c[0], clnode)
1697 return collect_manifests_and_files
1695 return collect_manifests_and_files
1698
1696
1699 # Figure out which manifest nodes (of the ones we think might be part
1697 # Figure out which manifest nodes (of the ones we think might be part
1700 # of the changegroup) the recipient must know about and remove them
1698 # of the changegroup) the recipient must know about and remove them
1701 # from the changegroup.
1699 # from the changegroup.
1702 def prune_manifests():
1700 def prune_manifests():
1703 has_mnfst_set = {}
1701 has_mnfst_set = {}
1704 for n in msng_mnfst_set:
1702 for n in msng_mnfst_set:
1705 # If a 'missing' manifest thinks it belongs to a changenode
1703 # If a 'missing' manifest thinks it belongs to a changenode
1706 # the recipient is assumed to have, obviously the recipient
1704 # the recipient is assumed to have, obviously the recipient
1707 # must have that manifest.
1705 # must have that manifest.
1708 linknode = cl.node(mnfst.linkrev(n))
1706 linknode = cl.node(mnfst.linkrev(n))
1709 if linknode in has_cl_set:
1707 if linknode in has_cl_set:
1710 has_mnfst_set[n] = 1
1708 has_mnfst_set[n] = 1
1711 prune_parents(mnfst, has_mnfst_set, msng_mnfst_set)
1709 prune_parents(mnfst, has_mnfst_set, msng_mnfst_set)
1712
1710
1713 # Use the information collected in collect_manifests_and_files to say
1711 # Use the information collected in collect_manifests_and_files to say
1714 # which changenode any manifestnode belongs to.
1712 # which changenode any manifestnode belongs to.
1715 def lookup_manifest_link(mnfstnode):
1713 def lookup_manifest_link(mnfstnode):
1716 return msng_mnfst_set[mnfstnode]
1714 return msng_mnfst_set[mnfstnode]
1717
1715
1718 # A function generating function that sets up the initial environment
1716 # A function generating function that sets up the initial environment
1719 # the inner function.
1717 # the inner function.
1720 def filenode_collector(changedfiles):
1718 def filenode_collector(changedfiles):
1721 next_rev = [0]
1719 next_rev = [0]
1722 # This gathers information from each manifestnode included in the
1720 # This gathers information from each manifestnode included in the
1723 # changegroup about which filenodes the manifest node references
1721 # changegroup about which filenodes the manifest node references
1724 # so we can include those in the changegroup too.
1722 # so we can include those in the changegroup too.
1725 #
1723 #
1726 # It also remembers which changenode each filenode belongs to. It
1724 # It also remembers which changenode each filenode belongs to. It
1727 # does this by assuming the a filenode belongs to the changenode
1725 # does this by assuming the a filenode belongs to the changenode
1728 # the first manifest that references it belongs to.
1726 # the first manifest that references it belongs to.
1729 def collect_msng_filenodes(mnfstnode):
1727 def collect_msng_filenodes(mnfstnode):
1730 r = mnfst.rev(mnfstnode)
1728 r = mnfst.rev(mnfstnode)
1731 if r == next_rev[0]:
1729 if r == next_rev[0]:
1732 # If the last rev we looked at was the one just previous,
1730 # If the last rev we looked at was the one just previous,
1733 # we only need to see a diff.
1731 # we only need to see a diff.
1734 deltamf = mnfst.readdelta(mnfstnode)
1732 deltamf = mnfst.readdelta(mnfstnode)
1735 # For each line in the delta
1733 # For each line in the delta
1736 for f, fnode in deltamf.items():
1734 for f, fnode in deltamf.items():
1737 f = changedfiles.get(f, None)
1735 f = changedfiles.get(f, None)
1738 # And if the file is in the list of files we care
1736 # And if the file is in the list of files we care
1739 # about.
1737 # about.
1740 if f is not None:
1738 if f is not None:
1741 # Get the changenode this manifest belongs to
1739 # Get the changenode this manifest belongs to
1742 clnode = msng_mnfst_set[mnfstnode]
1740 clnode = msng_mnfst_set[mnfstnode]
1743 # Create the set of filenodes for the file if
1741 # Create the set of filenodes for the file if
1744 # there isn't one already.
1742 # there isn't one already.
1745 ndset = msng_filenode_set.setdefault(f, {})
1743 ndset = msng_filenode_set.setdefault(f, {})
1746 # And set the filenode's changelog node to the
1744 # And set the filenode's changelog node to the
1747 # manifest's if it hasn't been set already.
1745 # manifest's if it hasn't been set already.
1748 ndset.setdefault(fnode, clnode)
1746 ndset.setdefault(fnode, clnode)
1749 else:
1747 else:
1750 # Otherwise we need a full manifest.
1748 # Otherwise we need a full manifest.
1751 m = mnfst.read(mnfstnode)
1749 m = mnfst.read(mnfstnode)
1752 # For every file in we care about.
1750 # For every file in we care about.
1753 for f in changedfiles:
1751 for f in changedfiles:
1754 fnode = m.get(f, None)
1752 fnode = m.get(f, None)
1755 # If it's in the manifest
1753 # If it's in the manifest
1756 if fnode is not None:
1754 if fnode is not None:
1757 # See comments above.
1755 # See comments above.
1758 clnode = msng_mnfst_set[mnfstnode]
1756 clnode = msng_mnfst_set[mnfstnode]
1759 ndset = msng_filenode_set.setdefault(f, {})
1757 ndset = msng_filenode_set.setdefault(f, {})
1760 ndset.setdefault(fnode, clnode)
1758 ndset.setdefault(fnode, clnode)
1761 # Remember the revision we hope to see next.
1759 # Remember the revision we hope to see next.
1762 next_rev[0] = r + 1
1760 next_rev[0] = r + 1
1763 return collect_msng_filenodes
1761 return collect_msng_filenodes
1764
1762
1765 # We have a list of filenodes we think we need for a file, lets remove
1763 # We have a list of filenodes we think we need for a file, lets remove
1766 # all those we now the recipient must have.
1764 # all those we now the recipient must have.
1767 def prune_filenodes(f, filerevlog):
1765 def prune_filenodes(f, filerevlog):
1768 msngset = msng_filenode_set[f]
1766 msngset = msng_filenode_set[f]
1769 hasset = {}
1767 hasset = {}
1770 # If a 'missing' filenode thinks it belongs to a changenode we
1768 # If a 'missing' filenode thinks it belongs to a changenode we
1771 # assume the recipient must have, then the recipient must have
1769 # assume the recipient must have, then the recipient must have
1772 # that filenode.
1770 # that filenode.
1773 for n in msngset:
1771 for n in msngset:
1774 clnode = cl.node(filerevlog.linkrev(n))
1772 clnode = cl.node(filerevlog.linkrev(n))
1775 if clnode in has_cl_set:
1773 if clnode in has_cl_set:
1776 hasset[n] = 1
1774 hasset[n] = 1
1777 prune_parents(filerevlog, hasset, msngset)
1775 prune_parents(filerevlog, hasset, msngset)
1778
1776
1779 # A function generator function that sets up the a context for the
1777 # A function generator function that sets up the a context for the
1780 # inner function.
1778 # inner function.
1781 def lookup_filenode_link_func(fname):
1779 def lookup_filenode_link_func(fname):
1782 msngset = msng_filenode_set[fname]
1780 msngset = msng_filenode_set[fname]
1783 # Lookup the changenode the filenode belongs to.
1781 # Lookup the changenode the filenode belongs to.
1784 def lookup_filenode_link(fnode):
1782 def lookup_filenode_link(fnode):
1785 return msngset[fnode]
1783 return msngset[fnode]
1786 return lookup_filenode_link
1784 return lookup_filenode_link
1787
1785
1788 # Add the nodes that were explicitly requested.
1786 # Add the nodes that were explicitly requested.
1789 def add_extra_nodes(name, nodes):
1787 def add_extra_nodes(name, nodes):
1790 if not extranodes or name not in extranodes:
1788 if not extranodes or name not in extranodes:
1791 return
1789 return
1792
1790
1793 for node, linknode in extranodes[name]:
1791 for node, linknode in extranodes[name]:
1794 if node not in nodes:
1792 if node not in nodes:
1795 nodes[node] = linknode
1793 nodes[node] = linknode
1796
1794
1797 # Now that we have all theses utility functions to help out and
1795 # Now that we have all theses utility functions to help out and
1798 # logically divide up the task, generate the group.
1796 # logically divide up the task, generate the group.
1799 def gengroup():
1797 def gengroup():
1800 # The set of changed files starts empty.
1798 # The set of changed files starts empty.
1801 changedfiles = {}
1799 changedfiles = {}
1802 # Create a changenode group generator that will call our functions
1800 # Create a changenode group generator that will call our functions
1803 # back to lookup the owning changenode and collect information.
1801 # back to lookup the owning changenode and collect information.
1804 group = cl.group(msng_cl_lst, identity,
1802 group = cl.group(msng_cl_lst, identity,
1805 manifest_and_file_collector(changedfiles))
1803 manifest_and_file_collector(changedfiles))
1806 for chnk in group:
1804 for chnk in group:
1807 yield chnk
1805 yield chnk
1808
1806
1809 # The list of manifests has been collected by the generator
1807 # The list of manifests has been collected by the generator
1810 # calling our functions back.
1808 # calling our functions back.
1811 prune_manifests()
1809 prune_manifests()
1812 add_extra_nodes(1, msng_mnfst_set)
1810 add_extra_nodes(1, msng_mnfst_set)
1813 msng_mnfst_lst = msng_mnfst_set.keys()
1811 msng_mnfst_lst = msng_mnfst_set.keys()
1814 # Sort the manifestnodes by revision number.
1812 # Sort the manifestnodes by revision number.
1815 msng_mnfst_lst.sort(cmp_by_rev_func(mnfst))
1813 msng_mnfst_lst.sort(cmp_by_rev_func(mnfst))
1816 # Create a generator for the manifestnodes that calls our lookup
1814 # Create a generator for the manifestnodes that calls our lookup
1817 # and data collection functions back.
1815 # and data collection functions back.
1818 group = mnfst.group(msng_mnfst_lst, lookup_manifest_link,
1816 group = mnfst.group(msng_mnfst_lst, lookup_manifest_link,
1819 filenode_collector(changedfiles))
1817 filenode_collector(changedfiles))
1820 for chnk in group:
1818 for chnk in group:
1821 yield chnk
1819 yield chnk
1822
1820
1823 # These are no longer needed, dereference and toss the memory for
1821 # These are no longer needed, dereference and toss the memory for
1824 # them.
1822 # them.
1825 msng_mnfst_lst = None
1823 msng_mnfst_lst = None
1826 msng_mnfst_set.clear()
1824 msng_mnfst_set.clear()
1827
1825
1828 if extranodes:
1826 if extranodes:
1829 for fname in extranodes:
1827 for fname in extranodes:
1830 if isinstance(fname, int):
1828 if isinstance(fname, int):
1831 continue
1829 continue
1832 add_extra_nodes(fname,
1830 add_extra_nodes(fname,
1833 msng_filenode_set.setdefault(fname, {}))
1831 msng_filenode_set.setdefault(fname, {}))
1834 changedfiles[fname] = 1
1832 changedfiles[fname] = 1
1835 changedfiles = changedfiles.keys()
1833 changedfiles = changedfiles.keys()
1836 changedfiles.sort()
1834 changedfiles.sort()
1837 # Go through all our files in order sorted by name.
1835 # Go through all our files in order sorted by name.
1838 for fname in changedfiles:
1836 for fname in changedfiles:
1839 filerevlog = self.file(fname)
1837 filerevlog = self.file(fname)
1840 if filerevlog.count() == 0:
1838 if filerevlog.count() == 0:
1841 raise util.Abort(_("empty or missing revlog for %s") % fname)
1839 raise util.Abort(_("empty or missing revlog for %s") % fname)
1842 # Toss out the filenodes that the recipient isn't really
1840 # Toss out the filenodes that the recipient isn't really
1843 # missing.
1841 # missing.
1844 if fname in msng_filenode_set:
1842 if fname in msng_filenode_set:
1845 prune_filenodes(fname, filerevlog)
1843 prune_filenodes(fname, filerevlog)
1846 msng_filenode_lst = msng_filenode_set[fname].keys()
1844 msng_filenode_lst = msng_filenode_set[fname].keys()
1847 else:
1845 else:
1848 msng_filenode_lst = []
1846 msng_filenode_lst = []
1849 # If any filenodes are left, generate the group for them,
1847 # If any filenodes are left, generate the group for them,
1850 # otherwise don't bother.
1848 # otherwise don't bother.
1851 if len(msng_filenode_lst) > 0:
1849 if len(msng_filenode_lst) > 0:
1852 yield changegroup.chunkheader(len(fname))
1850 yield changegroup.chunkheader(len(fname))
1853 yield fname
1851 yield fname
1854 # Sort the filenodes by their revision #
1852 # Sort the filenodes by their revision #
1855 msng_filenode_lst.sort(cmp_by_rev_func(filerevlog))
1853 msng_filenode_lst.sort(cmp_by_rev_func(filerevlog))
1856 # Create a group generator and only pass in a changenode
1854 # Create a group generator and only pass in a changenode
1857 # lookup function as we need to collect no information
1855 # lookup function as we need to collect no information
1858 # from filenodes.
1856 # from filenodes.
1859 group = filerevlog.group(msng_filenode_lst,
1857 group = filerevlog.group(msng_filenode_lst,
1860 lookup_filenode_link_func(fname))
1858 lookup_filenode_link_func(fname))
1861 for chnk in group:
1859 for chnk in group:
1862 yield chnk
1860 yield chnk
1863 if fname in msng_filenode_set:
1861 if fname in msng_filenode_set:
1864 # Don't need this anymore, toss it to free memory.
1862 # Don't need this anymore, toss it to free memory.
1865 del msng_filenode_set[fname]
1863 del msng_filenode_set[fname]
1866 # Signal that no more groups are left.
1864 # Signal that no more groups are left.
1867 yield changegroup.closechunk()
1865 yield changegroup.closechunk()
1868
1866
1869 if msng_cl_lst:
1867 if msng_cl_lst:
1870 self.hook('outgoing', node=hex(msng_cl_lst[0]), source=source)
1868 self.hook('outgoing', node=hex(msng_cl_lst[0]), source=source)
1871
1869
1872 return util.chunkbuffer(gengroup())
1870 return util.chunkbuffer(gengroup())
1873
1871
1874 def changegroup(self, basenodes, source):
1872 def changegroup(self, basenodes, source):
1875 """Generate a changegroup of all nodes that we have that a recipient
1873 """Generate a changegroup of all nodes that we have that a recipient
1876 doesn't.
1874 doesn't.
1877
1875
1878 This is much easier than the previous function as we can assume that
1876 This is much easier than the previous function as we can assume that
1879 the recipient has any changenode we aren't sending them."""
1877 the recipient has any changenode we aren't sending them."""
1880
1878
1881 self.hook('preoutgoing', throw=True, source=source)
1879 self.hook('preoutgoing', throw=True, source=source)
1882
1880
1883 cl = self.changelog
1881 cl = self.changelog
1884 nodes = cl.nodesbetween(basenodes, None)[0]
1882 nodes = cl.nodesbetween(basenodes, None)[0]
1885 revset = dict.fromkeys([cl.rev(n) for n in nodes])
1883 revset = dict.fromkeys([cl.rev(n) for n in nodes])
1886 self.changegroupinfo(nodes, source)
1884 self.changegroupinfo(nodes, source)
1887
1885
1888 def identity(x):
1886 def identity(x):
1889 return x
1887 return x
1890
1888
1891 def gennodelst(revlog):
1889 def gennodelst(revlog):
1892 for r in xrange(0, revlog.count()):
1890 for r in xrange(0, revlog.count()):
1893 n = revlog.node(r)
1891 n = revlog.node(r)
1894 if revlog.linkrev(n) in revset:
1892 if revlog.linkrev(n) in revset:
1895 yield n
1893 yield n
1896
1894
1897 def changed_file_collector(changedfileset):
1895 def changed_file_collector(changedfileset):
1898 def collect_changed_files(clnode):
1896 def collect_changed_files(clnode):
1899 c = cl.read(clnode)
1897 c = cl.read(clnode)
1900 for fname in c[3]:
1898 for fname in c[3]:
1901 changedfileset[fname] = 1
1899 changedfileset[fname] = 1
1902 return collect_changed_files
1900 return collect_changed_files
1903
1901
1904 def lookuprevlink_func(revlog):
1902 def lookuprevlink_func(revlog):
1905 def lookuprevlink(n):
1903 def lookuprevlink(n):
1906 return cl.node(revlog.linkrev(n))
1904 return cl.node(revlog.linkrev(n))
1907 return lookuprevlink
1905 return lookuprevlink
1908
1906
1909 def gengroup():
1907 def gengroup():
1910 # construct a list of all changed files
1908 # construct a list of all changed files
1911 changedfiles = {}
1909 changedfiles = {}
1912
1910
1913 for chnk in cl.group(nodes, identity,
1911 for chnk in cl.group(nodes, identity,
1914 changed_file_collector(changedfiles)):
1912 changed_file_collector(changedfiles)):
1915 yield chnk
1913 yield chnk
1916 changedfiles = changedfiles.keys()
1914 changedfiles = changedfiles.keys()
1917 changedfiles.sort()
1915 changedfiles.sort()
1918
1916
1919 mnfst = self.manifest
1917 mnfst = self.manifest
1920 nodeiter = gennodelst(mnfst)
1918 nodeiter = gennodelst(mnfst)
1921 for chnk in mnfst.group(nodeiter, lookuprevlink_func(mnfst)):
1919 for chnk in mnfst.group(nodeiter, lookuprevlink_func(mnfst)):
1922 yield chnk
1920 yield chnk
1923
1921
1924 for fname in changedfiles:
1922 for fname in changedfiles:
1925 filerevlog = self.file(fname)
1923 filerevlog = self.file(fname)
1926 if filerevlog.count() == 0:
1924 if filerevlog.count() == 0:
1927 raise util.Abort(_("empty or missing revlog for %s") % fname)
1925 raise util.Abort(_("empty or missing revlog for %s") % fname)
1928 nodeiter = gennodelst(filerevlog)
1926 nodeiter = gennodelst(filerevlog)
1929 nodeiter = list(nodeiter)
1927 nodeiter = list(nodeiter)
1930 if nodeiter:
1928 if nodeiter:
1931 yield changegroup.chunkheader(len(fname))
1929 yield changegroup.chunkheader(len(fname))
1932 yield fname
1930 yield fname
1933 lookup = lookuprevlink_func(filerevlog)
1931 lookup = lookuprevlink_func(filerevlog)
1934 for chnk in filerevlog.group(nodeiter, lookup):
1932 for chnk in filerevlog.group(nodeiter, lookup):
1935 yield chnk
1933 yield chnk
1936
1934
1937 yield changegroup.closechunk()
1935 yield changegroup.closechunk()
1938
1936
1939 if nodes:
1937 if nodes:
1940 self.hook('outgoing', node=hex(nodes[0]), source=source)
1938 self.hook('outgoing', node=hex(nodes[0]), source=source)
1941
1939
1942 return util.chunkbuffer(gengroup())
1940 return util.chunkbuffer(gengroup())
1943
1941
1944 def addchangegroup(self, source, srctype, url, emptyok=False):
1942 def addchangegroup(self, source, srctype, url, emptyok=False):
1945 """add changegroup to repo.
1943 """add changegroup to repo.
1946
1944
1947 return values:
1945 return values:
1948 - nothing changed or no source: 0
1946 - nothing changed or no source: 0
1949 - more heads than before: 1+added heads (2..n)
1947 - more heads than before: 1+added heads (2..n)
1950 - less heads than before: -1-removed heads (-2..-n)
1948 - less heads than before: -1-removed heads (-2..-n)
1951 - number of heads stays the same: 1
1949 - number of heads stays the same: 1
1952 """
1950 """
1953 def csmap(x):
1951 def csmap(x):
1954 self.ui.debug(_("add changeset %s\n") % short(x))
1952 self.ui.debug(_("add changeset %s\n") % short(x))
1955 return cl.count()
1953 return cl.count()
1956
1954
1957 def revmap(x):
1955 def revmap(x):
1958 return cl.rev(x)
1956 return cl.rev(x)
1959
1957
1960 if not source:
1958 if not source:
1961 return 0
1959 return 0
1962
1960
1963 self.hook('prechangegroup', throw=True, source=srctype, url=url)
1961 self.hook('prechangegroup', throw=True, source=srctype, url=url)
1964
1962
1965 changesets = files = revisions = 0
1963 changesets = files = revisions = 0
1966
1964
1967 # write changelog data to temp files so concurrent readers will not see
1965 # write changelog data to temp files so concurrent readers will not see
1968 # inconsistent view
1966 # inconsistent view
1969 cl = self.changelog
1967 cl = self.changelog
1970 cl.delayupdate()
1968 cl.delayupdate()
1971 oldheads = len(cl.heads())
1969 oldheads = len(cl.heads())
1972
1970
1973 tr = self.transaction()
1971 tr = self.transaction()
1974 try:
1972 try:
1975 trp = weakref.proxy(tr)
1973 trp = weakref.proxy(tr)
1976 # pull off the changeset group
1974 # pull off the changeset group
1977 self.ui.status(_("adding changesets\n"))
1975 self.ui.status(_("adding changesets\n"))
1978 cor = cl.count() - 1
1976 cor = cl.count() - 1
1979 chunkiter = changegroup.chunkiter(source)
1977 chunkiter = changegroup.chunkiter(source)
1980 if cl.addgroup(chunkiter, csmap, trp, 1) is None and not emptyok:
1978 if cl.addgroup(chunkiter, csmap, trp, 1) is None and not emptyok:
1981 raise util.Abort(_("received changelog group is empty"))
1979 raise util.Abort(_("received changelog group is empty"))
1982 cnr = cl.count() - 1
1980 cnr = cl.count() - 1
1983 changesets = cnr - cor
1981 changesets = cnr - cor
1984
1982
1985 # pull off the manifest group
1983 # pull off the manifest group
1986 self.ui.status(_("adding manifests\n"))
1984 self.ui.status(_("adding manifests\n"))
1987 chunkiter = changegroup.chunkiter(source)
1985 chunkiter = changegroup.chunkiter(source)
1988 # no need to check for empty manifest group here:
1986 # no need to check for empty manifest group here:
1989 # if the result of the merge of 1 and 2 is the same in 3 and 4,
1987 # if the result of the merge of 1 and 2 is the same in 3 and 4,
1990 # no new manifest will be created and the manifest group will
1988 # no new manifest will be created and the manifest group will
1991 # be empty during the pull
1989 # be empty during the pull
1992 self.manifest.addgroup(chunkiter, revmap, trp)
1990 self.manifest.addgroup(chunkiter, revmap, trp)
1993
1991
1994 # process the files
1992 # process the files
1995 self.ui.status(_("adding file changes\n"))
1993 self.ui.status(_("adding file changes\n"))
1996 while 1:
1994 while 1:
1997 f = changegroup.getchunk(source)
1995 f = changegroup.getchunk(source)
1998 if not f:
1996 if not f:
1999 break
1997 break
2000 self.ui.debug(_("adding %s revisions\n") % f)
1998 self.ui.debug(_("adding %s revisions\n") % f)
2001 fl = self.file(f)
1999 fl = self.file(f)
2002 o = fl.count()
2000 o = fl.count()
2003 chunkiter = changegroup.chunkiter(source)
2001 chunkiter = changegroup.chunkiter(source)
2004 if fl.addgroup(chunkiter, revmap, trp) is None:
2002 if fl.addgroup(chunkiter, revmap, trp) is None:
2005 raise util.Abort(_("received file revlog group is empty"))
2003 raise util.Abort(_("received file revlog group is empty"))
2006 revisions += fl.count() - o
2004 revisions += fl.count() - o
2007 files += 1
2005 files += 1
2008
2006
2009 # make changelog see real files again
2007 # make changelog see real files again
2010 cl.finalize(trp)
2008 cl.finalize(trp)
2011
2009
2012 newheads = len(self.changelog.heads())
2010 newheads = len(self.changelog.heads())
2013 heads = ""
2011 heads = ""
2014 if oldheads and newheads != oldheads:
2012 if oldheads and newheads != oldheads:
2015 heads = _(" (%+d heads)") % (newheads - oldheads)
2013 heads = _(" (%+d heads)") % (newheads - oldheads)
2016
2014
2017 self.ui.status(_("added %d changesets"
2015 self.ui.status(_("added %d changesets"
2018 " with %d changes to %d files%s\n")
2016 " with %d changes to %d files%s\n")
2019 % (changesets, revisions, files, heads))
2017 % (changesets, revisions, files, heads))
2020
2018
2021 if changesets > 0:
2019 if changesets > 0:
2022 self.hook('pretxnchangegroup', throw=True,
2020 self.hook('pretxnchangegroup', throw=True,
2023 node=hex(self.changelog.node(cor+1)), source=srctype,
2021 node=hex(self.changelog.node(cor+1)), source=srctype,
2024 url=url)
2022 url=url)
2025
2023
2026 tr.close()
2024 tr.close()
2027 finally:
2025 finally:
2028 del tr
2026 del tr
2029
2027
2030 if changesets > 0:
2028 if changesets > 0:
2031 # forcefully update the on-disk branch cache
2029 # forcefully update the on-disk branch cache
2032 self.ui.debug(_("updating the branch cache\n"))
2030 self.ui.debug(_("updating the branch cache\n"))
2033 self.branchtags()
2031 self.branchtags()
2034 self.hook("changegroup", node=hex(self.changelog.node(cor+1)),
2032 self.hook("changegroup", node=hex(self.changelog.node(cor+1)),
2035 source=srctype, url=url)
2033 source=srctype, url=url)
2036
2034
2037 for i in xrange(cor + 1, cnr + 1):
2035 for i in xrange(cor + 1, cnr + 1):
2038 self.hook("incoming", node=hex(self.changelog.node(i)),
2036 self.hook("incoming", node=hex(self.changelog.node(i)),
2039 source=srctype, url=url)
2037 source=srctype, url=url)
2040
2038
2041 # never return 0 here:
2039 # never return 0 here:
2042 if newheads < oldheads:
2040 if newheads < oldheads:
2043 return newheads - oldheads - 1
2041 return newheads - oldheads - 1
2044 else:
2042 else:
2045 return newheads - oldheads + 1
2043 return newheads - oldheads + 1
2046
2044
2047
2045
2048 def stream_in(self, remote):
2046 def stream_in(self, remote):
2049 fp = remote.stream_out()
2047 fp = remote.stream_out()
2050 l = fp.readline()
2048 l = fp.readline()
2051 try:
2049 try:
2052 resp = int(l)
2050 resp = int(l)
2053 except ValueError:
2051 except ValueError:
2054 raise util.UnexpectedOutput(
2052 raise util.UnexpectedOutput(
2055 _('Unexpected response from remote server:'), l)
2053 _('Unexpected response from remote server:'), l)
2056 if resp == 1:
2054 if resp == 1:
2057 raise util.Abort(_('operation forbidden by server'))
2055 raise util.Abort(_('operation forbidden by server'))
2058 elif resp == 2:
2056 elif resp == 2:
2059 raise util.Abort(_('locking the remote repository failed'))
2057 raise util.Abort(_('locking the remote repository failed'))
2060 elif resp != 0:
2058 elif resp != 0:
2061 raise util.Abort(_('the server sent an unknown error code'))
2059 raise util.Abort(_('the server sent an unknown error code'))
2062 self.ui.status(_('streaming all changes\n'))
2060 self.ui.status(_('streaming all changes\n'))
2063 l = fp.readline()
2061 l = fp.readline()
2064 try:
2062 try:
2065 total_files, total_bytes = map(int, l.split(' ', 1))
2063 total_files, total_bytes = map(int, l.split(' ', 1))
2066 except ValueError, TypeError:
2064 except ValueError, TypeError:
2067 raise util.UnexpectedOutput(
2065 raise util.UnexpectedOutput(
2068 _('Unexpected response from remote server:'), l)
2066 _('Unexpected response from remote server:'), l)
2069 self.ui.status(_('%d files to transfer, %s of data\n') %
2067 self.ui.status(_('%d files to transfer, %s of data\n') %
2070 (total_files, util.bytecount(total_bytes)))
2068 (total_files, util.bytecount(total_bytes)))
2071 start = time.time()
2069 start = time.time()
2072 for i in xrange(total_files):
2070 for i in xrange(total_files):
2073 # XXX doesn't support '\n' or '\r' in filenames
2071 # XXX doesn't support '\n' or '\r' in filenames
2074 l = fp.readline()
2072 l = fp.readline()
2075 try:
2073 try:
2076 name, size = l.split('\0', 1)
2074 name, size = l.split('\0', 1)
2077 size = int(size)
2075 size = int(size)
2078 except ValueError, TypeError:
2076 except ValueError, TypeError:
2079 raise util.UnexpectedOutput(
2077 raise util.UnexpectedOutput(
2080 _('Unexpected response from remote server:'), l)
2078 _('Unexpected response from remote server:'), l)
2081 self.ui.debug('adding %s (%s)\n' % (name, util.bytecount(size)))
2079 self.ui.debug('adding %s (%s)\n' % (name, util.bytecount(size)))
2082 ofp = self.sopener(name, 'w')
2080 ofp = self.sopener(name, 'w')
2083 for chunk in util.filechunkiter(fp, limit=size):
2081 for chunk in util.filechunkiter(fp, limit=size):
2084 ofp.write(chunk)
2082 ofp.write(chunk)
2085 ofp.close()
2083 ofp.close()
2086 elapsed = time.time() - start
2084 elapsed = time.time() - start
2087 if elapsed <= 0:
2085 if elapsed <= 0:
2088 elapsed = 0.001
2086 elapsed = 0.001
2089 self.ui.status(_('transferred %s in %.1f seconds (%s/sec)\n') %
2087 self.ui.status(_('transferred %s in %.1f seconds (%s/sec)\n') %
2090 (util.bytecount(total_bytes), elapsed,
2088 (util.bytecount(total_bytes), elapsed,
2091 util.bytecount(total_bytes / elapsed)))
2089 util.bytecount(total_bytes / elapsed)))
2092 self.invalidate()
2090 self.invalidate()
2093 return len(self.heads()) + 1
2091 return len(self.heads()) + 1
2094
2092
2095 def clone(self, remote, heads=[], stream=False):
2093 def clone(self, remote, heads=[], stream=False):
2096 '''clone remote repository.
2094 '''clone remote repository.
2097
2095
2098 keyword arguments:
2096 keyword arguments:
2099 heads: list of revs to clone (forces use of pull)
2097 heads: list of revs to clone (forces use of pull)
2100 stream: use streaming clone if possible'''
2098 stream: use streaming clone if possible'''
2101
2099
2102 # now, all clients that can request uncompressed clones can
2100 # now, all clients that can request uncompressed clones can
2103 # read repo formats supported by all servers that can serve
2101 # read repo formats supported by all servers that can serve
2104 # them.
2102 # them.
2105
2103
2106 # if revlog format changes, client will have to check version
2104 # if revlog format changes, client will have to check version
2107 # and format flags on "stream" capability, and use
2105 # and format flags on "stream" capability, and use
2108 # uncompressed only if compatible.
2106 # uncompressed only if compatible.
2109
2107
2110 if stream and not heads and remote.capable('stream'):
2108 if stream and not heads and remote.capable('stream'):
2111 return self.stream_in(remote)
2109 return self.stream_in(remote)
2112 return self.pull(remote, heads)
2110 return self.pull(remote, heads)
2113
2111
2114 # used to avoid circular references so destructors work
2112 # used to avoid circular references so destructors work
2115 def aftertrans(files):
2113 def aftertrans(files):
2116 renamefiles = [tuple(t) for t in files]
2114 renamefiles = [tuple(t) for t in files]
2117 def a():
2115 def a():
2118 for src, dest in renamefiles:
2116 for src, dest in renamefiles:
2119 util.rename(src, dest)
2117 util.rename(src, dest)
2120 return a
2118 return a
2121
2119
2122 def instance(ui, path, create):
2120 def instance(ui, path, create):
2123 return localrepository(ui, util.drop_scheme('file', path), create)
2121 return localrepository(ui, util.drop_scheme('file', path), create)
2124
2122
2125 def islocal(path):
2123 def islocal(path):
2126 return True
2124 return True
General Comments 0
You need to be logged in to leave comments. Login now