##// END OF EJS Templates
bookmarks: move property methods into localrepo
Matt Mackall -
r13355:cce2e7b7 default
parent child Browse files
Show More
@@ -1,431 +1,423
1 # Mercurial extension to provide the 'hg bookmark' command
1 # Mercurial extension to provide the 'hg bookmark' command
2 #
2 #
3 # Copyright 2008 David Soria Parra <dsp@php.net>
3 # Copyright 2008 David Soria Parra <dsp@php.net>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 '''track a line of development with movable markers
8 '''track a line of development with movable markers
9
9
10 Bookmarks are local movable markers to changesets. Every bookmark
10 Bookmarks are local movable markers to changesets. Every bookmark
11 points to a changeset identified by its hash. If you commit a
11 points to a changeset identified by its hash. If you commit a
12 changeset that is based on a changeset that has a bookmark on it, the
12 changeset that is based on a changeset that has a bookmark on it, the
13 bookmark shifts to the new changeset.
13 bookmark shifts to the new changeset.
14
14
15 It is possible to use bookmark names in every revision lookup (e.g.
15 It is possible to use bookmark names in every revision lookup (e.g.
16 :hg:`merge`, :hg:`update`).
16 :hg:`merge`, :hg:`update`).
17
17
18 By default, when several bookmarks point to the same changeset, they
18 By default, when several bookmarks point to the same changeset, they
19 will all move forward together. It is possible to obtain a more
19 will all move forward together. It is possible to obtain a more
20 git-like experience by adding the following configuration option to
20 git-like experience by adding the following configuration option to
21 your configuration file::
21 your configuration file::
22
22
23 [bookmarks]
23 [bookmarks]
24 track.current = True
24 track.current = True
25
25
26 This will cause Mercurial to track the bookmark that you are currently
26 This will cause Mercurial to track the bookmark that you are currently
27 using, and only update it. This is similar to git's approach to
27 using, and only update it. This is similar to git's approach to
28 branching.
28 branching.
29 '''
29 '''
30
30
31 from mercurial.i18n import _
31 from mercurial.i18n import _
32 from mercurial.node import nullid, nullrev, bin, hex, short
32 from mercurial.node import nullid, nullrev, bin, hex, short
33 from mercurial import util, commands, repair, extensions, pushkey, hg, url
33 from mercurial import util, commands, repair, extensions, pushkey, hg, url
34 from mercurial import revset, encoding
34 from mercurial import revset, encoding
35 from mercurial import bookmarks
35 from mercurial import bookmarks
36 import os
36 import os
37
37
38 def bookmark(ui, repo, mark=None, rev=None, force=False, delete=False, rename=None):
38 def bookmark(ui, repo, mark=None, rev=None, force=False, delete=False, rename=None):
39 '''track a line of development with movable markers
39 '''track a line of development with movable markers
40
40
41 Bookmarks are pointers to certain commits that move when
41 Bookmarks are pointers to certain commits that move when
42 committing. Bookmarks are local. They can be renamed, copied and
42 committing. Bookmarks are local. They can be renamed, copied and
43 deleted. It is possible to use bookmark names in :hg:`merge` and
43 deleted. It is possible to use bookmark names in :hg:`merge` and
44 :hg:`update` to merge and update respectively to a given bookmark.
44 :hg:`update` to merge and update respectively to a given bookmark.
45
45
46 You can use :hg:`bookmark NAME` to set a bookmark on the working
46 You can use :hg:`bookmark NAME` to set a bookmark on the working
47 directory's parent revision with the given name. If you specify
47 directory's parent revision with the given name. If you specify
48 a revision using -r REV (where REV may be an existing bookmark),
48 a revision using -r REV (where REV may be an existing bookmark),
49 the bookmark is assigned to that revision.
49 the bookmark is assigned to that revision.
50
50
51 Bookmarks can be pushed and pulled between repositories (see :hg:`help
51 Bookmarks can be pushed and pulled between repositories (see :hg:`help
52 push` and :hg:`help pull`). This requires the bookmark extension to be
52 push` and :hg:`help pull`). This requires the bookmark extension to be
53 enabled for both the local and remote repositories.
53 enabled for both the local and remote repositories.
54 '''
54 '''
55 hexfn = ui.debugflag and hex or short
55 hexfn = ui.debugflag and hex or short
56 marks = repo._bookmarks
56 marks = repo._bookmarks
57 cur = repo.changectx('.').node()
57 cur = repo.changectx('.').node()
58
58
59 if rename:
59 if rename:
60 if rename not in marks:
60 if rename not in marks:
61 raise util.Abort(_("a bookmark of this name does not exist"))
61 raise util.Abort(_("a bookmark of this name does not exist"))
62 if mark in marks and not force:
62 if mark in marks and not force:
63 raise util.Abort(_("a bookmark of the same name already exists"))
63 raise util.Abort(_("a bookmark of the same name already exists"))
64 if mark is None:
64 if mark is None:
65 raise util.Abort(_("new bookmark name required"))
65 raise util.Abort(_("new bookmark name required"))
66 marks[mark] = marks[rename]
66 marks[mark] = marks[rename]
67 del marks[rename]
67 del marks[rename]
68 if repo._bookmarkcurrent == rename:
68 if repo._bookmarkcurrent == rename:
69 bookmarks.setcurrent(repo, mark)
69 bookmarks.setcurrent(repo, mark)
70 bookmarks.write(repo)
70 bookmarks.write(repo)
71 return
71 return
72
72
73 if delete:
73 if delete:
74 if mark is None:
74 if mark is None:
75 raise util.Abort(_("bookmark name required"))
75 raise util.Abort(_("bookmark name required"))
76 if mark not in marks:
76 if mark not in marks:
77 raise util.Abort(_("a bookmark of this name does not exist"))
77 raise util.Abort(_("a bookmark of this name does not exist"))
78 if mark == repo._bookmarkcurrent:
78 if mark == repo._bookmarkcurrent:
79 bookmarks.setcurrent(repo, None)
79 bookmarks.setcurrent(repo, None)
80 del marks[mark]
80 del marks[mark]
81 bookmarks.write(repo)
81 bookmarks.write(repo)
82 return
82 return
83
83
84 if mark is not None:
84 if mark is not None:
85 if "\n" in mark:
85 if "\n" in mark:
86 raise util.Abort(_("bookmark name cannot contain newlines"))
86 raise util.Abort(_("bookmark name cannot contain newlines"))
87 mark = mark.strip()
87 mark = mark.strip()
88 if not mark:
88 if not mark:
89 raise util.Abort(_("bookmark names cannot consist entirely of "
89 raise util.Abort(_("bookmark names cannot consist entirely of "
90 "whitespace"))
90 "whitespace"))
91 if mark in marks and not force:
91 if mark in marks and not force:
92 raise util.Abort(_("a bookmark of the same name already exists"))
92 raise util.Abort(_("a bookmark of the same name already exists"))
93 if ((mark in repo.branchtags() or mark == repo.dirstate.branch())
93 if ((mark in repo.branchtags() or mark == repo.dirstate.branch())
94 and not force):
94 and not force):
95 raise util.Abort(
95 raise util.Abort(
96 _("a bookmark cannot have the name of an existing branch"))
96 _("a bookmark cannot have the name of an existing branch"))
97 if rev:
97 if rev:
98 marks[mark] = repo.lookup(rev)
98 marks[mark] = repo.lookup(rev)
99 else:
99 else:
100 marks[mark] = repo.changectx('.').node()
100 marks[mark] = repo.changectx('.').node()
101 bookmarks.setcurrent(repo, mark)
101 bookmarks.setcurrent(repo, mark)
102 bookmarks.write(repo)
102 bookmarks.write(repo)
103 return
103 return
104
104
105 if mark is None:
105 if mark is None:
106 if rev:
106 if rev:
107 raise util.Abort(_("bookmark name required"))
107 raise util.Abort(_("bookmark name required"))
108 if len(marks) == 0:
108 if len(marks) == 0:
109 ui.status(_("no bookmarks set\n"))
109 ui.status(_("no bookmarks set\n"))
110 else:
110 else:
111 for bmark, n in marks.iteritems():
111 for bmark, n in marks.iteritems():
112 if ui.configbool('bookmarks', 'track.current'):
112 if ui.configbool('bookmarks', 'track.current'):
113 current = repo._bookmarkcurrent
113 current = repo._bookmarkcurrent
114 if bmark == current and n == cur:
114 if bmark == current and n == cur:
115 prefix, label = '*', 'bookmarks.current'
115 prefix, label = '*', 'bookmarks.current'
116 else:
116 else:
117 prefix, label = ' ', ''
117 prefix, label = ' ', ''
118 else:
118 else:
119 if n == cur:
119 if n == cur:
120 prefix, label = '*', 'bookmarks.current'
120 prefix, label = '*', 'bookmarks.current'
121 else:
121 else:
122 prefix, label = ' ', ''
122 prefix, label = ' ', ''
123
123
124 if ui.quiet:
124 if ui.quiet:
125 ui.write("%s\n" % bmark, label=label)
125 ui.write("%s\n" % bmark, label=label)
126 else:
126 else:
127 ui.write(" %s %-25s %d:%s\n" % (
127 ui.write(" %s %-25s %d:%s\n" % (
128 prefix, bmark, repo.changelog.rev(n), hexfn(n)),
128 prefix, bmark, repo.changelog.rev(n), hexfn(n)),
129 label=label)
129 label=label)
130 return
130 return
131
131
132 def _revstostrip(changelog, node):
132 def _revstostrip(changelog, node):
133 srev = changelog.rev(node)
133 srev = changelog.rev(node)
134 tostrip = [srev]
134 tostrip = [srev]
135 saveheads = []
135 saveheads = []
136 for r in xrange(srev, len(changelog)):
136 for r in xrange(srev, len(changelog)):
137 parents = changelog.parentrevs(r)
137 parents = changelog.parentrevs(r)
138 if parents[0] in tostrip or parents[1] in tostrip:
138 if parents[0] in tostrip or parents[1] in tostrip:
139 tostrip.append(r)
139 tostrip.append(r)
140 if parents[1] != nullrev:
140 if parents[1] != nullrev:
141 for p in parents:
141 for p in parents:
142 if p not in tostrip and p > srev:
142 if p not in tostrip and p > srev:
143 saveheads.append(p)
143 saveheads.append(p)
144 return [r for r in tostrip if r not in saveheads]
144 return [r for r in tostrip if r not in saveheads]
145
145
146 def strip(oldstrip, ui, repo, node, backup="all"):
146 def strip(oldstrip, ui, repo, node, backup="all"):
147 """Strip bookmarks if revisions are stripped using
147 """Strip bookmarks if revisions are stripped using
148 the mercurial.strip method. This usually happens during
148 the mercurial.strip method. This usually happens during
149 qpush and qpop"""
149 qpush and qpop"""
150 revisions = _revstostrip(repo.changelog, node)
150 revisions = _revstostrip(repo.changelog, node)
151 marks = repo._bookmarks
151 marks = repo._bookmarks
152 update = []
152 update = []
153 for mark, n in marks.iteritems():
153 for mark, n in marks.iteritems():
154 if repo.changelog.rev(n) in revisions:
154 if repo.changelog.rev(n) in revisions:
155 update.append(mark)
155 update.append(mark)
156 oldstrip(ui, repo, node, backup)
156 oldstrip(ui, repo, node, backup)
157 if len(update) > 0:
157 if len(update) > 0:
158 for m in update:
158 for m in update:
159 marks[m] = repo.changectx('.').node()
159 marks[m] = repo.changectx('.').node()
160 bookmarks.write(repo)
160 bookmarks.write(repo)
161
161
162 def reposetup(ui, repo):
162 def reposetup(ui, repo):
163 if not repo.local():
163 if not repo.local():
164 return
164 return
165
165
166 class bookmark_repo(repo.__class__):
166 class bookmark_repo(repo.__class__):
167 @util.propertycache
168 def _bookmarks(self):
169 return bookmarks.read(self)
170
171 @util.propertycache
172 def _bookmarkcurrent(self):
173 return bookmarks.readcurrent(self)
174
175 def rollback(self, dryrun=False):
167 def rollback(self, dryrun=False):
176 if os.path.exists(self.join('undo.bookmarks')):
168 if os.path.exists(self.join('undo.bookmarks')):
177 if not dryrun:
169 if not dryrun:
178 util.rename(self.join('undo.bookmarks'), self.join('bookmarks'))
170 util.rename(self.join('undo.bookmarks'), self.join('bookmarks'))
179 elif not os.path.exists(self.sjoin("undo")):
171 elif not os.path.exists(self.sjoin("undo")):
180 # avoid "no rollback information available" message
172 # avoid "no rollback information available" message
181 return 0
173 return 0
182 return super(bookmark_repo, self).rollback(dryrun)
174 return super(bookmark_repo, self).rollback(dryrun)
183
175
184 def lookup(self, key):
176 def lookup(self, key):
185 if key in self._bookmarks:
177 if key in self._bookmarks:
186 key = self._bookmarks[key]
178 key = self._bookmarks[key]
187 return super(bookmark_repo, self).lookup(key)
179 return super(bookmark_repo, self).lookup(key)
188
180
189 def commitctx(self, ctx, error=False):
181 def commitctx(self, ctx, error=False):
190 """Add a revision to the repository and
182 """Add a revision to the repository and
191 move the bookmark"""
183 move the bookmark"""
192 wlock = self.wlock() # do both commit and bookmark with lock held
184 wlock = self.wlock() # do both commit and bookmark with lock held
193 try:
185 try:
194 node = super(bookmark_repo, self).commitctx(ctx, error)
186 node = super(bookmark_repo, self).commitctx(ctx, error)
195 if node is None:
187 if node is None:
196 return None
188 return None
197 parents = self.changelog.parents(node)
189 parents = self.changelog.parents(node)
198 if parents[1] == nullid:
190 if parents[1] == nullid:
199 parents = (parents[0],)
191 parents = (parents[0],)
200
192
201 bookmarks.update(self, parents, node)
193 bookmarks.update(self, parents, node)
202 return node
194 return node
203 finally:
195 finally:
204 wlock.release()
196 wlock.release()
205
197
206 def pull(self, remote, heads=None, force=False):
198 def pull(self, remote, heads=None, force=False):
207 result = super(bookmark_repo, self).pull(remote, heads, force)
199 result = super(bookmark_repo, self).pull(remote, heads, force)
208
200
209 self.ui.debug("checking for updated bookmarks\n")
201 self.ui.debug("checking for updated bookmarks\n")
210 rb = remote.listkeys('bookmarks')
202 rb = remote.listkeys('bookmarks')
211 changed = False
203 changed = False
212 for k in rb.keys():
204 for k in rb.keys():
213 if k in self._bookmarks:
205 if k in self._bookmarks:
214 nr, nl = rb[k], self._bookmarks[k]
206 nr, nl = rb[k], self._bookmarks[k]
215 if nr in self:
207 if nr in self:
216 cr = self[nr]
208 cr = self[nr]
217 cl = self[nl]
209 cl = self[nl]
218 if cl.rev() >= cr.rev():
210 if cl.rev() >= cr.rev():
219 continue
211 continue
220 if cr in cl.descendants():
212 if cr in cl.descendants():
221 self._bookmarks[k] = cr.node()
213 self._bookmarks[k] = cr.node()
222 changed = True
214 changed = True
223 self.ui.status(_("updating bookmark %s\n") % k)
215 self.ui.status(_("updating bookmark %s\n") % k)
224 else:
216 else:
225 self.ui.warn(_("not updating divergent"
217 self.ui.warn(_("not updating divergent"
226 " bookmark %s\n") % k)
218 " bookmark %s\n") % k)
227 if changed:
219 if changed:
228 bookmarks.write(repo)
220 bookmarks.write(repo)
229
221
230 return result
222 return result
231
223
232 def push(self, remote, force=False, revs=None, newbranch=False):
224 def push(self, remote, force=False, revs=None, newbranch=False):
233 result = super(bookmark_repo, self).push(remote, force, revs,
225 result = super(bookmark_repo, self).push(remote, force, revs,
234 newbranch)
226 newbranch)
235
227
236 self.ui.debug("checking for updated bookmarks\n")
228 self.ui.debug("checking for updated bookmarks\n")
237 rb = remote.listkeys('bookmarks')
229 rb = remote.listkeys('bookmarks')
238 for k in rb.keys():
230 for k in rb.keys():
239 if k in self._bookmarks:
231 if k in self._bookmarks:
240 nr, nl = rb[k], hex(self._bookmarks[k])
232 nr, nl = rb[k], hex(self._bookmarks[k])
241 if nr in self:
233 if nr in self:
242 cr = self[nr]
234 cr = self[nr]
243 cl = self[nl]
235 cl = self[nl]
244 if cl in cr.descendants():
236 if cl in cr.descendants():
245 r = remote.pushkey('bookmarks', k, nr, nl)
237 r = remote.pushkey('bookmarks', k, nr, nl)
246 if r:
238 if r:
247 self.ui.status(_("updating bookmark %s\n") % k)
239 self.ui.status(_("updating bookmark %s\n") % k)
248 else:
240 else:
249 self.ui.warn(_('updating bookmark %s'
241 self.ui.warn(_('updating bookmark %s'
250 ' failed!\n') % k)
242 ' failed!\n') % k)
251
243
252 return result
244 return result
253
245
254 def addchangegroup(self, *args, **kwargs):
246 def addchangegroup(self, *args, **kwargs):
255 result = super(bookmark_repo, self).addchangegroup(*args, **kwargs)
247 result = super(bookmark_repo, self).addchangegroup(*args, **kwargs)
256 if result > 1:
248 if result > 1:
257 # We have more heads than before
249 # We have more heads than before
258 return result
250 return result
259 node = self.changelog.tip()
251 node = self.changelog.tip()
260 parents = self.dirstate.parents()
252 parents = self.dirstate.parents()
261 bookmarks.update(self, parents, node)
253 bookmarks.update(self, parents, node)
262 return result
254 return result
263
255
264 def _findtags(self):
256 def _findtags(self):
265 """Merge bookmarks with normal tags"""
257 """Merge bookmarks with normal tags"""
266 (tags, tagtypes) = super(bookmark_repo, self)._findtags()
258 (tags, tagtypes) = super(bookmark_repo, self)._findtags()
267 tags.update(self._bookmarks)
259 tags.update(self._bookmarks)
268 return (tags, tagtypes)
260 return (tags, tagtypes)
269
261
270 if hasattr(repo, 'invalidate'):
262 if hasattr(repo, 'invalidate'):
271 def invalidate(self):
263 def invalidate(self):
272 super(bookmark_repo, self).invalidate()
264 super(bookmark_repo, self).invalidate()
273 for attr in ('_bookmarks', '_bookmarkcurrent'):
265 for attr in ('_bookmarks', '_bookmarkcurrent'):
274 if attr in self.__dict__:
266 if attr in self.__dict__:
275 delattr(self, attr)
267 delattr(self, attr)
276
268
277 repo.__class__ = bookmark_repo
269 repo.__class__ = bookmark_repo
278
270
279 def pull(oldpull, ui, repo, source="default", **opts):
271 def pull(oldpull, ui, repo, source="default", **opts):
280 # translate bookmark args to rev args for actual pull
272 # translate bookmark args to rev args for actual pull
281 if opts.get('bookmark'):
273 if opts.get('bookmark'):
282 # this is an unpleasant hack as pull will do this internally
274 # this is an unpleasant hack as pull will do this internally
283 source, branches = hg.parseurl(ui.expandpath(source),
275 source, branches = hg.parseurl(ui.expandpath(source),
284 opts.get('branch'))
276 opts.get('branch'))
285 other = hg.repository(hg.remoteui(repo, opts), source)
277 other = hg.repository(hg.remoteui(repo, opts), source)
286 rb = other.listkeys('bookmarks')
278 rb = other.listkeys('bookmarks')
287
279
288 for b in opts['bookmark']:
280 for b in opts['bookmark']:
289 if b not in rb:
281 if b not in rb:
290 raise util.Abort(_('remote bookmark %s not found!') % b)
282 raise util.Abort(_('remote bookmark %s not found!') % b)
291 opts.setdefault('rev', []).append(b)
283 opts.setdefault('rev', []).append(b)
292
284
293 result = oldpull(ui, repo, source, **opts)
285 result = oldpull(ui, repo, source, **opts)
294
286
295 # update specified bookmarks
287 # update specified bookmarks
296 if opts.get('bookmark'):
288 if opts.get('bookmark'):
297 for b in opts['bookmark']:
289 for b in opts['bookmark']:
298 # explicit pull overrides local bookmark if any
290 # explicit pull overrides local bookmark if any
299 ui.status(_("importing bookmark %s\n") % b)
291 ui.status(_("importing bookmark %s\n") % b)
300 repo._bookmarks[b] = repo[rb[b]].node()
292 repo._bookmarks[b] = repo[rb[b]].node()
301 bookmarks.write(repo)
293 bookmarks.write(repo)
302
294
303 return result
295 return result
304
296
305 def push(oldpush, ui, repo, dest=None, **opts):
297 def push(oldpush, ui, repo, dest=None, **opts):
306 dopush = True
298 dopush = True
307 if opts.get('bookmark'):
299 if opts.get('bookmark'):
308 dopush = False
300 dopush = False
309 for b in opts['bookmark']:
301 for b in opts['bookmark']:
310 if b in repo._bookmarks:
302 if b in repo._bookmarks:
311 dopush = True
303 dopush = True
312 opts.setdefault('rev', []).append(b)
304 opts.setdefault('rev', []).append(b)
313
305
314 result = 0
306 result = 0
315 if dopush:
307 if dopush:
316 result = oldpush(ui, repo, dest, **opts)
308 result = oldpush(ui, repo, dest, **opts)
317
309
318 if opts.get('bookmark'):
310 if opts.get('bookmark'):
319 # this is an unpleasant hack as push will do this internally
311 # this is an unpleasant hack as push will do this internally
320 dest = ui.expandpath(dest or 'default-push', dest or 'default')
312 dest = ui.expandpath(dest or 'default-push', dest or 'default')
321 dest, branches = hg.parseurl(dest, opts.get('branch'))
313 dest, branches = hg.parseurl(dest, opts.get('branch'))
322 other = hg.repository(hg.remoteui(repo, opts), dest)
314 other = hg.repository(hg.remoteui(repo, opts), dest)
323 rb = other.listkeys('bookmarks')
315 rb = other.listkeys('bookmarks')
324 for b in opts['bookmark']:
316 for b in opts['bookmark']:
325 # explicit push overrides remote bookmark if any
317 # explicit push overrides remote bookmark if any
326 if b in repo._bookmarks:
318 if b in repo._bookmarks:
327 ui.status(_("exporting bookmark %s\n") % b)
319 ui.status(_("exporting bookmark %s\n") % b)
328 new = repo[b].hex()
320 new = repo[b].hex()
329 elif b in rb:
321 elif b in rb:
330 ui.status(_("deleting remote bookmark %s\n") % b)
322 ui.status(_("deleting remote bookmark %s\n") % b)
331 new = '' # delete
323 new = '' # delete
332 else:
324 else:
333 ui.warn(_('bookmark %s does not exist on the local '
325 ui.warn(_('bookmark %s does not exist on the local '
334 'or remote repository!\n') % b)
326 'or remote repository!\n') % b)
335 return 2
327 return 2
336 old = rb.get(b, '')
328 old = rb.get(b, '')
337 r = other.pushkey('bookmarks', b, old, new)
329 r = other.pushkey('bookmarks', b, old, new)
338 if not r:
330 if not r:
339 ui.warn(_('updating bookmark %s failed!\n') % b)
331 ui.warn(_('updating bookmark %s failed!\n') % b)
340 if not result:
332 if not result:
341 result = 2
333 result = 2
342
334
343 return result
335 return result
344
336
345 def incoming(oldincoming, ui, repo, source="default", **opts):
337 def incoming(oldincoming, ui, repo, source="default", **opts):
346 if opts.get('bookmarks'):
338 if opts.get('bookmarks'):
347 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
339 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
348 other = hg.repository(hg.remoteui(repo, opts), source)
340 other = hg.repository(hg.remoteui(repo, opts), source)
349 ui.status(_('comparing with %s\n') % url.hidepassword(source))
341 ui.status(_('comparing with %s\n') % url.hidepassword(source))
350 return bookmarks.diff(ui, repo, other)
342 return bookmarks.diff(ui, repo, other)
351 else:
343 else:
352 return oldincoming(ui, repo, source, **opts)
344 return oldincoming(ui, repo, source, **opts)
353
345
354 def outgoing(oldoutgoing, ui, repo, dest=None, **opts):
346 def outgoing(oldoutgoing, ui, repo, dest=None, **opts):
355 if opts.get('bookmarks'):
347 if opts.get('bookmarks'):
356 dest = ui.expandpath(dest or 'default-push', dest or 'default')
348 dest = ui.expandpath(dest or 'default-push', dest or 'default')
357 dest, branches = hg.parseurl(dest, opts.get('branch'))
349 dest, branches = hg.parseurl(dest, opts.get('branch'))
358 other = hg.repository(hg.remoteui(repo, opts), dest)
350 other = hg.repository(hg.remoteui(repo, opts), dest)
359 ui.status(_('comparing with %s\n') % url.hidepassword(dest))
351 ui.status(_('comparing with %s\n') % url.hidepassword(dest))
360 return bookmarks.diff(ui, other, repo)
352 return bookmarks.diff(ui, other, repo)
361 else:
353 else:
362 return oldoutgoing(ui, repo, dest, **opts)
354 return oldoutgoing(ui, repo, dest, **opts)
363
355
364 def uisetup(ui):
356 def uisetup(ui):
365 extensions.wrapfunction(repair, "strip", strip)
357 extensions.wrapfunction(repair, "strip", strip)
366 if ui.configbool('bookmarks', 'track.current'):
358 if ui.configbool('bookmarks', 'track.current'):
367 extensions.wrapcommand(commands.table, 'update', updatecurbookmark)
359 extensions.wrapcommand(commands.table, 'update', updatecurbookmark)
368
360
369 entry = extensions.wrapcommand(commands.table, 'pull', pull)
361 entry = extensions.wrapcommand(commands.table, 'pull', pull)
370 entry[1].append(('B', 'bookmark', [],
362 entry[1].append(('B', 'bookmark', [],
371 _("bookmark to import"),
363 _("bookmark to import"),
372 _('BOOKMARK')))
364 _('BOOKMARK')))
373 entry = extensions.wrapcommand(commands.table, 'push', push)
365 entry = extensions.wrapcommand(commands.table, 'push', push)
374 entry[1].append(('B', 'bookmark', [],
366 entry[1].append(('B', 'bookmark', [],
375 _("bookmark to export"),
367 _("bookmark to export"),
376 _('BOOKMARK')))
368 _('BOOKMARK')))
377 entry = extensions.wrapcommand(commands.table, 'incoming', incoming)
369 entry = extensions.wrapcommand(commands.table, 'incoming', incoming)
378 entry[1].append(('B', 'bookmarks', False,
370 entry[1].append(('B', 'bookmarks', False,
379 _("compare bookmark")))
371 _("compare bookmark")))
380 entry = extensions.wrapcommand(commands.table, 'outgoing', outgoing)
372 entry = extensions.wrapcommand(commands.table, 'outgoing', outgoing)
381 entry[1].append(('B', 'bookmarks', False,
373 entry[1].append(('B', 'bookmarks', False,
382 _("compare bookmark")))
374 _("compare bookmark")))
383
375
384 def updatecurbookmark(orig, ui, repo, *args, **opts):
376 def updatecurbookmark(orig, ui, repo, *args, **opts):
385 '''Set the current bookmark
377 '''Set the current bookmark
386
378
387 If the user updates to a bookmark we update the .hg/bookmarks.current
379 If the user updates to a bookmark we update the .hg/bookmarks.current
388 file.
380 file.
389 '''
381 '''
390 res = orig(ui, repo, *args, **opts)
382 res = orig(ui, repo, *args, **opts)
391 rev = opts['rev']
383 rev = opts['rev']
392 if not rev and len(args) > 0:
384 if not rev and len(args) > 0:
393 rev = args[0]
385 rev = args[0]
394 bookmarks.setcurrent(repo, rev)
386 bookmarks.setcurrent(repo, rev)
395 return res
387 return res
396
388
397 def bmrevset(repo, subset, x):
389 def bmrevset(repo, subset, x):
398 """``bookmark([name])``
390 """``bookmark([name])``
399 The named bookmark or all bookmarks.
391 The named bookmark or all bookmarks.
400 """
392 """
401 # i18n: "bookmark" is a keyword
393 # i18n: "bookmark" is a keyword
402 args = revset.getargs(x, 0, 1, _('bookmark takes one or no arguments'))
394 args = revset.getargs(x, 0, 1, _('bookmark takes one or no arguments'))
403 if args:
395 if args:
404 bm = revset.getstring(args[0],
396 bm = revset.getstring(args[0],
405 # i18n: "bookmark" is a keyword
397 # i18n: "bookmark" is a keyword
406 _('the argument to bookmark must be a string'))
398 _('the argument to bookmark must be a string'))
407 bmrev = bookmarks.listbookmarks(repo).get(bm, None)
399 bmrev = bookmarks.listbookmarks(repo).get(bm, None)
408 if bmrev:
400 if bmrev:
409 bmrev = repo.changelog.rev(bin(bmrev))
401 bmrev = repo.changelog.rev(bin(bmrev))
410 return [r for r in subset if r == bmrev]
402 return [r for r in subset if r == bmrev]
411 bms = set([repo.changelog.rev(bin(r))
403 bms = set([repo.changelog.rev(bin(r))
412 for r in bookmarks.listbookmarks(repo).values()])
404 for r in bookmarks.listbookmarks(repo).values()])
413 return [r for r in subset if r in bms]
405 return [r for r in subset if r in bms]
414
406
415 def extsetup(ui):
407 def extsetup(ui):
416 revset.symbols['bookmark'] = bmrevset
408 revset.symbols['bookmark'] = bmrevset
417
409
418 cmdtable = {
410 cmdtable = {
419 "bookmarks":
411 "bookmarks":
420 (bookmark,
412 (bookmark,
421 [('f', 'force', False, _('force')),
413 [('f', 'force', False, _('force')),
422 ('r', 'rev', '', _('revision'), _('REV')),
414 ('r', 'rev', '', _('revision'), _('REV')),
423 ('d', 'delete', False, _('delete a given bookmark')),
415 ('d', 'delete', False, _('delete a given bookmark')),
424 ('m', 'rename', '', _('rename a given bookmark'), _('NAME'))],
416 ('m', 'rename', '', _('rename a given bookmark'), _('NAME'))],
425 _('hg bookmarks [-f] [-d] [-m NAME] [-r REV] [NAME]')),
417 _('hg bookmarks [-f] [-d] [-m NAME] [-r REV] [NAME]')),
426 }
418 }
427
419
428 colortable = {'bookmarks.current': 'green'}
420 colortable = {'bookmarks.current': 'green'}
429
421
430 # tell hggettext to extract docstrings from these functions:
422 # tell hggettext to extract docstrings from these functions:
431 i18nfunctions = [bmrevset]
423 i18nfunctions = [bmrevset]
@@ -1,1945 +1,1952
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 of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
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, subrepo, discovery, pushkey
10 import repo, changegroup, subrepo, discovery, pushkey
11 import changelog, dirstate, filelog, manifest, context
11 import changelog, dirstate, filelog, manifest, context, bookmarks
12 import lock, transaction, store, encoding
12 import lock, transaction, store, encoding
13 import util, extensions, hook, error
13 import util, extensions, hook, error
14 import match as matchmod
14 import match as matchmod
15 import merge as mergemod
15 import merge as mergemod
16 import tags as tagsmod
16 import tags as tagsmod
17 import url as urlmod
17 import url as urlmod
18 from lock import release
18 from lock import release
19 import weakref, errno, os, time, inspect
19 import weakref, errno, os, time, inspect
20 propertycache = util.propertycache
20 propertycache = util.propertycache
21
21
22 class localrepository(repo.repository):
22 class localrepository(repo.repository):
23 capabilities = set(('lookup', 'changegroupsubset', 'branchmap', 'pushkey'))
23 capabilities = set(('lookup', 'changegroupsubset', 'branchmap', 'pushkey'))
24 supportedformats = set(('revlogv1', 'parentdelta'))
24 supportedformats = set(('revlogv1', 'parentdelta'))
25 supported = supportedformats | set(('store', 'fncache', 'shared',
25 supported = supportedformats | set(('store', 'fncache', 'shared',
26 'dotencode'))
26 'dotencode'))
27
27
28 def __init__(self, baseui, path=None, create=0):
28 def __init__(self, baseui, path=None, create=0):
29 repo.repository.__init__(self)
29 repo.repository.__init__(self)
30 self.root = os.path.realpath(util.expandpath(path))
30 self.root = os.path.realpath(util.expandpath(path))
31 self.path = os.path.join(self.root, ".hg")
31 self.path = os.path.join(self.root, ".hg")
32 self.origroot = path
32 self.origroot = path
33 self.auditor = util.path_auditor(self.root, self._checknested)
33 self.auditor = util.path_auditor(self.root, self._checknested)
34 self.opener = util.opener(self.path)
34 self.opener = util.opener(self.path)
35 self.wopener = util.opener(self.root)
35 self.wopener = util.opener(self.root)
36 self.baseui = baseui
36 self.baseui = baseui
37 self.ui = baseui.copy()
37 self.ui = baseui.copy()
38
38
39 try:
39 try:
40 self.ui.readconfig(self.join("hgrc"), self.root)
40 self.ui.readconfig(self.join("hgrc"), self.root)
41 extensions.loadall(self.ui)
41 extensions.loadall(self.ui)
42 except IOError:
42 except IOError:
43 pass
43 pass
44
44
45 if not os.path.isdir(self.path):
45 if not os.path.isdir(self.path):
46 if create:
46 if create:
47 if not os.path.exists(path):
47 if not os.path.exists(path):
48 util.makedirs(path)
48 util.makedirs(path)
49 os.mkdir(self.path)
49 os.mkdir(self.path)
50 requirements = ["revlogv1"]
50 requirements = ["revlogv1"]
51 if self.ui.configbool('format', 'usestore', True):
51 if self.ui.configbool('format', 'usestore', True):
52 os.mkdir(os.path.join(self.path, "store"))
52 os.mkdir(os.path.join(self.path, "store"))
53 requirements.append("store")
53 requirements.append("store")
54 if self.ui.configbool('format', 'usefncache', True):
54 if self.ui.configbool('format', 'usefncache', True):
55 requirements.append("fncache")
55 requirements.append("fncache")
56 if self.ui.configbool('format', 'dotencode', True):
56 if self.ui.configbool('format', 'dotencode', True):
57 requirements.append('dotencode')
57 requirements.append('dotencode')
58 # create an invalid changelog
58 # create an invalid changelog
59 self.opener("00changelog.i", "a").write(
59 self.opener("00changelog.i", "a").write(
60 '\0\0\0\2' # represents revlogv2
60 '\0\0\0\2' # represents revlogv2
61 ' dummy changelog to prevent using the old repo layout'
61 ' dummy changelog to prevent using the old repo layout'
62 )
62 )
63 if self.ui.configbool('format', 'parentdelta', False):
63 if self.ui.configbool('format', 'parentdelta', False):
64 requirements.append("parentdelta")
64 requirements.append("parentdelta")
65 else:
65 else:
66 raise error.RepoError(_("repository %s not found") % path)
66 raise error.RepoError(_("repository %s not found") % path)
67 elif create:
67 elif create:
68 raise error.RepoError(_("repository %s already exists") % path)
68 raise error.RepoError(_("repository %s already exists") % path)
69 else:
69 else:
70 # find requirements
70 # find requirements
71 requirements = set()
71 requirements = set()
72 try:
72 try:
73 requirements = set(self.opener("requires").read().splitlines())
73 requirements = set(self.opener("requires").read().splitlines())
74 except IOError, inst:
74 except IOError, inst:
75 if inst.errno != errno.ENOENT:
75 if inst.errno != errno.ENOENT:
76 raise
76 raise
77 for r in requirements - self.supported:
77 for r in requirements - self.supported:
78 raise error.RepoError(_("requirement '%s' not supported") % r)
78 raise error.RepoError(_("requirement '%s' not supported") % r)
79
79
80 self.sharedpath = self.path
80 self.sharedpath = self.path
81 try:
81 try:
82 s = os.path.realpath(self.opener("sharedpath").read())
82 s = os.path.realpath(self.opener("sharedpath").read())
83 if not os.path.exists(s):
83 if not os.path.exists(s):
84 raise error.RepoError(
84 raise error.RepoError(
85 _('.hg/sharedpath points to nonexistent directory %s') % s)
85 _('.hg/sharedpath points to nonexistent directory %s') % s)
86 self.sharedpath = s
86 self.sharedpath = s
87 except IOError, inst:
87 except IOError, inst:
88 if inst.errno != errno.ENOENT:
88 if inst.errno != errno.ENOENT:
89 raise
89 raise
90
90
91 self.store = store.store(requirements, self.sharedpath, util.opener)
91 self.store = store.store(requirements, self.sharedpath, util.opener)
92 self.spath = self.store.path
92 self.spath = self.store.path
93 self.sopener = self.store.opener
93 self.sopener = self.store.opener
94 self.sjoin = self.store.join
94 self.sjoin = self.store.join
95 self.opener.createmode = self.store.createmode
95 self.opener.createmode = self.store.createmode
96 self._applyrequirements(requirements)
96 self._applyrequirements(requirements)
97 if create:
97 if create:
98 self._writerequirements()
98 self._writerequirements()
99
99
100 # These two define the set of tags for this repository. _tags
100 # These two define the set of tags for this repository. _tags
101 # maps tag name to node; _tagtypes maps tag name to 'global' or
101 # maps tag name to node; _tagtypes maps tag name to 'global' or
102 # 'local'. (Global tags are defined by .hgtags across all
102 # 'local'. (Global tags are defined by .hgtags across all
103 # heads, and local tags are defined in .hg/localtags.) They
103 # heads, and local tags are defined in .hg/localtags.) They
104 # constitute the in-memory cache of tags.
104 # constitute the in-memory cache of tags.
105 self._tags = None
105 self._tags = None
106 self._tagtypes = None
106 self._tagtypes = None
107
107
108 self._branchcache = None
108 self._branchcache = None
109 self._branchcachetip = None
109 self._branchcachetip = None
110 self.nodetagscache = None
110 self.nodetagscache = None
111 self.filterpats = {}
111 self.filterpats = {}
112 self._datafilters = {}
112 self._datafilters = {}
113 self._transref = self._lockref = self._wlockref = None
113 self._transref = self._lockref = self._wlockref = None
114
114
115 def _applyrequirements(self, requirements):
115 def _applyrequirements(self, requirements):
116 self.requirements = requirements
116 self.requirements = requirements
117 self.sopener.options = {}
117 self.sopener.options = {}
118 if 'parentdelta' in requirements:
118 if 'parentdelta' in requirements:
119 self.sopener.options['parentdelta'] = 1
119 self.sopener.options['parentdelta'] = 1
120
120
121 def _writerequirements(self):
121 def _writerequirements(self):
122 reqfile = self.opener("requires", "w")
122 reqfile = self.opener("requires", "w")
123 for r in self.requirements:
123 for r in self.requirements:
124 reqfile.write("%s\n" % r)
124 reqfile.write("%s\n" % r)
125 reqfile.close()
125 reqfile.close()
126
126
127 def _checknested(self, path):
127 def _checknested(self, path):
128 """Determine if path is a legal nested repository."""
128 """Determine if path is a legal nested repository."""
129 if not path.startswith(self.root):
129 if not path.startswith(self.root):
130 return False
130 return False
131 subpath = path[len(self.root) + 1:]
131 subpath = path[len(self.root) + 1:]
132
132
133 # XXX: Checking against the current working copy is wrong in
133 # XXX: Checking against the current working copy is wrong in
134 # the sense that it can reject things like
134 # the sense that it can reject things like
135 #
135 #
136 # $ hg cat -r 10 sub/x.txt
136 # $ hg cat -r 10 sub/x.txt
137 #
137 #
138 # if sub/ is no longer a subrepository in the working copy
138 # if sub/ is no longer a subrepository in the working copy
139 # parent revision.
139 # parent revision.
140 #
140 #
141 # However, it can of course also allow things that would have
141 # However, it can of course also allow things that would have
142 # been rejected before, such as the above cat command if sub/
142 # been rejected before, such as the above cat command if sub/
143 # is a subrepository now, but was a normal directory before.
143 # is a subrepository now, but was a normal directory before.
144 # The old path auditor would have rejected by mistake since it
144 # The old path auditor would have rejected by mistake since it
145 # panics when it sees sub/.hg/.
145 # panics when it sees sub/.hg/.
146 #
146 #
147 # All in all, checking against the working copy seems sensible
147 # All in all, checking against the working copy seems sensible
148 # since we want to prevent access to nested repositories on
148 # since we want to prevent access to nested repositories on
149 # the filesystem *now*.
149 # the filesystem *now*.
150 ctx = self[None]
150 ctx = self[None]
151 parts = util.splitpath(subpath)
151 parts = util.splitpath(subpath)
152 while parts:
152 while parts:
153 prefix = os.sep.join(parts)
153 prefix = os.sep.join(parts)
154 if prefix in ctx.substate:
154 if prefix in ctx.substate:
155 if prefix == subpath:
155 if prefix == subpath:
156 return True
156 return True
157 else:
157 else:
158 sub = ctx.sub(prefix)
158 sub = ctx.sub(prefix)
159 return sub.checknested(subpath[len(prefix) + 1:])
159 return sub.checknested(subpath[len(prefix) + 1:])
160 else:
160 else:
161 parts.pop()
161 parts.pop()
162 return False
162 return False
163
163
164 @util.propertycache
165 def _bookmarks(self):
166 return bookmarks.read(self)
167
168 @util.propertycache
169 def _bookmarkcurrent(self):
170 return bookmarks.readcurrent(self)
164
171
165 @propertycache
172 @propertycache
166 def changelog(self):
173 def changelog(self):
167 c = changelog.changelog(self.sopener)
174 c = changelog.changelog(self.sopener)
168 if 'HG_PENDING' in os.environ:
175 if 'HG_PENDING' in os.environ:
169 p = os.environ['HG_PENDING']
176 p = os.environ['HG_PENDING']
170 if p.startswith(self.root):
177 if p.startswith(self.root):
171 c.readpending('00changelog.i.a')
178 c.readpending('00changelog.i.a')
172 self.sopener.options['defversion'] = c.version
179 self.sopener.options['defversion'] = c.version
173 return c
180 return c
174
181
175 @propertycache
182 @propertycache
176 def manifest(self):
183 def manifest(self):
177 return manifest.manifest(self.sopener)
184 return manifest.manifest(self.sopener)
178
185
179 @propertycache
186 @propertycache
180 def dirstate(self):
187 def dirstate(self):
181 warned = [0]
188 warned = [0]
182 def validate(node):
189 def validate(node):
183 try:
190 try:
184 r = self.changelog.rev(node)
191 r = self.changelog.rev(node)
185 return node
192 return node
186 except error.LookupError:
193 except error.LookupError:
187 if not warned[0]:
194 if not warned[0]:
188 warned[0] = True
195 warned[0] = True
189 self.ui.warn(_("warning: ignoring unknown"
196 self.ui.warn(_("warning: ignoring unknown"
190 " working parent %s!\n") % short(node))
197 " working parent %s!\n") % short(node))
191 return nullid
198 return nullid
192
199
193 return dirstate.dirstate(self.opener, self.ui, self.root, validate)
200 return dirstate.dirstate(self.opener, self.ui, self.root, validate)
194
201
195 def __getitem__(self, changeid):
202 def __getitem__(self, changeid):
196 if changeid is None:
203 if changeid is None:
197 return context.workingctx(self)
204 return context.workingctx(self)
198 return context.changectx(self, changeid)
205 return context.changectx(self, changeid)
199
206
200 def __contains__(self, changeid):
207 def __contains__(self, changeid):
201 try:
208 try:
202 return bool(self.lookup(changeid))
209 return bool(self.lookup(changeid))
203 except error.RepoLookupError:
210 except error.RepoLookupError:
204 return False
211 return False
205
212
206 def __nonzero__(self):
213 def __nonzero__(self):
207 return True
214 return True
208
215
209 def __len__(self):
216 def __len__(self):
210 return len(self.changelog)
217 return len(self.changelog)
211
218
212 def __iter__(self):
219 def __iter__(self):
213 for i in xrange(len(self)):
220 for i in xrange(len(self)):
214 yield i
221 yield i
215
222
216 def url(self):
223 def url(self):
217 return 'file:' + self.root
224 return 'file:' + self.root
218
225
219 def hook(self, name, throw=False, **args):
226 def hook(self, name, throw=False, **args):
220 return hook.hook(self.ui, self, name, throw, **args)
227 return hook.hook(self.ui, self, name, throw, **args)
221
228
222 tag_disallowed = ':\r\n'
229 tag_disallowed = ':\r\n'
223
230
224 def _tag(self, names, node, message, local, user, date, extra={}):
231 def _tag(self, names, node, message, local, user, date, extra={}):
225 if isinstance(names, str):
232 if isinstance(names, str):
226 allchars = names
233 allchars = names
227 names = (names,)
234 names = (names,)
228 else:
235 else:
229 allchars = ''.join(names)
236 allchars = ''.join(names)
230 for c in self.tag_disallowed:
237 for c in self.tag_disallowed:
231 if c in allchars:
238 if c in allchars:
232 raise util.Abort(_('%r cannot be used in a tag name') % c)
239 raise util.Abort(_('%r cannot be used in a tag name') % c)
233
240
234 branches = self.branchmap()
241 branches = self.branchmap()
235 for name in names:
242 for name in names:
236 self.hook('pretag', throw=True, node=hex(node), tag=name,
243 self.hook('pretag', throw=True, node=hex(node), tag=name,
237 local=local)
244 local=local)
238 if name in branches:
245 if name in branches:
239 self.ui.warn(_("warning: tag %s conflicts with existing"
246 self.ui.warn(_("warning: tag %s conflicts with existing"
240 " branch name\n") % name)
247 " branch name\n") % name)
241
248
242 def writetags(fp, names, munge, prevtags):
249 def writetags(fp, names, munge, prevtags):
243 fp.seek(0, 2)
250 fp.seek(0, 2)
244 if prevtags and prevtags[-1] != '\n':
251 if prevtags and prevtags[-1] != '\n':
245 fp.write('\n')
252 fp.write('\n')
246 for name in names:
253 for name in names:
247 m = munge and munge(name) or name
254 m = munge and munge(name) or name
248 if self._tagtypes and name in self._tagtypes:
255 if self._tagtypes and name in self._tagtypes:
249 old = self._tags.get(name, nullid)
256 old = self._tags.get(name, nullid)
250 fp.write('%s %s\n' % (hex(old), m))
257 fp.write('%s %s\n' % (hex(old), m))
251 fp.write('%s %s\n' % (hex(node), m))
258 fp.write('%s %s\n' % (hex(node), m))
252 fp.close()
259 fp.close()
253
260
254 prevtags = ''
261 prevtags = ''
255 if local:
262 if local:
256 try:
263 try:
257 fp = self.opener('localtags', 'r+')
264 fp = self.opener('localtags', 'r+')
258 except IOError:
265 except IOError:
259 fp = self.opener('localtags', 'a')
266 fp = self.opener('localtags', 'a')
260 else:
267 else:
261 prevtags = fp.read()
268 prevtags = fp.read()
262
269
263 # local tags are stored in the current charset
270 # local tags are stored in the current charset
264 writetags(fp, names, None, prevtags)
271 writetags(fp, names, None, prevtags)
265 for name in names:
272 for name in names:
266 self.hook('tag', node=hex(node), tag=name, local=local)
273 self.hook('tag', node=hex(node), tag=name, local=local)
267 return
274 return
268
275
269 try:
276 try:
270 fp = self.wfile('.hgtags', 'rb+')
277 fp = self.wfile('.hgtags', 'rb+')
271 except IOError:
278 except IOError:
272 fp = self.wfile('.hgtags', 'ab')
279 fp = self.wfile('.hgtags', 'ab')
273 else:
280 else:
274 prevtags = fp.read()
281 prevtags = fp.read()
275
282
276 # committed tags are stored in UTF-8
283 # committed tags are stored in UTF-8
277 writetags(fp, names, encoding.fromlocal, prevtags)
284 writetags(fp, names, encoding.fromlocal, prevtags)
278
285
279 if '.hgtags' not in self.dirstate:
286 if '.hgtags' not in self.dirstate:
280 self[None].add(['.hgtags'])
287 self[None].add(['.hgtags'])
281
288
282 m = matchmod.exact(self.root, '', ['.hgtags'])
289 m = matchmod.exact(self.root, '', ['.hgtags'])
283 tagnode = self.commit(message, user, date, extra=extra, match=m)
290 tagnode = self.commit(message, user, date, extra=extra, match=m)
284
291
285 for name in names:
292 for name in names:
286 self.hook('tag', node=hex(node), tag=name, local=local)
293 self.hook('tag', node=hex(node), tag=name, local=local)
287
294
288 return tagnode
295 return tagnode
289
296
290 def tag(self, names, node, message, local, user, date):
297 def tag(self, names, node, message, local, user, date):
291 '''tag a revision with one or more symbolic names.
298 '''tag a revision with one or more symbolic names.
292
299
293 names is a list of strings or, when adding a single tag, names may be a
300 names is a list of strings or, when adding a single tag, names may be a
294 string.
301 string.
295
302
296 if local is True, the tags are stored in a per-repository file.
303 if local is True, the tags are stored in a per-repository file.
297 otherwise, they are stored in the .hgtags file, and a new
304 otherwise, they are stored in the .hgtags file, and a new
298 changeset is committed with the change.
305 changeset is committed with the change.
299
306
300 keyword arguments:
307 keyword arguments:
301
308
302 local: whether to store tags in non-version-controlled file
309 local: whether to store tags in non-version-controlled file
303 (default False)
310 (default False)
304
311
305 message: commit message to use if committing
312 message: commit message to use if committing
306
313
307 user: name of user to use if committing
314 user: name of user to use if committing
308
315
309 date: date tuple to use if committing'''
316 date: date tuple to use if committing'''
310
317
311 if not local:
318 if not local:
312 for x in self.status()[:5]:
319 for x in self.status()[:5]:
313 if '.hgtags' in x:
320 if '.hgtags' in x:
314 raise util.Abort(_('working copy of .hgtags is changed '
321 raise util.Abort(_('working copy of .hgtags is changed '
315 '(please commit .hgtags manually)'))
322 '(please commit .hgtags manually)'))
316
323
317 self.tags() # instantiate the cache
324 self.tags() # instantiate the cache
318 self._tag(names, node, message, local, user, date)
325 self._tag(names, node, message, local, user, date)
319
326
320 def tags(self):
327 def tags(self):
321 '''return a mapping of tag to node'''
328 '''return a mapping of tag to node'''
322 if self._tags is None:
329 if self._tags is None:
323 (self._tags, self._tagtypes) = self._findtags()
330 (self._tags, self._tagtypes) = self._findtags()
324
331
325 return self._tags
332 return self._tags
326
333
327 def _findtags(self):
334 def _findtags(self):
328 '''Do the hard work of finding tags. Return a pair of dicts
335 '''Do the hard work of finding tags. Return a pair of dicts
329 (tags, tagtypes) where tags maps tag name to node, and tagtypes
336 (tags, tagtypes) where tags maps tag name to node, and tagtypes
330 maps tag name to a string like \'global\' or \'local\'.
337 maps tag name to a string like \'global\' or \'local\'.
331 Subclasses or extensions are free to add their own tags, but
338 Subclasses or extensions are free to add their own tags, but
332 should be aware that the returned dicts will be retained for the
339 should be aware that the returned dicts will be retained for the
333 duration of the localrepo object.'''
340 duration of the localrepo object.'''
334
341
335 # XXX what tagtype should subclasses/extensions use? Currently
342 # XXX what tagtype should subclasses/extensions use? Currently
336 # mq and bookmarks add tags, but do not set the tagtype at all.
343 # mq and bookmarks add tags, but do not set the tagtype at all.
337 # Should each extension invent its own tag type? Should there
344 # Should each extension invent its own tag type? Should there
338 # be one tagtype for all such "virtual" tags? Or is the status
345 # be one tagtype for all such "virtual" tags? Or is the status
339 # quo fine?
346 # quo fine?
340
347
341 alltags = {} # map tag name to (node, hist)
348 alltags = {} # map tag name to (node, hist)
342 tagtypes = {}
349 tagtypes = {}
343
350
344 tagsmod.findglobaltags(self.ui, self, alltags, tagtypes)
351 tagsmod.findglobaltags(self.ui, self, alltags, tagtypes)
345 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
352 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
346
353
347 # Build the return dicts. Have to re-encode tag names because
354 # Build the return dicts. Have to re-encode tag names because
348 # the tags module always uses UTF-8 (in order not to lose info
355 # the tags module always uses UTF-8 (in order not to lose info
349 # writing to the cache), but the rest of Mercurial wants them in
356 # writing to the cache), but the rest of Mercurial wants them in
350 # local encoding.
357 # local encoding.
351 tags = {}
358 tags = {}
352 for (name, (node, hist)) in alltags.iteritems():
359 for (name, (node, hist)) in alltags.iteritems():
353 if node != nullid:
360 if node != nullid:
354 tags[encoding.tolocal(name)] = node
361 tags[encoding.tolocal(name)] = node
355 tags['tip'] = self.changelog.tip()
362 tags['tip'] = self.changelog.tip()
356 tagtypes = dict([(encoding.tolocal(name), value)
363 tagtypes = dict([(encoding.tolocal(name), value)
357 for (name, value) in tagtypes.iteritems()])
364 for (name, value) in tagtypes.iteritems()])
358 return (tags, tagtypes)
365 return (tags, tagtypes)
359
366
360 def tagtype(self, tagname):
367 def tagtype(self, tagname):
361 '''
368 '''
362 return the type of the given tag. result can be:
369 return the type of the given tag. result can be:
363
370
364 'local' : a local tag
371 'local' : a local tag
365 'global' : a global tag
372 'global' : a global tag
366 None : tag does not exist
373 None : tag does not exist
367 '''
374 '''
368
375
369 self.tags()
376 self.tags()
370
377
371 return self._tagtypes.get(tagname)
378 return self._tagtypes.get(tagname)
372
379
373 def tagslist(self):
380 def tagslist(self):
374 '''return a list of tags ordered by revision'''
381 '''return a list of tags ordered by revision'''
375 l = []
382 l = []
376 for t, n in self.tags().iteritems():
383 for t, n in self.tags().iteritems():
377 try:
384 try:
378 r = self.changelog.rev(n)
385 r = self.changelog.rev(n)
379 except:
386 except:
380 r = -2 # sort to the beginning of the list if unknown
387 r = -2 # sort to the beginning of the list if unknown
381 l.append((r, t, n))
388 l.append((r, t, n))
382 return [(t, n) for r, t, n in sorted(l)]
389 return [(t, n) for r, t, n in sorted(l)]
383
390
384 def nodetags(self, node):
391 def nodetags(self, node):
385 '''return the tags associated with a node'''
392 '''return the tags associated with a node'''
386 if not self.nodetagscache:
393 if not self.nodetagscache:
387 self.nodetagscache = {}
394 self.nodetagscache = {}
388 for t, n in self.tags().iteritems():
395 for t, n in self.tags().iteritems():
389 self.nodetagscache.setdefault(n, []).append(t)
396 self.nodetagscache.setdefault(n, []).append(t)
390 for tags in self.nodetagscache.itervalues():
397 for tags in self.nodetagscache.itervalues():
391 tags.sort()
398 tags.sort()
392 return self.nodetagscache.get(node, [])
399 return self.nodetagscache.get(node, [])
393
400
394 def _branchtags(self, partial, lrev):
401 def _branchtags(self, partial, lrev):
395 # TODO: rename this function?
402 # TODO: rename this function?
396 tiprev = len(self) - 1
403 tiprev = len(self) - 1
397 if lrev != tiprev:
404 if lrev != tiprev:
398 ctxgen = (self[r] for r in xrange(lrev + 1, tiprev + 1))
405 ctxgen = (self[r] for r in xrange(lrev + 1, tiprev + 1))
399 self._updatebranchcache(partial, ctxgen)
406 self._updatebranchcache(partial, ctxgen)
400 self._writebranchcache(partial, self.changelog.tip(), tiprev)
407 self._writebranchcache(partial, self.changelog.tip(), tiprev)
401
408
402 return partial
409 return partial
403
410
404 def updatebranchcache(self):
411 def updatebranchcache(self):
405 tip = self.changelog.tip()
412 tip = self.changelog.tip()
406 if self._branchcache is not None and self._branchcachetip == tip:
413 if self._branchcache is not None and self._branchcachetip == tip:
407 return self._branchcache
414 return self._branchcache
408
415
409 oldtip = self._branchcachetip
416 oldtip = self._branchcachetip
410 self._branchcachetip = tip
417 self._branchcachetip = tip
411 if oldtip is None or oldtip not in self.changelog.nodemap:
418 if oldtip is None or oldtip not in self.changelog.nodemap:
412 partial, last, lrev = self._readbranchcache()
419 partial, last, lrev = self._readbranchcache()
413 else:
420 else:
414 lrev = self.changelog.rev(oldtip)
421 lrev = self.changelog.rev(oldtip)
415 partial = self._branchcache
422 partial = self._branchcache
416
423
417 self._branchtags(partial, lrev)
424 self._branchtags(partial, lrev)
418 # this private cache holds all heads (not just tips)
425 # this private cache holds all heads (not just tips)
419 self._branchcache = partial
426 self._branchcache = partial
420
427
421 def branchmap(self):
428 def branchmap(self):
422 '''returns a dictionary {branch: [branchheads]}'''
429 '''returns a dictionary {branch: [branchheads]}'''
423 self.updatebranchcache()
430 self.updatebranchcache()
424 return self._branchcache
431 return self._branchcache
425
432
426 def branchtags(self):
433 def branchtags(self):
427 '''return a dict where branch names map to the tipmost head of
434 '''return a dict where branch names map to the tipmost head of
428 the branch, open heads come before closed'''
435 the branch, open heads come before closed'''
429 bt = {}
436 bt = {}
430 for bn, heads in self.branchmap().iteritems():
437 for bn, heads in self.branchmap().iteritems():
431 tip = heads[-1]
438 tip = heads[-1]
432 for h in reversed(heads):
439 for h in reversed(heads):
433 if 'close' not in self.changelog.read(h)[5]:
440 if 'close' not in self.changelog.read(h)[5]:
434 tip = h
441 tip = h
435 break
442 break
436 bt[bn] = tip
443 bt[bn] = tip
437 return bt
444 return bt
438
445
439 def _readbranchcache(self):
446 def _readbranchcache(self):
440 partial = {}
447 partial = {}
441 try:
448 try:
442 f = self.opener("cache/branchheads")
449 f = self.opener("cache/branchheads")
443 lines = f.read().split('\n')
450 lines = f.read().split('\n')
444 f.close()
451 f.close()
445 except (IOError, OSError):
452 except (IOError, OSError):
446 return {}, nullid, nullrev
453 return {}, nullid, nullrev
447
454
448 try:
455 try:
449 last, lrev = lines.pop(0).split(" ", 1)
456 last, lrev = lines.pop(0).split(" ", 1)
450 last, lrev = bin(last), int(lrev)
457 last, lrev = bin(last), int(lrev)
451 if lrev >= len(self) or self[lrev].node() != last:
458 if lrev >= len(self) or self[lrev].node() != last:
452 # invalidate the cache
459 # invalidate the cache
453 raise ValueError('invalidating branch cache (tip differs)')
460 raise ValueError('invalidating branch cache (tip differs)')
454 for l in lines:
461 for l in lines:
455 if not l:
462 if not l:
456 continue
463 continue
457 node, label = l.split(" ", 1)
464 node, label = l.split(" ", 1)
458 label = encoding.tolocal(label.strip())
465 label = encoding.tolocal(label.strip())
459 partial.setdefault(label, []).append(bin(node))
466 partial.setdefault(label, []).append(bin(node))
460 except KeyboardInterrupt:
467 except KeyboardInterrupt:
461 raise
468 raise
462 except Exception, inst:
469 except Exception, inst:
463 if self.ui.debugflag:
470 if self.ui.debugflag:
464 self.ui.warn(str(inst), '\n')
471 self.ui.warn(str(inst), '\n')
465 partial, last, lrev = {}, nullid, nullrev
472 partial, last, lrev = {}, nullid, nullrev
466 return partial, last, lrev
473 return partial, last, lrev
467
474
468 def _writebranchcache(self, branches, tip, tiprev):
475 def _writebranchcache(self, branches, tip, tiprev):
469 try:
476 try:
470 f = self.opener("cache/branchheads", "w", atomictemp=True)
477 f = self.opener("cache/branchheads", "w", atomictemp=True)
471 f.write("%s %s\n" % (hex(tip), tiprev))
478 f.write("%s %s\n" % (hex(tip), tiprev))
472 for label, nodes in branches.iteritems():
479 for label, nodes in branches.iteritems():
473 for node in nodes:
480 for node in nodes:
474 f.write("%s %s\n" % (hex(node), encoding.fromlocal(label)))
481 f.write("%s %s\n" % (hex(node), encoding.fromlocal(label)))
475 f.rename()
482 f.rename()
476 except (IOError, OSError):
483 except (IOError, OSError):
477 pass
484 pass
478
485
479 def _updatebranchcache(self, partial, ctxgen):
486 def _updatebranchcache(self, partial, ctxgen):
480 # collect new branch entries
487 # collect new branch entries
481 newbranches = {}
488 newbranches = {}
482 for c in ctxgen:
489 for c in ctxgen:
483 newbranches.setdefault(c.branch(), []).append(c.node())
490 newbranches.setdefault(c.branch(), []).append(c.node())
484 # if older branchheads are reachable from new ones, they aren't
491 # if older branchheads are reachable from new ones, they aren't
485 # really branchheads. Note checking parents is insufficient:
492 # really branchheads. Note checking parents is insufficient:
486 # 1 (branch a) -> 2 (branch b) -> 3 (branch a)
493 # 1 (branch a) -> 2 (branch b) -> 3 (branch a)
487 for branch, newnodes in newbranches.iteritems():
494 for branch, newnodes in newbranches.iteritems():
488 bheads = partial.setdefault(branch, [])
495 bheads = partial.setdefault(branch, [])
489 bheads.extend(newnodes)
496 bheads.extend(newnodes)
490 if len(bheads) <= 1:
497 if len(bheads) <= 1:
491 continue
498 continue
492 # starting from tip means fewer passes over reachable
499 # starting from tip means fewer passes over reachable
493 while newnodes:
500 while newnodes:
494 latest = newnodes.pop()
501 latest = newnodes.pop()
495 if latest not in bheads:
502 if latest not in bheads:
496 continue
503 continue
497 minbhrev = self[min([self[bh].rev() for bh in bheads])].node()
504 minbhrev = self[min([self[bh].rev() for bh in bheads])].node()
498 reachable = self.changelog.reachable(latest, minbhrev)
505 reachable = self.changelog.reachable(latest, minbhrev)
499 reachable.remove(latest)
506 reachable.remove(latest)
500 bheads = [b for b in bheads if b not in reachable]
507 bheads = [b for b in bheads if b not in reachable]
501 partial[branch] = bheads
508 partial[branch] = bheads
502
509
503 def lookup(self, key):
510 def lookup(self, key):
504 if isinstance(key, int):
511 if isinstance(key, int):
505 return self.changelog.node(key)
512 return self.changelog.node(key)
506 elif key == '.':
513 elif key == '.':
507 return self.dirstate.parents()[0]
514 return self.dirstate.parents()[0]
508 elif key == 'null':
515 elif key == 'null':
509 return nullid
516 return nullid
510 elif key == 'tip':
517 elif key == 'tip':
511 return self.changelog.tip()
518 return self.changelog.tip()
512 n = self.changelog._match(key)
519 n = self.changelog._match(key)
513 if n:
520 if n:
514 return n
521 return n
515 if key in self.tags():
522 if key in self.tags():
516 return self.tags()[key]
523 return self.tags()[key]
517 if key in self.branchtags():
524 if key in self.branchtags():
518 return self.branchtags()[key]
525 return self.branchtags()[key]
519 n = self.changelog._partialmatch(key)
526 n = self.changelog._partialmatch(key)
520 if n:
527 if n:
521 return n
528 return n
522
529
523 # can't find key, check if it might have come from damaged dirstate
530 # can't find key, check if it might have come from damaged dirstate
524 if key in self.dirstate.parents():
531 if key in self.dirstate.parents():
525 raise error.Abort(_("working directory has unknown parent '%s'!")
532 raise error.Abort(_("working directory has unknown parent '%s'!")
526 % short(key))
533 % short(key))
527 try:
534 try:
528 if len(key) == 20:
535 if len(key) == 20:
529 key = hex(key)
536 key = hex(key)
530 except:
537 except:
531 pass
538 pass
532 raise error.RepoLookupError(_("unknown revision '%s'") % key)
539 raise error.RepoLookupError(_("unknown revision '%s'") % key)
533
540
534 def lookupbranch(self, key, remote=None):
541 def lookupbranch(self, key, remote=None):
535 repo = remote or self
542 repo = remote or self
536 if key in repo.branchmap():
543 if key in repo.branchmap():
537 return key
544 return key
538
545
539 repo = (remote and remote.local()) and remote or self
546 repo = (remote and remote.local()) and remote or self
540 return repo[key].branch()
547 return repo[key].branch()
541
548
542 def local(self):
549 def local(self):
543 return True
550 return True
544
551
545 def join(self, f):
552 def join(self, f):
546 return os.path.join(self.path, f)
553 return os.path.join(self.path, f)
547
554
548 def wjoin(self, f):
555 def wjoin(self, f):
549 return os.path.join(self.root, f)
556 return os.path.join(self.root, f)
550
557
551 def file(self, f):
558 def file(self, f):
552 if f[0] == '/':
559 if f[0] == '/':
553 f = f[1:]
560 f = f[1:]
554 return filelog.filelog(self.sopener, f)
561 return filelog.filelog(self.sopener, f)
555
562
556 def changectx(self, changeid):
563 def changectx(self, changeid):
557 return self[changeid]
564 return self[changeid]
558
565
559 def parents(self, changeid=None):
566 def parents(self, changeid=None):
560 '''get list of changectxs for parents of changeid'''
567 '''get list of changectxs for parents of changeid'''
561 return self[changeid].parents()
568 return self[changeid].parents()
562
569
563 def filectx(self, path, changeid=None, fileid=None):
570 def filectx(self, path, changeid=None, fileid=None):
564 """changeid can be a changeset revision, node, or tag.
571 """changeid can be a changeset revision, node, or tag.
565 fileid can be a file revision or node."""
572 fileid can be a file revision or node."""
566 return context.filectx(self, path, changeid, fileid)
573 return context.filectx(self, path, changeid, fileid)
567
574
568 def getcwd(self):
575 def getcwd(self):
569 return self.dirstate.getcwd()
576 return self.dirstate.getcwd()
570
577
571 def pathto(self, f, cwd=None):
578 def pathto(self, f, cwd=None):
572 return self.dirstate.pathto(f, cwd)
579 return self.dirstate.pathto(f, cwd)
573
580
574 def wfile(self, f, mode='r'):
581 def wfile(self, f, mode='r'):
575 return self.wopener(f, mode)
582 return self.wopener(f, mode)
576
583
577 def _link(self, f):
584 def _link(self, f):
578 return os.path.islink(self.wjoin(f))
585 return os.path.islink(self.wjoin(f))
579
586
580 def _loadfilter(self, filter):
587 def _loadfilter(self, filter):
581 if filter not in self.filterpats:
588 if filter not in self.filterpats:
582 l = []
589 l = []
583 for pat, cmd in self.ui.configitems(filter):
590 for pat, cmd in self.ui.configitems(filter):
584 if cmd == '!':
591 if cmd == '!':
585 continue
592 continue
586 mf = matchmod.match(self.root, '', [pat])
593 mf = matchmod.match(self.root, '', [pat])
587 fn = None
594 fn = None
588 params = cmd
595 params = cmd
589 for name, filterfn in self._datafilters.iteritems():
596 for name, filterfn in self._datafilters.iteritems():
590 if cmd.startswith(name):
597 if cmd.startswith(name):
591 fn = filterfn
598 fn = filterfn
592 params = cmd[len(name):].lstrip()
599 params = cmd[len(name):].lstrip()
593 break
600 break
594 if not fn:
601 if not fn:
595 fn = lambda s, c, **kwargs: util.filter(s, c)
602 fn = lambda s, c, **kwargs: util.filter(s, c)
596 # Wrap old filters not supporting keyword arguments
603 # Wrap old filters not supporting keyword arguments
597 if not inspect.getargspec(fn)[2]:
604 if not inspect.getargspec(fn)[2]:
598 oldfn = fn
605 oldfn = fn
599 fn = lambda s, c, **kwargs: oldfn(s, c)
606 fn = lambda s, c, **kwargs: oldfn(s, c)
600 l.append((mf, fn, params))
607 l.append((mf, fn, params))
601 self.filterpats[filter] = l
608 self.filterpats[filter] = l
602 return self.filterpats[filter]
609 return self.filterpats[filter]
603
610
604 def _filter(self, filterpats, filename, data):
611 def _filter(self, filterpats, filename, data):
605 for mf, fn, cmd in filterpats:
612 for mf, fn, cmd in filterpats:
606 if mf(filename):
613 if mf(filename):
607 self.ui.debug("filtering %s through %s\n" % (filename, cmd))
614 self.ui.debug("filtering %s through %s\n" % (filename, cmd))
608 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
615 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
609 break
616 break
610
617
611 return data
618 return data
612
619
613 @propertycache
620 @propertycache
614 def _encodefilterpats(self):
621 def _encodefilterpats(self):
615 return self._loadfilter('encode')
622 return self._loadfilter('encode')
616
623
617 @propertycache
624 @propertycache
618 def _decodefilterpats(self):
625 def _decodefilterpats(self):
619 return self._loadfilter('decode')
626 return self._loadfilter('decode')
620
627
621 def adddatafilter(self, name, filter):
628 def adddatafilter(self, name, filter):
622 self._datafilters[name] = filter
629 self._datafilters[name] = filter
623
630
624 def wread(self, filename):
631 def wread(self, filename):
625 if self._link(filename):
632 if self._link(filename):
626 data = os.readlink(self.wjoin(filename))
633 data = os.readlink(self.wjoin(filename))
627 else:
634 else:
628 data = self.wopener(filename, 'r').read()
635 data = self.wopener(filename, 'r').read()
629 return self._filter(self._encodefilterpats, filename, data)
636 return self._filter(self._encodefilterpats, filename, data)
630
637
631 def wwrite(self, filename, data, flags):
638 def wwrite(self, filename, data, flags):
632 data = self._filter(self._decodefilterpats, filename, data)
639 data = self._filter(self._decodefilterpats, filename, data)
633 if 'l' in flags:
640 if 'l' in flags:
634 self.wopener.symlink(data, filename)
641 self.wopener.symlink(data, filename)
635 else:
642 else:
636 self.wopener(filename, 'w').write(data)
643 self.wopener(filename, 'w').write(data)
637 if 'x' in flags:
644 if 'x' in flags:
638 util.set_flags(self.wjoin(filename), False, True)
645 util.set_flags(self.wjoin(filename), False, True)
639
646
640 def wwritedata(self, filename, data):
647 def wwritedata(self, filename, data):
641 return self._filter(self._decodefilterpats, filename, data)
648 return self._filter(self._decodefilterpats, filename, data)
642
649
643 def transaction(self, desc):
650 def transaction(self, desc):
644 tr = self._transref and self._transref() or None
651 tr = self._transref and self._transref() or None
645 if tr and tr.running():
652 if tr and tr.running():
646 return tr.nest()
653 return tr.nest()
647
654
648 # abort here if the journal already exists
655 # abort here if the journal already exists
649 if os.path.exists(self.sjoin("journal")):
656 if os.path.exists(self.sjoin("journal")):
650 raise error.RepoError(
657 raise error.RepoError(
651 _("abandoned transaction found - run hg recover"))
658 _("abandoned transaction found - run hg recover"))
652
659
653 # save dirstate for rollback
660 # save dirstate for rollback
654 try:
661 try:
655 ds = self.opener("dirstate").read()
662 ds = self.opener("dirstate").read()
656 except IOError:
663 except IOError:
657 ds = ""
664 ds = ""
658 self.opener("journal.dirstate", "w").write(ds)
665 self.opener("journal.dirstate", "w").write(ds)
659 self.opener("journal.branch", "w").write(
666 self.opener("journal.branch", "w").write(
660 encoding.fromlocal(self.dirstate.branch()))
667 encoding.fromlocal(self.dirstate.branch()))
661 self.opener("journal.desc", "w").write("%d\n%s\n" % (len(self), desc))
668 self.opener("journal.desc", "w").write("%d\n%s\n" % (len(self), desc))
662
669
663 renames = [(self.sjoin("journal"), self.sjoin("undo")),
670 renames = [(self.sjoin("journal"), self.sjoin("undo")),
664 (self.join("journal.dirstate"), self.join("undo.dirstate")),
671 (self.join("journal.dirstate"), self.join("undo.dirstate")),
665 (self.join("journal.branch"), self.join("undo.branch")),
672 (self.join("journal.branch"), self.join("undo.branch")),
666 (self.join("journal.desc"), self.join("undo.desc"))]
673 (self.join("journal.desc"), self.join("undo.desc"))]
667 tr = transaction.transaction(self.ui.warn, self.sopener,
674 tr = transaction.transaction(self.ui.warn, self.sopener,
668 self.sjoin("journal"),
675 self.sjoin("journal"),
669 aftertrans(renames),
676 aftertrans(renames),
670 self.store.createmode)
677 self.store.createmode)
671 self._transref = weakref.ref(tr)
678 self._transref = weakref.ref(tr)
672 return tr
679 return tr
673
680
674 def recover(self):
681 def recover(self):
675 lock = self.lock()
682 lock = self.lock()
676 try:
683 try:
677 if os.path.exists(self.sjoin("journal")):
684 if os.path.exists(self.sjoin("journal")):
678 self.ui.status(_("rolling back interrupted transaction\n"))
685 self.ui.status(_("rolling back interrupted transaction\n"))
679 transaction.rollback(self.sopener, self.sjoin("journal"),
686 transaction.rollback(self.sopener, self.sjoin("journal"),
680 self.ui.warn)
687 self.ui.warn)
681 self.invalidate()
688 self.invalidate()
682 return True
689 return True
683 else:
690 else:
684 self.ui.warn(_("no interrupted transaction available\n"))
691 self.ui.warn(_("no interrupted transaction available\n"))
685 return False
692 return False
686 finally:
693 finally:
687 lock.release()
694 lock.release()
688
695
689 def rollback(self, dryrun=False):
696 def rollback(self, dryrun=False):
690 wlock = lock = None
697 wlock = lock = None
691 try:
698 try:
692 wlock = self.wlock()
699 wlock = self.wlock()
693 lock = self.lock()
700 lock = self.lock()
694 if os.path.exists(self.sjoin("undo")):
701 if os.path.exists(self.sjoin("undo")):
695 try:
702 try:
696 args = self.opener("undo.desc", "r").read().splitlines()
703 args = self.opener("undo.desc", "r").read().splitlines()
697 if len(args) >= 3 and self.ui.verbose:
704 if len(args) >= 3 and self.ui.verbose:
698 desc = _("rolling back to revision %s"
705 desc = _("rolling back to revision %s"
699 " (undo %s: %s)\n") % (
706 " (undo %s: %s)\n") % (
700 int(args[0]) - 1, args[1], args[2])
707 int(args[0]) - 1, args[1], args[2])
701 elif len(args) >= 2:
708 elif len(args) >= 2:
702 desc = _("rolling back to revision %s (undo %s)\n") % (
709 desc = _("rolling back to revision %s (undo %s)\n") % (
703 int(args[0]) - 1, args[1])
710 int(args[0]) - 1, args[1])
704 except IOError:
711 except IOError:
705 desc = _("rolling back unknown transaction\n")
712 desc = _("rolling back unknown transaction\n")
706 self.ui.status(desc)
713 self.ui.status(desc)
707 if dryrun:
714 if dryrun:
708 return
715 return
709 transaction.rollback(self.sopener, self.sjoin("undo"),
716 transaction.rollback(self.sopener, self.sjoin("undo"),
710 self.ui.warn)
717 self.ui.warn)
711 util.rename(self.join("undo.dirstate"), self.join("dirstate"))
718 util.rename(self.join("undo.dirstate"), self.join("dirstate"))
712 try:
719 try:
713 branch = self.opener("undo.branch").read()
720 branch = self.opener("undo.branch").read()
714 self.dirstate.setbranch(branch)
721 self.dirstate.setbranch(branch)
715 except IOError:
722 except IOError:
716 self.ui.warn(_("Named branch could not be reset, "
723 self.ui.warn(_("Named branch could not be reset, "
717 "current branch still is: %s\n")
724 "current branch still is: %s\n")
718 % self.dirstate.branch())
725 % self.dirstate.branch())
719 self.invalidate()
726 self.invalidate()
720 self.dirstate.invalidate()
727 self.dirstate.invalidate()
721 self.destroyed()
728 self.destroyed()
722 else:
729 else:
723 self.ui.warn(_("no rollback information available\n"))
730 self.ui.warn(_("no rollback information available\n"))
724 return 1
731 return 1
725 finally:
732 finally:
726 release(lock, wlock)
733 release(lock, wlock)
727
734
728 def invalidatecaches(self):
735 def invalidatecaches(self):
729 self._tags = None
736 self._tags = None
730 self._tagtypes = None
737 self._tagtypes = None
731 self.nodetagscache = None
738 self.nodetagscache = None
732 self._branchcache = None # in UTF-8
739 self._branchcache = None # in UTF-8
733 self._branchcachetip = None
740 self._branchcachetip = None
734
741
735 def invalidate(self):
742 def invalidate(self):
736 for a in ("changelog", "manifest"):
743 for a in ("changelog", "manifest"):
737 if a in self.__dict__:
744 if a in self.__dict__:
738 delattr(self, a)
745 delattr(self, a)
739 self.invalidatecaches()
746 self.invalidatecaches()
740
747
741 def _lock(self, lockname, wait, releasefn, acquirefn, desc):
748 def _lock(self, lockname, wait, releasefn, acquirefn, desc):
742 try:
749 try:
743 l = lock.lock(lockname, 0, releasefn, desc=desc)
750 l = lock.lock(lockname, 0, releasefn, desc=desc)
744 except error.LockHeld, inst:
751 except error.LockHeld, inst:
745 if not wait:
752 if not wait:
746 raise
753 raise
747 self.ui.warn(_("waiting for lock on %s held by %r\n") %
754 self.ui.warn(_("waiting for lock on %s held by %r\n") %
748 (desc, inst.locker))
755 (desc, inst.locker))
749 # default to 600 seconds timeout
756 # default to 600 seconds timeout
750 l = lock.lock(lockname, int(self.ui.config("ui", "timeout", "600")),
757 l = lock.lock(lockname, int(self.ui.config("ui", "timeout", "600")),
751 releasefn, desc=desc)
758 releasefn, desc=desc)
752 if acquirefn:
759 if acquirefn:
753 acquirefn()
760 acquirefn()
754 return l
761 return l
755
762
756 def lock(self, wait=True):
763 def lock(self, wait=True):
757 '''Lock the repository store (.hg/store) and return a weak reference
764 '''Lock the repository store (.hg/store) and return a weak reference
758 to the lock. Use this before modifying the store (e.g. committing or
765 to the lock. Use this before modifying the store (e.g. committing or
759 stripping). If you are opening a transaction, get a lock as well.)'''
766 stripping). If you are opening a transaction, get a lock as well.)'''
760 l = self._lockref and self._lockref()
767 l = self._lockref and self._lockref()
761 if l is not None and l.held:
768 if l is not None and l.held:
762 l.lock()
769 l.lock()
763 return l
770 return l
764
771
765 l = self._lock(self.sjoin("lock"), wait, None, self.invalidate,
772 l = self._lock(self.sjoin("lock"), wait, None, self.invalidate,
766 _('repository %s') % self.origroot)
773 _('repository %s') % self.origroot)
767 self._lockref = weakref.ref(l)
774 self._lockref = weakref.ref(l)
768 return l
775 return l
769
776
770 def wlock(self, wait=True):
777 def wlock(self, wait=True):
771 '''Lock the non-store parts of the repository (everything under
778 '''Lock the non-store parts of the repository (everything under
772 .hg except .hg/store) and return a weak reference to the lock.
779 .hg except .hg/store) and return a weak reference to the lock.
773 Use this before modifying files in .hg.'''
780 Use this before modifying files in .hg.'''
774 l = self._wlockref and self._wlockref()
781 l = self._wlockref and self._wlockref()
775 if l is not None and l.held:
782 if l is not None and l.held:
776 l.lock()
783 l.lock()
777 return l
784 return l
778
785
779 l = self._lock(self.join("wlock"), wait, self.dirstate.write,
786 l = self._lock(self.join("wlock"), wait, self.dirstate.write,
780 self.dirstate.invalidate, _('working directory of %s') %
787 self.dirstate.invalidate, _('working directory of %s') %
781 self.origroot)
788 self.origroot)
782 self._wlockref = weakref.ref(l)
789 self._wlockref = weakref.ref(l)
783 return l
790 return l
784
791
785 def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
792 def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
786 """
793 """
787 commit an individual file as part of a larger transaction
794 commit an individual file as part of a larger transaction
788 """
795 """
789
796
790 fname = fctx.path()
797 fname = fctx.path()
791 text = fctx.data()
798 text = fctx.data()
792 flog = self.file(fname)
799 flog = self.file(fname)
793 fparent1 = manifest1.get(fname, nullid)
800 fparent1 = manifest1.get(fname, nullid)
794 fparent2 = fparent2o = manifest2.get(fname, nullid)
801 fparent2 = fparent2o = manifest2.get(fname, nullid)
795
802
796 meta = {}
803 meta = {}
797 copy = fctx.renamed()
804 copy = fctx.renamed()
798 if copy and copy[0] != fname:
805 if copy and copy[0] != fname:
799 # Mark the new revision of this file as a copy of another
806 # Mark the new revision of this file as a copy of another
800 # file. This copy data will effectively act as a parent
807 # file. This copy data will effectively act as a parent
801 # of this new revision. If this is a merge, the first
808 # of this new revision. If this is a merge, the first
802 # parent will be the nullid (meaning "look up the copy data")
809 # parent will be the nullid (meaning "look up the copy data")
803 # and the second one will be the other parent. For example:
810 # and the second one will be the other parent. For example:
804 #
811 #
805 # 0 --- 1 --- 3 rev1 changes file foo
812 # 0 --- 1 --- 3 rev1 changes file foo
806 # \ / rev2 renames foo to bar and changes it
813 # \ / rev2 renames foo to bar and changes it
807 # \- 2 -/ rev3 should have bar with all changes and
814 # \- 2 -/ rev3 should have bar with all changes and
808 # should record that bar descends from
815 # should record that bar descends from
809 # bar in rev2 and foo in rev1
816 # bar in rev2 and foo in rev1
810 #
817 #
811 # this allows this merge to succeed:
818 # this allows this merge to succeed:
812 #
819 #
813 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
820 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
814 # \ / merging rev3 and rev4 should use bar@rev2
821 # \ / merging rev3 and rev4 should use bar@rev2
815 # \- 2 --- 4 as the merge base
822 # \- 2 --- 4 as the merge base
816 #
823 #
817
824
818 cfname = copy[0]
825 cfname = copy[0]
819 crev = manifest1.get(cfname)
826 crev = manifest1.get(cfname)
820 newfparent = fparent2
827 newfparent = fparent2
821
828
822 if manifest2: # branch merge
829 if manifest2: # branch merge
823 if fparent2 == nullid or crev is None: # copied on remote side
830 if fparent2 == nullid or crev is None: # copied on remote side
824 if cfname in manifest2:
831 if cfname in manifest2:
825 crev = manifest2[cfname]
832 crev = manifest2[cfname]
826 newfparent = fparent1
833 newfparent = fparent1
827
834
828 # find source in nearest ancestor if we've lost track
835 # find source in nearest ancestor if we've lost track
829 if not crev:
836 if not crev:
830 self.ui.debug(" %s: searching for copy revision for %s\n" %
837 self.ui.debug(" %s: searching for copy revision for %s\n" %
831 (fname, cfname))
838 (fname, cfname))
832 for ancestor in self[None].ancestors():
839 for ancestor in self[None].ancestors():
833 if cfname in ancestor:
840 if cfname in ancestor:
834 crev = ancestor[cfname].filenode()
841 crev = ancestor[cfname].filenode()
835 break
842 break
836
843
837 if crev:
844 if crev:
838 self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev)))
845 self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev)))
839 meta["copy"] = cfname
846 meta["copy"] = cfname
840 meta["copyrev"] = hex(crev)
847 meta["copyrev"] = hex(crev)
841 fparent1, fparent2 = nullid, newfparent
848 fparent1, fparent2 = nullid, newfparent
842 else:
849 else:
843 self.ui.warn(_("warning: can't find ancestor for '%s' "
850 self.ui.warn(_("warning: can't find ancestor for '%s' "
844 "copied from '%s'!\n") % (fname, cfname))
851 "copied from '%s'!\n") % (fname, cfname))
845
852
846 elif fparent2 != nullid:
853 elif fparent2 != nullid:
847 # is one parent an ancestor of the other?
854 # is one parent an ancestor of the other?
848 fparentancestor = flog.ancestor(fparent1, fparent2)
855 fparentancestor = flog.ancestor(fparent1, fparent2)
849 if fparentancestor == fparent1:
856 if fparentancestor == fparent1:
850 fparent1, fparent2 = fparent2, nullid
857 fparent1, fparent2 = fparent2, nullid
851 elif fparentancestor == fparent2:
858 elif fparentancestor == fparent2:
852 fparent2 = nullid
859 fparent2 = nullid
853
860
854 # is the file changed?
861 # is the file changed?
855 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
862 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
856 changelist.append(fname)
863 changelist.append(fname)
857 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
864 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
858
865
859 # are just the flags changed during merge?
866 # are just the flags changed during merge?
860 if fparent1 != fparent2o and manifest1.flags(fname) != fctx.flags():
867 if fparent1 != fparent2o and manifest1.flags(fname) != fctx.flags():
861 changelist.append(fname)
868 changelist.append(fname)
862
869
863 return fparent1
870 return fparent1
864
871
865 def commit(self, text="", user=None, date=None, match=None, force=False,
872 def commit(self, text="", user=None, date=None, match=None, force=False,
866 editor=False, extra={}):
873 editor=False, extra={}):
867 """Add a new revision to current repository.
874 """Add a new revision to current repository.
868
875
869 Revision information is gathered from the working directory,
876 Revision information is gathered from the working directory,
870 match can be used to filter the committed files. If editor is
877 match can be used to filter the committed files. If editor is
871 supplied, it is called to get a commit message.
878 supplied, it is called to get a commit message.
872 """
879 """
873
880
874 def fail(f, msg):
881 def fail(f, msg):
875 raise util.Abort('%s: %s' % (f, msg))
882 raise util.Abort('%s: %s' % (f, msg))
876
883
877 if not match:
884 if not match:
878 match = matchmod.always(self.root, '')
885 match = matchmod.always(self.root, '')
879
886
880 if not force:
887 if not force:
881 vdirs = []
888 vdirs = []
882 match.dir = vdirs.append
889 match.dir = vdirs.append
883 match.bad = fail
890 match.bad = fail
884
891
885 wlock = self.wlock()
892 wlock = self.wlock()
886 try:
893 try:
887 wctx = self[None]
894 wctx = self[None]
888 merge = len(wctx.parents()) > 1
895 merge = len(wctx.parents()) > 1
889
896
890 if (not force and merge and match and
897 if (not force and merge and match and
891 (match.files() or match.anypats())):
898 (match.files() or match.anypats())):
892 raise util.Abort(_('cannot partially commit a merge '
899 raise util.Abort(_('cannot partially commit a merge '
893 '(do not specify files or patterns)'))
900 '(do not specify files or patterns)'))
894
901
895 changes = self.status(match=match, clean=force)
902 changes = self.status(match=match, clean=force)
896 if force:
903 if force:
897 changes[0].extend(changes[6]) # mq may commit unchanged files
904 changes[0].extend(changes[6]) # mq may commit unchanged files
898
905
899 # check subrepos
906 # check subrepos
900 subs = []
907 subs = []
901 removedsubs = set()
908 removedsubs = set()
902 for p in wctx.parents():
909 for p in wctx.parents():
903 removedsubs.update(s for s in p.substate if match(s))
910 removedsubs.update(s for s in p.substate if match(s))
904 for s in wctx.substate:
911 for s in wctx.substate:
905 removedsubs.discard(s)
912 removedsubs.discard(s)
906 if match(s) and wctx.sub(s).dirty():
913 if match(s) and wctx.sub(s).dirty():
907 subs.append(s)
914 subs.append(s)
908 if (subs or removedsubs):
915 if (subs or removedsubs):
909 if (not match('.hgsub') and
916 if (not match('.hgsub') and
910 '.hgsub' in (wctx.modified() + wctx.added())):
917 '.hgsub' in (wctx.modified() + wctx.added())):
911 raise util.Abort(_("can't commit subrepos without .hgsub"))
918 raise util.Abort(_("can't commit subrepos without .hgsub"))
912 if '.hgsubstate' not in changes[0]:
919 if '.hgsubstate' not in changes[0]:
913 changes[0].insert(0, '.hgsubstate')
920 changes[0].insert(0, '.hgsubstate')
914
921
915 # make sure all explicit patterns are matched
922 # make sure all explicit patterns are matched
916 if not force and match.files():
923 if not force and match.files():
917 matched = set(changes[0] + changes[1] + changes[2])
924 matched = set(changes[0] + changes[1] + changes[2])
918
925
919 for f in match.files():
926 for f in match.files():
920 if f == '.' or f in matched or f in wctx.substate:
927 if f == '.' or f in matched or f in wctx.substate:
921 continue
928 continue
922 if f in changes[3]: # missing
929 if f in changes[3]: # missing
923 fail(f, _('file not found!'))
930 fail(f, _('file not found!'))
924 if f in vdirs: # visited directory
931 if f in vdirs: # visited directory
925 d = f + '/'
932 d = f + '/'
926 for mf in matched:
933 for mf in matched:
927 if mf.startswith(d):
934 if mf.startswith(d):
928 break
935 break
929 else:
936 else:
930 fail(f, _("no match under directory!"))
937 fail(f, _("no match under directory!"))
931 elif f not in self.dirstate:
938 elif f not in self.dirstate:
932 fail(f, _("file not tracked!"))
939 fail(f, _("file not tracked!"))
933
940
934 if (not force and not extra.get("close") and not merge
941 if (not force and not extra.get("close") and not merge
935 and not (changes[0] or changes[1] or changes[2])
942 and not (changes[0] or changes[1] or changes[2])
936 and wctx.branch() == wctx.p1().branch()):
943 and wctx.branch() == wctx.p1().branch()):
937 return None
944 return None
938
945
939 ms = mergemod.mergestate(self)
946 ms = mergemod.mergestate(self)
940 for f in changes[0]:
947 for f in changes[0]:
941 if f in ms and ms[f] == 'u':
948 if f in ms and ms[f] == 'u':
942 raise util.Abort(_("unresolved merge conflicts "
949 raise util.Abort(_("unresolved merge conflicts "
943 "(see hg resolve)"))
950 "(see hg resolve)"))
944
951
945 cctx = context.workingctx(self, text, user, date, extra, changes)
952 cctx = context.workingctx(self, text, user, date, extra, changes)
946 if editor:
953 if editor:
947 cctx._text = editor(self, cctx, subs)
954 cctx._text = editor(self, cctx, subs)
948 edited = (text != cctx._text)
955 edited = (text != cctx._text)
949
956
950 # commit subs
957 # commit subs
951 if subs or removedsubs:
958 if subs or removedsubs:
952 state = wctx.substate.copy()
959 state = wctx.substate.copy()
953 for s in sorted(subs):
960 for s in sorted(subs):
954 sub = wctx.sub(s)
961 sub = wctx.sub(s)
955 self.ui.status(_('committing subrepository %s\n') %
962 self.ui.status(_('committing subrepository %s\n') %
956 subrepo.subrelpath(sub))
963 subrepo.subrelpath(sub))
957 sr = sub.commit(cctx._text, user, date)
964 sr = sub.commit(cctx._text, user, date)
958 state[s] = (state[s][0], sr)
965 state[s] = (state[s][0], sr)
959 subrepo.writestate(self, state)
966 subrepo.writestate(self, state)
960
967
961 # Save commit message in case this transaction gets rolled back
968 # Save commit message in case this transaction gets rolled back
962 # (e.g. by a pretxncommit hook). Leave the content alone on
969 # (e.g. by a pretxncommit hook). Leave the content alone on
963 # the assumption that the user will use the same editor again.
970 # the assumption that the user will use the same editor again.
964 msgfile = self.opener('last-message.txt', 'wb')
971 msgfile = self.opener('last-message.txt', 'wb')
965 msgfile.write(cctx._text)
972 msgfile.write(cctx._text)
966 msgfile.close()
973 msgfile.close()
967
974
968 p1, p2 = self.dirstate.parents()
975 p1, p2 = self.dirstate.parents()
969 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
976 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
970 try:
977 try:
971 self.hook("precommit", throw=True, parent1=hookp1, parent2=hookp2)
978 self.hook("precommit", throw=True, parent1=hookp1, parent2=hookp2)
972 ret = self.commitctx(cctx, True)
979 ret = self.commitctx(cctx, True)
973 except:
980 except:
974 if edited:
981 if edited:
975 msgfn = self.pathto(msgfile.name[len(self.root)+1:])
982 msgfn = self.pathto(msgfile.name[len(self.root)+1:])
976 self.ui.write(
983 self.ui.write(
977 _('note: commit message saved in %s\n') % msgfn)
984 _('note: commit message saved in %s\n') % msgfn)
978 raise
985 raise
979
986
980 # update dirstate and mergestate
987 # update dirstate and mergestate
981 for f in changes[0] + changes[1]:
988 for f in changes[0] + changes[1]:
982 self.dirstate.normal(f)
989 self.dirstate.normal(f)
983 for f in changes[2]:
990 for f in changes[2]:
984 self.dirstate.forget(f)
991 self.dirstate.forget(f)
985 self.dirstate.setparents(ret)
992 self.dirstate.setparents(ret)
986 ms.reset()
993 ms.reset()
987 finally:
994 finally:
988 wlock.release()
995 wlock.release()
989
996
990 self.hook("commit", node=hex(ret), parent1=hookp1, parent2=hookp2)
997 self.hook("commit", node=hex(ret), parent1=hookp1, parent2=hookp2)
991 return ret
998 return ret
992
999
993 def commitctx(self, ctx, error=False):
1000 def commitctx(self, ctx, error=False):
994 """Add a new revision to current repository.
1001 """Add a new revision to current repository.
995 Revision information is passed via the context argument.
1002 Revision information is passed via the context argument.
996 """
1003 """
997
1004
998 tr = lock = None
1005 tr = lock = None
999 removed = list(ctx.removed())
1006 removed = list(ctx.removed())
1000 p1, p2 = ctx.p1(), ctx.p2()
1007 p1, p2 = ctx.p1(), ctx.p2()
1001 m1 = p1.manifest().copy()
1008 m1 = p1.manifest().copy()
1002 m2 = p2.manifest()
1009 m2 = p2.manifest()
1003 user = ctx.user()
1010 user = ctx.user()
1004
1011
1005 lock = self.lock()
1012 lock = self.lock()
1006 try:
1013 try:
1007 tr = self.transaction("commit")
1014 tr = self.transaction("commit")
1008 trp = weakref.proxy(tr)
1015 trp = weakref.proxy(tr)
1009
1016
1010 # check in files
1017 # check in files
1011 new = {}
1018 new = {}
1012 changed = []
1019 changed = []
1013 linkrev = len(self)
1020 linkrev = len(self)
1014 for f in sorted(ctx.modified() + ctx.added()):
1021 for f in sorted(ctx.modified() + ctx.added()):
1015 self.ui.note(f + "\n")
1022 self.ui.note(f + "\n")
1016 try:
1023 try:
1017 fctx = ctx[f]
1024 fctx = ctx[f]
1018 new[f] = self._filecommit(fctx, m1, m2, linkrev, trp,
1025 new[f] = self._filecommit(fctx, m1, m2, linkrev, trp,
1019 changed)
1026 changed)
1020 m1.set(f, fctx.flags())
1027 m1.set(f, fctx.flags())
1021 except OSError, inst:
1028 except OSError, inst:
1022 self.ui.warn(_("trouble committing %s!\n") % f)
1029 self.ui.warn(_("trouble committing %s!\n") % f)
1023 raise
1030 raise
1024 except IOError, inst:
1031 except IOError, inst:
1025 errcode = getattr(inst, 'errno', errno.ENOENT)
1032 errcode = getattr(inst, 'errno', errno.ENOENT)
1026 if error or errcode and errcode != errno.ENOENT:
1033 if error or errcode and errcode != errno.ENOENT:
1027 self.ui.warn(_("trouble committing %s!\n") % f)
1034 self.ui.warn(_("trouble committing %s!\n") % f)
1028 raise
1035 raise
1029 else:
1036 else:
1030 removed.append(f)
1037 removed.append(f)
1031
1038
1032 # update manifest
1039 # update manifest
1033 m1.update(new)
1040 m1.update(new)
1034 removed = [f for f in sorted(removed) if f in m1 or f in m2]
1041 removed = [f for f in sorted(removed) if f in m1 or f in m2]
1035 drop = [f for f in removed if f in m1]
1042 drop = [f for f in removed if f in m1]
1036 for f in drop:
1043 for f in drop:
1037 del m1[f]
1044 del m1[f]
1038 mn = self.manifest.add(m1, trp, linkrev, p1.manifestnode(),
1045 mn = self.manifest.add(m1, trp, linkrev, p1.manifestnode(),
1039 p2.manifestnode(), (new, drop))
1046 p2.manifestnode(), (new, drop))
1040
1047
1041 # update changelog
1048 # update changelog
1042 self.changelog.delayupdate()
1049 self.changelog.delayupdate()
1043 n = self.changelog.add(mn, changed + removed, ctx.description(),
1050 n = self.changelog.add(mn, changed + removed, ctx.description(),
1044 trp, p1.node(), p2.node(),
1051 trp, p1.node(), p2.node(),
1045 user, ctx.date(), ctx.extra().copy())
1052 user, ctx.date(), ctx.extra().copy())
1046 p = lambda: self.changelog.writepending() and self.root or ""
1053 p = lambda: self.changelog.writepending() and self.root or ""
1047 xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
1054 xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
1048 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
1055 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
1049 parent2=xp2, pending=p)
1056 parent2=xp2, pending=p)
1050 self.changelog.finalize(trp)
1057 self.changelog.finalize(trp)
1051 tr.close()
1058 tr.close()
1052
1059
1053 if self._branchcache:
1060 if self._branchcache:
1054 self.updatebranchcache()
1061 self.updatebranchcache()
1055 return n
1062 return n
1056 finally:
1063 finally:
1057 if tr:
1064 if tr:
1058 tr.release()
1065 tr.release()
1059 lock.release()
1066 lock.release()
1060
1067
1061 def destroyed(self):
1068 def destroyed(self):
1062 '''Inform the repository that nodes have been destroyed.
1069 '''Inform the repository that nodes have been destroyed.
1063 Intended for use by strip and rollback, so there's a common
1070 Intended for use by strip and rollback, so there's a common
1064 place for anything that has to be done after destroying history.'''
1071 place for anything that has to be done after destroying history.'''
1065 # XXX it might be nice if we could take the list of destroyed
1072 # XXX it might be nice if we could take the list of destroyed
1066 # nodes, but I don't see an easy way for rollback() to do that
1073 # nodes, but I don't see an easy way for rollback() to do that
1067
1074
1068 # Ensure the persistent tag cache is updated. Doing it now
1075 # Ensure the persistent tag cache is updated. Doing it now
1069 # means that the tag cache only has to worry about destroyed
1076 # means that the tag cache only has to worry about destroyed
1070 # heads immediately after a strip/rollback. That in turn
1077 # heads immediately after a strip/rollback. That in turn
1071 # guarantees that "cachetip == currenttip" (comparing both rev
1078 # guarantees that "cachetip == currenttip" (comparing both rev
1072 # and node) always means no nodes have been added or destroyed.
1079 # and node) always means no nodes have been added or destroyed.
1073
1080
1074 # XXX this is suboptimal when qrefresh'ing: we strip the current
1081 # XXX this is suboptimal when qrefresh'ing: we strip the current
1075 # head, refresh the tag cache, then immediately add a new head.
1082 # head, refresh the tag cache, then immediately add a new head.
1076 # But I think doing it this way is necessary for the "instant
1083 # But I think doing it this way is necessary for the "instant
1077 # tag cache retrieval" case to work.
1084 # tag cache retrieval" case to work.
1078 self.invalidatecaches()
1085 self.invalidatecaches()
1079
1086
1080 def walk(self, match, node=None):
1087 def walk(self, match, node=None):
1081 '''
1088 '''
1082 walk recursively through the directory tree or a given
1089 walk recursively through the directory tree or a given
1083 changeset, finding all files matched by the match
1090 changeset, finding all files matched by the match
1084 function
1091 function
1085 '''
1092 '''
1086 return self[node].walk(match)
1093 return self[node].walk(match)
1087
1094
1088 def status(self, node1='.', node2=None, match=None,
1095 def status(self, node1='.', node2=None, match=None,
1089 ignored=False, clean=False, unknown=False,
1096 ignored=False, clean=False, unknown=False,
1090 listsubrepos=False):
1097 listsubrepos=False):
1091 """return status of files between two nodes or node and working directory
1098 """return status of files between two nodes or node and working directory
1092
1099
1093 If node1 is None, use the first dirstate parent instead.
1100 If node1 is None, use the first dirstate parent instead.
1094 If node2 is None, compare node1 with working directory.
1101 If node2 is None, compare node1 with working directory.
1095 """
1102 """
1096
1103
1097 def mfmatches(ctx):
1104 def mfmatches(ctx):
1098 mf = ctx.manifest().copy()
1105 mf = ctx.manifest().copy()
1099 for fn in mf.keys():
1106 for fn in mf.keys():
1100 if not match(fn):
1107 if not match(fn):
1101 del mf[fn]
1108 del mf[fn]
1102 return mf
1109 return mf
1103
1110
1104 if isinstance(node1, context.changectx):
1111 if isinstance(node1, context.changectx):
1105 ctx1 = node1
1112 ctx1 = node1
1106 else:
1113 else:
1107 ctx1 = self[node1]
1114 ctx1 = self[node1]
1108 if isinstance(node2, context.changectx):
1115 if isinstance(node2, context.changectx):
1109 ctx2 = node2
1116 ctx2 = node2
1110 else:
1117 else:
1111 ctx2 = self[node2]
1118 ctx2 = self[node2]
1112
1119
1113 working = ctx2.rev() is None
1120 working = ctx2.rev() is None
1114 parentworking = working and ctx1 == self['.']
1121 parentworking = working and ctx1 == self['.']
1115 match = match or matchmod.always(self.root, self.getcwd())
1122 match = match or matchmod.always(self.root, self.getcwd())
1116 listignored, listclean, listunknown = ignored, clean, unknown
1123 listignored, listclean, listunknown = ignored, clean, unknown
1117
1124
1118 # load earliest manifest first for caching reasons
1125 # load earliest manifest first for caching reasons
1119 if not working and ctx2.rev() < ctx1.rev():
1126 if not working and ctx2.rev() < ctx1.rev():
1120 ctx2.manifest()
1127 ctx2.manifest()
1121
1128
1122 if not parentworking:
1129 if not parentworking:
1123 def bad(f, msg):
1130 def bad(f, msg):
1124 if f not in ctx1:
1131 if f not in ctx1:
1125 self.ui.warn('%s: %s\n' % (self.dirstate.pathto(f), msg))
1132 self.ui.warn('%s: %s\n' % (self.dirstate.pathto(f), msg))
1126 match.bad = bad
1133 match.bad = bad
1127
1134
1128 if working: # we need to scan the working dir
1135 if working: # we need to scan the working dir
1129 subrepos = []
1136 subrepos = []
1130 if '.hgsub' in self.dirstate:
1137 if '.hgsub' in self.dirstate:
1131 subrepos = ctx1.substate.keys()
1138 subrepos = ctx1.substate.keys()
1132 s = self.dirstate.status(match, subrepos, listignored,
1139 s = self.dirstate.status(match, subrepos, listignored,
1133 listclean, listunknown)
1140 listclean, listunknown)
1134 cmp, modified, added, removed, deleted, unknown, ignored, clean = s
1141 cmp, modified, added, removed, deleted, unknown, ignored, clean = s
1135
1142
1136 # check for any possibly clean files
1143 # check for any possibly clean files
1137 if parentworking and cmp:
1144 if parentworking and cmp:
1138 fixup = []
1145 fixup = []
1139 # do a full compare of any files that might have changed
1146 # do a full compare of any files that might have changed
1140 for f in sorted(cmp):
1147 for f in sorted(cmp):
1141 if (f not in ctx1 or ctx2.flags(f) != ctx1.flags(f)
1148 if (f not in ctx1 or ctx2.flags(f) != ctx1.flags(f)
1142 or ctx1[f].cmp(ctx2[f])):
1149 or ctx1[f].cmp(ctx2[f])):
1143 modified.append(f)
1150 modified.append(f)
1144 else:
1151 else:
1145 fixup.append(f)
1152 fixup.append(f)
1146
1153
1147 # update dirstate for files that are actually clean
1154 # update dirstate for files that are actually clean
1148 if fixup:
1155 if fixup:
1149 if listclean:
1156 if listclean:
1150 clean += fixup
1157 clean += fixup
1151
1158
1152 try:
1159 try:
1153 # updating the dirstate is optional
1160 # updating the dirstate is optional
1154 # so we don't wait on the lock
1161 # so we don't wait on the lock
1155 wlock = self.wlock(False)
1162 wlock = self.wlock(False)
1156 try:
1163 try:
1157 for f in fixup:
1164 for f in fixup:
1158 self.dirstate.normal(f)
1165 self.dirstate.normal(f)
1159 finally:
1166 finally:
1160 wlock.release()
1167 wlock.release()
1161 except error.LockError:
1168 except error.LockError:
1162 pass
1169 pass
1163
1170
1164 if not parentworking:
1171 if not parentworking:
1165 mf1 = mfmatches(ctx1)
1172 mf1 = mfmatches(ctx1)
1166 if working:
1173 if working:
1167 # we are comparing working dir against non-parent
1174 # we are comparing working dir against non-parent
1168 # generate a pseudo-manifest for the working dir
1175 # generate a pseudo-manifest for the working dir
1169 mf2 = mfmatches(self['.'])
1176 mf2 = mfmatches(self['.'])
1170 for f in cmp + modified + added:
1177 for f in cmp + modified + added:
1171 mf2[f] = None
1178 mf2[f] = None
1172 mf2.set(f, ctx2.flags(f))
1179 mf2.set(f, ctx2.flags(f))
1173 for f in removed:
1180 for f in removed:
1174 if f in mf2:
1181 if f in mf2:
1175 del mf2[f]
1182 del mf2[f]
1176 else:
1183 else:
1177 # we are comparing two revisions
1184 # we are comparing two revisions
1178 deleted, unknown, ignored = [], [], []
1185 deleted, unknown, ignored = [], [], []
1179 mf2 = mfmatches(ctx2)
1186 mf2 = mfmatches(ctx2)
1180
1187
1181 modified, added, clean = [], [], []
1188 modified, added, clean = [], [], []
1182 for fn in mf2:
1189 for fn in mf2:
1183 if fn in mf1:
1190 if fn in mf1:
1184 if (mf1.flags(fn) != mf2.flags(fn) or
1191 if (mf1.flags(fn) != mf2.flags(fn) or
1185 (mf1[fn] != mf2[fn] and
1192 (mf1[fn] != mf2[fn] and
1186 (mf2[fn] or ctx1[fn].cmp(ctx2[fn])))):
1193 (mf2[fn] or ctx1[fn].cmp(ctx2[fn])))):
1187 modified.append(fn)
1194 modified.append(fn)
1188 elif listclean:
1195 elif listclean:
1189 clean.append(fn)
1196 clean.append(fn)
1190 del mf1[fn]
1197 del mf1[fn]
1191 else:
1198 else:
1192 added.append(fn)
1199 added.append(fn)
1193 removed = mf1.keys()
1200 removed = mf1.keys()
1194
1201
1195 r = modified, added, removed, deleted, unknown, ignored, clean
1202 r = modified, added, removed, deleted, unknown, ignored, clean
1196
1203
1197 if listsubrepos:
1204 if listsubrepos:
1198 for subpath, sub in subrepo.itersubrepos(ctx1, ctx2):
1205 for subpath, sub in subrepo.itersubrepos(ctx1, ctx2):
1199 if working:
1206 if working:
1200 rev2 = None
1207 rev2 = None
1201 else:
1208 else:
1202 rev2 = ctx2.substate[subpath][1]
1209 rev2 = ctx2.substate[subpath][1]
1203 try:
1210 try:
1204 submatch = matchmod.narrowmatcher(subpath, match)
1211 submatch = matchmod.narrowmatcher(subpath, match)
1205 s = sub.status(rev2, match=submatch, ignored=listignored,
1212 s = sub.status(rev2, match=submatch, ignored=listignored,
1206 clean=listclean, unknown=listunknown,
1213 clean=listclean, unknown=listunknown,
1207 listsubrepos=True)
1214 listsubrepos=True)
1208 for rfiles, sfiles in zip(r, s):
1215 for rfiles, sfiles in zip(r, s):
1209 rfiles.extend("%s/%s" % (subpath, f) for f in sfiles)
1216 rfiles.extend("%s/%s" % (subpath, f) for f in sfiles)
1210 except error.LookupError:
1217 except error.LookupError:
1211 self.ui.status(_("skipping missing subrepository: %s\n")
1218 self.ui.status(_("skipping missing subrepository: %s\n")
1212 % subpath)
1219 % subpath)
1213
1220
1214 [l.sort() for l in r]
1221 [l.sort() for l in r]
1215 return r
1222 return r
1216
1223
1217 def heads(self, start=None):
1224 def heads(self, start=None):
1218 heads = self.changelog.heads(start)
1225 heads = self.changelog.heads(start)
1219 # sort the output in rev descending order
1226 # sort the output in rev descending order
1220 return sorted(heads, key=self.changelog.rev, reverse=True)
1227 return sorted(heads, key=self.changelog.rev, reverse=True)
1221
1228
1222 def branchheads(self, branch=None, start=None, closed=False):
1229 def branchheads(self, branch=None, start=None, closed=False):
1223 '''return a (possibly filtered) list of heads for the given branch
1230 '''return a (possibly filtered) list of heads for the given branch
1224
1231
1225 Heads are returned in topological order, from newest to oldest.
1232 Heads are returned in topological order, from newest to oldest.
1226 If branch is None, use the dirstate branch.
1233 If branch is None, use the dirstate branch.
1227 If start is not None, return only heads reachable from start.
1234 If start is not None, return only heads reachable from start.
1228 If closed is True, return heads that are marked as closed as well.
1235 If closed is True, return heads that are marked as closed as well.
1229 '''
1236 '''
1230 if branch is None:
1237 if branch is None:
1231 branch = self[None].branch()
1238 branch = self[None].branch()
1232 branches = self.branchmap()
1239 branches = self.branchmap()
1233 if branch not in branches:
1240 if branch not in branches:
1234 return []
1241 return []
1235 # the cache returns heads ordered lowest to highest
1242 # the cache returns heads ordered lowest to highest
1236 bheads = list(reversed(branches[branch]))
1243 bheads = list(reversed(branches[branch]))
1237 if start is not None:
1244 if start is not None:
1238 # filter out the heads that cannot be reached from startrev
1245 # filter out the heads that cannot be reached from startrev
1239 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
1246 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
1240 bheads = [h for h in bheads if h in fbheads]
1247 bheads = [h for h in bheads if h in fbheads]
1241 if not closed:
1248 if not closed:
1242 bheads = [h for h in bheads if
1249 bheads = [h for h in bheads if
1243 ('close' not in self.changelog.read(h)[5])]
1250 ('close' not in self.changelog.read(h)[5])]
1244 return bheads
1251 return bheads
1245
1252
1246 def branches(self, nodes):
1253 def branches(self, nodes):
1247 if not nodes:
1254 if not nodes:
1248 nodes = [self.changelog.tip()]
1255 nodes = [self.changelog.tip()]
1249 b = []
1256 b = []
1250 for n in nodes:
1257 for n in nodes:
1251 t = n
1258 t = n
1252 while 1:
1259 while 1:
1253 p = self.changelog.parents(n)
1260 p = self.changelog.parents(n)
1254 if p[1] != nullid or p[0] == nullid:
1261 if p[1] != nullid or p[0] == nullid:
1255 b.append((t, n, p[0], p[1]))
1262 b.append((t, n, p[0], p[1]))
1256 break
1263 break
1257 n = p[0]
1264 n = p[0]
1258 return b
1265 return b
1259
1266
1260 def between(self, pairs):
1267 def between(self, pairs):
1261 r = []
1268 r = []
1262
1269
1263 for top, bottom in pairs:
1270 for top, bottom in pairs:
1264 n, l, i = top, [], 0
1271 n, l, i = top, [], 0
1265 f = 1
1272 f = 1
1266
1273
1267 while n != bottom and n != nullid:
1274 while n != bottom and n != nullid:
1268 p = self.changelog.parents(n)[0]
1275 p = self.changelog.parents(n)[0]
1269 if i == f:
1276 if i == f:
1270 l.append(n)
1277 l.append(n)
1271 f = f * 2
1278 f = f * 2
1272 n = p
1279 n = p
1273 i += 1
1280 i += 1
1274
1281
1275 r.append(l)
1282 r.append(l)
1276
1283
1277 return r
1284 return r
1278
1285
1279 def pull(self, remote, heads=None, force=False):
1286 def pull(self, remote, heads=None, force=False):
1280 lock = self.lock()
1287 lock = self.lock()
1281 try:
1288 try:
1282 tmp = discovery.findcommonincoming(self, remote, heads=heads,
1289 tmp = discovery.findcommonincoming(self, remote, heads=heads,
1283 force=force)
1290 force=force)
1284 common, fetch, rheads = tmp
1291 common, fetch, rheads = tmp
1285 if not fetch:
1292 if not fetch:
1286 self.ui.status(_("no changes found\n"))
1293 self.ui.status(_("no changes found\n"))
1287 return 0
1294 return 0
1288
1295
1289 if heads is None and fetch == [nullid]:
1296 if heads is None and fetch == [nullid]:
1290 self.ui.status(_("requesting all changes\n"))
1297 self.ui.status(_("requesting all changes\n"))
1291 elif heads is None and remote.capable('changegroupsubset'):
1298 elif heads is None and remote.capable('changegroupsubset'):
1292 # issue1320, avoid a race if remote changed after discovery
1299 # issue1320, avoid a race if remote changed after discovery
1293 heads = rheads
1300 heads = rheads
1294
1301
1295 if heads is None:
1302 if heads is None:
1296 cg = remote.changegroup(fetch, 'pull')
1303 cg = remote.changegroup(fetch, 'pull')
1297 else:
1304 else:
1298 if not remote.capable('changegroupsubset'):
1305 if not remote.capable('changegroupsubset'):
1299 raise util.Abort(_("partial pull cannot be done because "
1306 raise util.Abort(_("partial pull cannot be done because "
1300 "other repository doesn't support "
1307 "other repository doesn't support "
1301 "changegroupsubset."))
1308 "changegroupsubset."))
1302 cg = remote.changegroupsubset(fetch, heads, 'pull')
1309 cg = remote.changegroupsubset(fetch, heads, 'pull')
1303 return self.addchangegroup(cg, 'pull', remote.url(), lock=lock)
1310 return self.addchangegroup(cg, 'pull', remote.url(), lock=lock)
1304 finally:
1311 finally:
1305 lock.release()
1312 lock.release()
1306
1313
1307 def checkpush(self, force, revs):
1314 def checkpush(self, force, revs):
1308 """Extensions can override this function if additional checks have
1315 """Extensions can override this function if additional checks have
1309 to be performed before pushing, or call it if they override push
1316 to be performed before pushing, or call it if they override push
1310 command.
1317 command.
1311 """
1318 """
1312 pass
1319 pass
1313
1320
1314 def push(self, remote, force=False, revs=None, newbranch=False):
1321 def push(self, remote, force=False, revs=None, newbranch=False):
1315 '''Push outgoing changesets (limited by revs) from the current
1322 '''Push outgoing changesets (limited by revs) from the current
1316 repository to remote. Return an integer:
1323 repository to remote. Return an integer:
1317 - 0 means HTTP error *or* nothing to push
1324 - 0 means HTTP error *or* nothing to push
1318 - 1 means we pushed and remote head count is unchanged *or*
1325 - 1 means we pushed and remote head count is unchanged *or*
1319 we have outgoing changesets but refused to push
1326 we have outgoing changesets but refused to push
1320 - other values as described by addchangegroup()
1327 - other values as described by addchangegroup()
1321 '''
1328 '''
1322 # there are two ways to push to remote repo:
1329 # there are two ways to push to remote repo:
1323 #
1330 #
1324 # addchangegroup assumes local user can lock remote
1331 # addchangegroup assumes local user can lock remote
1325 # repo (local filesystem, old ssh servers).
1332 # repo (local filesystem, old ssh servers).
1326 #
1333 #
1327 # unbundle assumes local user cannot lock remote repo (new ssh
1334 # unbundle assumes local user cannot lock remote repo (new ssh
1328 # servers, http servers).
1335 # servers, http servers).
1329
1336
1330 self.checkpush(force, revs)
1337 self.checkpush(force, revs)
1331 lock = None
1338 lock = None
1332 unbundle = remote.capable('unbundle')
1339 unbundle = remote.capable('unbundle')
1333 if not unbundle:
1340 if not unbundle:
1334 lock = remote.lock()
1341 lock = remote.lock()
1335 try:
1342 try:
1336 ret = discovery.prepush(self, remote, force, revs, newbranch)
1343 ret = discovery.prepush(self, remote, force, revs, newbranch)
1337 if ret[0] is None:
1344 if ret[0] is None:
1338 # and here we return 0 for "nothing to push" or 1 for
1345 # and here we return 0 for "nothing to push" or 1 for
1339 # "something to push but I refuse"
1346 # "something to push but I refuse"
1340 return ret[1]
1347 return ret[1]
1341
1348
1342 cg, remote_heads = ret
1349 cg, remote_heads = ret
1343 if unbundle:
1350 if unbundle:
1344 # local repo finds heads on server, finds out what revs it must
1351 # local repo finds heads on server, finds out what revs it must
1345 # push. once revs transferred, if server finds it has
1352 # push. once revs transferred, if server finds it has
1346 # different heads (someone else won commit/push race), server
1353 # different heads (someone else won commit/push race), server
1347 # aborts.
1354 # aborts.
1348 if force:
1355 if force:
1349 remote_heads = ['force']
1356 remote_heads = ['force']
1350 # ssh: return remote's addchangegroup()
1357 # ssh: return remote's addchangegroup()
1351 # http: return remote's addchangegroup() or 0 for error
1358 # http: return remote's addchangegroup() or 0 for error
1352 return remote.unbundle(cg, remote_heads, 'push')
1359 return remote.unbundle(cg, remote_heads, 'push')
1353 else:
1360 else:
1354 # we return an integer indicating remote head count change
1361 # we return an integer indicating remote head count change
1355 return remote.addchangegroup(cg, 'push', self.url(), lock=lock)
1362 return remote.addchangegroup(cg, 'push', self.url(), lock=lock)
1356 finally:
1363 finally:
1357 if lock is not None:
1364 if lock is not None:
1358 lock.release()
1365 lock.release()
1359
1366
1360 def changegroupinfo(self, nodes, source):
1367 def changegroupinfo(self, nodes, source):
1361 if self.ui.verbose or source == 'bundle':
1368 if self.ui.verbose or source == 'bundle':
1362 self.ui.status(_("%d changesets found\n") % len(nodes))
1369 self.ui.status(_("%d changesets found\n") % len(nodes))
1363 if self.ui.debugflag:
1370 if self.ui.debugflag:
1364 self.ui.debug("list of changesets:\n")
1371 self.ui.debug("list of changesets:\n")
1365 for node in nodes:
1372 for node in nodes:
1366 self.ui.debug("%s\n" % hex(node))
1373 self.ui.debug("%s\n" % hex(node))
1367
1374
1368 def changegroupsubset(self, bases, heads, source, extranodes=None):
1375 def changegroupsubset(self, bases, heads, source, extranodes=None):
1369 """Compute a changegroup consisting of all the nodes that are
1376 """Compute a changegroup consisting of all the nodes that are
1370 descendents of any of the bases and ancestors of any of the heads.
1377 descendents of any of the bases and ancestors of any of the heads.
1371 Return a chunkbuffer object whose read() method will return
1378 Return a chunkbuffer object whose read() method will return
1372 successive changegroup chunks.
1379 successive changegroup chunks.
1373
1380
1374 It is fairly complex as determining which filenodes and which
1381 It is fairly complex as determining which filenodes and which
1375 manifest nodes need to be included for the changeset to be complete
1382 manifest nodes need to be included for the changeset to be complete
1376 is non-trivial.
1383 is non-trivial.
1377
1384
1378 Another wrinkle is doing the reverse, figuring out which changeset in
1385 Another wrinkle is doing the reverse, figuring out which changeset in
1379 the changegroup a particular filenode or manifestnode belongs to.
1386 the changegroup a particular filenode or manifestnode belongs to.
1380
1387
1381 The caller can specify some nodes that must be included in the
1388 The caller can specify some nodes that must be included in the
1382 changegroup using the extranodes argument. It should be a dict
1389 changegroup using the extranodes argument. It should be a dict
1383 where the keys are the filenames (or 1 for the manifest), and the
1390 where the keys are the filenames (or 1 for the manifest), and the
1384 values are lists of (node, linknode) tuples, where node is a wanted
1391 values are lists of (node, linknode) tuples, where node is a wanted
1385 node and linknode is the changelog node that should be transmitted as
1392 node and linknode is the changelog node that should be transmitted as
1386 the linkrev.
1393 the linkrev.
1387 """
1394 """
1388
1395
1389 # Set up some initial variables
1396 # Set up some initial variables
1390 # Make it easy to refer to self.changelog
1397 # Make it easy to refer to self.changelog
1391 cl = self.changelog
1398 cl = self.changelog
1392 # Compute the list of changesets in this changegroup.
1399 # Compute the list of changesets in this changegroup.
1393 # Some bases may turn out to be superfluous, and some heads may be
1400 # Some bases may turn out to be superfluous, and some heads may be
1394 # too. nodesbetween will return the minimal set of bases and heads
1401 # too. nodesbetween will return the minimal set of bases and heads
1395 # necessary to re-create the changegroup.
1402 # necessary to re-create the changegroup.
1396 if not bases:
1403 if not bases:
1397 bases = [nullid]
1404 bases = [nullid]
1398 msng_cl_lst, bases, heads = cl.nodesbetween(bases, heads)
1405 msng_cl_lst, bases, heads = cl.nodesbetween(bases, heads)
1399
1406
1400 if extranodes is None:
1407 if extranodes is None:
1401 # can we go through the fast path ?
1408 # can we go through the fast path ?
1402 heads.sort()
1409 heads.sort()
1403 allheads = self.heads()
1410 allheads = self.heads()
1404 allheads.sort()
1411 allheads.sort()
1405 if heads == allheads:
1412 if heads == allheads:
1406 return self._changegroup(msng_cl_lst, source)
1413 return self._changegroup(msng_cl_lst, source)
1407
1414
1408 # slow path
1415 # slow path
1409 self.hook('preoutgoing', throw=True, source=source)
1416 self.hook('preoutgoing', throw=True, source=source)
1410
1417
1411 self.changegroupinfo(msng_cl_lst, source)
1418 self.changegroupinfo(msng_cl_lst, source)
1412
1419
1413 # We assume that all ancestors of bases are known
1420 # We assume that all ancestors of bases are known
1414 commonrevs = set(cl.ancestors(*[cl.rev(n) for n in bases]))
1421 commonrevs = set(cl.ancestors(*[cl.rev(n) for n in bases]))
1415
1422
1416 # Make it easy to refer to self.manifest
1423 # Make it easy to refer to self.manifest
1417 mnfst = self.manifest
1424 mnfst = self.manifest
1418 # We don't know which manifests are missing yet
1425 # We don't know which manifests are missing yet
1419 msng_mnfst_set = {}
1426 msng_mnfst_set = {}
1420 # Nor do we know which filenodes are missing.
1427 # Nor do we know which filenodes are missing.
1421 msng_filenode_set = {}
1428 msng_filenode_set = {}
1422
1429
1423 # A changeset always belongs to itself, so the changenode lookup
1430 # A changeset always belongs to itself, so the changenode lookup
1424 # function for a changenode is identity.
1431 # function for a changenode is identity.
1425 def identity(x):
1432 def identity(x):
1426 return x
1433 return x
1427
1434
1428 # A function generating function that sets up the initial environment
1435 # A function generating function that sets up the initial environment
1429 # the inner function.
1436 # the inner function.
1430 def filenode_collector(changedfiles):
1437 def filenode_collector(changedfiles):
1431 # This gathers information from each manifestnode included in the
1438 # This gathers information from each manifestnode included in the
1432 # changegroup about which filenodes the manifest node references
1439 # changegroup about which filenodes the manifest node references
1433 # so we can include those in the changegroup too.
1440 # so we can include those in the changegroup too.
1434 #
1441 #
1435 # It also remembers which changenode each filenode belongs to. It
1442 # It also remembers which changenode each filenode belongs to. It
1436 # does this by assuming the a filenode belongs to the changenode
1443 # does this by assuming the a filenode belongs to the changenode
1437 # the first manifest that references it belongs to.
1444 # the first manifest that references it belongs to.
1438 def collect_msng_filenodes(mnfstnode):
1445 def collect_msng_filenodes(mnfstnode):
1439 r = mnfst.rev(mnfstnode)
1446 r = mnfst.rev(mnfstnode)
1440 if mnfst.deltaparent(r) in mnfst.parentrevs(r):
1447 if mnfst.deltaparent(r) in mnfst.parentrevs(r):
1441 # If the previous rev is one of the parents,
1448 # If the previous rev is one of the parents,
1442 # we only need to see a diff.
1449 # we only need to see a diff.
1443 deltamf = mnfst.readdelta(mnfstnode)
1450 deltamf = mnfst.readdelta(mnfstnode)
1444 # For each line in the delta
1451 # For each line in the delta
1445 for f, fnode in deltamf.iteritems():
1452 for f, fnode in deltamf.iteritems():
1446 # And if the file is in the list of files we care
1453 # And if the file is in the list of files we care
1447 # about.
1454 # about.
1448 if f in changedfiles:
1455 if f in changedfiles:
1449 # Get the changenode this manifest belongs to
1456 # Get the changenode this manifest belongs to
1450 clnode = msng_mnfst_set[mnfstnode]
1457 clnode = msng_mnfst_set[mnfstnode]
1451 # Create the set of filenodes for the file if
1458 # Create the set of filenodes for the file if
1452 # there isn't one already.
1459 # there isn't one already.
1453 ndset = msng_filenode_set.setdefault(f, {})
1460 ndset = msng_filenode_set.setdefault(f, {})
1454 # And set the filenode's changelog node to the
1461 # And set the filenode's changelog node to the
1455 # manifest's if it hasn't been set already.
1462 # manifest's if it hasn't been set already.
1456 ndset.setdefault(fnode, clnode)
1463 ndset.setdefault(fnode, clnode)
1457 else:
1464 else:
1458 # Otherwise we need a full manifest.
1465 # Otherwise we need a full manifest.
1459 m = mnfst.read(mnfstnode)
1466 m = mnfst.read(mnfstnode)
1460 # For every file in we care about.
1467 # For every file in we care about.
1461 for f in changedfiles:
1468 for f in changedfiles:
1462 fnode = m.get(f, None)
1469 fnode = m.get(f, None)
1463 # If it's in the manifest
1470 # If it's in the manifest
1464 if fnode is not None:
1471 if fnode is not None:
1465 # See comments above.
1472 # See comments above.
1466 clnode = msng_mnfst_set[mnfstnode]
1473 clnode = msng_mnfst_set[mnfstnode]
1467 ndset = msng_filenode_set.setdefault(f, {})
1474 ndset = msng_filenode_set.setdefault(f, {})
1468 ndset.setdefault(fnode, clnode)
1475 ndset.setdefault(fnode, clnode)
1469 return collect_msng_filenodes
1476 return collect_msng_filenodes
1470
1477
1471 # If we determine that a particular file or manifest node must be a
1478 # If we determine that a particular file or manifest node must be a
1472 # node that the recipient of the changegroup will already have, we can
1479 # node that the recipient of the changegroup will already have, we can
1473 # also assume the recipient will have all the parents. This function
1480 # also assume the recipient will have all the parents. This function
1474 # prunes them from the set of missing nodes.
1481 # prunes them from the set of missing nodes.
1475 def prune(revlog, missingnodes):
1482 def prune(revlog, missingnodes):
1476 hasset = set()
1483 hasset = set()
1477 # If a 'missing' filenode thinks it belongs to a changenode we
1484 # If a 'missing' filenode thinks it belongs to a changenode we
1478 # assume the recipient must have, then the recipient must have
1485 # assume the recipient must have, then the recipient must have
1479 # that filenode.
1486 # that filenode.
1480 for n in missingnodes:
1487 for n in missingnodes:
1481 clrev = revlog.linkrev(revlog.rev(n))
1488 clrev = revlog.linkrev(revlog.rev(n))
1482 if clrev in commonrevs:
1489 if clrev in commonrevs:
1483 hasset.add(n)
1490 hasset.add(n)
1484 for n in hasset:
1491 for n in hasset:
1485 missingnodes.pop(n, None)
1492 missingnodes.pop(n, None)
1486 for r in revlog.ancestors(*[revlog.rev(n) for n in hasset]):
1493 for r in revlog.ancestors(*[revlog.rev(n) for n in hasset]):
1487 missingnodes.pop(revlog.node(r), None)
1494 missingnodes.pop(revlog.node(r), None)
1488
1495
1489 # Add the nodes that were explicitly requested.
1496 # Add the nodes that were explicitly requested.
1490 def add_extra_nodes(name, nodes):
1497 def add_extra_nodes(name, nodes):
1491 if not extranodes or name not in extranodes:
1498 if not extranodes or name not in extranodes:
1492 return
1499 return
1493
1500
1494 for node, linknode in extranodes[name]:
1501 for node, linknode in extranodes[name]:
1495 if node not in nodes:
1502 if node not in nodes:
1496 nodes[node] = linknode
1503 nodes[node] = linknode
1497
1504
1498 # Now that we have all theses utility functions to help out and
1505 # Now that we have all theses utility functions to help out and
1499 # logically divide up the task, generate the group.
1506 # logically divide up the task, generate the group.
1500 def gengroup():
1507 def gengroup():
1501 # The set of changed files starts empty.
1508 # The set of changed files starts empty.
1502 changedfiles = set()
1509 changedfiles = set()
1503 collect = changegroup.collector(cl, msng_mnfst_set, changedfiles)
1510 collect = changegroup.collector(cl, msng_mnfst_set, changedfiles)
1504
1511
1505 # Create a changenode group generator that will call our functions
1512 # Create a changenode group generator that will call our functions
1506 # back to lookup the owning changenode and collect information.
1513 # back to lookup the owning changenode and collect information.
1507 group = cl.group(msng_cl_lst, identity, collect)
1514 group = cl.group(msng_cl_lst, identity, collect)
1508 for cnt, chnk in enumerate(group):
1515 for cnt, chnk in enumerate(group):
1509 yield chnk
1516 yield chnk
1510 # revlog.group yields three entries per node, so
1517 # revlog.group yields three entries per node, so
1511 # dividing by 3 gives an approximation of how many
1518 # dividing by 3 gives an approximation of how many
1512 # nodes have been processed.
1519 # nodes have been processed.
1513 self.ui.progress(_('bundling'), cnt / 3,
1520 self.ui.progress(_('bundling'), cnt / 3,
1514 unit=_('changesets'))
1521 unit=_('changesets'))
1515 changecount = cnt / 3
1522 changecount = cnt / 3
1516 self.ui.progress(_('bundling'), None)
1523 self.ui.progress(_('bundling'), None)
1517
1524
1518 prune(mnfst, msng_mnfst_set)
1525 prune(mnfst, msng_mnfst_set)
1519 add_extra_nodes(1, msng_mnfst_set)
1526 add_extra_nodes(1, msng_mnfst_set)
1520 msng_mnfst_lst = msng_mnfst_set.keys()
1527 msng_mnfst_lst = msng_mnfst_set.keys()
1521 # Sort the manifestnodes by revision number.
1528 # Sort the manifestnodes by revision number.
1522 msng_mnfst_lst.sort(key=mnfst.rev)
1529 msng_mnfst_lst.sort(key=mnfst.rev)
1523 # Create a generator for the manifestnodes that calls our lookup
1530 # Create a generator for the manifestnodes that calls our lookup
1524 # and data collection functions back.
1531 # and data collection functions back.
1525 group = mnfst.group(msng_mnfst_lst,
1532 group = mnfst.group(msng_mnfst_lst,
1526 lambda mnode: msng_mnfst_set[mnode],
1533 lambda mnode: msng_mnfst_set[mnode],
1527 filenode_collector(changedfiles))
1534 filenode_collector(changedfiles))
1528 efiles = {}
1535 efiles = {}
1529 for cnt, chnk in enumerate(group):
1536 for cnt, chnk in enumerate(group):
1530 if cnt % 3 == 1:
1537 if cnt % 3 == 1:
1531 mnode = chnk[:20]
1538 mnode = chnk[:20]
1532 efiles.update(mnfst.readdelta(mnode))
1539 efiles.update(mnfst.readdelta(mnode))
1533 yield chnk
1540 yield chnk
1534 # see above comment for why we divide by 3
1541 # see above comment for why we divide by 3
1535 self.ui.progress(_('bundling'), cnt / 3,
1542 self.ui.progress(_('bundling'), cnt / 3,
1536 unit=_('manifests'), total=changecount)
1543 unit=_('manifests'), total=changecount)
1537 self.ui.progress(_('bundling'), None)
1544 self.ui.progress(_('bundling'), None)
1538 efiles = len(efiles)
1545 efiles = len(efiles)
1539
1546
1540 # These are no longer needed, dereference and toss the memory for
1547 # These are no longer needed, dereference and toss the memory for
1541 # them.
1548 # them.
1542 msng_mnfst_lst = None
1549 msng_mnfst_lst = None
1543 msng_mnfst_set.clear()
1550 msng_mnfst_set.clear()
1544
1551
1545 if extranodes:
1552 if extranodes:
1546 for fname in extranodes:
1553 for fname in extranodes:
1547 if isinstance(fname, int):
1554 if isinstance(fname, int):
1548 continue
1555 continue
1549 msng_filenode_set.setdefault(fname, {})
1556 msng_filenode_set.setdefault(fname, {})
1550 changedfiles.add(fname)
1557 changedfiles.add(fname)
1551 # Go through all our files in order sorted by name.
1558 # Go through all our files in order sorted by name.
1552 for idx, fname in enumerate(sorted(changedfiles)):
1559 for idx, fname in enumerate(sorted(changedfiles)):
1553 filerevlog = self.file(fname)
1560 filerevlog = self.file(fname)
1554 if not len(filerevlog):
1561 if not len(filerevlog):
1555 raise util.Abort(_("empty or missing revlog for %s") % fname)
1562 raise util.Abort(_("empty or missing revlog for %s") % fname)
1556 # Toss out the filenodes that the recipient isn't really
1563 # Toss out the filenodes that the recipient isn't really
1557 # missing.
1564 # missing.
1558 missingfnodes = msng_filenode_set.pop(fname, {})
1565 missingfnodes = msng_filenode_set.pop(fname, {})
1559 prune(filerevlog, missingfnodes)
1566 prune(filerevlog, missingfnodes)
1560 add_extra_nodes(fname, missingfnodes)
1567 add_extra_nodes(fname, missingfnodes)
1561 # If any filenodes are left, generate the group for them,
1568 # If any filenodes are left, generate the group for them,
1562 # otherwise don't bother.
1569 # otherwise don't bother.
1563 if missingfnodes:
1570 if missingfnodes:
1564 yield changegroup.chunkheader(len(fname))
1571 yield changegroup.chunkheader(len(fname))
1565 yield fname
1572 yield fname
1566 # Sort the filenodes by their revision # (topological order)
1573 # Sort the filenodes by their revision # (topological order)
1567 nodeiter = list(missingfnodes)
1574 nodeiter = list(missingfnodes)
1568 nodeiter.sort(key=filerevlog.rev)
1575 nodeiter.sort(key=filerevlog.rev)
1569 # Create a group generator and only pass in a changenode
1576 # Create a group generator and only pass in a changenode
1570 # lookup function as we need to collect no information
1577 # lookup function as we need to collect no information
1571 # from filenodes.
1578 # from filenodes.
1572 group = filerevlog.group(nodeiter,
1579 group = filerevlog.group(nodeiter,
1573 lambda fnode: missingfnodes[fnode])
1580 lambda fnode: missingfnodes[fnode])
1574 for chnk in group:
1581 for chnk in group:
1575 # even though we print the same progress on
1582 # even though we print the same progress on
1576 # most loop iterations, put the progress call
1583 # most loop iterations, put the progress call
1577 # here so that time estimates (if any) can be updated
1584 # here so that time estimates (if any) can be updated
1578 self.ui.progress(
1585 self.ui.progress(
1579 _('bundling'), idx, item=fname,
1586 _('bundling'), idx, item=fname,
1580 unit=_('files'), total=efiles)
1587 unit=_('files'), total=efiles)
1581 yield chnk
1588 yield chnk
1582 # Signal that no more groups are left.
1589 # Signal that no more groups are left.
1583 yield changegroup.closechunk()
1590 yield changegroup.closechunk()
1584 self.ui.progress(_('bundling'), None)
1591 self.ui.progress(_('bundling'), None)
1585
1592
1586 if msng_cl_lst:
1593 if msng_cl_lst:
1587 self.hook('outgoing', node=hex(msng_cl_lst[0]), source=source)
1594 self.hook('outgoing', node=hex(msng_cl_lst[0]), source=source)
1588
1595
1589 return changegroup.unbundle10(util.chunkbuffer(gengroup()), 'UN')
1596 return changegroup.unbundle10(util.chunkbuffer(gengroup()), 'UN')
1590
1597
1591 def changegroup(self, basenodes, source):
1598 def changegroup(self, basenodes, source):
1592 # to avoid a race we use changegroupsubset() (issue1320)
1599 # to avoid a race we use changegroupsubset() (issue1320)
1593 return self.changegroupsubset(basenodes, self.heads(), source)
1600 return self.changegroupsubset(basenodes, self.heads(), source)
1594
1601
1595 def _changegroup(self, nodes, source):
1602 def _changegroup(self, nodes, source):
1596 """Compute the changegroup of all nodes that we have that a recipient
1603 """Compute the changegroup of all nodes that we have that a recipient
1597 doesn't. Return a chunkbuffer object whose read() method will return
1604 doesn't. Return a chunkbuffer object whose read() method will return
1598 successive changegroup chunks.
1605 successive changegroup chunks.
1599
1606
1600 This is much easier than the previous function as we can assume that
1607 This is much easier than the previous function as we can assume that
1601 the recipient has any changenode we aren't sending them.
1608 the recipient has any changenode we aren't sending them.
1602
1609
1603 nodes is the set of nodes to send"""
1610 nodes is the set of nodes to send"""
1604
1611
1605 self.hook('preoutgoing', throw=True, source=source)
1612 self.hook('preoutgoing', throw=True, source=source)
1606
1613
1607 cl = self.changelog
1614 cl = self.changelog
1608 revset = set([cl.rev(n) for n in nodes])
1615 revset = set([cl.rev(n) for n in nodes])
1609 self.changegroupinfo(nodes, source)
1616 self.changegroupinfo(nodes, source)
1610
1617
1611 def identity(x):
1618 def identity(x):
1612 return x
1619 return x
1613
1620
1614 def gennodelst(log):
1621 def gennodelst(log):
1615 for r in log:
1622 for r in log:
1616 if log.linkrev(r) in revset:
1623 if log.linkrev(r) in revset:
1617 yield log.node(r)
1624 yield log.node(r)
1618
1625
1619 def lookuplinkrev_func(revlog):
1626 def lookuplinkrev_func(revlog):
1620 def lookuplinkrev(n):
1627 def lookuplinkrev(n):
1621 return cl.node(revlog.linkrev(revlog.rev(n)))
1628 return cl.node(revlog.linkrev(revlog.rev(n)))
1622 return lookuplinkrev
1629 return lookuplinkrev
1623
1630
1624 def gengroup():
1631 def gengroup():
1625 '''yield a sequence of changegroup chunks (strings)'''
1632 '''yield a sequence of changegroup chunks (strings)'''
1626 # construct a list of all changed files
1633 # construct a list of all changed files
1627 changedfiles = set()
1634 changedfiles = set()
1628 mmfs = {}
1635 mmfs = {}
1629 collect = changegroup.collector(cl, mmfs, changedfiles)
1636 collect = changegroup.collector(cl, mmfs, changedfiles)
1630
1637
1631 for cnt, chnk in enumerate(cl.group(nodes, identity, collect)):
1638 for cnt, chnk in enumerate(cl.group(nodes, identity, collect)):
1632 # revlog.group yields three entries per node, so
1639 # revlog.group yields three entries per node, so
1633 # dividing by 3 gives an approximation of how many
1640 # dividing by 3 gives an approximation of how many
1634 # nodes have been processed.
1641 # nodes have been processed.
1635 self.ui.progress(_('bundling'), cnt / 3, unit=_('changesets'))
1642 self.ui.progress(_('bundling'), cnt / 3, unit=_('changesets'))
1636 yield chnk
1643 yield chnk
1637 changecount = cnt / 3
1644 changecount = cnt / 3
1638 self.ui.progress(_('bundling'), None)
1645 self.ui.progress(_('bundling'), None)
1639
1646
1640 mnfst = self.manifest
1647 mnfst = self.manifest
1641 nodeiter = gennodelst(mnfst)
1648 nodeiter = gennodelst(mnfst)
1642 efiles = {}
1649 efiles = {}
1643 for cnt, chnk in enumerate(mnfst.group(nodeiter,
1650 for cnt, chnk in enumerate(mnfst.group(nodeiter,
1644 lookuplinkrev_func(mnfst))):
1651 lookuplinkrev_func(mnfst))):
1645 if cnt % 3 == 1:
1652 if cnt % 3 == 1:
1646 mnode = chnk[:20]
1653 mnode = chnk[:20]
1647 efiles.update(mnfst.readdelta(mnode))
1654 efiles.update(mnfst.readdelta(mnode))
1648 # see above comment for why we divide by 3
1655 # see above comment for why we divide by 3
1649 self.ui.progress(_('bundling'), cnt / 3,
1656 self.ui.progress(_('bundling'), cnt / 3,
1650 unit=_('manifests'), total=changecount)
1657 unit=_('manifests'), total=changecount)
1651 yield chnk
1658 yield chnk
1652 efiles = len(efiles)
1659 efiles = len(efiles)
1653 self.ui.progress(_('bundling'), None)
1660 self.ui.progress(_('bundling'), None)
1654
1661
1655 for idx, fname in enumerate(sorted(changedfiles)):
1662 for idx, fname in enumerate(sorted(changedfiles)):
1656 filerevlog = self.file(fname)
1663 filerevlog = self.file(fname)
1657 if not len(filerevlog):
1664 if not len(filerevlog):
1658 raise util.Abort(_("empty or missing revlog for %s") % fname)
1665 raise util.Abort(_("empty or missing revlog for %s") % fname)
1659 nodeiter = gennodelst(filerevlog)
1666 nodeiter = gennodelst(filerevlog)
1660 nodeiter = list(nodeiter)
1667 nodeiter = list(nodeiter)
1661 if nodeiter:
1668 if nodeiter:
1662 yield changegroup.chunkheader(len(fname))
1669 yield changegroup.chunkheader(len(fname))
1663 yield fname
1670 yield fname
1664 lookup = lookuplinkrev_func(filerevlog)
1671 lookup = lookuplinkrev_func(filerevlog)
1665 for chnk in filerevlog.group(nodeiter, lookup):
1672 for chnk in filerevlog.group(nodeiter, lookup):
1666 self.ui.progress(
1673 self.ui.progress(
1667 _('bundling'), idx, item=fname,
1674 _('bundling'), idx, item=fname,
1668 total=efiles, unit=_('files'))
1675 total=efiles, unit=_('files'))
1669 yield chnk
1676 yield chnk
1670 self.ui.progress(_('bundling'), None)
1677 self.ui.progress(_('bundling'), None)
1671
1678
1672 yield changegroup.closechunk()
1679 yield changegroup.closechunk()
1673
1680
1674 if nodes:
1681 if nodes:
1675 self.hook('outgoing', node=hex(nodes[0]), source=source)
1682 self.hook('outgoing', node=hex(nodes[0]), source=source)
1676
1683
1677 return changegroup.unbundle10(util.chunkbuffer(gengroup()), 'UN')
1684 return changegroup.unbundle10(util.chunkbuffer(gengroup()), 'UN')
1678
1685
1679 def addchangegroup(self, source, srctype, url, emptyok=False, lock=None):
1686 def addchangegroup(self, source, srctype, url, emptyok=False, lock=None):
1680 """Add the changegroup returned by source.read() to this repo.
1687 """Add the changegroup returned by source.read() to this repo.
1681 srctype is a string like 'push', 'pull', or 'unbundle'. url is
1688 srctype is a string like 'push', 'pull', or 'unbundle'. url is
1682 the URL of the repo where this changegroup is coming from.
1689 the URL of the repo where this changegroup is coming from.
1683 If lock is not None, the function takes ownership of the lock
1690 If lock is not None, the function takes ownership of the lock
1684 and releases it after the changegroup is added.
1691 and releases it after the changegroup is added.
1685
1692
1686 Return an integer summarizing the change to this repo:
1693 Return an integer summarizing the change to this repo:
1687 - nothing changed or no source: 0
1694 - nothing changed or no source: 0
1688 - more heads than before: 1+added heads (2..n)
1695 - more heads than before: 1+added heads (2..n)
1689 - fewer heads than before: -1-removed heads (-2..-n)
1696 - fewer heads than before: -1-removed heads (-2..-n)
1690 - number of heads stays the same: 1
1697 - number of heads stays the same: 1
1691 """
1698 """
1692 def csmap(x):
1699 def csmap(x):
1693 self.ui.debug("add changeset %s\n" % short(x))
1700 self.ui.debug("add changeset %s\n" % short(x))
1694 return len(cl)
1701 return len(cl)
1695
1702
1696 def revmap(x):
1703 def revmap(x):
1697 return cl.rev(x)
1704 return cl.rev(x)
1698
1705
1699 if not source:
1706 if not source:
1700 return 0
1707 return 0
1701
1708
1702 self.hook('prechangegroup', throw=True, source=srctype, url=url)
1709 self.hook('prechangegroup', throw=True, source=srctype, url=url)
1703
1710
1704 changesets = files = revisions = 0
1711 changesets = files = revisions = 0
1705 efiles = set()
1712 efiles = set()
1706
1713
1707 # write changelog data to temp files so concurrent readers will not see
1714 # write changelog data to temp files so concurrent readers will not see
1708 # inconsistent view
1715 # inconsistent view
1709 cl = self.changelog
1716 cl = self.changelog
1710 cl.delayupdate()
1717 cl.delayupdate()
1711 oldheads = len(cl.heads())
1718 oldheads = len(cl.heads())
1712
1719
1713 tr = self.transaction("\n".join([srctype, urlmod.hidepassword(url)]))
1720 tr = self.transaction("\n".join([srctype, urlmod.hidepassword(url)]))
1714 try:
1721 try:
1715 trp = weakref.proxy(tr)
1722 trp = weakref.proxy(tr)
1716 # pull off the changeset group
1723 # pull off the changeset group
1717 self.ui.status(_("adding changesets\n"))
1724 self.ui.status(_("adding changesets\n"))
1718 clstart = len(cl)
1725 clstart = len(cl)
1719 class prog(object):
1726 class prog(object):
1720 step = _('changesets')
1727 step = _('changesets')
1721 count = 1
1728 count = 1
1722 ui = self.ui
1729 ui = self.ui
1723 total = None
1730 total = None
1724 def __call__(self):
1731 def __call__(self):
1725 self.ui.progress(self.step, self.count, unit=_('chunks'),
1732 self.ui.progress(self.step, self.count, unit=_('chunks'),
1726 total=self.total)
1733 total=self.total)
1727 self.count += 1
1734 self.count += 1
1728 pr = prog()
1735 pr = prog()
1729 source.callback = pr
1736 source.callback = pr
1730
1737
1731 if (cl.addgroup(source, csmap, trp) is None
1738 if (cl.addgroup(source, csmap, trp) is None
1732 and not emptyok):
1739 and not emptyok):
1733 raise util.Abort(_("received changelog group is empty"))
1740 raise util.Abort(_("received changelog group is empty"))
1734 clend = len(cl)
1741 clend = len(cl)
1735 changesets = clend - clstart
1742 changesets = clend - clstart
1736 for c in xrange(clstart, clend):
1743 for c in xrange(clstart, clend):
1737 efiles.update(self[c].files())
1744 efiles.update(self[c].files())
1738 efiles = len(efiles)
1745 efiles = len(efiles)
1739 self.ui.progress(_('changesets'), None)
1746 self.ui.progress(_('changesets'), None)
1740
1747
1741 # pull off the manifest group
1748 # pull off the manifest group
1742 self.ui.status(_("adding manifests\n"))
1749 self.ui.status(_("adding manifests\n"))
1743 pr.step = _('manifests')
1750 pr.step = _('manifests')
1744 pr.count = 1
1751 pr.count = 1
1745 pr.total = changesets # manifests <= changesets
1752 pr.total = changesets # manifests <= changesets
1746 # no need to check for empty manifest group here:
1753 # no need to check for empty manifest group here:
1747 # if the result of the merge of 1 and 2 is the same in 3 and 4,
1754 # if the result of the merge of 1 and 2 is the same in 3 and 4,
1748 # no new manifest will be created and the manifest group will
1755 # no new manifest will be created and the manifest group will
1749 # be empty during the pull
1756 # be empty during the pull
1750 self.manifest.addgroup(source, revmap, trp)
1757 self.manifest.addgroup(source, revmap, trp)
1751 self.ui.progress(_('manifests'), None)
1758 self.ui.progress(_('manifests'), None)
1752
1759
1753 needfiles = {}
1760 needfiles = {}
1754 if self.ui.configbool('server', 'validate', default=False):
1761 if self.ui.configbool('server', 'validate', default=False):
1755 # validate incoming csets have their manifests
1762 # validate incoming csets have their manifests
1756 for cset in xrange(clstart, clend):
1763 for cset in xrange(clstart, clend):
1757 mfest = self.changelog.read(self.changelog.node(cset))[0]
1764 mfest = self.changelog.read(self.changelog.node(cset))[0]
1758 mfest = self.manifest.readdelta(mfest)
1765 mfest = self.manifest.readdelta(mfest)
1759 # store file nodes we must see
1766 # store file nodes we must see
1760 for f, n in mfest.iteritems():
1767 for f, n in mfest.iteritems():
1761 needfiles.setdefault(f, set()).add(n)
1768 needfiles.setdefault(f, set()).add(n)
1762
1769
1763 # process the files
1770 # process the files
1764 self.ui.status(_("adding file changes\n"))
1771 self.ui.status(_("adding file changes\n"))
1765 pr.step = 'files'
1772 pr.step = 'files'
1766 pr.count = 1
1773 pr.count = 1
1767 pr.total = efiles
1774 pr.total = efiles
1768 source.callback = None
1775 source.callback = None
1769
1776
1770 while 1:
1777 while 1:
1771 f = source.chunk()
1778 f = source.chunk()
1772 if not f:
1779 if not f:
1773 break
1780 break
1774 self.ui.debug("adding %s revisions\n" % f)
1781 self.ui.debug("adding %s revisions\n" % f)
1775 pr()
1782 pr()
1776 fl = self.file(f)
1783 fl = self.file(f)
1777 o = len(fl)
1784 o = len(fl)
1778 if fl.addgroup(source, revmap, trp) is None:
1785 if fl.addgroup(source, revmap, trp) is None:
1779 raise util.Abort(_("received file revlog group is empty"))
1786 raise util.Abort(_("received file revlog group is empty"))
1780 revisions += len(fl) - o
1787 revisions += len(fl) - o
1781 files += 1
1788 files += 1
1782 if f in needfiles:
1789 if f in needfiles:
1783 needs = needfiles[f]
1790 needs = needfiles[f]
1784 for new in xrange(o, len(fl)):
1791 for new in xrange(o, len(fl)):
1785 n = fl.node(new)
1792 n = fl.node(new)
1786 if n in needs:
1793 if n in needs:
1787 needs.remove(n)
1794 needs.remove(n)
1788 if not needs:
1795 if not needs:
1789 del needfiles[f]
1796 del needfiles[f]
1790 self.ui.progress(_('files'), None)
1797 self.ui.progress(_('files'), None)
1791
1798
1792 for f, needs in needfiles.iteritems():
1799 for f, needs in needfiles.iteritems():
1793 fl = self.file(f)
1800 fl = self.file(f)
1794 for n in needs:
1801 for n in needs:
1795 try:
1802 try:
1796 fl.rev(n)
1803 fl.rev(n)
1797 except error.LookupError:
1804 except error.LookupError:
1798 raise util.Abort(
1805 raise util.Abort(
1799 _('missing file data for %s:%s - run hg verify') %
1806 _('missing file data for %s:%s - run hg verify') %
1800 (f, hex(n)))
1807 (f, hex(n)))
1801
1808
1802 newheads = len(cl.heads())
1809 newheads = len(cl.heads())
1803 heads = ""
1810 heads = ""
1804 if oldheads and newheads != oldheads:
1811 if oldheads and newheads != oldheads:
1805 heads = _(" (%+d heads)") % (newheads - oldheads)
1812 heads = _(" (%+d heads)") % (newheads - oldheads)
1806
1813
1807 self.ui.status(_("added %d changesets"
1814 self.ui.status(_("added %d changesets"
1808 " with %d changes to %d files%s\n")
1815 " with %d changes to %d files%s\n")
1809 % (changesets, revisions, files, heads))
1816 % (changesets, revisions, files, heads))
1810
1817
1811 if changesets > 0:
1818 if changesets > 0:
1812 p = lambda: cl.writepending() and self.root or ""
1819 p = lambda: cl.writepending() and self.root or ""
1813 self.hook('pretxnchangegroup', throw=True,
1820 self.hook('pretxnchangegroup', throw=True,
1814 node=hex(cl.node(clstart)), source=srctype,
1821 node=hex(cl.node(clstart)), source=srctype,
1815 url=url, pending=p)
1822 url=url, pending=p)
1816
1823
1817 # make changelog see real files again
1824 # make changelog see real files again
1818 cl.finalize(trp)
1825 cl.finalize(trp)
1819
1826
1820 tr.close()
1827 tr.close()
1821 finally:
1828 finally:
1822 tr.release()
1829 tr.release()
1823 if lock:
1830 if lock:
1824 lock.release()
1831 lock.release()
1825
1832
1826 if changesets > 0:
1833 if changesets > 0:
1827 # forcefully update the on-disk branch cache
1834 # forcefully update the on-disk branch cache
1828 self.ui.debug("updating the branch cache\n")
1835 self.ui.debug("updating the branch cache\n")
1829 self.updatebranchcache()
1836 self.updatebranchcache()
1830 self.hook("changegroup", node=hex(cl.node(clstart)),
1837 self.hook("changegroup", node=hex(cl.node(clstart)),
1831 source=srctype, url=url)
1838 source=srctype, url=url)
1832
1839
1833 for i in xrange(clstart, clend):
1840 for i in xrange(clstart, clend):
1834 self.hook("incoming", node=hex(cl.node(i)),
1841 self.hook("incoming", node=hex(cl.node(i)),
1835 source=srctype, url=url)
1842 source=srctype, url=url)
1836
1843
1837 # never return 0 here:
1844 # never return 0 here:
1838 if newheads < oldheads:
1845 if newheads < oldheads:
1839 return newheads - oldheads - 1
1846 return newheads - oldheads - 1
1840 else:
1847 else:
1841 return newheads - oldheads + 1
1848 return newheads - oldheads + 1
1842
1849
1843
1850
1844 def stream_in(self, remote, requirements):
1851 def stream_in(self, remote, requirements):
1845 fp = remote.stream_out()
1852 fp = remote.stream_out()
1846 l = fp.readline()
1853 l = fp.readline()
1847 try:
1854 try:
1848 resp = int(l)
1855 resp = int(l)
1849 except ValueError:
1856 except ValueError:
1850 raise error.ResponseError(
1857 raise error.ResponseError(
1851 _('Unexpected response from remote server:'), l)
1858 _('Unexpected response from remote server:'), l)
1852 if resp == 1:
1859 if resp == 1:
1853 raise util.Abort(_('operation forbidden by server'))
1860 raise util.Abort(_('operation forbidden by server'))
1854 elif resp == 2:
1861 elif resp == 2:
1855 raise util.Abort(_('locking the remote repository failed'))
1862 raise util.Abort(_('locking the remote repository failed'))
1856 elif resp != 0:
1863 elif resp != 0:
1857 raise util.Abort(_('the server sent an unknown error code'))
1864 raise util.Abort(_('the server sent an unknown error code'))
1858 self.ui.status(_('streaming all changes\n'))
1865 self.ui.status(_('streaming all changes\n'))
1859 l = fp.readline()
1866 l = fp.readline()
1860 try:
1867 try:
1861 total_files, total_bytes = map(int, l.split(' ', 1))
1868 total_files, total_bytes = map(int, l.split(' ', 1))
1862 except (ValueError, TypeError):
1869 except (ValueError, TypeError):
1863 raise error.ResponseError(
1870 raise error.ResponseError(
1864 _('Unexpected response from remote server:'), l)
1871 _('Unexpected response from remote server:'), l)
1865 self.ui.status(_('%d files to transfer, %s of data\n') %
1872 self.ui.status(_('%d files to transfer, %s of data\n') %
1866 (total_files, util.bytecount(total_bytes)))
1873 (total_files, util.bytecount(total_bytes)))
1867 start = time.time()
1874 start = time.time()
1868 for i in xrange(total_files):
1875 for i in xrange(total_files):
1869 # XXX doesn't support '\n' or '\r' in filenames
1876 # XXX doesn't support '\n' or '\r' in filenames
1870 l = fp.readline()
1877 l = fp.readline()
1871 try:
1878 try:
1872 name, size = l.split('\0', 1)
1879 name, size = l.split('\0', 1)
1873 size = int(size)
1880 size = int(size)
1874 except (ValueError, TypeError):
1881 except (ValueError, TypeError):
1875 raise error.ResponseError(
1882 raise error.ResponseError(
1876 _('Unexpected response from remote server:'), l)
1883 _('Unexpected response from remote server:'), l)
1877 self.ui.debug('adding %s (%s)\n' % (name, util.bytecount(size)))
1884 self.ui.debug('adding %s (%s)\n' % (name, util.bytecount(size)))
1878 # for backwards compat, name was partially encoded
1885 # for backwards compat, name was partially encoded
1879 ofp = self.sopener(store.decodedir(name), 'w')
1886 ofp = self.sopener(store.decodedir(name), 'w')
1880 for chunk in util.filechunkiter(fp, limit=size):
1887 for chunk in util.filechunkiter(fp, limit=size):
1881 ofp.write(chunk)
1888 ofp.write(chunk)
1882 ofp.close()
1889 ofp.close()
1883 elapsed = time.time() - start
1890 elapsed = time.time() - start
1884 if elapsed <= 0:
1891 if elapsed <= 0:
1885 elapsed = 0.001
1892 elapsed = 0.001
1886 self.ui.status(_('transferred %s in %.1f seconds (%s/sec)\n') %
1893 self.ui.status(_('transferred %s in %.1f seconds (%s/sec)\n') %
1887 (util.bytecount(total_bytes), elapsed,
1894 (util.bytecount(total_bytes), elapsed,
1888 util.bytecount(total_bytes / elapsed)))
1895 util.bytecount(total_bytes / elapsed)))
1889
1896
1890 # new requirements = old non-format requirements + new format-related
1897 # new requirements = old non-format requirements + new format-related
1891 # requirements from the streamed-in repository
1898 # requirements from the streamed-in repository
1892 requirements.update(set(self.requirements) - self.supportedformats)
1899 requirements.update(set(self.requirements) - self.supportedformats)
1893 self._applyrequirements(requirements)
1900 self._applyrequirements(requirements)
1894 self._writerequirements()
1901 self._writerequirements()
1895
1902
1896 self.invalidate()
1903 self.invalidate()
1897 return len(self.heads()) + 1
1904 return len(self.heads()) + 1
1898
1905
1899 def clone(self, remote, heads=[], stream=False):
1906 def clone(self, remote, heads=[], stream=False):
1900 '''clone remote repository.
1907 '''clone remote repository.
1901
1908
1902 keyword arguments:
1909 keyword arguments:
1903 heads: list of revs to clone (forces use of pull)
1910 heads: list of revs to clone (forces use of pull)
1904 stream: use streaming clone if possible'''
1911 stream: use streaming clone if possible'''
1905
1912
1906 # now, all clients that can request uncompressed clones can
1913 # now, all clients that can request uncompressed clones can
1907 # read repo formats supported by all servers that can serve
1914 # read repo formats supported by all servers that can serve
1908 # them.
1915 # them.
1909
1916
1910 # if revlog format changes, client will have to check version
1917 # if revlog format changes, client will have to check version
1911 # and format flags on "stream" capability, and use
1918 # and format flags on "stream" capability, and use
1912 # uncompressed only if compatible.
1919 # uncompressed only if compatible.
1913
1920
1914 if stream and not heads:
1921 if stream and not heads:
1915 # 'stream' means remote revlog format is revlogv1 only
1922 # 'stream' means remote revlog format is revlogv1 only
1916 if remote.capable('stream'):
1923 if remote.capable('stream'):
1917 return self.stream_in(remote, set(('revlogv1',)))
1924 return self.stream_in(remote, set(('revlogv1',)))
1918 # otherwise, 'streamreqs' contains the remote revlog format
1925 # otherwise, 'streamreqs' contains the remote revlog format
1919 streamreqs = remote.capable('streamreqs')
1926 streamreqs = remote.capable('streamreqs')
1920 if streamreqs:
1927 if streamreqs:
1921 streamreqs = set(streamreqs.split(','))
1928 streamreqs = set(streamreqs.split(','))
1922 # if we support it, stream in and adjust our requirements
1929 # if we support it, stream in and adjust our requirements
1923 if not streamreqs - self.supportedformats:
1930 if not streamreqs - self.supportedformats:
1924 return self.stream_in(remote, streamreqs)
1931 return self.stream_in(remote, streamreqs)
1925 return self.pull(remote, heads)
1932 return self.pull(remote, heads)
1926
1933
1927 def pushkey(self, namespace, key, old, new):
1934 def pushkey(self, namespace, key, old, new):
1928 return pushkey.push(self, namespace, key, old, new)
1935 return pushkey.push(self, namespace, key, old, new)
1929
1936
1930 def listkeys(self, namespace):
1937 def listkeys(self, namespace):
1931 return pushkey.list(self, namespace)
1938 return pushkey.list(self, namespace)
1932
1939
1933 # used to avoid circular references so destructors work
1940 # used to avoid circular references so destructors work
1934 def aftertrans(files):
1941 def aftertrans(files):
1935 renamefiles = [tuple(t) for t in files]
1942 renamefiles = [tuple(t) for t in files]
1936 def a():
1943 def a():
1937 for src, dest in renamefiles:
1944 for src, dest in renamefiles:
1938 util.rename(src, dest)
1945 util.rename(src, dest)
1939 return a
1946 return a
1940
1947
1941 def instance(ui, path, create):
1948 def instance(ui, path, create):
1942 return localrepository(ui, util.drop_scheme('file', path), create)
1949 return localrepository(ui, util.drop_scheme('file', path), create)
1943
1950
1944 def islocal(path):
1951 def islocal(path):
1945 return True
1952 return True
General Comments 0
You need to be logged in to leave comments. Login now