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