##// END OF EJS Templates
context: let workingctx.date(), .user() and description() be overriden
Patrick Mezard -
r6709:f84f507c default
parent child Browse files
Show More
@@ -1,663 +1,675 b''
1 # context.py - changeset and file context objects for mercurial
1 # context.py - changeset and file context objects for mercurial
2 #
2 #
3 # Copyright 2006, 2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2006, 2007 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms
5 # This software may be used and distributed according to the terms
6 # of the GNU General Public License, incorporated herein by reference.
6 # of the GNU General Public License, incorporated herein by reference.
7
7
8 from node import nullid, nullrev, short
8 from node import nullid, nullrev, short
9 from i18n import _
9 from i18n import _
10 import ancestor, bdiff, revlog, util, os, errno
10 import ancestor, bdiff, revlog, util, os, errno
11
11
12 class changectx(object):
12 class changectx(object):
13 """A changecontext object makes access to data related to a particular
13 """A changecontext object makes access to data related to a particular
14 changeset convenient."""
14 changeset convenient."""
15 def __init__(self, repo, changeid=None):
15 def __init__(self, repo, changeid=None):
16 """changeid is a revision number, node, or tag"""
16 """changeid is a revision number, node, or tag"""
17 self._repo = repo
17 self._repo = repo
18
18
19 if not changeid and changeid != 0:
19 if not changeid and changeid != 0:
20 p1, p2 = self._repo.dirstate.parents()
20 p1, p2 = self._repo.dirstate.parents()
21 self._rev = self._repo.changelog.rev(p1)
21 self._rev = self._repo.changelog.rev(p1)
22 if self._rev == -1:
22 if self._rev == -1:
23 changeid = 'tip'
23 changeid = 'tip'
24 else:
24 else:
25 self._node = p1
25 self._node = p1
26 return
26 return
27
27
28 self._node = self._repo.lookup(changeid)
28 self._node = self._repo.lookup(changeid)
29 self._rev = self._repo.changelog.rev(self._node)
29 self._rev = self._repo.changelog.rev(self._node)
30
30
31 def __str__(self):
31 def __str__(self):
32 return short(self.node())
32 return short(self.node())
33
33
34 def __repr__(self):
34 def __repr__(self):
35 return "<changectx %s>" % str(self)
35 return "<changectx %s>" % str(self)
36
36
37 def __hash__(self):
37 def __hash__(self):
38 try:
38 try:
39 return hash(self._rev)
39 return hash(self._rev)
40 except AttributeError:
40 except AttributeError:
41 return id(self)
41 return id(self)
42
42
43 def __eq__(self, other):
43 def __eq__(self, other):
44 try:
44 try:
45 return self._rev == other._rev
45 return self._rev == other._rev
46 except AttributeError:
46 except AttributeError:
47 return False
47 return False
48
48
49 def __ne__(self, other):
49 def __ne__(self, other):
50 return not (self == other)
50 return not (self == other)
51
51
52 def __nonzero__(self):
52 def __nonzero__(self):
53 return self._rev != nullrev
53 return self._rev != nullrev
54
54
55 def __getattr__(self, name):
55 def __getattr__(self, name):
56 if name == '_changeset':
56 if name == '_changeset':
57 self._changeset = self._repo.changelog.read(self.node())
57 self._changeset = self._repo.changelog.read(self.node())
58 return self._changeset
58 return self._changeset
59 elif name == '_manifest':
59 elif name == '_manifest':
60 self._manifest = self._repo.manifest.read(self._changeset[0])
60 self._manifest = self._repo.manifest.read(self._changeset[0])
61 return self._manifest
61 return self._manifest
62 elif name == '_manifestdelta':
62 elif name == '_manifestdelta':
63 md = self._repo.manifest.readdelta(self._changeset[0])
63 md = self._repo.manifest.readdelta(self._changeset[0])
64 self._manifestdelta = md
64 self._manifestdelta = md
65 return self._manifestdelta
65 return self._manifestdelta
66 else:
66 else:
67 raise AttributeError, name
67 raise AttributeError, name
68
68
69 def __contains__(self, key):
69 def __contains__(self, key):
70 return key in self._manifest
70 return key in self._manifest
71
71
72 def __getitem__(self, key):
72 def __getitem__(self, key):
73 return self.filectx(key)
73 return self.filectx(key)
74
74
75 def __iter__(self):
75 def __iter__(self):
76 a = self._manifest.keys()
76 a = self._manifest.keys()
77 a.sort()
77 a.sort()
78 for f in a:
78 for f in a:
79 yield f
79 yield f
80
80
81 def changeset(self): return self._changeset
81 def changeset(self): return self._changeset
82 def manifest(self): return self._manifest
82 def manifest(self): return self._manifest
83
83
84 def rev(self): return self._rev
84 def rev(self): return self._rev
85 def node(self): return self._node
85 def node(self): return self._node
86 def user(self): return self._changeset[1]
86 def user(self): return self._changeset[1]
87 def date(self): return self._changeset[2]
87 def date(self): return self._changeset[2]
88 def files(self): return self._changeset[3]
88 def files(self): return self._changeset[3]
89 def description(self): return self._changeset[4]
89 def description(self): return self._changeset[4]
90 def branch(self): return self._changeset[5].get("branch")
90 def branch(self): return self._changeset[5].get("branch")
91 def extra(self): return self._changeset[5]
91 def extra(self): return self._changeset[5]
92 def tags(self): return self._repo.nodetags(self._node)
92 def tags(self): return self._repo.nodetags(self._node)
93
93
94 def parents(self):
94 def parents(self):
95 """return contexts for each parent changeset"""
95 """return contexts for each parent changeset"""
96 p = self._repo.changelog.parents(self._node)
96 p = self._repo.changelog.parents(self._node)
97 return [changectx(self._repo, x) for x in p]
97 return [changectx(self._repo, x) for x in p]
98
98
99 def children(self):
99 def children(self):
100 """return contexts for each child changeset"""
100 """return contexts for each child changeset"""
101 c = self._repo.changelog.children(self._node)
101 c = self._repo.changelog.children(self._node)
102 return [changectx(self._repo, x) for x in c]
102 return [changectx(self._repo, x) for x in c]
103
103
104 def _fileinfo(self, path):
104 def _fileinfo(self, path):
105 if '_manifest' in self.__dict__:
105 if '_manifest' in self.__dict__:
106 try:
106 try:
107 return self._manifest[path], self._manifest.flags(path)
107 return self._manifest[path], self._manifest.flags(path)
108 except KeyError:
108 except KeyError:
109 raise revlog.LookupError(self._node, path,
109 raise revlog.LookupError(self._node, path,
110 _('not found in manifest'))
110 _('not found in manifest'))
111 if '_manifestdelta' in self.__dict__ or path in self.files():
111 if '_manifestdelta' in self.__dict__ or path in self.files():
112 if path in self._manifestdelta:
112 if path in self._manifestdelta:
113 return self._manifestdelta[path], self._manifestdelta.flags(path)
113 return self._manifestdelta[path], self._manifestdelta.flags(path)
114 node, flag = self._repo.manifest.find(self._changeset[0], path)
114 node, flag = self._repo.manifest.find(self._changeset[0], path)
115 if not node:
115 if not node:
116 raise revlog.LookupError(self._node, path,
116 raise revlog.LookupError(self._node, path,
117 _('not found in manifest'))
117 _('not found in manifest'))
118
118
119 return node, flag
119 return node, flag
120
120
121 def filenode(self, path):
121 def filenode(self, path):
122 return self._fileinfo(path)[0]
122 return self._fileinfo(path)[0]
123
123
124 def fileflags(self, path):
124 def fileflags(self, path):
125 try:
125 try:
126 return self._fileinfo(path)[1]
126 return self._fileinfo(path)[1]
127 except revlog.LookupError:
127 except revlog.LookupError:
128 return ''
128 return ''
129
129
130 def filectx(self, path, fileid=None, filelog=None):
130 def filectx(self, path, fileid=None, filelog=None):
131 """get a file context from this changeset"""
131 """get a file context from this changeset"""
132 if fileid is None:
132 if fileid is None:
133 fileid = self.filenode(path)
133 fileid = self.filenode(path)
134 return filectx(self._repo, path, fileid=fileid,
134 return filectx(self._repo, path, fileid=fileid,
135 changectx=self, filelog=filelog)
135 changectx=self, filelog=filelog)
136
136
137 def filectxs(self):
137 def filectxs(self):
138 """generate a file context for each file in this changeset's
138 """generate a file context for each file in this changeset's
139 manifest"""
139 manifest"""
140 mf = self.manifest()
140 mf = self.manifest()
141 m = mf.keys()
141 m = mf.keys()
142 m.sort()
142 m.sort()
143 for f in m:
143 for f in m:
144 yield self.filectx(f, fileid=mf[f])
144 yield self.filectx(f, fileid=mf[f])
145
145
146 def ancestor(self, c2):
146 def ancestor(self, c2):
147 """
147 """
148 return the ancestor context of self and c2
148 return the ancestor context of self and c2
149 """
149 """
150 n = self._repo.changelog.ancestor(self._node, c2._node)
150 n = self._repo.changelog.ancestor(self._node, c2._node)
151 return changectx(self._repo, n)
151 return changectx(self._repo, n)
152
152
153 class filectx(object):
153 class filectx(object):
154 """A filecontext object makes access to data related to a particular
154 """A filecontext object makes access to data related to a particular
155 filerevision convenient."""
155 filerevision convenient."""
156 def __init__(self, repo, path, changeid=None, fileid=None,
156 def __init__(self, repo, path, changeid=None, fileid=None,
157 filelog=None, changectx=None):
157 filelog=None, changectx=None):
158 """changeid can be a changeset revision, node, or tag.
158 """changeid can be a changeset revision, node, or tag.
159 fileid can be a file revision or node."""
159 fileid can be a file revision or node."""
160 self._repo = repo
160 self._repo = repo
161 self._path = path
161 self._path = path
162
162
163 assert (changeid is not None
163 assert (changeid is not None
164 or fileid is not None
164 or fileid is not None
165 or changectx is not None)
165 or changectx is not None)
166
166
167 if filelog:
167 if filelog:
168 self._filelog = filelog
168 self._filelog = filelog
169
169
170 if changeid is not None:
170 if changeid is not None:
171 self._changeid = changeid
171 self._changeid = changeid
172 if changectx is not None:
172 if changectx is not None:
173 self._changectx = changectx
173 self._changectx = changectx
174 if fileid is not None:
174 if fileid is not None:
175 self._fileid = fileid
175 self._fileid = fileid
176
176
177 def __getattr__(self, name):
177 def __getattr__(self, name):
178 if name == '_changectx':
178 if name == '_changectx':
179 self._changectx = changectx(self._repo, self._changeid)
179 self._changectx = changectx(self._repo, self._changeid)
180 return self._changectx
180 return self._changectx
181 elif name == '_filelog':
181 elif name == '_filelog':
182 self._filelog = self._repo.file(self._path)
182 self._filelog = self._repo.file(self._path)
183 return self._filelog
183 return self._filelog
184 elif name == '_changeid':
184 elif name == '_changeid':
185 if '_changectx' in self.__dict__:
185 if '_changectx' in self.__dict__:
186 self._changeid = self._changectx.rev()
186 self._changeid = self._changectx.rev()
187 else:
187 else:
188 self._changeid = self._filelog.linkrev(self._filenode)
188 self._changeid = self._filelog.linkrev(self._filenode)
189 return self._changeid
189 return self._changeid
190 elif name == '_filenode':
190 elif name == '_filenode':
191 if '_fileid' in self.__dict__:
191 if '_fileid' in self.__dict__:
192 self._filenode = self._filelog.lookup(self._fileid)
192 self._filenode = self._filelog.lookup(self._fileid)
193 else:
193 else:
194 self._filenode = self._changectx.filenode(self._path)
194 self._filenode = self._changectx.filenode(self._path)
195 return self._filenode
195 return self._filenode
196 elif name == '_filerev':
196 elif name == '_filerev':
197 self._filerev = self._filelog.rev(self._filenode)
197 self._filerev = self._filelog.rev(self._filenode)
198 return self._filerev
198 return self._filerev
199 elif name == '_repopath':
199 elif name == '_repopath':
200 self._repopath = self._path
200 self._repopath = self._path
201 return self._repopath
201 return self._repopath
202 else:
202 else:
203 raise AttributeError, name
203 raise AttributeError, name
204
204
205 def __nonzero__(self):
205 def __nonzero__(self):
206 try:
206 try:
207 n = self._filenode
207 n = self._filenode
208 return True
208 return True
209 except revlog.LookupError:
209 except revlog.LookupError:
210 # file is missing
210 # file is missing
211 return False
211 return False
212
212
213 def __str__(self):
213 def __str__(self):
214 return "%s@%s" % (self.path(), short(self.node()))
214 return "%s@%s" % (self.path(), short(self.node()))
215
215
216 def __repr__(self):
216 def __repr__(self):
217 return "<filectx %s>" % str(self)
217 return "<filectx %s>" % str(self)
218
218
219 def __hash__(self):
219 def __hash__(self):
220 try:
220 try:
221 return hash((self._path, self._fileid))
221 return hash((self._path, self._fileid))
222 except AttributeError:
222 except AttributeError:
223 return id(self)
223 return id(self)
224
224
225 def __eq__(self, other):
225 def __eq__(self, other):
226 try:
226 try:
227 return (self._path == other._path
227 return (self._path == other._path
228 and self._fileid == other._fileid)
228 and self._fileid == other._fileid)
229 except AttributeError:
229 except AttributeError:
230 return False
230 return False
231
231
232 def __ne__(self, other):
232 def __ne__(self, other):
233 return not (self == other)
233 return not (self == other)
234
234
235 def filectx(self, fileid):
235 def filectx(self, fileid):
236 '''opens an arbitrary revision of the file without
236 '''opens an arbitrary revision of the file without
237 opening a new filelog'''
237 opening a new filelog'''
238 return filectx(self._repo, self._path, fileid=fileid,
238 return filectx(self._repo, self._path, fileid=fileid,
239 filelog=self._filelog)
239 filelog=self._filelog)
240
240
241 def filerev(self): return self._filerev
241 def filerev(self): return self._filerev
242 def filenode(self): return self._filenode
242 def filenode(self): return self._filenode
243 def fileflags(self): return self._changectx.fileflags(self._path)
243 def fileflags(self): return self._changectx.fileflags(self._path)
244 def isexec(self): return 'x' in self.fileflags()
244 def isexec(self): return 'x' in self.fileflags()
245 def islink(self): return 'l' in self.fileflags()
245 def islink(self): return 'l' in self.fileflags()
246 def filelog(self): return self._filelog
246 def filelog(self): return self._filelog
247
247
248 def rev(self):
248 def rev(self):
249 if '_changectx' in self.__dict__:
249 if '_changectx' in self.__dict__:
250 return self._changectx.rev()
250 return self._changectx.rev()
251 if '_changeid' in self.__dict__:
251 if '_changeid' in self.__dict__:
252 return self._changectx.rev()
252 return self._changectx.rev()
253 return self._filelog.linkrev(self._filenode)
253 return self._filelog.linkrev(self._filenode)
254
254
255 def linkrev(self): return self._filelog.linkrev(self._filenode)
255 def linkrev(self): return self._filelog.linkrev(self._filenode)
256 def node(self): return self._changectx.node()
256 def node(self): return self._changectx.node()
257 def user(self): return self._changectx.user()
257 def user(self): return self._changectx.user()
258 def date(self): return self._changectx.date()
258 def date(self): return self._changectx.date()
259 def files(self): return self._changectx.files()
259 def files(self): return self._changectx.files()
260 def description(self): return self._changectx.description()
260 def description(self): return self._changectx.description()
261 def branch(self): return self._changectx.branch()
261 def branch(self): return self._changectx.branch()
262 def manifest(self): return self._changectx.manifest()
262 def manifest(self): return self._changectx.manifest()
263 def changectx(self): return self._changectx
263 def changectx(self): return self._changectx
264
264
265 def data(self): return self._filelog.read(self._filenode)
265 def data(self): return self._filelog.read(self._filenode)
266 def path(self): return self._path
266 def path(self): return self._path
267 def size(self): return self._filelog.size(self._filerev)
267 def size(self): return self._filelog.size(self._filerev)
268
268
269 def cmp(self, text): return self._filelog.cmp(self._filenode, text)
269 def cmp(self, text): return self._filelog.cmp(self._filenode, text)
270
270
271 def renamed(self):
271 def renamed(self):
272 """check if file was actually renamed in this changeset revision
272 """check if file was actually renamed in this changeset revision
273
273
274 If rename logged in file revision, we report copy for changeset only
274 If rename logged in file revision, we report copy for changeset only
275 if file revisions linkrev points back to the changeset in question
275 if file revisions linkrev points back to the changeset in question
276 or both changeset parents contain different file revisions.
276 or both changeset parents contain different file revisions.
277 """
277 """
278
278
279 renamed = self._filelog.renamed(self._filenode)
279 renamed = self._filelog.renamed(self._filenode)
280 if not renamed:
280 if not renamed:
281 return renamed
281 return renamed
282
282
283 if self.rev() == self.linkrev():
283 if self.rev() == self.linkrev():
284 return renamed
284 return renamed
285
285
286 name = self.path()
286 name = self.path()
287 fnode = self._filenode
287 fnode = self._filenode
288 for p in self._changectx.parents():
288 for p in self._changectx.parents():
289 try:
289 try:
290 if fnode == p.filenode(name):
290 if fnode == p.filenode(name):
291 return None
291 return None
292 except revlog.LookupError:
292 except revlog.LookupError:
293 pass
293 pass
294 return renamed
294 return renamed
295
295
296 def parents(self):
296 def parents(self):
297 p = self._path
297 p = self._path
298 fl = self._filelog
298 fl = self._filelog
299 pl = [(p, n, fl) for n in self._filelog.parents(self._filenode)]
299 pl = [(p, n, fl) for n in self._filelog.parents(self._filenode)]
300
300
301 r = self._filelog.renamed(self._filenode)
301 r = self._filelog.renamed(self._filenode)
302 if r:
302 if r:
303 pl[0] = (r[0], r[1], None)
303 pl[0] = (r[0], r[1], None)
304
304
305 return [filectx(self._repo, p, fileid=n, filelog=l)
305 return [filectx(self._repo, p, fileid=n, filelog=l)
306 for p,n,l in pl if n != nullid]
306 for p,n,l in pl if n != nullid]
307
307
308 def children(self):
308 def children(self):
309 # hard for renames
309 # hard for renames
310 c = self._filelog.children(self._filenode)
310 c = self._filelog.children(self._filenode)
311 return [filectx(self._repo, self._path, fileid=x,
311 return [filectx(self._repo, self._path, fileid=x,
312 filelog=self._filelog) for x in c]
312 filelog=self._filelog) for x in c]
313
313
314 def annotate(self, follow=False, linenumber=None):
314 def annotate(self, follow=False, linenumber=None):
315 '''returns a list of tuples of (ctx, line) for each line
315 '''returns a list of tuples of (ctx, line) for each line
316 in the file, where ctx is the filectx of the node where
316 in the file, where ctx is the filectx of the node where
317 that line was last changed.
317 that line was last changed.
318 This returns tuples of ((ctx, linenumber), line) for each line,
318 This returns tuples of ((ctx, linenumber), line) for each line,
319 if "linenumber" parameter is NOT "None".
319 if "linenumber" parameter is NOT "None".
320 In such tuples, linenumber means one at the first appearance
320 In such tuples, linenumber means one at the first appearance
321 in the managed file.
321 in the managed file.
322 To reduce annotation cost,
322 To reduce annotation cost,
323 this returns fixed value(False is used) as linenumber,
323 this returns fixed value(False is used) as linenumber,
324 if "linenumber" parameter is "False".'''
324 if "linenumber" parameter is "False".'''
325
325
326 def decorate_compat(text, rev):
326 def decorate_compat(text, rev):
327 return ([rev] * len(text.splitlines()), text)
327 return ([rev] * len(text.splitlines()), text)
328
328
329 def without_linenumber(text, rev):
329 def without_linenumber(text, rev):
330 return ([(rev, False)] * len(text.splitlines()), text)
330 return ([(rev, False)] * len(text.splitlines()), text)
331
331
332 def with_linenumber(text, rev):
332 def with_linenumber(text, rev):
333 size = len(text.splitlines())
333 size = len(text.splitlines())
334 return ([(rev, i) for i in xrange(1, size + 1)], text)
334 return ([(rev, i) for i in xrange(1, size + 1)], text)
335
335
336 decorate = (((linenumber is None) and decorate_compat) or
336 decorate = (((linenumber is None) and decorate_compat) or
337 (linenumber and with_linenumber) or
337 (linenumber and with_linenumber) or
338 without_linenumber)
338 without_linenumber)
339
339
340 def pair(parent, child):
340 def pair(parent, child):
341 for a1, a2, b1, b2 in bdiff.blocks(parent[1], child[1]):
341 for a1, a2, b1, b2 in bdiff.blocks(parent[1], child[1]):
342 child[0][b1:b2] = parent[0][a1:a2]
342 child[0][b1:b2] = parent[0][a1:a2]
343 return child
343 return child
344
344
345 getlog = util.cachefunc(lambda x: self._repo.file(x))
345 getlog = util.cachefunc(lambda x: self._repo.file(x))
346 def getctx(path, fileid):
346 def getctx(path, fileid):
347 log = path == self._path and self._filelog or getlog(path)
347 log = path == self._path and self._filelog or getlog(path)
348 return filectx(self._repo, path, fileid=fileid, filelog=log)
348 return filectx(self._repo, path, fileid=fileid, filelog=log)
349 getctx = util.cachefunc(getctx)
349 getctx = util.cachefunc(getctx)
350
350
351 def parents(f):
351 def parents(f):
352 # we want to reuse filectx objects as much as possible
352 # we want to reuse filectx objects as much as possible
353 p = f._path
353 p = f._path
354 if f._filerev is None: # working dir
354 if f._filerev is None: # working dir
355 pl = [(n.path(), n.filerev()) for n in f.parents()]
355 pl = [(n.path(), n.filerev()) for n in f.parents()]
356 else:
356 else:
357 pl = [(p, n) for n in f._filelog.parentrevs(f._filerev)]
357 pl = [(p, n) for n in f._filelog.parentrevs(f._filerev)]
358
358
359 if follow:
359 if follow:
360 r = f.renamed()
360 r = f.renamed()
361 if r:
361 if r:
362 pl[0] = (r[0], getlog(r[0]).rev(r[1]))
362 pl[0] = (r[0], getlog(r[0]).rev(r[1]))
363
363
364 return [getctx(p, n) for p, n in pl if n != nullrev]
364 return [getctx(p, n) for p, n in pl if n != nullrev]
365
365
366 # use linkrev to find the first changeset where self appeared
366 # use linkrev to find the first changeset where self appeared
367 if self.rev() != self.linkrev():
367 if self.rev() != self.linkrev():
368 base = self.filectx(self.filerev())
368 base = self.filectx(self.filerev())
369 else:
369 else:
370 base = self
370 base = self
371
371
372 # find all ancestors
372 # find all ancestors
373 needed = {base: 1}
373 needed = {base: 1}
374 visit = [base]
374 visit = [base]
375 files = [base._path]
375 files = [base._path]
376 while visit:
376 while visit:
377 f = visit.pop(0)
377 f = visit.pop(0)
378 for p in parents(f):
378 for p in parents(f):
379 if p not in needed:
379 if p not in needed:
380 needed[p] = 1
380 needed[p] = 1
381 visit.append(p)
381 visit.append(p)
382 if p._path not in files:
382 if p._path not in files:
383 files.append(p._path)
383 files.append(p._path)
384 else:
384 else:
385 # count how many times we'll use this
385 # count how many times we'll use this
386 needed[p] += 1
386 needed[p] += 1
387
387
388 # sort by revision (per file) which is a topological order
388 # sort by revision (per file) which is a topological order
389 visit = []
389 visit = []
390 for f in files:
390 for f in files:
391 fn = [(n.rev(), n) for n in needed.keys() if n._path == f]
391 fn = [(n.rev(), n) for n in needed.keys() if n._path == f]
392 visit.extend(fn)
392 visit.extend(fn)
393 visit.sort()
393 visit.sort()
394 hist = {}
394 hist = {}
395
395
396 for r, f in visit:
396 for r, f in visit:
397 curr = decorate(f.data(), f)
397 curr = decorate(f.data(), f)
398 for p in parents(f):
398 for p in parents(f):
399 if p != nullid:
399 if p != nullid:
400 curr = pair(hist[p], curr)
400 curr = pair(hist[p], curr)
401 # trim the history of unneeded revs
401 # trim the history of unneeded revs
402 needed[p] -= 1
402 needed[p] -= 1
403 if not needed[p]:
403 if not needed[p]:
404 del hist[p]
404 del hist[p]
405 hist[f] = curr
405 hist[f] = curr
406
406
407 return zip(hist[f][0], hist[f][1].splitlines(1))
407 return zip(hist[f][0], hist[f][1].splitlines(1))
408
408
409 def ancestor(self, fc2):
409 def ancestor(self, fc2):
410 """
410 """
411 find the common ancestor file context, if any, of self, and fc2
411 find the common ancestor file context, if any, of self, and fc2
412 """
412 """
413
413
414 acache = {}
414 acache = {}
415
415
416 # prime the ancestor cache for the working directory
416 # prime the ancestor cache for the working directory
417 for c in (self, fc2):
417 for c in (self, fc2):
418 if c._filerev == None:
418 if c._filerev == None:
419 pl = [(n.path(), n.filenode()) for n in c.parents()]
419 pl = [(n.path(), n.filenode()) for n in c.parents()]
420 acache[(c._path, None)] = pl
420 acache[(c._path, None)] = pl
421
421
422 flcache = {self._repopath:self._filelog, fc2._repopath:fc2._filelog}
422 flcache = {self._repopath:self._filelog, fc2._repopath:fc2._filelog}
423 def parents(vertex):
423 def parents(vertex):
424 if vertex in acache:
424 if vertex in acache:
425 return acache[vertex]
425 return acache[vertex]
426 f, n = vertex
426 f, n = vertex
427 if f not in flcache:
427 if f not in flcache:
428 flcache[f] = self._repo.file(f)
428 flcache[f] = self._repo.file(f)
429 fl = flcache[f]
429 fl = flcache[f]
430 pl = [(f, p) for p in fl.parents(n) if p != nullid]
430 pl = [(f, p) for p in fl.parents(n) if p != nullid]
431 re = fl.renamed(n)
431 re = fl.renamed(n)
432 if re:
432 if re:
433 pl.append(re)
433 pl.append(re)
434 acache[vertex] = pl
434 acache[vertex] = pl
435 return pl
435 return pl
436
436
437 a, b = (self._path, self._filenode), (fc2._path, fc2._filenode)
437 a, b = (self._path, self._filenode), (fc2._path, fc2._filenode)
438 v = ancestor.ancestor(a, b, parents)
438 v = ancestor.ancestor(a, b, parents)
439 if v:
439 if v:
440 f, n = v
440 f, n = v
441 return filectx(self._repo, f, fileid=n, filelog=flcache[f])
441 return filectx(self._repo, f, fileid=n, filelog=flcache[f])
442
442
443 return None
443 return None
444
444
445 class workingctx(changectx):
445 class workingctx(changectx):
446 """A workingctx object makes access to data related to
446 """A workingctx object makes access to data related to
447 the current working directory convenient.
447 the current working directory convenient.
448 parents - a pair of parent nodeids, or None to use the dirstate.
448 parents - a pair of parent nodeids, or None to use the dirstate.
449 date - any valid date string or (unixtime, offset), or None.
450 user - username string, or None.
449 extra - a dictionary of extra values, or None.
451 extra - a dictionary of extra values, or None.
450 changes - a list of file lists as returned by localrepo.status()
452 changes - a list of file lists as returned by localrepo.status()
451 or None to use the repository status.
453 or None to use the repository status.
452 """
454 """
453 def __init__(self, repo, parents=None, extra=None, changes=None):
455 def __init__(self, repo, parents=None, text="", user=None, date=None,
456 extra=None, changes=None):
454 self._repo = repo
457 self._repo = repo
455 self._rev = None
458 self._rev = None
456 self._node = None
459 self._node = None
460 self._text = text
461 if date is not None:
462 self._date = util.parsedate(date)
463 else:
464 self._date = util.makedate()
465 if user:
466 self._user = user
467 else:
468 self._user = self._repo.ui.username()
457 if parents:
469 if parents:
458 p1, p2 = parents
470 p1, p2 = parents
459 self._parents = [self._repo.changectx(p) for p in (p1, p2)]
471 self._parents = [self._repo.changectx(p) for p in (p1, p2)]
460 if changes:
472 if changes:
461 self._status = list(changes)
473 self._status = list(changes)
462
474
463 self._extra = {}
475 self._extra = {}
464 if extra:
476 if extra:
465 self._extra = extra.copy()
477 self._extra = extra.copy()
466 if 'branch' not in self._extra:
478 if 'branch' not in self._extra:
467 branch = self._repo.dirstate.branch()
479 branch = self._repo.dirstate.branch()
468 try:
480 try:
469 branch = branch.decode('UTF-8').encode('UTF-8')
481 branch = branch.decode('UTF-8').encode('UTF-8')
470 except UnicodeDecodeError:
482 except UnicodeDecodeError:
471 raise util.Abort(_('branch name not in UTF-8!'))
483 raise util.Abort(_('branch name not in UTF-8!'))
472 self._extra['branch'] = branch
484 self._extra['branch'] = branch
473 if self._extra['branch'] == '':
485 if self._extra['branch'] == '':
474 self._extra['branch'] = 'default'
486 self._extra['branch'] = 'default'
475
487
476 def __str__(self):
488 def __str__(self):
477 return str(self._parents[0]) + "+"
489 return str(self._parents[0]) + "+"
478
490
479 def __nonzero__(self):
491 def __nonzero__(self):
480 return True
492 return True
481
493
482 def __getattr__(self, name):
494 def __getattr__(self, name):
483 if name == '_parents':
495 if name == '_parents':
484 self._parents = self._repo.parents()
496 self._parents = self._repo.parents()
485 return self._parents
497 return self._parents
486 if name == '_status':
498 if name == '_status':
487 self._status = self._repo.status()
499 self._status = self._repo.status()
488 return self._status
500 return self._status
489 if name == '_manifest':
501 if name == '_manifest':
490 self._buildmanifest()
502 self._buildmanifest()
491 return self._manifest
503 return self._manifest
492 else:
504 else:
493 raise AttributeError, name
505 raise AttributeError, name
494
506
495 def _buildmanifest(self):
507 def _buildmanifest(self):
496 """generate a manifest corresponding to the working directory"""
508 """generate a manifest corresponding to the working directory"""
497
509
498 man = self._parents[0].manifest().copy()
510 man = self._parents[0].manifest().copy()
499 copied = self._repo.dirstate.copies()
511 copied = self._repo.dirstate.copies()
500 is_exec = util.execfunc(self._repo.root,
512 is_exec = util.execfunc(self._repo.root,
501 lambda p: man.execf(copied.get(p,p)))
513 lambda p: man.execf(copied.get(p,p)))
502 is_link = util.linkfunc(self._repo.root,
514 is_link = util.linkfunc(self._repo.root,
503 lambda p: man.linkf(copied.get(p,p)))
515 lambda p: man.linkf(copied.get(p,p)))
504 modified, added, removed, deleted, unknown = self._status[:5]
516 modified, added, removed, deleted, unknown = self._status[:5]
505 for i, l in (("a", added), ("m", modified), ("u", unknown)):
517 for i, l in (("a", added), ("m", modified), ("u", unknown)):
506 for f in l:
518 for f in l:
507 man[f] = man.get(copied.get(f, f), nullid) + i
519 man[f] = man.get(copied.get(f, f), nullid) + i
508 try:
520 try:
509 man.set(f, is_exec(f), is_link(f))
521 man.set(f, is_exec(f), is_link(f))
510 except OSError:
522 except OSError:
511 pass
523 pass
512
524
513 for f in deleted + removed:
525 for f in deleted + removed:
514 if f in man:
526 if f in man:
515 del man[f]
527 del man[f]
516
528
517 self._manifest = man
529 self._manifest = man
518
530
519 def manifest(self): return self._manifest
531 def manifest(self): return self._manifest
520
532
521 def user(self): return self._repo.ui.username()
533 def user(self): return self._user
522 def date(self): return util.makedate()
534 def date(self): return self._date
523 def description(self): return ""
535 def description(self): return self._text
524 def files(self):
536 def files(self):
525 f = self.modified() + self.added() + self.removed()
537 f = self.modified() + self.added() + self.removed()
526 f.sort()
538 f.sort()
527 return f
539 return f
528
540
529 def modified(self): return self._status[0]
541 def modified(self): return self._status[0]
530 def added(self): return self._status[1]
542 def added(self): return self._status[1]
531 def removed(self): return self._status[2]
543 def removed(self): return self._status[2]
532 def deleted(self): return self._status[3]
544 def deleted(self): return self._status[3]
533 def unknown(self): return self._status[4]
545 def unknown(self): return self._status[4]
534 def clean(self): return self._status[5]
546 def clean(self): return self._status[5]
535 def branch(self): return self._extra['branch']
547 def branch(self): return self._extra['branch']
536 def extra(self): return self._extra
548 def extra(self): return self._extra
537
549
538 def tags(self):
550 def tags(self):
539 t = []
551 t = []
540 [t.extend(p.tags()) for p in self.parents()]
552 [t.extend(p.tags()) for p in self.parents()]
541 return t
553 return t
542
554
543 def parents(self):
555 def parents(self):
544 """return contexts for each parent changeset"""
556 """return contexts for each parent changeset"""
545 return self._parents
557 return self._parents
546
558
547 def children(self):
559 def children(self):
548 return []
560 return []
549
561
550 def fileflags(self, path):
562 def fileflags(self, path):
551 if '_manifest' in self.__dict__:
563 if '_manifest' in self.__dict__:
552 try:
564 try:
553 return self._manifest.flags(path)
565 return self._manifest.flags(path)
554 except KeyError:
566 except KeyError:
555 return ''
567 return ''
556
568
557 pnode = self._parents[0].changeset()[0]
569 pnode = self._parents[0].changeset()[0]
558 orig = self._repo.dirstate.copies().get(path, path)
570 orig = self._repo.dirstate.copies().get(path, path)
559 node, flag = self._repo.manifest.find(pnode, orig)
571 node, flag = self._repo.manifest.find(pnode, orig)
560 is_link = util.linkfunc(self._repo.root,
572 is_link = util.linkfunc(self._repo.root,
561 lambda p: flag and 'l' in flag)
573 lambda p: flag and 'l' in flag)
562 is_exec = util.execfunc(self._repo.root,
574 is_exec = util.execfunc(self._repo.root,
563 lambda p: flag and 'x' in flag)
575 lambda p: flag and 'x' in flag)
564 try:
576 try:
565 return (is_link(path) and 'l' or '') + (is_exec(path) and 'x' or '')
577 return (is_link(path) and 'l' or '') + (is_exec(path) and 'x' or '')
566 except OSError:
578 except OSError:
567 pass
579 pass
568
580
569 if not node or path in self.deleted() or path in self.removed():
581 if not node or path in self.deleted() or path in self.removed():
570 return ''
582 return ''
571 return flag
583 return flag
572
584
573 def filectx(self, path, filelog=None):
585 def filectx(self, path, filelog=None):
574 """get a file context from the working directory"""
586 """get a file context from the working directory"""
575 return workingfilectx(self._repo, path, workingctx=self,
587 return workingfilectx(self._repo, path, workingctx=self,
576 filelog=filelog)
588 filelog=filelog)
577
589
578 def ancestor(self, c2):
590 def ancestor(self, c2):
579 """return the ancestor context of self and c2"""
591 """return the ancestor context of self and c2"""
580 return self._parents[0].ancestor(c2) # punt on two parents for now
592 return self._parents[0].ancestor(c2) # punt on two parents for now
581
593
582 class workingfilectx(filectx):
594 class workingfilectx(filectx):
583 """A workingfilectx object makes access to data related to a particular
595 """A workingfilectx object makes access to data related to a particular
584 file in the working directory convenient."""
596 file in the working directory convenient."""
585 def __init__(self, repo, path, filelog=None, workingctx=None):
597 def __init__(self, repo, path, filelog=None, workingctx=None):
586 """changeid can be a changeset revision, node, or tag.
598 """changeid can be a changeset revision, node, or tag.
587 fileid can be a file revision or node."""
599 fileid can be a file revision or node."""
588 self._repo = repo
600 self._repo = repo
589 self._path = path
601 self._path = path
590 self._changeid = None
602 self._changeid = None
591 self._filerev = self._filenode = None
603 self._filerev = self._filenode = None
592
604
593 if filelog:
605 if filelog:
594 self._filelog = filelog
606 self._filelog = filelog
595 if workingctx:
607 if workingctx:
596 self._changectx = workingctx
608 self._changectx = workingctx
597
609
598 def __getattr__(self, name):
610 def __getattr__(self, name):
599 if name == '_changectx':
611 if name == '_changectx':
600 self._changectx = workingctx(self._repo)
612 self._changectx = workingctx(self._repo)
601 return self._changectx
613 return self._changectx
602 elif name == '_repopath':
614 elif name == '_repopath':
603 self._repopath = (self._repo.dirstate.copied(self._path)
615 self._repopath = (self._repo.dirstate.copied(self._path)
604 or self._path)
616 or self._path)
605 return self._repopath
617 return self._repopath
606 elif name == '_filelog':
618 elif name == '_filelog':
607 self._filelog = self._repo.file(self._repopath)
619 self._filelog = self._repo.file(self._repopath)
608 return self._filelog
620 return self._filelog
609 else:
621 else:
610 raise AttributeError, name
622 raise AttributeError, name
611
623
612 def __nonzero__(self):
624 def __nonzero__(self):
613 return True
625 return True
614
626
615 def __str__(self):
627 def __str__(self):
616 return "%s@%s" % (self.path(), self._changectx)
628 return "%s@%s" % (self.path(), self._changectx)
617
629
618 def filectx(self, fileid):
630 def filectx(self, fileid):
619 '''opens an arbitrary revision of the file without
631 '''opens an arbitrary revision of the file without
620 opening a new filelog'''
632 opening a new filelog'''
621 return filectx(self._repo, self._repopath, fileid=fileid,
633 return filectx(self._repo, self._repopath, fileid=fileid,
622 filelog=self._filelog)
634 filelog=self._filelog)
623
635
624 def rev(self):
636 def rev(self):
625 if '_changectx' in self.__dict__:
637 if '_changectx' in self.__dict__:
626 return self._changectx.rev()
638 return self._changectx.rev()
627 return self._filelog.linkrev(self._filenode)
639 return self._filelog.linkrev(self._filenode)
628
640
629 def data(self): return self._repo.wread(self._path)
641 def data(self): return self._repo.wread(self._path)
630 def renamed(self):
642 def renamed(self):
631 rp = self._repopath
643 rp = self._repopath
632 if rp == self._path:
644 if rp == self._path:
633 return None
645 return None
634 return rp, self._changectx._parents[0]._manifest.get(rp, nullid)
646 return rp, self._changectx._parents[0]._manifest.get(rp, nullid)
635
647
636 def parents(self):
648 def parents(self):
637 '''return parent filectxs, following copies if necessary'''
649 '''return parent filectxs, following copies if necessary'''
638 p = self._path
650 p = self._path
639 rp = self._repopath
651 rp = self._repopath
640 pcl = self._changectx._parents
652 pcl = self._changectx._parents
641 fl = self._filelog
653 fl = self._filelog
642 pl = [(rp, pcl[0]._manifest.get(rp, nullid), fl)]
654 pl = [(rp, pcl[0]._manifest.get(rp, nullid), fl)]
643 if len(pcl) > 1:
655 if len(pcl) > 1:
644 if rp != p:
656 if rp != p:
645 fl = None
657 fl = None
646 pl.append((p, pcl[1]._manifest.get(p, nullid), fl))
658 pl.append((p, pcl[1]._manifest.get(p, nullid), fl))
647
659
648 return [filectx(self._repo, p, fileid=n, filelog=l)
660 return [filectx(self._repo, p, fileid=n, filelog=l)
649 for p,n,l in pl if n != nullid]
661 for p,n,l in pl if n != nullid]
650
662
651 def children(self):
663 def children(self):
652 return []
664 return []
653
665
654 def size(self): return os.stat(self._repo.wjoin(self._path)).st_size
666 def size(self): return os.stat(self._repo.wjoin(self._path)).st_size
655 def date(self):
667 def date(self):
656 t, tz = self._changectx.date()
668 t, tz = self._changectx.date()
657 try:
669 try:
658 return (int(os.lstat(self._repo.wjoin(self._path)).st_mtime), tz)
670 return (int(os.lstat(self._repo.wjoin(self._path)).st_mtime), tz)
659 except OSError, err:
671 except OSError, err:
660 if err.errno != errno.ENOENT: raise
672 if err.errno != errno.ENOENT: raise
661 return (t, tz)
673 return (t, tz)
662
674
663 def cmp(self, text): return self._repo.wread(self._path) == text
675 def cmp(self, text): return self._repo.wread(self._path) == text
@@ -1,2125 +1,2128 b''
1 # localrepo.py - read/write repository class for mercurial
1 # localrepo.py - read/write repository class for mercurial
2 #
2 #
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms
5 # This software may be used and distributed according to the terms
6 # of the GNU General Public License, incorporated herein by reference.
6 # of the GNU General Public License, incorporated herein by reference.
7
7
8 from node import bin, hex, nullid, nullrev, short
8 from node import bin, hex, nullid, nullrev, short
9 from i18n import _
9 from i18n import _
10 import repo, changegroup
10 import repo, changegroup
11 import changelog, dirstate, filelog, manifest, context, weakref
11 import changelog, dirstate, filelog, manifest, context, weakref
12 import lock, transaction, stat, errno, ui
12 import lock, transaction, stat, errno, ui
13 import os, revlog, time, util, extensions, hook, inspect
13 import os, revlog, time, util, extensions, hook, inspect
14 import match as match_
14 import match as match_
15
15
16 class localrepository(repo.repository):
16 class localrepository(repo.repository):
17 capabilities = util.set(('lookup', 'changegroupsubset'))
17 capabilities = util.set(('lookup', 'changegroupsubset'))
18 supported = ('revlogv1', 'store')
18 supported = ('revlogv1', 'store')
19
19
20 def __init__(self, parentui, path=None, create=0):
20 def __init__(self, parentui, path=None, create=0):
21 repo.repository.__init__(self)
21 repo.repository.__init__(self)
22 self.root = os.path.realpath(path)
22 self.root = os.path.realpath(path)
23 self.path = os.path.join(self.root, ".hg")
23 self.path = os.path.join(self.root, ".hg")
24 self.origroot = path
24 self.origroot = path
25 self.opener = util.opener(self.path)
25 self.opener = util.opener(self.path)
26 self.wopener = util.opener(self.root)
26 self.wopener = util.opener(self.root)
27
27
28 if not os.path.isdir(self.path):
28 if not os.path.isdir(self.path):
29 if create:
29 if create:
30 if not os.path.exists(path):
30 if not os.path.exists(path):
31 os.mkdir(path)
31 os.mkdir(path)
32 os.mkdir(self.path)
32 os.mkdir(self.path)
33 requirements = ["revlogv1"]
33 requirements = ["revlogv1"]
34 if parentui.configbool('format', 'usestore', True):
34 if parentui.configbool('format', 'usestore', True):
35 os.mkdir(os.path.join(self.path, "store"))
35 os.mkdir(os.path.join(self.path, "store"))
36 requirements.append("store")
36 requirements.append("store")
37 # create an invalid changelog
37 # create an invalid changelog
38 self.opener("00changelog.i", "a").write(
38 self.opener("00changelog.i", "a").write(
39 '\0\0\0\2' # represents revlogv2
39 '\0\0\0\2' # represents revlogv2
40 ' dummy changelog to prevent using the old repo layout'
40 ' dummy changelog to prevent using the old repo layout'
41 )
41 )
42 reqfile = self.opener("requires", "w")
42 reqfile = self.opener("requires", "w")
43 for r in requirements:
43 for r in requirements:
44 reqfile.write("%s\n" % r)
44 reqfile.write("%s\n" % r)
45 reqfile.close()
45 reqfile.close()
46 else:
46 else:
47 raise repo.RepoError(_("repository %s not found") % path)
47 raise repo.RepoError(_("repository %s not found") % path)
48 elif create:
48 elif create:
49 raise repo.RepoError(_("repository %s already exists") % path)
49 raise repo.RepoError(_("repository %s already exists") % path)
50 else:
50 else:
51 # find requirements
51 # find requirements
52 try:
52 try:
53 requirements = self.opener("requires").read().splitlines()
53 requirements = self.opener("requires").read().splitlines()
54 except IOError, inst:
54 except IOError, inst:
55 if inst.errno != errno.ENOENT:
55 if inst.errno != errno.ENOENT:
56 raise
56 raise
57 requirements = []
57 requirements = []
58 # check them
58 # check them
59 for r in requirements:
59 for r in requirements:
60 if r not in self.supported:
60 if r not in self.supported:
61 raise repo.RepoError(_("requirement '%s' not supported") % r)
61 raise repo.RepoError(_("requirement '%s' not supported") % r)
62
62
63 # setup store
63 # setup store
64 if "store" in requirements:
64 if "store" in requirements:
65 self.encodefn = util.encodefilename
65 self.encodefn = util.encodefilename
66 self.decodefn = util.decodefilename
66 self.decodefn = util.decodefilename
67 self.spath = os.path.join(self.path, "store")
67 self.spath = os.path.join(self.path, "store")
68 else:
68 else:
69 self.encodefn = lambda x: x
69 self.encodefn = lambda x: x
70 self.decodefn = lambda x: x
70 self.decodefn = lambda x: x
71 self.spath = self.path
71 self.spath = self.path
72
72
73 try:
73 try:
74 # files in .hg/ will be created using this mode
74 # files in .hg/ will be created using this mode
75 mode = os.stat(self.spath).st_mode
75 mode = os.stat(self.spath).st_mode
76 # avoid some useless chmods
76 # avoid some useless chmods
77 if (0777 & ~util._umask) == (0777 & mode):
77 if (0777 & ~util._umask) == (0777 & mode):
78 mode = None
78 mode = None
79 except OSError:
79 except OSError:
80 mode = None
80 mode = None
81
81
82 self._createmode = mode
82 self._createmode = mode
83 self.opener.createmode = mode
83 self.opener.createmode = mode
84 sopener = util.opener(self.spath)
84 sopener = util.opener(self.spath)
85 sopener.createmode = mode
85 sopener.createmode = mode
86 self.sopener = util.encodedopener(sopener, self.encodefn)
86 self.sopener = util.encodedopener(sopener, self.encodefn)
87
87
88 self.ui = ui.ui(parentui=parentui)
88 self.ui = ui.ui(parentui=parentui)
89 try:
89 try:
90 self.ui.readconfig(self.join("hgrc"), self.root)
90 self.ui.readconfig(self.join("hgrc"), self.root)
91 extensions.loadall(self.ui)
91 extensions.loadall(self.ui)
92 except IOError:
92 except IOError:
93 pass
93 pass
94
94
95 self.tagscache = None
95 self.tagscache = None
96 self._tagstypecache = None
96 self._tagstypecache = None
97 self.branchcache = None
97 self.branchcache = None
98 self._ubranchcache = None # UTF-8 version of branchcache
98 self._ubranchcache = None # UTF-8 version of branchcache
99 self._branchcachetip = None
99 self._branchcachetip = None
100 self.nodetagscache = None
100 self.nodetagscache = None
101 self.filterpats = {}
101 self.filterpats = {}
102 self._datafilters = {}
102 self._datafilters = {}
103 self._transref = self._lockref = self._wlockref = None
103 self._transref = self._lockref = self._wlockref = None
104
104
105 def __getattr__(self, name):
105 def __getattr__(self, name):
106 if name == 'changelog':
106 if name == 'changelog':
107 self.changelog = changelog.changelog(self.sopener)
107 self.changelog = changelog.changelog(self.sopener)
108 self.sopener.defversion = self.changelog.version
108 self.sopener.defversion = self.changelog.version
109 return self.changelog
109 return self.changelog
110 if name == 'manifest':
110 if name == 'manifest':
111 self.changelog
111 self.changelog
112 self.manifest = manifest.manifest(self.sopener)
112 self.manifest = manifest.manifest(self.sopener)
113 return self.manifest
113 return self.manifest
114 if name == 'dirstate':
114 if name == 'dirstate':
115 self.dirstate = dirstate.dirstate(self.opener, self.ui, self.root)
115 self.dirstate = dirstate.dirstate(self.opener, self.ui, self.root)
116 return self.dirstate
116 return self.dirstate
117 else:
117 else:
118 raise AttributeError, name
118 raise AttributeError, name
119
119
120 def url(self):
120 def url(self):
121 return 'file:' + self.root
121 return 'file:' + self.root
122
122
123 def hook(self, name, throw=False, **args):
123 def hook(self, name, throw=False, **args):
124 return hook.hook(self.ui, self, name, throw, **args)
124 return hook.hook(self.ui, self, name, throw, **args)
125
125
126 tag_disallowed = ':\r\n'
126 tag_disallowed = ':\r\n'
127
127
128 def _tag(self, names, node, message, local, user, date, parent=None,
128 def _tag(self, names, node, message, local, user, date, parent=None,
129 extra={}):
129 extra={}):
130 use_dirstate = parent is None
130 use_dirstate = parent is None
131
131
132 if isinstance(names, str):
132 if isinstance(names, str):
133 allchars = names
133 allchars = names
134 names = (names,)
134 names = (names,)
135 else:
135 else:
136 allchars = ''.join(names)
136 allchars = ''.join(names)
137 for c in self.tag_disallowed:
137 for c in self.tag_disallowed:
138 if c in allchars:
138 if c in allchars:
139 raise util.Abort(_('%r cannot be used in a tag name') % c)
139 raise util.Abort(_('%r cannot be used in a tag name') % c)
140
140
141 for name in names:
141 for name in names:
142 self.hook('pretag', throw=True, node=hex(node), tag=name,
142 self.hook('pretag', throw=True, node=hex(node), tag=name,
143 local=local)
143 local=local)
144
144
145 def writetags(fp, names, munge, prevtags):
145 def writetags(fp, names, munge, prevtags):
146 fp.seek(0, 2)
146 fp.seek(0, 2)
147 if prevtags and prevtags[-1] != '\n':
147 if prevtags and prevtags[-1] != '\n':
148 fp.write('\n')
148 fp.write('\n')
149 for name in names:
149 for name in names:
150 m = munge and munge(name) or name
150 m = munge and munge(name) or name
151 if self._tagstypecache and name in self._tagstypecache:
151 if self._tagstypecache and name in self._tagstypecache:
152 old = self.tagscache.get(name, nullid)
152 old = self.tagscache.get(name, nullid)
153 fp.write('%s %s\n' % (hex(old), m))
153 fp.write('%s %s\n' % (hex(old), m))
154 fp.write('%s %s\n' % (hex(node), m))
154 fp.write('%s %s\n' % (hex(node), m))
155 fp.close()
155 fp.close()
156
156
157 prevtags = ''
157 prevtags = ''
158 if local:
158 if local:
159 try:
159 try:
160 fp = self.opener('localtags', 'r+')
160 fp = self.opener('localtags', 'r+')
161 except IOError, err:
161 except IOError, err:
162 fp = self.opener('localtags', 'a')
162 fp = self.opener('localtags', 'a')
163 else:
163 else:
164 prevtags = fp.read()
164 prevtags = fp.read()
165
165
166 # local tags are stored in the current charset
166 # local tags are stored in the current charset
167 writetags(fp, names, None, prevtags)
167 writetags(fp, names, None, prevtags)
168 for name in names:
168 for name in names:
169 self.hook('tag', node=hex(node), tag=name, local=local)
169 self.hook('tag', node=hex(node), tag=name, local=local)
170 return
170 return
171
171
172 if use_dirstate:
172 if use_dirstate:
173 try:
173 try:
174 fp = self.wfile('.hgtags', 'rb+')
174 fp = self.wfile('.hgtags', 'rb+')
175 except IOError, err:
175 except IOError, err:
176 fp = self.wfile('.hgtags', 'ab')
176 fp = self.wfile('.hgtags', 'ab')
177 else:
177 else:
178 prevtags = fp.read()
178 prevtags = fp.read()
179 else:
179 else:
180 try:
180 try:
181 prevtags = self.filectx('.hgtags', parent).data()
181 prevtags = self.filectx('.hgtags', parent).data()
182 except revlog.LookupError:
182 except revlog.LookupError:
183 pass
183 pass
184 fp = self.wfile('.hgtags', 'wb')
184 fp = self.wfile('.hgtags', 'wb')
185 if prevtags:
185 if prevtags:
186 fp.write(prevtags)
186 fp.write(prevtags)
187
187
188 # committed tags are stored in UTF-8
188 # committed tags are stored in UTF-8
189 writetags(fp, names, util.fromlocal, prevtags)
189 writetags(fp, names, util.fromlocal, prevtags)
190
190
191 if use_dirstate and '.hgtags' not in self.dirstate:
191 if use_dirstate and '.hgtags' not in self.dirstate:
192 self.add(['.hgtags'])
192 self.add(['.hgtags'])
193
193
194 tagnode = self.commit(['.hgtags'], message, user, date, p1=parent,
194 tagnode = self.commit(['.hgtags'], message, user, date, p1=parent,
195 extra=extra)
195 extra=extra)
196
196
197 for name in names:
197 for name in names:
198 self.hook('tag', node=hex(node), tag=name, local=local)
198 self.hook('tag', node=hex(node), tag=name, local=local)
199
199
200 return tagnode
200 return tagnode
201
201
202 def tag(self, names, node, message, local, user, date):
202 def tag(self, names, node, message, local, user, date):
203 '''tag a revision with one or more symbolic names.
203 '''tag a revision with one or more symbolic names.
204
204
205 names is a list of strings or, when adding a single tag, names may be a
205 names is a list of strings or, when adding a single tag, names may be a
206 string.
206 string.
207
207
208 if local is True, the tags are stored in a per-repository file.
208 if local is True, the tags are stored in a per-repository file.
209 otherwise, they are stored in the .hgtags file, and a new
209 otherwise, they are stored in the .hgtags file, and a new
210 changeset is committed with the change.
210 changeset is committed with the change.
211
211
212 keyword arguments:
212 keyword arguments:
213
213
214 local: whether to store tags in non-version-controlled file
214 local: whether to store tags in non-version-controlled file
215 (default False)
215 (default False)
216
216
217 message: commit message to use if committing
217 message: commit message to use if committing
218
218
219 user: name of user to use if committing
219 user: name of user to use if committing
220
220
221 date: date tuple to use if committing'''
221 date: date tuple to use if committing'''
222
222
223 for x in self.status()[:5]:
223 for x in self.status()[:5]:
224 if '.hgtags' in x:
224 if '.hgtags' in x:
225 raise util.Abort(_('working copy of .hgtags is changed '
225 raise util.Abort(_('working copy of .hgtags is changed '
226 '(please commit .hgtags manually)'))
226 '(please commit .hgtags manually)'))
227
227
228 self._tag(names, node, message, local, user, date)
228 self._tag(names, node, message, local, user, date)
229
229
230 def tags(self):
230 def tags(self):
231 '''return a mapping of tag to node'''
231 '''return a mapping of tag to node'''
232 if self.tagscache:
232 if self.tagscache:
233 return self.tagscache
233 return self.tagscache
234
234
235 globaltags = {}
235 globaltags = {}
236 tagtypes = {}
236 tagtypes = {}
237
237
238 def readtags(lines, fn, tagtype):
238 def readtags(lines, fn, tagtype):
239 filetags = {}
239 filetags = {}
240 count = 0
240 count = 0
241
241
242 def warn(msg):
242 def warn(msg):
243 self.ui.warn(_("%s, line %s: %s\n") % (fn, count, msg))
243 self.ui.warn(_("%s, line %s: %s\n") % (fn, count, msg))
244
244
245 for l in lines:
245 for l in lines:
246 count += 1
246 count += 1
247 if not l:
247 if not l:
248 continue
248 continue
249 s = l.split(" ", 1)
249 s = l.split(" ", 1)
250 if len(s) != 2:
250 if len(s) != 2:
251 warn(_("cannot parse entry"))
251 warn(_("cannot parse entry"))
252 continue
252 continue
253 node, key = s
253 node, key = s
254 key = util.tolocal(key.strip()) # stored in UTF-8
254 key = util.tolocal(key.strip()) # stored in UTF-8
255 try:
255 try:
256 bin_n = bin(node)
256 bin_n = bin(node)
257 except TypeError:
257 except TypeError:
258 warn(_("node '%s' is not well formed") % node)
258 warn(_("node '%s' is not well formed") % node)
259 continue
259 continue
260 if bin_n not in self.changelog.nodemap:
260 if bin_n not in self.changelog.nodemap:
261 warn(_("tag '%s' refers to unknown node") % key)
261 warn(_("tag '%s' refers to unknown node") % key)
262 continue
262 continue
263
263
264 h = []
264 h = []
265 if key in filetags:
265 if key in filetags:
266 n, h = filetags[key]
266 n, h = filetags[key]
267 h.append(n)
267 h.append(n)
268 filetags[key] = (bin_n, h)
268 filetags[key] = (bin_n, h)
269
269
270 for k, nh in filetags.items():
270 for k, nh in filetags.items():
271 if k not in globaltags:
271 if k not in globaltags:
272 globaltags[k] = nh
272 globaltags[k] = nh
273 tagtypes[k] = tagtype
273 tagtypes[k] = tagtype
274 continue
274 continue
275
275
276 # we prefer the global tag if:
276 # we prefer the global tag if:
277 # it supercedes us OR
277 # it supercedes us OR
278 # mutual supercedes and it has a higher rank
278 # mutual supercedes and it has a higher rank
279 # otherwise we win because we're tip-most
279 # otherwise we win because we're tip-most
280 an, ah = nh
280 an, ah = nh
281 bn, bh = globaltags[k]
281 bn, bh = globaltags[k]
282 if (bn != an and an in bh and
282 if (bn != an and an in bh and
283 (bn not in ah or len(bh) > len(ah))):
283 (bn not in ah or len(bh) > len(ah))):
284 an = bn
284 an = bn
285 ah.extend([n for n in bh if n not in ah])
285 ah.extend([n for n in bh if n not in ah])
286 globaltags[k] = an, ah
286 globaltags[k] = an, ah
287 tagtypes[k] = tagtype
287 tagtypes[k] = tagtype
288
288
289 # read the tags file from each head, ending with the tip
289 # read the tags file from each head, ending with the tip
290 f = None
290 f = None
291 for rev, node, fnode in self._hgtagsnodes():
291 for rev, node, fnode in self._hgtagsnodes():
292 f = (f and f.filectx(fnode) or
292 f = (f and f.filectx(fnode) or
293 self.filectx('.hgtags', fileid=fnode))
293 self.filectx('.hgtags', fileid=fnode))
294 readtags(f.data().splitlines(), f, "global")
294 readtags(f.data().splitlines(), f, "global")
295
295
296 try:
296 try:
297 data = util.fromlocal(self.opener("localtags").read())
297 data = util.fromlocal(self.opener("localtags").read())
298 # localtags are stored in the local character set
298 # localtags are stored in the local character set
299 # while the internal tag table is stored in UTF-8
299 # while the internal tag table is stored in UTF-8
300 readtags(data.splitlines(), "localtags", "local")
300 readtags(data.splitlines(), "localtags", "local")
301 except IOError:
301 except IOError:
302 pass
302 pass
303
303
304 self.tagscache = {}
304 self.tagscache = {}
305 self._tagstypecache = {}
305 self._tagstypecache = {}
306 for k,nh in globaltags.items():
306 for k,nh in globaltags.items():
307 n = nh[0]
307 n = nh[0]
308 if n != nullid:
308 if n != nullid:
309 self.tagscache[k] = n
309 self.tagscache[k] = n
310 self._tagstypecache[k] = tagtypes[k]
310 self._tagstypecache[k] = tagtypes[k]
311 self.tagscache['tip'] = self.changelog.tip()
311 self.tagscache['tip'] = self.changelog.tip()
312 return self.tagscache
312 return self.tagscache
313
313
314 def tagtype(self, tagname):
314 def tagtype(self, tagname):
315 '''
315 '''
316 return the type of the given tag. result can be:
316 return the type of the given tag. result can be:
317
317
318 'local' : a local tag
318 'local' : a local tag
319 'global' : a global tag
319 'global' : a global tag
320 None : tag does not exist
320 None : tag does not exist
321 '''
321 '''
322
322
323 self.tags()
323 self.tags()
324
324
325 return self._tagstypecache.get(tagname)
325 return self._tagstypecache.get(tagname)
326
326
327 def _hgtagsnodes(self):
327 def _hgtagsnodes(self):
328 heads = self.heads()
328 heads = self.heads()
329 heads.reverse()
329 heads.reverse()
330 last = {}
330 last = {}
331 ret = []
331 ret = []
332 for node in heads:
332 for node in heads:
333 c = self.changectx(node)
333 c = self.changectx(node)
334 rev = c.rev()
334 rev = c.rev()
335 try:
335 try:
336 fnode = c.filenode('.hgtags')
336 fnode = c.filenode('.hgtags')
337 except revlog.LookupError:
337 except revlog.LookupError:
338 continue
338 continue
339 ret.append((rev, node, fnode))
339 ret.append((rev, node, fnode))
340 if fnode in last:
340 if fnode in last:
341 ret[last[fnode]] = None
341 ret[last[fnode]] = None
342 last[fnode] = len(ret) - 1
342 last[fnode] = len(ret) - 1
343 return [item for item in ret if item]
343 return [item for item in ret if item]
344
344
345 def tagslist(self):
345 def tagslist(self):
346 '''return a list of tags ordered by revision'''
346 '''return a list of tags ordered by revision'''
347 l = []
347 l = []
348 for t, n in self.tags().items():
348 for t, n in self.tags().items():
349 try:
349 try:
350 r = self.changelog.rev(n)
350 r = self.changelog.rev(n)
351 except:
351 except:
352 r = -2 # sort to the beginning of the list if unknown
352 r = -2 # sort to the beginning of the list if unknown
353 l.append((r, t, n))
353 l.append((r, t, n))
354 l.sort()
354 l.sort()
355 return [(t, n) for r, t, n in l]
355 return [(t, n) for r, t, n in l]
356
356
357 def nodetags(self, node):
357 def nodetags(self, node):
358 '''return the tags associated with a node'''
358 '''return the tags associated with a node'''
359 if not self.nodetagscache:
359 if not self.nodetagscache:
360 self.nodetagscache = {}
360 self.nodetagscache = {}
361 for t, n in self.tags().items():
361 for t, n in self.tags().items():
362 self.nodetagscache.setdefault(n, []).append(t)
362 self.nodetagscache.setdefault(n, []).append(t)
363 return self.nodetagscache.get(node, [])
363 return self.nodetagscache.get(node, [])
364
364
365 def _branchtags(self, partial, lrev):
365 def _branchtags(self, partial, lrev):
366 tiprev = self.changelog.count() - 1
366 tiprev = self.changelog.count() - 1
367 if lrev != tiprev:
367 if lrev != tiprev:
368 self._updatebranchcache(partial, lrev+1, tiprev+1)
368 self._updatebranchcache(partial, lrev+1, tiprev+1)
369 self._writebranchcache(partial, self.changelog.tip(), tiprev)
369 self._writebranchcache(partial, self.changelog.tip(), tiprev)
370
370
371 return partial
371 return partial
372
372
373 def branchtags(self):
373 def branchtags(self):
374 tip = self.changelog.tip()
374 tip = self.changelog.tip()
375 if self.branchcache is not None and self._branchcachetip == tip:
375 if self.branchcache is not None and self._branchcachetip == tip:
376 return self.branchcache
376 return self.branchcache
377
377
378 oldtip = self._branchcachetip
378 oldtip = self._branchcachetip
379 self._branchcachetip = tip
379 self._branchcachetip = tip
380 if self.branchcache is None:
380 if self.branchcache is None:
381 self.branchcache = {} # avoid recursion in changectx
381 self.branchcache = {} # avoid recursion in changectx
382 else:
382 else:
383 self.branchcache.clear() # keep using the same dict
383 self.branchcache.clear() # keep using the same dict
384 if oldtip is None or oldtip not in self.changelog.nodemap:
384 if oldtip is None or oldtip not in self.changelog.nodemap:
385 partial, last, lrev = self._readbranchcache()
385 partial, last, lrev = self._readbranchcache()
386 else:
386 else:
387 lrev = self.changelog.rev(oldtip)
387 lrev = self.changelog.rev(oldtip)
388 partial = self._ubranchcache
388 partial = self._ubranchcache
389
389
390 self._branchtags(partial, lrev)
390 self._branchtags(partial, lrev)
391
391
392 # the branch cache is stored on disk as UTF-8, but in the local
392 # the branch cache is stored on disk as UTF-8, but in the local
393 # charset internally
393 # charset internally
394 for k, v in partial.items():
394 for k, v in partial.items():
395 self.branchcache[util.tolocal(k)] = v
395 self.branchcache[util.tolocal(k)] = v
396 self._ubranchcache = partial
396 self._ubranchcache = partial
397 return self.branchcache
397 return self.branchcache
398
398
399 def _readbranchcache(self):
399 def _readbranchcache(self):
400 partial = {}
400 partial = {}
401 try:
401 try:
402 f = self.opener("branch.cache")
402 f = self.opener("branch.cache")
403 lines = f.read().split('\n')
403 lines = f.read().split('\n')
404 f.close()
404 f.close()
405 except (IOError, OSError):
405 except (IOError, OSError):
406 return {}, nullid, nullrev
406 return {}, nullid, nullrev
407
407
408 try:
408 try:
409 last, lrev = lines.pop(0).split(" ", 1)
409 last, lrev = lines.pop(0).split(" ", 1)
410 last, lrev = bin(last), int(lrev)
410 last, lrev = bin(last), int(lrev)
411 if not (lrev < self.changelog.count() and
411 if not (lrev < self.changelog.count() and
412 self.changelog.node(lrev) == last): # sanity check
412 self.changelog.node(lrev) == last): # sanity check
413 # invalidate the cache
413 # invalidate the cache
414 raise ValueError('invalidating branch cache (tip differs)')
414 raise ValueError('invalidating branch cache (tip differs)')
415 for l in lines:
415 for l in lines:
416 if not l: continue
416 if not l: continue
417 node, label = l.split(" ", 1)
417 node, label = l.split(" ", 1)
418 partial[label.strip()] = bin(node)
418 partial[label.strip()] = bin(node)
419 except (KeyboardInterrupt, util.SignalInterrupt):
419 except (KeyboardInterrupt, util.SignalInterrupt):
420 raise
420 raise
421 except Exception, inst:
421 except Exception, inst:
422 if self.ui.debugflag:
422 if self.ui.debugflag:
423 self.ui.warn(str(inst), '\n')
423 self.ui.warn(str(inst), '\n')
424 partial, last, lrev = {}, nullid, nullrev
424 partial, last, lrev = {}, nullid, nullrev
425 return partial, last, lrev
425 return partial, last, lrev
426
426
427 def _writebranchcache(self, branches, tip, tiprev):
427 def _writebranchcache(self, branches, tip, tiprev):
428 try:
428 try:
429 f = self.opener("branch.cache", "w", atomictemp=True)
429 f = self.opener("branch.cache", "w", atomictemp=True)
430 f.write("%s %s\n" % (hex(tip), tiprev))
430 f.write("%s %s\n" % (hex(tip), tiprev))
431 for label, node in branches.iteritems():
431 for label, node in branches.iteritems():
432 f.write("%s %s\n" % (hex(node), label))
432 f.write("%s %s\n" % (hex(node), label))
433 f.rename()
433 f.rename()
434 except (IOError, OSError):
434 except (IOError, OSError):
435 pass
435 pass
436
436
437 def _updatebranchcache(self, partial, start, end):
437 def _updatebranchcache(self, partial, start, end):
438 for r in xrange(start, end):
438 for r in xrange(start, end):
439 c = self.changectx(r)
439 c = self.changectx(r)
440 b = c.branch()
440 b = c.branch()
441 partial[b] = c.node()
441 partial[b] = c.node()
442
442
443 def lookup(self, key):
443 def lookup(self, key):
444 if key == '.':
444 if key == '.':
445 key, second = self.dirstate.parents()
445 key, second = self.dirstate.parents()
446 if key == nullid:
446 if key == nullid:
447 raise repo.RepoError(_("no revision checked out"))
447 raise repo.RepoError(_("no revision checked out"))
448 if second != nullid:
448 if second != nullid:
449 self.ui.warn(_("warning: working directory has two parents, "
449 self.ui.warn(_("warning: working directory has two parents, "
450 "tag '.' uses the first\n"))
450 "tag '.' uses the first\n"))
451 elif key == 'null':
451 elif key == 'null':
452 return nullid
452 return nullid
453 n = self.changelog._match(key)
453 n = self.changelog._match(key)
454 if n:
454 if n:
455 return n
455 return n
456 if key in self.tags():
456 if key in self.tags():
457 return self.tags()[key]
457 return self.tags()[key]
458 if key in self.branchtags():
458 if key in self.branchtags():
459 return self.branchtags()[key]
459 return self.branchtags()[key]
460 n = self.changelog._partialmatch(key)
460 n = self.changelog._partialmatch(key)
461 if n:
461 if n:
462 return n
462 return n
463 try:
463 try:
464 if len(key) == 20:
464 if len(key) == 20:
465 key = hex(key)
465 key = hex(key)
466 except:
466 except:
467 pass
467 pass
468 raise repo.RepoError(_("unknown revision '%s'") % key)
468 raise repo.RepoError(_("unknown revision '%s'") % key)
469
469
470 def local(self):
470 def local(self):
471 return True
471 return True
472
472
473 def join(self, f):
473 def join(self, f):
474 return os.path.join(self.path, f)
474 return os.path.join(self.path, f)
475
475
476 def sjoin(self, f):
476 def sjoin(self, f):
477 f = self.encodefn(f)
477 f = self.encodefn(f)
478 return os.path.join(self.spath, f)
478 return os.path.join(self.spath, f)
479
479
480 def wjoin(self, f):
480 def wjoin(self, f):
481 return os.path.join(self.root, f)
481 return os.path.join(self.root, f)
482
482
483 def rjoin(self, f):
483 def rjoin(self, f):
484 return os.path.join(self.root, util.pconvert(f))
484 return os.path.join(self.root, util.pconvert(f))
485
485
486 def file(self, f):
486 def file(self, f):
487 if f[0] == '/':
487 if f[0] == '/':
488 f = f[1:]
488 f = f[1:]
489 return filelog.filelog(self.sopener, f)
489 return filelog.filelog(self.sopener, f)
490
490
491 def changectx(self, changeid=None):
491 def changectx(self, changeid=None):
492 return context.changectx(self, changeid)
492 return context.changectx(self, changeid)
493
493
494 def workingctx(self, parents=None, extra=None, changes=None):
494 def workingctx(self, parents=None, text="", user=None, date=None,
495 return context.workingctx(self, parents, extra, changes)
495 extra=None, changes=None):
496 return context.workingctx(self, parents, text, user, date, extra,
497 changes)
496
498
497 def parents(self, changeid=None):
499 def parents(self, changeid=None):
498 '''
500 '''
499 get list of changectxs for parents of changeid or working directory
501 get list of changectxs for parents of changeid or working directory
500 '''
502 '''
501 if changeid is None:
503 if changeid is None:
502 pl = self.dirstate.parents()
504 pl = self.dirstate.parents()
503 else:
505 else:
504 n = self.changelog.lookup(changeid)
506 n = self.changelog.lookup(changeid)
505 pl = self.changelog.parents(n)
507 pl = self.changelog.parents(n)
506 if pl[1] == nullid:
508 if pl[1] == nullid:
507 return [self.changectx(pl[0])]
509 return [self.changectx(pl[0])]
508 return [self.changectx(pl[0]), self.changectx(pl[1])]
510 return [self.changectx(pl[0]), self.changectx(pl[1])]
509
511
510 def filectx(self, path, changeid=None, fileid=None):
512 def filectx(self, path, changeid=None, fileid=None):
511 """changeid can be a changeset revision, node, or tag.
513 """changeid can be a changeset revision, node, or tag.
512 fileid can be a file revision or node."""
514 fileid can be a file revision or node."""
513 return context.filectx(self, path, changeid, fileid)
515 return context.filectx(self, path, changeid, fileid)
514
516
515 def getcwd(self):
517 def getcwd(self):
516 return self.dirstate.getcwd()
518 return self.dirstate.getcwd()
517
519
518 def pathto(self, f, cwd=None):
520 def pathto(self, f, cwd=None):
519 return self.dirstate.pathto(f, cwd)
521 return self.dirstate.pathto(f, cwd)
520
522
521 def wfile(self, f, mode='r'):
523 def wfile(self, f, mode='r'):
522 return self.wopener(f, mode)
524 return self.wopener(f, mode)
523
525
524 def _link(self, f):
526 def _link(self, f):
525 return os.path.islink(self.wjoin(f))
527 return os.path.islink(self.wjoin(f))
526
528
527 def _filter(self, filter, filename, data):
529 def _filter(self, filter, filename, data):
528 if filter not in self.filterpats:
530 if filter not in self.filterpats:
529 l = []
531 l = []
530 for pat, cmd in self.ui.configitems(filter):
532 for pat, cmd in self.ui.configitems(filter):
531 mf = util.matcher(self.root, "", [pat], [], [])[1]
533 mf = util.matcher(self.root, "", [pat], [], [])[1]
532 fn = None
534 fn = None
533 params = cmd
535 params = cmd
534 for name, filterfn in self._datafilters.iteritems():
536 for name, filterfn in self._datafilters.iteritems():
535 if cmd.startswith(name):
537 if cmd.startswith(name):
536 fn = filterfn
538 fn = filterfn
537 params = cmd[len(name):].lstrip()
539 params = cmd[len(name):].lstrip()
538 break
540 break
539 if not fn:
541 if not fn:
540 fn = lambda s, c, **kwargs: util.filter(s, c)
542 fn = lambda s, c, **kwargs: util.filter(s, c)
541 # Wrap old filters not supporting keyword arguments
543 # Wrap old filters not supporting keyword arguments
542 if not inspect.getargspec(fn)[2]:
544 if not inspect.getargspec(fn)[2]:
543 oldfn = fn
545 oldfn = fn
544 fn = lambda s, c, **kwargs: oldfn(s, c)
546 fn = lambda s, c, **kwargs: oldfn(s, c)
545 l.append((mf, fn, params))
547 l.append((mf, fn, params))
546 self.filterpats[filter] = l
548 self.filterpats[filter] = l
547
549
548 for mf, fn, cmd in self.filterpats[filter]:
550 for mf, fn, cmd in self.filterpats[filter]:
549 if mf(filename):
551 if mf(filename):
550 self.ui.debug(_("filtering %s through %s\n") % (filename, cmd))
552 self.ui.debug(_("filtering %s through %s\n") % (filename, cmd))
551 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
553 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
552 break
554 break
553
555
554 return data
556 return data
555
557
556 def adddatafilter(self, name, filter):
558 def adddatafilter(self, name, filter):
557 self._datafilters[name] = filter
559 self._datafilters[name] = filter
558
560
559 def wread(self, filename):
561 def wread(self, filename):
560 if self._link(filename):
562 if self._link(filename):
561 data = os.readlink(self.wjoin(filename))
563 data = os.readlink(self.wjoin(filename))
562 else:
564 else:
563 data = self.wopener(filename, 'r').read()
565 data = self.wopener(filename, 'r').read()
564 return self._filter("encode", filename, data)
566 return self._filter("encode", filename, data)
565
567
566 def wwrite(self, filename, data, flags):
568 def wwrite(self, filename, data, flags):
567 data = self._filter("decode", filename, data)
569 data = self._filter("decode", filename, data)
568 try:
570 try:
569 os.unlink(self.wjoin(filename))
571 os.unlink(self.wjoin(filename))
570 except OSError:
572 except OSError:
571 pass
573 pass
572 self.wopener(filename, 'w').write(data)
574 self.wopener(filename, 'w').write(data)
573 util.set_flags(self.wjoin(filename), flags)
575 util.set_flags(self.wjoin(filename), flags)
574
576
575 def wwritedata(self, filename, data):
577 def wwritedata(self, filename, data):
576 return self._filter("decode", filename, data)
578 return self._filter("decode", filename, data)
577
579
578 def transaction(self):
580 def transaction(self):
579 if self._transref and self._transref():
581 if self._transref and self._transref():
580 return self._transref().nest()
582 return self._transref().nest()
581
583
582 # abort here if the journal already exists
584 # abort here if the journal already exists
583 if os.path.exists(self.sjoin("journal")):
585 if os.path.exists(self.sjoin("journal")):
584 raise repo.RepoError(_("journal already exists - run hg recover"))
586 raise repo.RepoError(_("journal already exists - run hg recover"))
585
587
586 # save dirstate for rollback
588 # save dirstate for rollback
587 try:
589 try:
588 ds = self.opener("dirstate").read()
590 ds = self.opener("dirstate").read()
589 except IOError:
591 except IOError:
590 ds = ""
592 ds = ""
591 self.opener("journal.dirstate", "w").write(ds)
593 self.opener("journal.dirstate", "w").write(ds)
592 self.opener("journal.branch", "w").write(self.dirstate.branch())
594 self.opener("journal.branch", "w").write(self.dirstate.branch())
593
595
594 renames = [(self.sjoin("journal"), self.sjoin("undo")),
596 renames = [(self.sjoin("journal"), self.sjoin("undo")),
595 (self.join("journal.dirstate"), self.join("undo.dirstate")),
597 (self.join("journal.dirstate"), self.join("undo.dirstate")),
596 (self.join("journal.branch"), self.join("undo.branch"))]
598 (self.join("journal.branch"), self.join("undo.branch"))]
597 tr = transaction.transaction(self.ui.warn, self.sopener,
599 tr = transaction.transaction(self.ui.warn, self.sopener,
598 self.sjoin("journal"),
600 self.sjoin("journal"),
599 aftertrans(renames),
601 aftertrans(renames),
600 self._createmode)
602 self._createmode)
601 self._transref = weakref.ref(tr)
603 self._transref = weakref.ref(tr)
602 return tr
604 return tr
603
605
604 def recover(self):
606 def recover(self):
605 l = self.lock()
607 l = self.lock()
606 try:
608 try:
607 if os.path.exists(self.sjoin("journal")):
609 if os.path.exists(self.sjoin("journal")):
608 self.ui.status(_("rolling back interrupted transaction\n"))
610 self.ui.status(_("rolling back interrupted transaction\n"))
609 transaction.rollback(self.sopener, self.sjoin("journal"))
611 transaction.rollback(self.sopener, self.sjoin("journal"))
610 self.invalidate()
612 self.invalidate()
611 return True
613 return True
612 else:
614 else:
613 self.ui.warn(_("no interrupted transaction available\n"))
615 self.ui.warn(_("no interrupted transaction available\n"))
614 return False
616 return False
615 finally:
617 finally:
616 del l
618 del l
617
619
618 def rollback(self):
620 def rollback(self):
619 wlock = lock = None
621 wlock = lock = None
620 try:
622 try:
621 wlock = self.wlock()
623 wlock = self.wlock()
622 lock = self.lock()
624 lock = self.lock()
623 if os.path.exists(self.sjoin("undo")):
625 if os.path.exists(self.sjoin("undo")):
624 self.ui.status(_("rolling back last transaction\n"))
626 self.ui.status(_("rolling back last transaction\n"))
625 transaction.rollback(self.sopener, self.sjoin("undo"))
627 transaction.rollback(self.sopener, self.sjoin("undo"))
626 util.rename(self.join("undo.dirstate"), self.join("dirstate"))
628 util.rename(self.join("undo.dirstate"), self.join("dirstate"))
627 try:
629 try:
628 branch = self.opener("undo.branch").read()
630 branch = self.opener("undo.branch").read()
629 self.dirstate.setbranch(branch)
631 self.dirstate.setbranch(branch)
630 except IOError:
632 except IOError:
631 self.ui.warn(_("Named branch could not be reset, "
633 self.ui.warn(_("Named branch could not be reset, "
632 "current branch still is: %s\n")
634 "current branch still is: %s\n")
633 % util.tolocal(self.dirstate.branch()))
635 % util.tolocal(self.dirstate.branch()))
634 self.invalidate()
636 self.invalidate()
635 self.dirstate.invalidate()
637 self.dirstate.invalidate()
636 else:
638 else:
637 self.ui.warn(_("no rollback information available\n"))
639 self.ui.warn(_("no rollback information available\n"))
638 finally:
640 finally:
639 del lock, wlock
641 del lock, wlock
640
642
641 def invalidate(self):
643 def invalidate(self):
642 for a in "changelog manifest".split():
644 for a in "changelog manifest".split():
643 if a in self.__dict__:
645 if a in self.__dict__:
644 delattr(self, a)
646 delattr(self, a)
645 self.tagscache = None
647 self.tagscache = None
646 self._tagstypecache = None
648 self._tagstypecache = None
647 self.nodetagscache = None
649 self.nodetagscache = None
648 self.branchcache = None
650 self.branchcache = None
649 self._ubranchcache = None
651 self._ubranchcache = None
650 self._branchcachetip = None
652 self._branchcachetip = None
651
653
652 def _lock(self, lockname, wait, releasefn, acquirefn, desc):
654 def _lock(self, lockname, wait, releasefn, acquirefn, desc):
653 try:
655 try:
654 l = lock.lock(lockname, 0, releasefn, desc=desc)
656 l = lock.lock(lockname, 0, releasefn, desc=desc)
655 except lock.LockHeld, inst:
657 except lock.LockHeld, inst:
656 if not wait:
658 if not wait:
657 raise
659 raise
658 self.ui.warn(_("waiting for lock on %s held by %r\n") %
660 self.ui.warn(_("waiting for lock on %s held by %r\n") %
659 (desc, inst.locker))
661 (desc, inst.locker))
660 # default to 600 seconds timeout
662 # default to 600 seconds timeout
661 l = lock.lock(lockname, int(self.ui.config("ui", "timeout", "600")),
663 l = lock.lock(lockname, int(self.ui.config("ui", "timeout", "600")),
662 releasefn, desc=desc)
664 releasefn, desc=desc)
663 if acquirefn:
665 if acquirefn:
664 acquirefn()
666 acquirefn()
665 return l
667 return l
666
668
667 def lock(self, wait=True):
669 def lock(self, wait=True):
668 if self._lockref and self._lockref():
670 if self._lockref and self._lockref():
669 return self._lockref()
671 return self._lockref()
670
672
671 l = self._lock(self.sjoin("lock"), wait, None, self.invalidate,
673 l = self._lock(self.sjoin("lock"), wait, None, self.invalidate,
672 _('repository %s') % self.origroot)
674 _('repository %s') % self.origroot)
673 self._lockref = weakref.ref(l)
675 self._lockref = weakref.ref(l)
674 return l
676 return l
675
677
676 def wlock(self, wait=True):
678 def wlock(self, wait=True):
677 if self._wlockref and self._wlockref():
679 if self._wlockref and self._wlockref():
678 return self._wlockref()
680 return self._wlockref()
679
681
680 l = self._lock(self.join("wlock"), wait, self.dirstate.write,
682 l = self._lock(self.join("wlock"), wait, self.dirstate.write,
681 self.dirstate.invalidate, _('working directory of %s') %
683 self.dirstate.invalidate, _('working directory of %s') %
682 self.origroot)
684 self.origroot)
683 self._wlockref = weakref.ref(l)
685 self._wlockref = weakref.ref(l)
684 return l
686 return l
685
687
686 def filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
688 def filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
687 """
689 """
688 commit an individual file as part of a larger transaction
690 commit an individual file as part of a larger transaction
689 """
691 """
690
692
691 fn = fctx.path()
693 fn = fctx.path()
692 t = fctx.data()
694 t = fctx.data()
693 fl = self.file(fn)
695 fl = self.file(fn)
694 fp1 = manifest1.get(fn, nullid)
696 fp1 = manifest1.get(fn, nullid)
695 fp2 = manifest2.get(fn, nullid)
697 fp2 = manifest2.get(fn, nullid)
696
698
697 meta = {}
699 meta = {}
698 cp = fctx.renamed()
700 cp = fctx.renamed()
699 if cp and cp[0] != fn:
701 if cp and cp[0] != fn:
700 cp = cp[0]
702 cp = cp[0]
701 # Mark the new revision of this file as a copy of another
703 # Mark the new revision of this file as a copy of another
702 # file. This copy data will effectively act as a parent
704 # file. This copy data will effectively act as a parent
703 # of this new revision. If this is a merge, the first
705 # of this new revision. If this is a merge, the first
704 # parent will be the nullid (meaning "look up the copy data")
706 # parent will be the nullid (meaning "look up the copy data")
705 # and the second one will be the other parent. For example:
707 # and the second one will be the other parent. For example:
706 #
708 #
707 # 0 --- 1 --- 3 rev1 changes file foo
709 # 0 --- 1 --- 3 rev1 changes file foo
708 # \ / rev2 renames foo to bar and changes it
710 # \ / rev2 renames foo to bar and changes it
709 # \- 2 -/ rev3 should have bar with all changes and
711 # \- 2 -/ rev3 should have bar with all changes and
710 # should record that bar descends from
712 # should record that bar descends from
711 # bar in rev2 and foo in rev1
713 # bar in rev2 and foo in rev1
712 #
714 #
713 # this allows this merge to succeed:
715 # this allows this merge to succeed:
714 #
716 #
715 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
717 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
716 # \ / merging rev3 and rev4 should use bar@rev2
718 # \ / merging rev3 and rev4 should use bar@rev2
717 # \- 2 --- 4 as the merge base
719 # \- 2 --- 4 as the merge base
718 #
720 #
719 meta["copy"] = cp
721 meta["copy"] = cp
720 if not manifest2: # not a branch merge
722 if not manifest2: # not a branch merge
721 meta["copyrev"] = hex(manifest1[cp])
723 meta["copyrev"] = hex(manifest1[cp])
722 fp2 = nullid
724 fp2 = nullid
723 elif fp2 != nullid: # copied on remote side
725 elif fp2 != nullid: # copied on remote side
724 meta["copyrev"] = hex(manifest1[cp])
726 meta["copyrev"] = hex(manifest1[cp])
725 elif fp1 != nullid: # copied on local side, reversed
727 elif fp1 != nullid: # copied on local side, reversed
726 meta["copyrev"] = hex(manifest2[cp])
728 meta["copyrev"] = hex(manifest2[cp])
727 fp2 = fp1
729 fp2 = fp1
728 elif cp in manifest2: # directory rename on local side
730 elif cp in manifest2: # directory rename on local side
729 meta["copyrev"] = hex(manifest2[cp])
731 meta["copyrev"] = hex(manifest2[cp])
730 else: # directory rename on remote side
732 else: # directory rename on remote side
731 meta["copyrev"] = hex(manifest1[cp])
733 meta["copyrev"] = hex(manifest1[cp])
732 self.ui.debug(_(" %s: copy %s:%s\n") %
734 self.ui.debug(_(" %s: copy %s:%s\n") %
733 (fn, cp, meta["copyrev"]))
735 (fn, cp, meta["copyrev"]))
734 fp1 = nullid
736 fp1 = nullid
735 elif fp2 != nullid:
737 elif fp2 != nullid:
736 # is one parent an ancestor of the other?
738 # is one parent an ancestor of the other?
737 fpa = fl.ancestor(fp1, fp2)
739 fpa = fl.ancestor(fp1, fp2)
738 if fpa == fp1:
740 if fpa == fp1:
739 fp1, fp2 = fp2, nullid
741 fp1, fp2 = fp2, nullid
740 elif fpa == fp2:
742 elif fpa == fp2:
741 fp2 = nullid
743 fp2 = nullid
742
744
743 # is the file unmodified from the parent? report existing entry
745 # is the file unmodified from the parent? report existing entry
744 if fp2 == nullid and not fl.cmp(fp1, t) and not meta:
746 if fp2 == nullid and not fl.cmp(fp1, t) and not meta:
745 return fp1
747 return fp1
746
748
747 changelist.append(fn)
749 changelist.append(fn)
748 return fl.add(t, meta, tr, linkrev, fp1, fp2)
750 return fl.add(t, meta, tr, linkrev, fp1, fp2)
749
751
750 def rawcommit(self, files, text, user, date, p1=None, p2=None, extra={}):
752 def rawcommit(self, files, text, user, date, p1=None, p2=None, extra={}):
751 if p1 is None:
753 if p1 is None:
752 p1, p2 = self.dirstate.parents()
754 p1, p2 = self.dirstate.parents()
753 return self.commit(files=files, text=text, user=user, date=date,
755 return self.commit(files=files, text=text, user=user, date=date,
754 p1=p1, p2=p2, extra=extra, empty_ok=True)
756 p1=p1, p2=p2, extra=extra, empty_ok=True)
755
757
756 def commit(self, files=None, text="", user=None, date=None,
758 def commit(self, files=None, text="", user=None, date=None,
757 match=None, force=False, force_editor=False,
759 match=None, force=False, force_editor=False,
758 p1=None, p2=None, extra={}, empty_ok=False):
760 p1=None, p2=None, extra={}, empty_ok=False):
759 wlock = lock = tr = None
761 wlock = lock = tr = None
760 valid = 0 # don't save the dirstate if this isn't set
762 valid = 0 # don't save the dirstate if this isn't set
761 if files:
763 if files:
762 files = util.unique(files)
764 files = util.unique(files)
763 try:
765 try:
764 wlock = self.wlock()
766 wlock = self.wlock()
765 lock = self.lock()
767 lock = self.lock()
766 commit = []
768 commit = []
767 remove = []
769 remove = []
768 changed = []
770 changed = []
769 use_dirstate = (p1 is None) # not rawcommit
771 use_dirstate = (p1 is None) # not rawcommit
770
772
771 if use_dirstate:
773 if use_dirstate:
772 p1, p2 = self.dirstate.parents()
774 p1, p2 = self.dirstate.parents()
773 update_dirstate = True
775 update_dirstate = True
774
776
775 if (not force and p2 != nullid and
777 if (not force and p2 != nullid and
776 (match and (match.files() or match.anypats()))):
778 (match and (match.files() or match.anypats()))):
777 raise util.Abort(_('cannot partially commit a merge '
779 raise util.Abort(_('cannot partially commit a merge '
778 '(do not specify files or patterns)'))
780 '(do not specify files or patterns)'))
779
781
780 if files:
782 if files:
781 modified, removed = [], []
783 modified, removed = [], []
782 for f in files:
784 for f in files:
783 s = self.dirstate[f]
785 s = self.dirstate[f]
784 if s in 'nma':
786 if s in 'nma':
785 modified.append(f)
787 modified.append(f)
786 elif s == 'r':
788 elif s == 'r':
787 removed.append(f)
789 removed.append(f)
788 else:
790 else:
789 self.ui.warn(_("%s not tracked!\n") % f)
791 self.ui.warn(_("%s not tracked!\n") % f)
790 changes = [modified, [], removed, [], []]
792 changes = [modified, [], removed, [], []]
791 else:
793 else:
792 changes = self.status(match=match)
794 changes = self.status(match=match)
793 else:
795 else:
794 p1, p2 = p1, p2 or nullid
796 p1, p2 = p1, p2 or nullid
795 update_dirstate = (self.dirstate.parents()[0] == p1)
797 update_dirstate = (self.dirstate.parents()[0] == p1)
796 changes = [files, [], [], [], []]
798 changes = [files, [], [], [], []]
797
799
798 wctx = self.workingctx((p1, p2), extra, changes)
800 wctx = self.workingctx((p1, p2), text, user, date, extra, changes)
799 commit = wctx.modified() + wctx.added()
801 commit = wctx.modified() + wctx.added()
800 remove = wctx.removed()
802 remove = wctx.removed()
801 extra = wctx.extra().copy()
803 extra = wctx.extra().copy()
802 branchname = extra['branch']
804 branchname = extra['branch']
805 user = wctx.user()
806 text = wctx.description()
803
807
804 c1 = self.changelog.read(p1)
808 c1 = self.changelog.read(p1)
805 c2 = self.changelog.read(p2)
809 c2 = self.changelog.read(p2)
806 m1 = self.manifest.read(c1[0]).copy()
810 m1 = self.manifest.read(c1[0]).copy()
807 m2 = self.manifest.read(c2[0])
811 m2 = self.manifest.read(c2[0])
808
812
809 if use_dirstate:
813 if use_dirstate:
810 oldname = c1[5].get("branch") # stored in UTF-8
814 oldname = c1[5].get("branch") # stored in UTF-8
811 if (not commit and not remove and not force and p2 == nullid
815 if (not commit and not remove and not force and p2 == nullid
812 and branchname == oldname):
816 and branchname == oldname):
813 self.ui.status(_("nothing changed\n"))
817 self.ui.status(_("nothing changed\n"))
814 return None
818 return None
815
819
816 xp1 = hex(p1)
820 xp1 = hex(p1)
817 if p2 == nullid: xp2 = ''
821 if p2 == nullid: xp2 = ''
818 else: xp2 = hex(p2)
822 else: xp2 = hex(p2)
819
823
820 self.hook("precommit", throw=True, parent1=xp1, parent2=xp2)
824 self.hook("precommit", throw=True, parent1=xp1, parent2=xp2)
821
825
822 tr = self.transaction()
826 tr = self.transaction()
823 trp = weakref.proxy(tr)
827 trp = weakref.proxy(tr)
824
828
825 # check in files
829 # check in files
826 new = {}
830 new = {}
827 linkrev = self.changelog.count()
831 linkrev = self.changelog.count()
828 commit.sort()
832 commit.sort()
829 for f in commit:
833 for f in commit:
830 self.ui.note(f + "\n")
834 self.ui.note(f + "\n")
831 fctx = wctx.filectx(f)
835 fctx = wctx.filectx(f)
832 try:
836 try:
833 new[f] = self.filecommit(fctx, m1, m2, linkrev, trp, changed)
837 new[f] = self.filecommit(fctx, m1, m2, linkrev, trp, changed)
834 new_exec = fctx.isexec()
838 new_exec = fctx.isexec()
835 new_link = fctx.islink()
839 new_link = fctx.islink()
836 if ((not changed or changed[-1] != f) and
840 if ((not changed or changed[-1] != f) and
837 m2.get(f) != new[f]):
841 m2.get(f) != new[f]):
838 # mention the file in the changelog if some
842 # mention the file in the changelog if some
839 # flag changed, even if there was no content
843 # flag changed, even if there was no content
840 # change.
844 # change.
841 old_exec = m1.execf(f)
845 old_exec = m1.execf(f)
842 old_link = m1.linkf(f)
846 old_link = m1.linkf(f)
843 if old_exec != new_exec or old_link != new_link:
847 if old_exec != new_exec or old_link != new_link:
844 changed.append(f)
848 changed.append(f)
845 m1.set(f, new_exec, new_link)
849 m1.set(f, new_exec, new_link)
846 if use_dirstate:
850 if use_dirstate:
847 self.dirstate.normal(f)
851 self.dirstate.normal(f)
848
852
849 except (OSError, IOError):
853 except (OSError, IOError):
850 if use_dirstate:
854 if use_dirstate:
851 self.ui.warn(_("trouble committing %s!\n") % f)
855 self.ui.warn(_("trouble committing %s!\n") % f)
852 raise
856 raise
853 else:
857 else:
854 remove.append(f)
858 remove.append(f)
855
859
856 # update manifest
860 # update manifest
857 m1.update(new)
861 m1.update(new)
858 remove.sort()
862 remove.sort()
859 removed = []
863 removed = []
860
864
861 for f in remove:
865 for f in remove:
862 if f in m1:
866 if f in m1:
863 del m1[f]
867 del m1[f]
864 removed.append(f)
868 removed.append(f)
865 elif f in m2:
869 elif f in m2:
866 removed.append(f)
870 removed.append(f)
867 mn = self.manifest.add(m1, trp, linkrev, c1[0], c2[0],
871 mn = self.manifest.add(m1, trp, linkrev, c1[0], c2[0],
868 (new, removed))
872 (new, removed))
869
873
870 # add changeset
874 # add changeset
871 user = user or self.ui.username()
872 if (not empty_ok and not text) or force_editor:
875 if (not empty_ok and not text) or force_editor:
873 edittext = []
876 edittext = []
874 if text:
877 if text:
875 edittext.append(text)
878 edittext.append(text)
876 edittext.append("")
879 edittext.append("")
877 edittext.append(_("HG: Enter commit message."
880 edittext.append(_("HG: Enter commit message."
878 " Lines beginning with 'HG:' are removed."))
881 " Lines beginning with 'HG:' are removed."))
879 edittext.append("HG: --")
882 edittext.append("HG: --")
880 edittext.append("HG: user: %s" % user)
883 edittext.append("HG: user: %s" % user)
881 if p2 != nullid:
884 if p2 != nullid:
882 edittext.append("HG: branch merge")
885 edittext.append("HG: branch merge")
883 if branchname:
886 if branchname:
884 edittext.append("HG: branch '%s'" % util.tolocal(branchname))
887 edittext.append("HG: branch '%s'" % util.tolocal(branchname))
885 edittext.extend(["HG: changed %s" % f for f in changed])
888 edittext.extend(["HG: changed %s" % f for f in changed])
886 edittext.extend(["HG: removed %s" % f for f in removed])
889 edittext.extend(["HG: removed %s" % f for f in removed])
887 if not changed and not remove:
890 if not changed and not remove:
888 edittext.append("HG: no files changed")
891 edittext.append("HG: no files changed")
889 edittext.append("")
892 edittext.append("")
890 # run editor in the repository root
893 # run editor in the repository root
891 olddir = os.getcwd()
894 olddir = os.getcwd()
892 os.chdir(self.root)
895 os.chdir(self.root)
893 text = self.ui.edit("\n".join(edittext), user)
896 text = self.ui.edit("\n".join(edittext), user)
894 os.chdir(olddir)
897 os.chdir(olddir)
895
898
896 lines = [line.rstrip() for line in text.rstrip().splitlines()]
899 lines = [line.rstrip() for line in text.rstrip().splitlines()]
897 while lines and not lines[0]:
900 while lines and not lines[0]:
898 del lines[0]
901 del lines[0]
899 if not lines and use_dirstate:
902 if not lines and use_dirstate:
900 raise util.Abort(_("empty commit message"))
903 raise util.Abort(_("empty commit message"))
901 text = '\n'.join(lines)
904 text = '\n'.join(lines)
902
905
903 n = self.changelog.add(mn, changed + removed, text, trp, p1, p2,
906 n = self.changelog.add(mn, changed + removed, text, trp, p1, p2,
904 user, date, extra)
907 user, wctx.date(), extra)
905 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
908 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
906 parent2=xp2)
909 parent2=xp2)
907 tr.close()
910 tr.close()
908
911
909 if self.branchcache:
912 if self.branchcache:
910 self.branchtags()
913 self.branchtags()
911
914
912 if use_dirstate or update_dirstate:
915 if use_dirstate or update_dirstate:
913 self.dirstate.setparents(n)
916 self.dirstate.setparents(n)
914 if use_dirstate:
917 if use_dirstate:
915 for f in removed:
918 for f in removed:
916 self.dirstate.forget(f)
919 self.dirstate.forget(f)
917 valid = 1 # our dirstate updates are complete
920 valid = 1 # our dirstate updates are complete
918
921
919 self.hook("commit", node=hex(n), parent1=xp1, parent2=xp2)
922 self.hook("commit", node=hex(n), parent1=xp1, parent2=xp2)
920 return n
923 return n
921 finally:
924 finally:
922 if not valid: # don't save our updated dirstate
925 if not valid: # don't save our updated dirstate
923 self.dirstate.invalidate()
926 self.dirstate.invalidate()
924 del tr, lock, wlock
927 del tr, lock, wlock
925
928
926 def walk(self, match, node=None):
929 def walk(self, match, node=None):
927 '''
930 '''
928 walk recursively through the directory tree or a given
931 walk recursively through the directory tree or a given
929 changeset, finding all files matched by the match
932 changeset, finding all files matched by the match
930 function
933 function
931 '''
934 '''
932
935
933 if node:
936 if node:
934 fdict = dict.fromkeys(match.files())
937 fdict = dict.fromkeys(match.files())
935 # for dirstate.walk, files=['.'] means "walk the whole tree".
938 # for dirstate.walk, files=['.'] means "walk the whole tree".
936 # follow that here, too
939 # follow that here, too
937 fdict.pop('.', None)
940 fdict.pop('.', None)
938 mdict = self.manifest.read(self.changelog.read(node)[0])
941 mdict = self.manifest.read(self.changelog.read(node)[0])
939 mfiles = mdict.keys()
942 mfiles = mdict.keys()
940 mfiles.sort()
943 mfiles.sort()
941 for fn in mfiles:
944 for fn in mfiles:
942 for ffn in fdict:
945 for ffn in fdict:
943 # match if the file is the exact name or a directory
946 # match if the file is the exact name or a directory
944 if ffn == fn or fn.startswith("%s/" % ffn):
947 if ffn == fn or fn.startswith("%s/" % ffn):
945 del fdict[ffn]
948 del fdict[ffn]
946 break
949 break
947 if match(fn):
950 if match(fn):
948 yield fn
951 yield fn
949 ffiles = fdict.keys()
952 ffiles = fdict.keys()
950 ffiles.sort()
953 ffiles.sort()
951 for fn in ffiles:
954 for fn in ffiles:
952 if match.bad(fn, 'No such file in rev ' + short(node)) \
955 if match.bad(fn, 'No such file in rev ' + short(node)) \
953 and match(fn):
956 and match(fn):
954 yield fn
957 yield fn
955 else:
958 else:
956 for fn in self.dirstate.walk(match):
959 for fn in self.dirstate.walk(match):
957 yield fn
960 yield fn
958
961
959 def status(self, node1=None, node2=None, match=None,
962 def status(self, node1=None, node2=None, match=None,
960 list_ignored=False, list_clean=False, list_unknown=True):
963 list_ignored=False, list_clean=False, list_unknown=True):
961 """return status of files between two nodes or node and working directory
964 """return status of files between two nodes or node and working directory
962
965
963 If node1 is None, use the first dirstate parent instead.
966 If node1 is None, use the first dirstate parent instead.
964 If node2 is None, compare node1 with working directory.
967 If node2 is None, compare node1 with working directory.
965 """
968 """
966
969
967 def fcmp(fn, getnode):
970 def fcmp(fn, getnode):
968 t1 = self.wread(fn)
971 t1 = self.wread(fn)
969 return self.file(fn).cmp(getnode(fn), t1)
972 return self.file(fn).cmp(getnode(fn), t1)
970
973
971 def mfmatches(node):
974 def mfmatches(node):
972 change = self.changelog.read(node)
975 change = self.changelog.read(node)
973 mf = self.manifest.read(change[0]).copy()
976 mf = self.manifest.read(change[0]).copy()
974 for fn in mf.keys():
977 for fn in mf.keys():
975 if not match(fn):
978 if not match(fn):
976 del mf[fn]
979 del mf[fn]
977 return mf
980 return mf
978
981
979 if not match:
982 if not match:
980 match = match_.always(self.root, self.getcwd())
983 match = match_.always(self.root, self.getcwd())
981
984
982 modified, added, removed, deleted, unknown = [], [], [], [], []
985 modified, added, removed, deleted, unknown = [], [], [], [], []
983 ignored, clean = [], []
986 ignored, clean = [], []
984
987
985 compareworking = False
988 compareworking = False
986 if not node1 or (not node2 and node1 == self.dirstate.parents()[0]):
989 if not node1 or (not node2 and node1 == self.dirstate.parents()[0]):
987 compareworking = True
990 compareworking = True
988
991
989 if not compareworking:
992 if not compareworking:
990 # read the manifest from node1 before the manifest from node2,
993 # read the manifest from node1 before the manifest from node2,
991 # so that we'll hit the manifest cache if we're going through
994 # so that we'll hit the manifest cache if we're going through
992 # all the revisions in parent->child order.
995 # all the revisions in parent->child order.
993 mf1 = mfmatches(node1)
996 mf1 = mfmatches(node1)
994
997
995 # are we comparing the working directory?
998 # are we comparing the working directory?
996 if not node2:
999 if not node2:
997 (lookup, modified, added, removed, deleted, unknown,
1000 (lookup, modified, added, removed, deleted, unknown,
998 ignored, clean) = self.dirstate.status(match, list_ignored,
1001 ignored, clean) = self.dirstate.status(match, list_ignored,
999 list_clean, list_unknown)
1002 list_clean, list_unknown)
1000 # are we comparing working dir against its parent?
1003 # are we comparing working dir against its parent?
1001 if compareworking:
1004 if compareworking:
1002 if lookup:
1005 if lookup:
1003 fixup = []
1006 fixup = []
1004 # do a full compare of any files that might have changed
1007 # do a full compare of any files that might have changed
1005 ctx = self.changectx()
1008 ctx = self.changectx()
1006 mexec = lambda f: 'x' in ctx.fileflags(f)
1009 mexec = lambda f: 'x' in ctx.fileflags(f)
1007 mlink = lambda f: 'l' in ctx.fileflags(f)
1010 mlink = lambda f: 'l' in ctx.fileflags(f)
1008 is_exec = util.execfunc(self.root, mexec)
1011 is_exec = util.execfunc(self.root, mexec)
1009 is_link = util.linkfunc(self.root, mlink)
1012 is_link = util.linkfunc(self.root, mlink)
1010 def flags(f):
1013 def flags(f):
1011 return is_link(f) and 'l' or is_exec(f) and 'x' or ''
1014 return is_link(f) and 'l' or is_exec(f) and 'x' or ''
1012 for f in lookup:
1015 for f in lookup:
1013 if (f not in ctx or flags(f) != ctx.fileflags(f)
1016 if (f not in ctx or flags(f) != ctx.fileflags(f)
1014 or ctx[f].cmp(self.wread(f))):
1017 or ctx[f].cmp(self.wread(f))):
1015 modified.append(f)
1018 modified.append(f)
1016 else:
1019 else:
1017 fixup.append(f)
1020 fixup.append(f)
1018 if list_clean:
1021 if list_clean:
1019 clean.append(f)
1022 clean.append(f)
1020
1023
1021 # update dirstate for files that are actually clean
1024 # update dirstate for files that are actually clean
1022 if fixup:
1025 if fixup:
1023 wlock = None
1026 wlock = None
1024 try:
1027 try:
1025 try:
1028 try:
1026 wlock = self.wlock(False)
1029 wlock = self.wlock(False)
1027 except lock.LockException:
1030 except lock.LockException:
1028 pass
1031 pass
1029 if wlock:
1032 if wlock:
1030 for f in fixup:
1033 for f in fixup:
1031 self.dirstate.normal(f)
1034 self.dirstate.normal(f)
1032 finally:
1035 finally:
1033 del wlock
1036 del wlock
1034 else:
1037 else:
1035 # we are comparing working dir against non-parent
1038 # we are comparing working dir against non-parent
1036 # generate a pseudo-manifest for the working dir
1039 # generate a pseudo-manifest for the working dir
1037 # XXX: create it in dirstate.py ?
1040 # XXX: create it in dirstate.py ?
1038 mf2 = mfmatches(self.dirstate.parents()[0])
1041 mf2 = mfmatches(self.dirstate.parents()[0])
1039 is_exec = util.execfunc(self.root, mf2.execf)
1042 is_exec = util.execfunc(self.root, mf2.execf)
1040 is_link = util.linkfunc(self.root, mf2.linkf)
1043 is_link = util.linkfunc(self.root, mf2.linkf)
1041 for f in lookup + modified + added:
1044 for f in lookup + modified + added:
1042 mf2[f] = ""
1045 mf2[f] = ""
1043 mf2.set(f, is_exec(f), is_link(f))
1046 mf2.set(f, is_exec(f), is_link(f))
1044 for f in removed:
1047 for f in removed:
1045 if f in mf2:
1048 if f in mf2:
1046 del mf2[f]
1049 del mf2[f]
1047
1050
1048 else:
1051 else:
1049 # we are comparing two revisions
1052 # we are comparing two revisions
1050 mf2 = mfmatches(node2)
1053 mf2 = mfmatches(node2)
1051
1054
1052 if not compareworking:
1055 if not compareworking:
1053 # flush lists from dirstate before comparing manifests
1056 # flush lists from dirstate before comparing manifests
1054 modified, added, clean = [], [], []
1057 modified, added, clean = [], [], []
1055
1058
1056 # make sure to sort the files so we talk to the disk in a
1059 # make sure to sort the files so we talk to the disk in a
1057 # reasonable order
1060 # reasonable order
1058 mf2keys = mf2.keys()
1061 mf2keys = mf2.keys()
1059 mf2keys.sort()
1062 mf2keys.sort()
1060 getnode = lambda fn: mf1.get(fn, nullid)
1063 getnode = lambda fn: mf1.get(fn, nullid)
1061 for fn in mf2keys:
1064 for fn in mf2keys:
1062 if fn in mf1:
1065 if fn in mf1:
1063 if (mf1.flags(fn) != mf2.flags(fn) or
1066 if (mf1.flags(fn) != mf2.flags(fn) or
1064 (mf1[fn] != mf2[fn] and
1067 (mf1[fn] != mf2[fn] and
1065 (mf2[fn] != "" or fcmp(fn, getnode)))):
1068 (mf2[fn] != "" or fcmp(fn, getnode)))):
1066 modified.append(fn)
1069 modified.append(fn)
1067 elif list_clean:
1070 elif list_clean:
1068 clean.append(fn)
1071 clean.append(fn)
1069 del mf1[fn]
1072 del mf1[fn]
1070 else:
1073 else:
1071 added.append(fn)
1074 added.append(fn)
1072
1075
1073 removed = mf1.keys()
1076 removed = mf1.keys()
1074
1077
1075 # sort and return results:
1078 # sort and return results:
1076 for l in modified, added, removed, deleted, unknown, ignored, clean:
1079 for l in modified, added, removed, deleted, unknown, ignored, clean:
1077 l.sort()
1080 l.sort()
1078 return (modified, added, removed, deleted, unknown, ignored, clean)
1081 return (modified, added, removed, deleted, unknown, ignored, clean)
1079
1082
1080 def add(self, list):
1083 def add(self, list):
1081 wlock = self.wlock()
1084 wlock = self.wlock()
1082 try:
1085 try:
1083 rejected = []
1086 rejected = []
1084 for f in list:
1087 for f in list:
1085 p = self.wjoin(f)
1088 p = self.wjoin(f)
1086 try:
1089 try:
1087 st = os.lstat(p)
1090 st = os.lstat(p)
1088 except:
1091 except:
1089 self.ui.warn(_("%s does not exist!\n") % f)
1092 self.ui.warn(_("%s does not exist!\n") % f)
1090 rejected.append(f)
1093 rejected.append(f)
1091 continue
1094 continue
1092 if st.st_size > 10000000:
1095 if st.st_size > 10000000:
1093 self.ui.warn(_("%s: files over 10MB may cause memory and"
1096 self.ui.warn(_("%s: files over 10MB may cause memory and"
1094 " performance problems\n"
1097 " performance problems\n"
1095 "(use 'hg revert %s' to unadd the file)\n")
1098 "(use 'hg revert %s' to unadd the file)\n")
1096 % (f, f))
1099 % (f, f))
1097 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1100 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1098 self.ui.warn(_("%s not added: only files and symlinks "
1101 self.ui.warn(_("%s not added: only files and symlinks "
1099 "supported currently\n") % f)
1102 "supported currently\n") % f)
1100 rejected.append(p)
1103 rejected.append(p)
1101 elif self.dirstate[f] in 'amn':
1104 elif self.dirstate[f] in 'amn':
1102 self.ui.warn(_("%s already tracked!\n") % f)
1105 self.ui.warn(_("%s already tracked!\n") % f)
1103 elif self.dirstate[f] == 'r':
1106 elif self.dirstate[f] == 'r':
1104 self.dirstate.normallookup(f)
1107 self.dirstate.normallookup(f)
1105 else:
1108 else:
1106 self.dirstate.add(f)
1109 self.dirstate.add(f)
1107 return rejected
1110 return rejected
1108 finally:
1111 finally:
1109 del wlock
1112 del wlock
1110
1113
1111 def forget(self, list):
1114 def forget(self, list):
1112 wlock = self.wlock()
1115 wlock = self.wlock()
1113 try:
1116 try:
1114 for f in list:
1117 for f in list:
1115 if self.dirstate[f] != 'a':
1118 if self.dirstate[f] != 'a':
1116 self.ui.warn(_("%s not added!\n") % f)
1119 self.ui.warn(_("%s not added!\n") % f)
1117 else:
1120 else:
1118 self.dirstate.forget(f)
1121 self.dirstate.forget(f)
1119 finally:
1122 finally:
1120 del wlock
1123 del wlock
1121
1124
1122 def remove(self, list, unlink=False):
1125 def remove(self, list, unlink=False):
1123 wlock = None
1126 wlock = None
1124 try:
1127 try:
1125 if unlink:
1128 if unlink:
1126 for f in list:
1129 for f in list:
1127 try:
1130 try:
1128 util.unlink(self.wjoin(f))
1131 util.unlink(self.wjoin(f))
1129 except OSError, inst:
1132 except OSError, inst:
1130 if inst.errno != errno.ENOENT:
1133 if inst.errno != errno.ENOENT:
1131 raise
1134 raise
1132 wlock = self.wlock()
1135 wlock = self.wlock()
1133 for f in list:
1136 for f in list:
1134 if unlink and os.path.exists(self.wjoin(f)):
1137 if unlink and os.path.exists(self.wjoin(f)):
1135 self.ui.warn(_("%s still exists!\n") % f)
1138 self.ui.warn(_("%s still exists!\n") % f)
1136 elif self.dirstate[f] == 'a':
1139 elif self.dirstate[f] == 'a':
1137 self.dirstate.forget(f)
1140 self.dirstate.forget(f)
1138 elif f not in self.dirstate:
1141 elif f not in self.dirstate:
1139 self.ui.warn(_("%s not tracked!\n") % f)
1142 self.ui.warn(_("%s not tracked!\n") % f)
1140 else:
1143 else:
1141 self.dirstate.remove(f)
1144 self.dirstate.remove(f)
1142 finally:
1145 finally:
1143 del wlock
1146 del wlock
1144
1147
1145 def undelete(self, list):
1148 def undelete(self, list):
1146 wlock = None
1149 wlock = None
1147 try:
1150 try:
1148 manifests = [self.manifest.read(self.changelog.read(p)[0])
1151 manifests = [self.manifest.read(self.changelog.read(p)[0])
1149 for p in self.dirstate.parents() if p != nullid]
1152 for p in self.dirstate.parents() if p != nullid]
1150 wlock = self.wlock()
1153 wlock = self.wlock()
1151 for f in list:
1154 for f in list:
1152 if self.dirstate[f] != 'r':
1155 if self.dirstate[f] != 'r':
1153 self.ui.warn("%s not removed!\n" % f)
1156 self.ui.warn("%s not removed!\n" % f)
1154 else:
1157 else:
1155 m = f in manifests[0] and manifests[0] or manifests[1]
1158 m = f in manifests[0] and manifests[0] or manifests[1]
1156 t = self.file(f).read(m[f])
1159 t = self.file(f).read(m[f])
1157 self.wwrite(f, t, m.flags(f))
1160 self.wwrite(f, t, m.flags(f))
1158 self.dirstate.normal(f)
1161 self.dirstate.normal(f)
1159 finally:
1162 finally:
1160 del wlock
1163 del wlock
1161
1164
1162 def copy(self, source, dest):
1165 def copy(self, source, dest):
1163 wlock = None
1166 wlock = None
1164 try:
1167 try:
1165 p = self.wjoin(dest)
1168 p = self.wjoin(dest)
1166 if not (os.path.exists(p) or os.path.islink(p)):
1169 if not (os.path.exists(p) or os.path.islink(p)):
1167 self.ui.warn(_("%s does not exist!\n") % dest)
1170 self.ui.warn(_("%s does not exist!\n") % dest)
1168 elif not (os.path.isfile(p) or os.path.islink(p)):
1171 elif not (os.path.isfile(p) or os.path.islink(p)):
1169 self.ui.warn(_("copy failed: %s is not a file or a "
1172 self.ui.warn(_("copy failed: %s is not a file or a "
1170 "symbolic link\n") % dest)
1173 "symbolic link\n") % dest)
1171 else:
1174 else:
1172 wlock = self.wlock()
1175 wlock = self.wlock()
1173 if dest not in self.dirstate:
1176 if dest not in self.dirstate:
1174 self.dirstate.add(dest)
1177 self.dirstate.add(dest)
1175 self.dirstate.copy(source, dest)
1178 self.dirstate.copy(source, dest)
1176 finally:
1179 finally:
1177 del wlock
1180 del wlock
1178
1181
1179 def heads(self, start=None):
1182 def heads(self, start=None):
1180 heads = self.changelog.heads(start)
1183 heads = self.changelog.heads(start)
1181 # sort the output in rev descending order
1184 # sort the output in rev descending order
1182 heads = [(-self.changelog.rev(h), h) for h in heads]
1185 heads = [(-self.changelog.rev(h), h) for h in heads]
1183 heads.sort()
1186 heads.sort()
1184 return [n for (r, n) in heads]
1187 return [n for (r, n) in heads]
1185
1188
1186 def branchheads(self, branch, start=None):
1189 def branchheads(self, branch, start=None):
1187 branches = self.branchtags()
1190 branches = self.branchtags()
1188 if branch not in branches:
1191 if branch not in branches:
1189 return []
1192 return []
1190 # The basic algorithm is this:
1193 # The basic algorithm is this:
1191 #
1194 #
1192 # Start from the branch tip since there are no later revisions that can
1195 # Start from the branch tip since there are no later revisions that can
1193 # possibly be in this branch, and the tip is a guaranteed head.
1196 # possibly be in this branch, and the tip is a guaranteed head.
1194 #
1197 #
1195 # Remember the tip's parents as the first ancestors, since these by
1198 # Remember the tip's parents as the first ancestors, since these by
1196 # definition are not heads.
1199 # definition are not heads.
1197 #
1200 #
1198 # Step backwards from the brach tip through all the revisions. We are
1201 # Step backwards from the brach tip through all the revisions. We are
1199 # guaranteed by the rules of Mercurial that we will now be visiting the
1202 # guaranteed by the rules of Mercurial that we will now be visiting the
1200 # nodes in reverse topological order (children before parents).
1203 # nodes in reverse topological order (children before parents).
1201 #
1204 #
1202 # If a revision is one of the ancestors of a head then we can toss it
1205 # If a revision is one of the ancestors of a head then we can toss it
1203 # out of the ancestors set (we've already found it and won't be
1206 # out of the ancestors set (we've already found it and won't be
1204 # visiting it again) and put its parents in the ancestors set.
1207 # visiting it again) and put its parents in the ancestors set.
1205 #
1208 #
1206 # Otherwise, if a revision is in the branch it's another head, since it
1209 # Otherwise, if a revision is in the branch it's another head, since it
1207 # wasn't in the ancestor list of an existing head. So add it to the
1210 # wasn't in the ancestor list of an existing head. So add it to the
1208 # head list, and add its parents to the ancestor list.
1211 # head list, and add its parents to the ancestor list.
1209 #
1212 #
1210 # If it is not in the branch ignore it.
1213 # If it is not in the branch ignore it.
1211 #
1214 #
1212 # Once we have a list of heads, use nodesbetween to filter out all the
1215 # Once we have a list of heads, use nodesbetween to filter out all the
1213 # heads that cannot be reached from startrev. There may be a more
1216 # heads that cannot be reached from startrev. There may be a more
1214 # efficient way to do this as part of the previous algorithm.
1217 # efficient way to do this as part of the previous algorithm.
1215
1218
1216 set = util.set
1219 set = util.set
1217 heads = [self.changelog.rev(branches[branch])]
1220 heads = [self.changelog.rev(branches[branch])]
1218 # Don't care if ancestors contains nullrev or not.
1221 # Don't care if ancestors contains nullrev or not.
1219 ancestors = set(self.changelog.parentrevs(heads[0]))
1222 ancestors = set(self.changelog.parentrevs(heads[0]))
1220 for rev in xrange(heads[0] - 1, nullrev, -1):
1223 for rev in xrange(heads[0] - 1, nullrev, -1):
1221 if rev in ancestors:
1224 if rev in ancestors:
1222 ancestors.update(self.changelog.parentrevs(rev))
1225 ancestors.update(self.changelog.parentrevs(rev))
1223 ancestors.remove(rev)
1226 ancestors.remove(rev)
1224 elif self.changectx(rev).branch() == branch:
1227 elif self.changectx(rev).branch() == branch:
1225 heads.append(rev)
1228 heads.append(rev)
1226 ancestors.update(self.changelog.parentrevs(rev))
1229 ancestors.update(self.changelog.parentrevs(rev))
1227 heads = [self.changelog.node(rev) for rev in heads]
1230 heads = [self.changelog.node(rev) for rev in heads]
1228 if start is not None:
1231 if start is not None:
1229 heads = self.changelog.nodesbetween([start], heads)[2]
1232 heads = self.changelog.nodesbetween([start], heads)[2]
1230 return heads
1233 return heads
1231
1234
1232 def branches(self, nodes):
1235 def branches(self, nodes):
1233 if not nodes:
1236 if not nodes:
1234 nodes = [self.changelog.tip()]
1237 nodes = [self.changelog.tip()]
1235 b = []
1238 b = []
1236 for n in nodes:
1239 for n in nodes:
1237 t = n
1240 t = n
1238 while 1:
1241 while 1:
1239 p = self.changelog.parents(n)
1242 p = self.changelog.parents(n)
1240 if p[1] != nullid or p[0] == nullid:
1243 if p[1] != nullid or p[0] == nullid:
1241 b.append((t, n, p[0], p[1]))
1244 b.append((t, n, p[0], p[1]))
1242 break
1245 break
1243 n = p[0]
1246 n = p[0]
1244 return b
1247 return b
1245
1248
1246 def between(self, pairs):
1249 def between(self, pairs):
1247 r = []
1250 r = []
1248
1251
1249 for top, bottom in pairs:
1252 for top, bottom in pairs:
1250 n, l, i = top, [], 0
1253 n, l, i = top, [], 0
1251 f = 1
1254 f = 1
1252
1255
1253 while n != bottom:
1256 while n != bottom:
1254 p = self.changelog.parents(n)[0]
1257 p = self.changelog.parents(n)[0]
1255 if i == f:
1258 if i == f:
1256 l.append(n)
1259 l.append(n)
1257 f = f * 2
1260 f = f * 2
1258 n = p
1261 n = p
1259 i += 1
1262 i += 1
1260
1263
1261 r.append(l)
1264 r.append(l)
1262
1265
1263 return r
1266 return r
1264
1267
1265 def findincoming(self, remote, base=None, heads=None, force=False):
1268 def findincoming(self, remote, base=None, heads=None, force=False):
1266 """Return list of roots of the subsets of missing nodes from remote
1269 """Return list of roots of the subsets of missing nodes from remote
1267
1270
1268 If base dict is specified, assume that these nodes and their parents
1271 If base dict is specified, assume that these nodes and their parents
1269 exist on the remote side and that no child of a node of base exists
1272 exist on the remote side and that no child of a node of base exists
1270 in both remote and self.
1273 in both remote and self.
1271 Furthermore base will be updated to include the nodes that exists
1274 Furthermore base will be updated to include the nodes that exists
1272 in self and remote but no children exists in self and remote.
1275 in self and remote but no children exists in self and remote.
1273 If a list of heads is specified, return only nodes which are heads
1276 If a list of heads is specified, return only nodes which are heads
1274 or ancestors of these heads.
1277 or ancestors of these heads.
1275
1278
1276 All the ancestors of base are in self and in remote.
1279 All the ancestors of base are in self and in remote.
1277 All the descendants of the list returned are missing in self.
1280 All the descendants of the list returned are missing in self.
1278 (and so we know that the rest of the nodes are missing in remote, see
1281 (and so we know that the rest of the nodes are missing in remote, see
1279 outgoing)
1282 outgoing)
1280 """
1283 """
1281 m = self.changelog.nodemap
1284 m = self.changelog.nodemap
1282 search = []
1285 search = []
1283 fetch = {}
1286 fetch = {}
1284 seen = {}
1287 seen = {}
1285 seenbranch = {}
1288 seenbranch = {}
1286 if base == None:
1289 if base == None:
1287 base = {}
1290 base = {}
1288
1291
1289 if not heads:
1292 if not heads:
1290 heads = remote.heads()
1293 heads = remote.heads()
1291
1294
1292 if self.changelog.tip() == nullid:
1295 if self.changelog.tip() == nullid:
1293 base[nullid] = 1
1296 base[nullid] = 1
1294 if heads != [nullid]:
1297 if heads != [nullid]:
1295 return [nullid]
1298 return [nullid]
1296 return []
1299 return []
1297
1300
1298 # assume we're closer to the tip than the root
1301 # assume we're closer to the tip than the root
1299 # and start by examining the heads
1302 # and start by examining the heads
1300 self.ui.status(_("searching for changes\n"))
1303 self.ui.status(_("searching for changes\n"))
1301
1304
1302 unknown = []
1305 unknown = []
1303 for h in heads:
1306 for h in heads:
1304 if h not in m:
1307 if h not in m:
1305 unknown.append(h)
1308 unknown.append(h)
1306 else:
1309 else:
1307 base[h] = 1
1310 base[h] = 1
1308
1311
1309 if not unknown:
1312 if not unknown:
1310 return []
1313 return []
1311
1314
1312 req = dict.fromkeys(unknown)
1315 req = dict.fromkeys(unknown)
1313 reqcnt = 0
1316 reqcnt = 0
1314
1317
1315 # search through remote branches
1318 # search through remote branches
1316 # a 'branch' here is a linear segment of history, with four parts:
1319 # a 'branch' here is a linear segment of history, with four parts:
1317 # head, root, first parent, second parent
1320 # head, root, first parent, second parent
1318 # (a branch always has two parents (or none) by definition)
1321 # (a branch always has two parents (or none) by definition)
1319 unknown = remote.branches(unknown)
1322 unknown = remote.branches(unknown)
1320 while unknown:
1323 while unknown:
1321 r = []
1324 r = []
1322 while unknown:
1325 while unknown:
1323 n = unknown.pop(0)
1326 n = unknown.pop(0)
1324 if n[0] in seen:
1327 if n[0] in seen:
1325 continue
1328 continue
1326
1329
1327 self.ui.debug(_("examining %s:%s\n")
1330 self.ui.debug(_("examining %s:%s\n")
1328 % (short(n[0]), short(n[1])))
1331 % (short(n[0]), short(n[1])))
1329 if n[0] == nullid: # found the end of the branch
1332 if n[0] == nullid: # found the end of the branch
1330 pass
1333 pass
1331 elif n in seenbranch:
1334 elif n in seenbranch:
1332 self.ui.debug(_("branch already found\n"))
1335 self.ui.debug(_("branch already found\n"))
1333 continue
1336 continue
1334 elif n[1] and n[1] in m: # do we know the base?
1337 elif n[1] and n[1] in m: # do we know the base?
1335 self.ui.debug(_("found incomplete branch %s:%s\n")
1338 self.ui.debug(_("found incomplete branch %s:%s\n")
1336 % (short(n[0]), short(n[1])))
1339 % (short(n[0]), short(n[1])))
1337 search.append(n) # schedule branch range for scanning
1340 search.append(n) # schedule branch range for scanning
1338 seenbranch[n] = 1
1341 seenbranch[n] = 1
1339 else:
1342 else:
1340 if n[1] not in seen and n[1] not in fetch:
1343 if n[1] not in seen and n[1] not in fetch:
1341 if n[2] in m and n[3] in m:
1344 if n[2] in m and n[3] in m:
1342 self.ui.debug(_("found new changeset %s\n") %
1345 self.ui.debug(_("found new changeset %s\n") %
1343 short(n[1]))
1346 short(n[1]))
1344 fetch[n[1]] = 1 # earliest unknown
1347 fetch[n[1]] = 1 # earliest unknown
1345 for p in n[2:4]:
1348 for p in n[2:4]:
1346 if p in m:
1349 if p in m:
1347 base[p] = 1 # latest known
1350 base[p] = 1 # latest known
1348
1351
1349 for p in n[2:4]:
1352 for p in n[2:4]:
1350 if p not in req and p not in m:
1353 if p not in req and p not in m:
1351 r.append(p)
1354 r.append(p)
1352 req[p] = 1
1355 req[p] = 1
1353 seen[n[0]] = 1
1356 seen[n[0]] = 1
1354
1357
1355 if r:
1358 if r:
1356 reqcnt += 1
1359 reqcnt += 1
1357 self.ui.debug(_("request %d: %s\n") %
1360 self.ui.debug(_("request %d: %s\n") %
1358 (reqcnt, " ".join(map(short, r))))
1361 (reqcnt, " ".join(map(short, r))))
1359 for p in xrange(0, len(r), 10):
1362 for p in xrange(0, len(r), 10):
1360 for b in remote.branches(r[p:p+10]):
1363 for b in remote.branches(r[p:p+10]):
1361 self.ui.debug(_("received %s:%s\n") %
1364 self.ui.debug(_("received %s:%s\n") %
1362 (short(b[0]), short(b[1])))
1365 (short(b[0]), short(b[1])))
1363 unknown.append(b)
1366 unknown.append(b)
1364
1367
1365 # do binary search on the branches we found
1368 # do binary search on the branches we found
1366 while search:
1369 while search:
1367 n = search.pop(0)
1370 n = search.pop(0)
1368 reqcnt += 1
1371 reqcnt += 1
1369 l = remote.between([(n[0], n[1])])[0]
1372 l = remote.between([(n[0], n[1])])[0]
1370 l.append(n[1])
1373 l.append(n[1])
1371 p = n[0]
1374 p = n[0]
1372 f = 1
1375 f = 1
1373 for i in l:
1376 for i in l:
1374 self.ui.debug(_("narrowing %d:%d %s\n") % (f, len(l), short(i)))
1377 self.ui.debug(_("narrowing %d:%d %s\n") % (f, len(l), short(i)))
1375 if i in m:
1378 if i in m:
1376 if f <= 2:
1379 if f <= 2:
1377 self.ui.debug(_("found new branch changeset %s\n") %
1380 self.ui.debug(_("found new branch changeset %s\n") %
1378 short(p))
1381 short(p))
1379 fetch[p] = 1
1382 fetch[p] = 1
1380 base[i] = 1
1383 base[i] = 1
1381 else:
1384 else:
1382 self.ui.debug(_("narrowed branch search to %s:%s\n")
1385 self.ui.debug(_("narrowed branch search to %s:%s\n")
1383 % (short(p), short(i)))
1386 % (short(p), short(i)))
1384 search.append((p, i))
1387 search.append((p, i))
1385 break
1388 break
1386 p, f = i, f * 2
1389 p, f = i, f * 2
1387
1390
1388 # sanity check our fetch list
1391 # sanity check our fetch list
1389 for f in fetch.keys():
1392 for f in fetch.keys():
1390 if f in m:
1393 if f in m:
1391 raise repo.RepoError(_("already have changeset ") + short(f[:4]))
1394 raise repo.RepoError(_("already have changeset ") + short(f[:4]))
1392
1395
1393 if base.keys() == [nullid]:
1396 if base.keys() == [nullid]:
1394 if force:
1397 if force:
1395 self.ui.warn(_("warning: repository is unrelated\n"))
1398 self.ui.warn(_("warning: repository is unrelated\n"))
1396 else:
1399 else:
1397 raise util.Abort(_("repository is unrelated"))
1400 raise util.Abort(_("repository is unrelated"))
1398
1401
1399 self.ui.debug(_("found new changesets starting at ") +
1402 self.ui.debug(_("found new changesets starting at ") +
1400 " ".join([short(f) for f in fetch]) + "\n")
1403 " ".join([short(f) for f in fetch]) + "\n")
1401
1404
1402 self.ui.debug(_("%d total queries\n") % reqcnt)
1405 self.ui.debug(_("%d total queries\n") % reqcnt)
1403
1406
1404 return fetch.keys()
1407 return fetch.keys()
1405
1408
1406 def findoutgoing(self, remote, base=None, heads=None, force=False):
1409 def findoutgoing(self, remote, base=None, heads=None, force=False):
1407 """Return list of nodes that are roots of subsets not in remote
1410 """Return list of nodes that are roots of subsets not in remote
1408
1411
1409 If base dict is specified, assume that these nodes and their parents
1412 If base dict is specified, assume that these nodes and their parents
1410 exist on the remote side.
1413 exist on the remote side.
1411 If a list of heads is specified, return only nodes which are heads
1414 If a list of heads is specified, return only nodes which are heads
1412 or ancestors of these heads, and return a second element which
1415 or ancestors of these heads, and return a second element which
1413 contains all remote heads which get new children.
1416 contains all remote heads which get new children.
1414 """
1417 """
1415 if base == None:
1418 if base == None:
1416 base = {}
1419 base = {}
1417 self.findincoming(remote, base, heads, force=force)
1420 self.findincoming(remote, base, heads, force=force)
1418
1421
1419 self.ui.debug(_("common changesets up to ")
1422 self.ui.debug(_("common changesets up to ")
1420 + " ".join(map(short, base.keys())) + "\n")
1423 + " ".join(map(short, base.keys())) + "\n")
1421
1424
1422 remain = dict.fromkeys(self.changelog.nodemap)
1425 remain = dict.fromkeys(self.changelog.nodemap)
1423
1426
1424 # prune everything remote has from the tree
1427 # prune everything remote has from the tree
1425 del remain[nullid]
1428 del remain[nullid]
1426 remove = base.keys()
1429 remove = base.keys()
1427 while remove:
1430 while remove:
1428 n = remove.pop(0)
1431 n = remove.pop(0)
1429 if n in remain:
1432 if n in remain:
1430 del remain[n]
1433 del remain[n]
1431 for p in self.changelog.parents(n):
1434 for p in self.changelog.parents(n):
1432 remove.append(p)
1435 remove.append(p)
1433
1436
1434 # find every node whose parents have been pruned
1437 # find every node whose parents have been pruned
1435 subset = []
1438 subset = []
1436 # find every remote head that will get new children
1439 # find every remote head that will get new children
1437 updated_heads = {}
1440 updated_heads = {}
1438 for n in remain:
1441 for n in remain:
1439 p1, p2 = self.changelog.parents(n)
1442 p1, p2 = self.changelog.parents(n)
1440 if p1 not in remain and p2 not in remain:
1443 if p1 not in remain and p2 not in remain:
1441 subset.append(n)
1444 subset.append(n)
1442 if heads:
1445 if heads:
1443 if p1 in heads:
1446 if p1 in heads:
1444 updated_heads[p1] = True
1447 updated_heads[p1] = True
1445 if p2 in heads:
1448 if p2 in heads:
1446 updated_heads[p2] = True
1449 updated_heads[p2] = True
1447
1450
1448 # this is the set of all roots we have to push
1451 # this is the set of all roots we have to push
1449 if heads:
1452 if heads:
1450 return subset, updated_heads.keys()
1453 return subset, updated_heads.keys()
1451 else:
1454 else:
1452 return subset
1455 return subset
1453
1456
1454 def pull(self, remote, heads=None, force=False):
1457 def pull(self, remote, heads=None, force=False):
1455 lock = self.lock()
1458 lock = self.lock()
1456 try:
1459 try:
1457 fetch = self.findincoming(remote, heads=heads, force=force)
1460 fetch = self.findincoming(remote, heads=heads, force=force)
1458 if fetch == [nullid]:
1461 if fetch == [nullid]:
1459 self.ui.status(_("requesting all changes\n"))
1462 self.ui.status(_("requesting all changes\n"))
1460
1463
1461 if not fetch:
1464 if not fetch:
1462 self.ui.status(_("no changes found\n"))
1465 self.ui.status(_("no changes found\n"))
1463 return 0
1466 return 0
1464
1467
1465 if heads is None:
1468 if heads is None:
1466 cg = remote.changegroup(fetch, 'pull')
1469 cg = remote.changegroup(fetch, 'pull')
1467 else:
1470 else:
1468 if 'changegroupsubset' not in remote.capabilities:
1471 if 'changegroupsubset' not in remote.capabilities:
1469 raise util.Abort(_("Partial pull cannot be done because other repository doesn't support changegroupsubset."))
1472 raise util.Abort(_("Partial pull cannot be done because other repository doesn't support changegroupsubset."))
1470 cg = remote.changegroupsubset(fetch, heads, 'pull')
1473 cg = remote.changegroupsubset(fetch, heads, 'pull')
1471 return self.addchangegroup(cg, 'pull', remote.url())
1474 return self.addchangegroup(cg, 'pull', remote.url())
1472 finally:
1475 finally:
1473 del lock
1476 del lock
1474
1477
1475 def push(self, remote, force=False, revs=None):
1478 def push(self, remote, force=False, revs=None):
1476 # there are two ways to push to remote repo:
1479 # there are two ways to push to remote repo:
1477 #
1480 #
1478 # addchangegroup assumes local user can lock remote
1481 # addchangegroup assumes local user can lock remote
1479 # repo (local filesystem, old ssh servers).
1482 # repo (local filesystem, old ssh servers).
1480 #
1483 #
1481 # unbundle assumes local user cannot lock remote repo (new ssh
1484 # unbundle assumes local user cannot lock remote repo (new ssh
1482 # servers, http servers).
1485 # servers, http servers).
1483
1486
1484 if remote.capable('unbundle'):
1487 if remote.capable('unbundle'):
1485 return self.push_unbundle(remote, force, revs)
1488 return self.push_unbundle(remote, force, revs)
1486 return self.push_addchangegroup(remote, force, revs)
1489 return self.push_addchangegroup(remote, force, revs)
1487
1490
1488 def prepush(self, remote, force, revs):
1491 def prepush(self, remote, force, revs):
1489 base = {}
1492 base = {}
1490 remote_heads = remote.heads()
1493 remote_heads = remote.heads()
1491 inc = self.findincoming(remote, base, remote_heads, force=force)
1494 inc = self.findincoming(remote, base, remote_heads, force=force)
1492
1495
1493 update, updated_heads = self.findoutgoing(remote, base, remote_heads)
1496 update, updated_heads = self.findoutgoing(remote, base, remote_heads)
1494 if revs is not None:
1497 if revs is not None:
1495 msng_cl, bases, heads = self.changelog.nodesbetween(update, revs)
1498 msng_cl, bases, heads = self.changelog.nodesbetween(update, revs)
1496 else:
1499 else:
1497 bases, heads = update, self.changelog.heads()
1500 bases, heads = update, self.changelog.heads()
1498
1501
1499 if not bases:
1502 if not bases:
1500 self.ui.status(_("no changes found\n"))
1503 self.ui.status(_("no changes found\n"))
1501 return None, 1
1504 return None, 1
1502 elif not force:
1505 elif not force:
1503 # check if we're creating new remote heads
1506 # check if we're creating new remote heads
1504 # to be a remote head after push, node must be either
1507 # to be a remote head after push, node must be either
1505 # - unknown locally
1508 # - unknown locally
1506 # - a local outgoing head descended from update
1509 # - a local outgoing head descended from update
1507 # - a remote head that's known locally and not
1510 # - a remote head that's known locally and not
1508 # ancestral to an outgoing head
1511 # ancestral to an outgoing head
1509
1512
1510 warn = 0
1513 warn = 0
1511
1514
1512 if remote_heads == [nullid]:
1515 if remote_heads == [nullid]:
1513 warn = 0
1516 warn = 0
1514 elif not revs and len(heads) > len(remote_heads):
1517 elif not revs and len(heads) > len(remote_heads):
1515 warn = 1
1518 warn = 1
1516 else:
1519 else:
1517 newheads = list(heads)
1520 newheads = list(heads)
1518 for r in remote_heads:
1521 for r in remote_heads:
1519 if r in self.changelog.nodemap:
1522 if r in self.changelog.nodemap:
1520 desc = self.changelog.heads(r, heads)
1523 desc = self.changelog.heads(r, heads)
1521 l = [h for h in heads if h in desc]
1524 l = [h for h in heads if h in desc]
1522 if not l:
1525 if not l:
1523 newheads.append(r)
1526 newheads.append(r)
1524 else:
1527 else:
1525 newheads.append(r)
1528 newheads.append(r)
1526 if len(newheads) > len(remote_heads):
1529 if len(newheads) > len(remote_heads):
1527 warn = 1
1530 warn = 1
1528
1531
1529 if warn:
1532 if warn:
1530 self.ui.warn(_("abort: push creates new remote heads!\n"))
1533 self.ui.warn(_("abort: push creates new remote heads!\n"))
1531 self.ui.status(_("(did you forget to merge?"
1534 self.ui.status(_("(did you forget to merge?"
1532 " use push -f to force)\n"))
1535 " use push -f to force)\n"))
1533 return None, 0
1536 return None, 0
1534 elif inc:
1537 elif inc:
1535 self.ui.warn(_("note: unsynced remote changes!\n"))
1538 self.ui.warn(_("note: unsynced remote changes!\n"))
1536
1539
1537
1540
1538 if revs is None:
1541 if revs is None:
1539 cg = self.changegroup(update, 'push')
1542 cg = self.changegroup(update, 'push')
1540 else:
1543 else:
1541 cg = self.changegroupsubset(update, revs, 'push')
1544 cg = self.changegroupsubset(update, revs, 'push')
1542 return cg, remote_heads
1545 return cg, remote_heads
1543
1546
1544 def push_addchangegroup(self, remote, force, revs):
1547 def push_addchangegroup(self, remote, force, revs):
1545 lock = remote.lock()
1548 lock = remote.lock()
1546 try:
1549 try:
1547 ret = self.prepush(remote, force, revs)
1550 ret = self.prepush(remote, force, revs)
1548 if ret[0] is not None:
1551 if ret[0] is not None:
1549 cg, remote_heads = ret
1552 cg, remote_heads = ret
1550 return remote.addchangegroup(cg, 'push', self.url())
1553 return remote.addchangegroup(cg, 'push', self.url())
1551 return ret[1]
1554 return ret[1]
1552 finally:
1555 finally:
1553 del lock
1556 del lock
1554
1557
1555 def push_unbundle(self, remote, force, revs):
1558 def push_unbundle(self, remote, force, revs):
1556 # local repo finds heads on server, finds out what revs it
1559 # local repo finds heads on server, finds out what revs it
1557 # must push. once revs transferred, if server finds it has
1560 # must push. once revs transferred, if server finds it has
1558 # different heads (someone else won commit/push race), server
1561 # different heads (someone else won commit/push race), server
1559 # aborts.
1562 # aborts.
1560
1563
1561 ret = self.prepush(remote, force, revs)
1564 ret = self.prepush(remote, force, revs)
1562 if ret[0] is not None:
1565 if ret[0] is not None:
1563 cg, remote_heads = ret
1566 cg, remote_heads = ret
1564 if force: remote_heads = ['force']
1567 if force: remote_heads = ['force']
1565 return remote.unbundle(cg, remote_heads, 'push')
1568 return remote.unbundle(cg, remote_heads, 'push')
1566 return ret[1]
1569 return ret[1]
1567
1570
1568 def changegroupinfo(self, nodes, source):
1571 def changegroupinfo(self, nodes, source):
1569 if self.ui.verbose or source == 'bundle':
1572 if self.ui.verbose or source == 'bundle':
1570 self.ui.status(_("%d changesets found\n") % len(nodes))
1573 self.ui.status(_("%d changesets found\n") % len(nodes))
1571 if self.ui.debugflag:
1574 if self.ui.debugflag:
1572 self.ui.debug(_("List of changesets:\n"))
1575 self.ui.debug(_("List of changesets:\n"))
1573 for node in nodes:
1576 for node in nodes:
1574 self.ui.debug("%s\n" % hex(node))
1577 self.ui.debug("%s\n" % hex(node))
1575
1578
1576 def changegroupsubset(self, bases, heads, source, extranodes=None):
1579 def changegroupsubset(self, bases, heads, source, extranodes=None):
1577 """This function generates a changegroup consisting of all the nodes
1580 """This function generates a changegroup consisting of all the nodes
1578 that are descendents of any of the bases, and ancestors of any of
1581 that are descendents of any of the bases, and ancestors of any of
1579 the heads.
1582 the heads.
1580
1583
1581 It is fairly complex as determining which filenodes and which
1584 It is fairly complex as determining which filenodes and which
1582 manifest nodes need to be included for the changeset to be complete
1585 manifest nodes need to be included for the changeset to be complete
1583 is non-trivial.
1586 is non-trivial.
1584
1587
1585 Another wrinkle is doing the reverse, figuring out which changeset in
1588 Another wrinkle is doing the reverse, figuring out which changeset in
1586 the changegroup a particular filenode or manifestnode belongs to.
1589 the changegroup a particular filenode or manifestnode belongs to.
1587
1590
1588 The caller can specify some nodes that must be included in the
1591 The caller can specify some nodes that must be included in the
1589 changegroup using the extranodes argument. It should be a dict
1592 changegroup using the extranodes argument. It should be a dict
1590 where the keys are the filenames (or 1 for the manifest), and the
1593 where the keys are the filenames (or 1 for the manifest), and the
1591 values are lists of (node, linknode) tuples, where node is a wanted
1594 values are lists of (node, linknode) tuples, where node is a wanted
1592 node and linknode is the changelog node that should be transmitted as
1595 node and linknode is the changelog node that should be transmitted as
1593 the linkrev.
1596 the linkrev.
1594 """
1597 """
1595
1598
1596 self.hook('preoutgoing', throw=True, source=source)
1599 self.hook('preoutgoing', throw=True, source=source)
1597
1600
1598 # Set up some initial variables
1601 # Set up some initial variables
1599 # Make it easy to refer to self.changelog
1602 # Make it easy to refer to self.changelog
1600 cl = self.changelog
1603 cl = self.changelog
1601 # msng is short for missing - compute the list of changesets in this
1604 # msng is short for missing - compute the list of changesets in this
1602 # changegroup.
1605 # changegroup.
1603 msng_cl_lst, bases, heads = cl.nodesbetween(bases, heads)
1606 msng_cl_lst, bases, heads = cl.nodesbetween(bases, heads)
1604 self.changegroupinfo(msng_cl_lst, source)
1607 self.changegroupinfo(msng_cl_lst, source)
1605 # Some bases may turn out to be superfluous, and some heads may be
1608 # Some bases may turn out to be superfluous, and some heads may be
1606 # too. nodesbetween will return the minimal set of bases and heads
1609 # too. nodesbetween will return the minimal set of bases and heads
1607 # necessary to re-create the changegroup.
1610 # necessary to re-create the changegroup.
1608
1611
1609 # Known heads are the list of heads that it is assumed the recipient
1612 # Known heads are the list of heads that it is assumed the recipient
1610 # of this changegroup will know about.
1613 # of this changegroup will know about.
1611 knownheads = {}
1614 knownheads = {}
1612 # We assume that all parents of bases are known heads.
1615 # We assume that all parents of bases are known heads.
1613 for n in bases:
1616 for n in bases:
1614 for p in cl.parents(n):
1617 for p in cl.parents(n):
1615 if p != nullid:
1618 if p != nullid:
1616 knownheads[p] = 1
1619 knownheads[p] = 1
1617 knownheads = knownheads.keys()
1620 knownheads = knownheads.keys()
1618 if knownheads:
1621 if knownheads:
1619 # Now that we know what heads are known, we can compute which
1622 # Now that we know what heads are known, we can compute which
1620 # changesets are known. The recipient must know about all
1623 # changesets are known. The recipient must know about all
1621 # changesets required to reach the known heads from the null
1624 # changesets required to reach the known heads from the null
1622 # changeset.
1625 # changeset.
1623 has_cl_set, junk, junk = cl.nodesbetween(None, knownheads)
1626 has_cl_set, junk, junk = cl.nodesbetween(None, knownheads)
1624 junk = None
1627 junk = None
1625 # Transform the list into an ersatz set.
1628 # Transform the list into an ersatz set.
1626 has_cl_set = dict.fromkeys(has_cl_set)
1629 has_cl_set = dict.fromkeys(has_cl_set)
1627 else:
1630 else:
1628 # If there were no known heads, the recipient cannot be assumed to
1631 # If there were no known heads, the recipient cannot be assumed to
1629 # know about any changesets.
1632 # know about any changesets.
1630 has_cl_set = {}
1633 has_cl_set = {}
1631
1634
1632 # Make it easy to refer to self.manifest
1635 # Make it easy to refer to self.manifest
1633 mnfst = self.manifest
1636 mnfst = self.manifest
1634 # We don't know which manifests are missing yet
1637 # We don't know which manifests are missing yet
1635 msng_mnfst_set = {}
1638 msng_mnfst_set = {}
1636 # Nor do we know which filenodes are missing.
1639 # Nor do we know which filenodes are missing.
1637 msng_filenode_set = {}
1640 msng_filenode_set = {}
1638
1641
1639 junk = mnfst.index[mnfst.count() - 1] # Get around a bug in lazyindex
1642 junk = mnfst.index[mnfst.count() - 1] # Get around a bug in lazyindex
1640 junk = None
1643 junk = None
1641
1644
1642 # A changeset always belongs to itself, so the changenode lookup
1645 # A changeset always belongs to itself, so the changenode lookup
1643 # function for a changenode is identity.
1646 # function for a changenode is identity.
1644 def identity(x):
1647 def identity(x):
1645 return x
1648 return x
1646
1649
1647 # A function generating function. Sets up an environment for the
1650 # A function generating function. Sets up an environment for the
1648 # inner function.
1651 # inner function.
1649 def cmp_by_rev_func(revlog):
1652 def cmp_by_rev_func(revlog):
1650 # Compare two nodes by their revision number in the environment's
1653 # Compare two nodes by their revision number in the environment's
1651 # revision history. Since the revision number both represents the
1654 # revision history. Since the revision number both represents the
1652 # most efficient order to read the nodes in, and represents a
1655 # most efficient order to read the nodes in, and represents a
1653 # topological sorting of the nodes, this function is often useful.
1656 # topological sorting of the nodes, this function is often useful.
1654 def cmp_by_rev(a, b):
1657 def cmp_by_rev(a, b):
1655 return cmp(revlog.rev(a), revlog.rev(b))
1658 return cmp(revlog.rev(a), revlog.rev(b))
1656 return cmp_by_rev
1659 return cmp_by_rev
1657
1660
1658 # If we determine that a particular file or manifest node must be a
1661 # If we determine that a particular file or manifest node must be a
1659 # node that the recipient of the changegroup will already have, we can
1662 # node that the recipient of the changegroup will already have, we can
1660 # also assume the recipient will have all the parents. This function
1663 # also assume the recipient will have all the parents. This function
1661 # prunes them from the set of missing nodes.
1664 # prunes them from the set of missing nodes.
1662 def prune_parents(revlog, hasset, msngset):
1665 def prune_parents(revlog, hasset, msngset):
1663 haslst = hasset.keys()
1666 haslst = hasset.keys()
1664 haslst.sort(cmp_by_rev_func(revlog))
1667 haslst.sort(cmp_by_rev_func(revlog))
1665 for node in haslst:
1668 for node in haslst:
1666 parentlst = [p for p in revlog.parents(node) if p != nullid]
1669 parentlst = [p for p in revlog.parents(node) if p != nullid]
1667 while parentlst:
1670 while parentlst:
1668 n = parentlst.pop()
1671 n = parentlst.pop()
1669 if n not in hasset:
1672 if n not in hasset:
1670 hasset[n] = 1
1673 hasset[n] = 1
1671 p = [p for p in revlog.parents(n) if p != nullid]
1674 p = [p for p in revlog.parents(n) if p != nullid]
1672 parentlst.extend(p)
1675 parentlst.extend(p)
1673 for n in hasset:
1676 for n in hasset:
1674 msngset.pop(n, None)
1677 msngset.pop(n, None)
1675
1678
1676 # This is a function generating function used to set up an environment
1679 # This is a function generating function used to set up an environment
1677 # for the inner function to execute in.
1680 # for the inner function to execute in.
1678 def manifest_and_file_collector(changedfileset):
1681 def manifest_and_file_collector(changedfileset):
1679 # This is an information gathering function that gathers
1682 # This is an information gathering function that gathers
1680 # information from each changeset node that goes out as part of
1683 # information from each changeset node that goes out as part of
1681 # the changegroup. The information gathered is a list of which
1684 # the changegroup. The information gathered is a list of which
1682 # manifest nodes are potentially required (the recipient may
1685 # manifest nodes are potentially required (the recipient may
1683 # already have them) and total list of all files which were
1686 # already have them) and total list of all files which were
1684 # changed in any changeset in the changegroup.
1687 # changed in any changeset in the changegroup.
1685 #
1688 #
1686 # We also remember the first changenode we saw any manifest
1689 # We also remember the first changenode we saw any manifest
1687 # referenced by so we can later determine which changenode 'owns'
1690 # referenced by so we can later determine which changenode 'owns'
1688 # the manifest.
1691 # the manifest.
1689 def collect_manifests_and_files(clnode):
1692 def collect_manifests_and_files(clnode):
1690 c = cl.read(clnode)
1693 c = cl.read(clnode)
1691 for f in c[3]:
1694 for f in c[3]:
1692 # This is to make sure we only have one instance of each
1695 # This is to make sure we only have one instance of each
1693 # filename string for each filename.
1696 # filename string for each filename.
1694 changedfileset.setdefault(f, f)
1697 changedfileset.setdefault(f, f)
1695 msng_mnfst_set.setdefault(c[0], clnode)
1698 msng_mnfst_set.setdefault(c[0], clnode)
1696 return collect_manifests_and_files
1699 return collect_manifests_and_files
1697
1700
1698 # Figure out which manifest nodes (of the ones we think might be part
1701 # Figure out which manifest nodes (of the ones we think might be part
1699 # of the changegroup) the recipient must know about and remove them
1702 # of the changegroup) the recipient must know about and remove them
1700 # from the changegroup.
1703 # from the changegroup.
1701 def prune_manifests():
1704 def prune_manifests():
1702 has_mnfst_set = {}
1705 has_mnfst_set = {}
1703 for n in msng_mnfst_set:
1706 for n in msng_mnfst_set:
1704 # If a 'missing' manifest thinks it belongs to a changenode
1707 # If a 'missing' manifest thinks it belongs to a changenode
1705 # the recipient is assumed to have, obviously the recipient
1708 # the recipient is assumed to have, obviously the recipient
1706 # must have that manifest.
1709 # must have that manifest.
1707 linknode = cl.node(mnfst.linkrev(n))
1710 linknode = cl.node(mnfst.linkrev(n))
1708 if linknode in has_cl_set:
1711 if linknode in has_cl_set:
1709 has_mnfst_set[n] = 1
1712 has_mnfst_set[n] = 1
1710 prune_parents(mnfst, has_mnfst_set, msng_mnfst_set)
1713 prune_parents(mnfst, has_mnfst_set, msng_mnfst_set)
1711
1714
1712 # Use the information collected in collect_manifests_and_files to say
1715 # Use the information collected in collect_manifests_and_files to say
1713 # which changenode any manifestnode belongs to.
1716 # which changenode any manifestnode belongs to.
1714 def lookup_manifest_link(mnfstnode):
1717 def lookup_manifest_link(mnfstnode):
1715 return msng_mnfst_set[mnfstnode]
1718 return msng_mnfst_set[mnfstnode]
1716
1719
1717 # A function generating function that sets up the initial environment
1720 # A function generating function that sets up the initial environment
1718 # the inner function.
1721 # the inner function.
1719 def filenode_collector(changedfiles):
1722 def filenode_collector(changedfiles):
1720 next_rev = [0]
1723 next_rev = [0]
1721 # This gathers information from each manifestnode included in the
1724 # This gathers information from each manifestnode included in the
1722 # changegroup about which filenodes the manifest node references
1725 # changegroup about which filenodes the manifest node references
1723 # so we can include those in the changegroup too.
1726 # so we can include those in the changegroup too.
1724 #
1727 #
1725 # It also remembers which changenode each filenode belongs to. It
1728 # It also remembers which changenode each filenode belongs to. It
1726 # does this by assuming the a filenode belongs to the changenode
1729 # does this by assuming the a filenode belongs to the changenode
1727 # the first manifest that references it belongs to.
1730 # the first manifest that references it belongs to.
1728 def collect_msng_filenodes(mnfstnode):
1731 def collect_msng_filenodes(mnfstnode):
1729 r = mnfst.rev(mnfstnode)
1732 r = mnfst.rev(mnfstnode)
1730 if r == next_rev[0]:
1733 if r == next_rev[0]:
1731 # If the last rev we looked at was the one just previous,
1734 # If the last rev we looked at was the one just previous,
1732 # we only need to see a diff.
1735 # we only need to see a diff.
1733 deltamf = mnfst.readdelta(mnfstnode)
1736 deltamf = mnfst.readdelta(mnfstnode)
1734 # For each line in the delta
1737 # For each line in the delta
1735 for f, fnode in deltamf.items():
1738 for f, fnode in deltamf.items():
1736 f = changedfiles.get(f, None)
1739 f = changedfiles.get(f, None)
1737 # And if the file is in the list of files we care
1740 # And if the file is in the list of files we care
1738 # about.
1741 # about.
1739 if f is not None:
1742 if f is not None:
1740 # Get the changenode this manifest belongs to
1743 # Get the changenode this manifest belongs to
1741 clnode = msng_mnfst_set[mnfstnode]
1744 clnode = msng_mnfst_set[mnfstnode]
1742 # Create the set of filenodes for the file if
1745 # Create the set of filenodes for the file if
1743 # there isn't one already.
1746 # there isn't one already.
1744 ndset = msng_filenode_set.setdefault(f, {})
1747 ndset = msng_filenode_set.setdefault(f, {})
1745 # And set the filenode's changelog node to the
1748 # And set the filenode's changelog node to the
1746 # manifest's if it hasn't been set already.
1749 # manifest's if it hasn't been set already.
1747 ndset.setdefault(fnode, clnode)
1750 ndset.setdefault(fnode, clnode)
1748 else:
1751 else:
1749 # Otherwise we need a full manifest.
1752 # Otherwise we need a full manifest.
1750 m = mnfst.read(mnfstnode)
1753 m = mnfst.read(mnfstnode)
1751 # For every file in we care about.
1754 # For every file in we care about.
1752 for f in changedfiles:
1755 for f in changedfiles:
1753 fnode = m.get(f, None)
1756 fnode = m.get(f, None)
1754 # If it's in the manifest
1757 # If it's in the manifest
1755 if fnode is not None:
1758 if fnode is not None:
1756 # See comments above.
1759 # See comments above.
1757 clnode = msng_mnfst_set[mnfstnode]
1760 clnode = msng_mnfst_set[mnfstnode]
1758 ndset = msng_filenode_set.setdefault(f, {})
1761 ndset = msng_filenode_set.setdefault(f, {})
1759 ndset.setdefault(fnode, clnode)
1762 ndset.setdefault(fnode, clnode)
1760 # Remember the revision we hope to see next.
1763 # Remember the revision we hope to see next.
1761 next_rev[0] = r + 1
1764 next_rev[0] = r + 1
1762 return collect_msng_filenodes
1765 return collect_msng_filenodes
1763
1766
1764 # We have a list of filenodes we think we need for a file, lets remove
1767 # We have a list of filenodes we think we need for a file, lets remove
1765 # all those we now the recipient must have.
1768 # all those we now the recipient must have.
1766 def prune_filenodes(f, filerevlog):
1769 def prune_filenodes(f, filerevlog):
1767 msngset = msng_filenode_set[f]
1770 msngset = msng_filenode_set[f]
1768 hasset = {}
1771 hasset = {}
1769 # If a 'missing' filenode thinks it belongs to a changenode we
1772 # If a 'missing' filenode thinks it belongs to a changenode we
1770 # assume the recipient must have, then the recipient must have
1773 # assume the recipient must have, then the recipient must have
1771 # that filenode.
1774 # that filenode.
1772 for n in msngset:
1775 for n in msngset:
1773 clnode = cl.node(filerevlog.linkrev(n))
1776 clnode = cl.node(filerevlog.linkrev(n))
1774 if clnode in has_cl_set:
1777 if clnode in has_cl_set:
1775 hasset[n] = 1
1778 hasset[n] = 1
1776 prune_parents(filerevlog, hasset, msngset)
1779 prune_parents(filerevlog, hasset, msngset)
1777
1780
1778 # A function generator function that sets up the a context for the
1781 # A function generator function that sets up the a context for the
1779 # inner function.
1782 # inner function.
1780 def lookup_filenode_link_func(fname):
1783 def lookup_filenode_link_func(fname):
1781 msngset = msng_filenode_set[fname]
1784 msngset = msng_filenode_set[fname]
1782 # Lookup the changenode the filenode belongs to.
1785 # Lookup the changenode the filenode belongs to.
1783 def lookup_filenode_link(fnode):
1786 def lookup_filenode_link(fnode):
1784 return msngset[fnode]
1787 return msngset[fnode]
1785 return lookup_filenode_link
1788 return lookup_filenode_link
1786
1789
1787 # Add the nodes that were explicitly requested.
1790 # Add the nodes that were explicitly requested.
1788 def add_extra_nodes(name, nodes):
1791 def add_extra_nodes(name, nodes):
1789 if not extranodes or name not in extranodes:
1792 if not extranodes or name not in extranodes:
1790 return
1793 return
1791
1794
1792 for node, linknode in extranodes[name]:
1795 for node, linknode in extranodes[name]:
1793 if node not in nodes:
1796 if node not in nodes:
1794 nodes[node] = linknode
1797 nodes[node] = linknode
1795
1798
1796 # Now that we have all theses utility functions to help out and
1799 # Now that we have all theses utility functions to help out and
1797 # logically divide up the task, generate the group.
1800 # logically divide up the task, generate the group.
1798 def gengroup():
1801 def gengroup():
1799 # The set of changed files starts empty.
1802 # The set of changed files starts empty.
1800 changedfiles = {}
1803 changedfiles = {}
1801 # Create a changenode group generator that will call our functions
1804 # Create a changenode group generator that will call our functions
1802 # back to lookup the owning changenode and collect information.
1805 # back to lookup the owning changenode and collect information.
1803 group = cl.group(msng_cl_lst, identity,
1806 group = cl.group(msng_cl_lst, identity,
1804 manifest_and_file_collector(changedfiles))
1807 manifest_and_file_collector(changedfiles))
1805 for chnk in group:
1808 for chnk in group:
1806 yield chnk
1809 yield chnk
1807
1810
1808 # The list of manifests has been collected by the generator
1811 # The list of manifests has been collected by the generator
1809 # calling our functions back.
1812 # calling our functions back.
1810 prune_manifests()
1813 prune_manifests()
1811 add_extra_nodes(1, msng_mnfst_set)
1814 add_extra_nodes(1, msng_mnfst_set)
1812 msng_mnfst_lst = msng_mnfst_set.keys()
1815 msng_mnfst_lst = msng_mnfst_set.keys()
1813 # Sort the manifestnodes by revision number.
1816 # Sort the manifestnodes by revision number.
1814 msng_mnfst_lst.sort(cmp_by_rev_func(mnfst))
1817 msng_mnfst_lst.sort(cmp_by_rev_func(mnfst))
1815 # Create a generator for the manifestnodes that calls our lookup
1818 # Create a generator for the manifestnodes that calls our lookup
1816 # and data collection functions back.
1819 # and data collection functions back.
1817 group = mnfst.group(msng_mnfst_lst, lookup_manifest_link,
1820 group = mnfst.group(msng_mnfst_lst, lookup_manifest_link,
1818 filenode_collector(changedfiles))
1821 filenode_collector(changedfiles))
1819 for chnk in group:
1822 for chnk in group:
1820 yield chnk
1823 yield chnk
1821
1824
1822 # These are no longer needed, dereference and toss the memory for
1825 # These are no longer needed, dereference and toss the memory for
1823 # them.
1826 # them.
1824 msng_mnfst_lst = None
1827 msng_mnfst_lst = None
1825 msng_mnfst_set.clear()
1828 msng_mnfst_set.clear()
1826
1829
1827 if extranodes:
1830 if extranodes:
1828 for fname in extranodes:
1831 for fname in extranodes:
1829 if isinstance(fname, int):
1832 if isinstance(fname, int):
1830 continue
1833 continue
1831 add_extra_nodes(fname,
1834 add_extra_nodes(fname,
1832 msng_filenode_set.setdefault(fname, {}))
1835 msng_filenode_set.setdefault(fname, {}))
1833 changedfiles[fname] = 1
1836 changedfiles[fname] = 1
1834 changedfiles = changedfiles.keys()
1837 changedfiles = changedfiles.keys()
1835 changedfiles.sort()
1838 changedfiles.sort()
1836 # Go through all our files in order sorted by name.
1839 # Go through all our files in order sorted by name.
1837 for fname in changedfiles:
1840 for fname in changedfiles:
1838 filerevlog = self.file(fname)
1841 filerevlog = self.file(fname)
1839 if filerevlog.count() == 0:
1842 if filerevlog.count() == 0:
1840 raise util.Abort(_("empty or missing revlog for %s") % fname)
1843 raise util.Abort(_("empty or missing revlog for %s") % fname)
1841 # Toss out the filenodes that the recipient isn't really
1844 # Toss out the filenodes that the recipient isn't really
1842 # missing.
1845 # missing.
1843 if fname in msng_filenode_set:
1846 if fname in msng_filenode_set:
1844 prune_filenodes(fname, filerevlog)
1847 prune_filenodes(fname, filerevlog)
1845 msng_filenode_lst = msng_filenode_set[fname].keys()
1848 msng_filenode_lst = msng_filenode_set[fname].keys()
1846 else:
1849 else:
1847 msng_filenode_lst = []
1850 msng_filenode_lst = []
1848 # If any filenodes are left, generate the group for them,
1851 # If any filenodes are left, generate the group for them,
1849 # otherwise don't bother.
1852 # otherwise don't bother.
1850 if len(msng_filenode_lst) > 0:
1853 if len(msng_filenode_lst) > 0:
1851 yield changegroup.chunkheader(len(fname))
1854 yield changegroup.chunkheader(len(fname))
1852 yield fname
1855 yield fname
1853 # Sort the filenodes by their revision #
1856 # Sort the filenodes by their revision #
1854 msng_filenode_lst.sort(cmp_by_rev_func(filerevlog))
1857 msng_filenode_lst.sort(cmp_by_rev_func(filerevlog))
1855 # Create a group generator and only pass in a changenode
1858 # Create a group generator and only pass in a changenode
1856 # lookup function as we need to collect no information
1859 # lookup function as we need to collect no information
1857 # from filenodes.
1860 # from filenodes.
1858 group = filerevlog.group(msng_filenode_lst,
1861 group = filerevlog.group(msng_filenode_lst,
1859 lookup_filenode_link_func(fname))
1862 lookup_filenode_link_func(fname))
1860 for chnk in group:
1863 for chnk in group:
1861 yield chnk
1864 yield chnk
1862 if fname in msng_filenode_set:
1865 if fname in msng_filenode_set:
1863 # Don't need this anymore, toss it to free memory.
1866 # Don't need this anymore, toss it to free memory.
1864 del msng_filenode_set[fname]
1867 del msng_filenode_set[fname]
1865 # Signal that no more groups are left.
1868 # Signal that no more groups are left.
1866 yield changegroup.closechunk()
1869 yield changegroup.closechunk()
1867
1870
1868 if msng_cl_lst:
1871 if msng_cl_lst:
1869 self.hook('outgoing', node=hex(msng_cl_lst[0]), source=source)
1872 self.hook('outgoing', node=hex(msng_cl_lst[0]), source=source)
1870
1873
1871 return util.chunkbuffer(gengroup())
1874 return util.chunkbuffer(gengroup())
1872
1875
1873 def changegroup(self, basenodes, source):
1876 def changegroup(self, basenodes, source):
1874 """Generate a changegroup of all nodes that we have that a recipient
1877 """Generate a changegroup of all nodes that we have that a recipient
1875 doesn't.
1878 doesn't.
1876
1879
1877 This is much easier than the previous function as we can assume that
1880 This is much easier than the previous function as we can assume that
1878 the recipient has any changenode we aren't sending them."""
1881 the recipient has any changenode we aren't sending them."""
1879
1882
1880 self.hook('preoutgoing', throw=True, source=source)
1883 self.hook('preoutgoing', throw=True, source=source)
1881
1884
1882 cl = self.changelog
1885 cl = self.changelog
1883 nodes = cl.nodesbetween(basenodes, None)[0]
1886 nodes = cl.nodesbetween(basenodes, None)[0]
1884 revset = dict.fromkeys([cl.rev(n) for n in nodes])
1887 revset = dict.fromkeys([cl.rev(n) for n in nodes])
1885 self.changegroupinfo(nodes, source)
1888 self.changegroupinfo(nodes, source)
1886
1889
1887 def identity(x):
1890 def identity(x):
1888 return x
1891 return x
1889
1892
1890 def gennodelst(revlog):
1893 def gennodelst(revlog):
1891 for r in xrange(0, revlog.count()):
1894 for r in xrange(0, revlog.count()):
1892 n = revlog.node(r)
1895 n = revlog.node(r)
1893 if revlog.linkrev(n) in revset:
1896 if revlog.linkrev(n) in revset:
1894 yield n
1897 yield n
1895
1898
1896 def changed_file_collector(changedfileset):
1899 def changed_file_collector(changedfileset):
1897 def collect_changed_files(clnode):
1900 def collect_changed_files(clnode):
1898 c = cl.read(clnode)
1901 c = cl.read(clnode)
1899 for fname in c[3]:
1902 for fname in c[3]:
1900 changedfileset[fname] = 1
1903 changedfileset[fname] = 1
1901 return collect_changed_files
1904 return collect_changed_files
1902
1905
1903 def lookuprevlink_func(revlog):
1906 def lookuprevlink_func(revlog):
1904 def lookuprevlink(n):
1907 def lookuprevlink(n):
1905 return cl.node(revlog.linkrev(n))
1908 return cl.node(revlog.linkrev(n))
1906 return lookuprevlink
1909 return lookuprevlink
1907
1910
1908 def gengroup():
1911 def gengroup():
1909 # construct a list of all changed files
1912 # construct a list of all changed files
1910 changedfiles = {}
1913 changedfiles = {}
1911
1914
1912 for chnk in cl.group(nodes, identity,
1915 for chnk in cl.group(nodes, identity,
1913 changed_file_collector(changedfiles)):
1916 changed_file_collector(changedfiles)):
1914 yield chnk
1917 yield chnk
1915 changedfiles = changedfiles.keys()
1918 changedfiles = changedfiles.keys()
1916 changedfiles.sort()
1919 changedfiles.sort()
1917
1920
1918 mnfst = self.manifest
1921 mnfst = self.manifest
1919 nodeiter = gennodelst(mnfst)
1922 nodeiter = gennodelst(mnfst)
1920 for chnk in mnfst.group(nodeiter, lookuprevlink_func(mnfst)):
1923 for chnk in mnfst.group(nodeiter, lookuprevlink_func(mnfst)):
1921 yield chnk
1924 yield chnk
1922
1925
1923 for fname in changedfiles:
1926 for fname in changedfiles:
1924 filerevlog = self.file(fname)
1927 filerevlog = self.file(fname)
1925 if filerevlog.count() == 0:
1928 if filerevlog.count() == 0:
1926 raise util.Abort(_("empty or missing revlog for %s") % fname)
1929 raise util.Abort(_("empty or missing revlog for %s") % fname)
1927 nodeiter = gennodelst(filerevlog)
1930 nodeiter = gennodelst(filerevlog)
1928 nodeiter = list(nodeiter)
1931 nodeiter = list(nodeiter)
1929 if nodeiter:
1932 if nodeiter:
1930 yield changegroup.chunkheader(len(fname))
1933 yield changegroup.chunkheader(len(fname))
1931 yield fname
1934 yield fname
1932 lookup = lookuprevlink_func(filerevlog)
1935 lookup = lookuprevlink_func(filerevlog)
1933 for chnk in filerevlog.group(nodeiter, lookup):
1936 for chnk in filerevlog.group(nodeiter, lookup):
1934 yield chnk
1937 yield chnk
1935
1938
1936 yield changegroup.closechunk()
1939 yield changegroup.closechunk()
1937
1940
1938 if nodes:
1941 if nodes:
1939 self.hook('outgoing', node=hex(nodes[0]), source=source)
1942 self.hook('outgoing', node=hex(nodes[0]), source=source)
1940
1943
1941 return util.chunkbuffer(gengroup())
1944 return util.chunkbuffer(gengroup())
1942
1945
1943 def addchangegroup(self, source, srctype, url, emptyok=False):
1946 def addchangegroup(self, source, srctype, url, emptyok=False):
1944 """add changegroup to repo.
1947 """add changegroup to repo.
1945
1948
1946 return values:
1949 return values:
1947 - nothing changed or no source: 0
1950 - nothing changed or no source: 0
1948 - more heads than before: 1+added heads (2..n)
1951 - more heads than before: 1+added heads (2..n)
1949 - less heads than before: -1-removed heads (-2..-n)
1952 - less heads than before: -1-removed heads (-2..-n)
1950 - number of heads stays the same: 1
1953 - number of heads stays the same: 1
1951 """
1954 """
1952 def csmap(x):
1955 def csmap(x):
1953 self.ui.debug(_("add changeset %s\n") % short(x))
1956 self.ui.debug(_("add changeset %s\n") % short(x))
1954 return cl.count()
1957 return cl.count()
1955
1958
1956 def revmap(x):
1959 def revmap(x):
1957 return cl.rev(x)
1960 return cl.rev(x)
1958
1961
1959 if not source:
1962 if not source:
1960 return 0
1963 return 0
1961
1964
1962 self.hook('prechangegroup', throw=True, source=srctype, url=url)
1965 self.hook('prechangegroup', throw=True, source=srctype, url=url)
1963
1966
1964 changesets = files = revisions = 0
1967 changesets = files = revisions = 0
1965
1968
1966 # write changelog data to temp files so concurrent readers will not see
1969 # write changelog data to temp files so concurrent readers will not see
1967 # inconsistent view
1970 # inconsistent view
1968 cl = self.changelog
1971 cl = self.changelog
1969 cl.delayupdate()
1972 cl.delayupdate()
1970 oldheads = len(cl.heads())
1973 oldheads = len(cl.heads())
1971
1974
1972 tr = self.transaction()
1975 tr = self.transaction()
1973 try:
1976 try:
1974 trp = weakref.proxy(tr)
1977 trp = weakref.proxy(tr)
1975 # pull off the changeset group
1978 # pull off the changeset group
1976 self.ui.status(_("adding changesets\n"))
1979 self.ui.status(_("adding changesets\n"))
1977 cor = cl.count() - 1
1980 cor = cl.count() - 1
1978 chunkiter = changegroup.chunkiter(source)
1981 chunkiter = changegroup.chunkiter(source)
1979 if cl.addgroup(chunkiter, csmap, trp) is None and not emptyok:
1982 if cl.addgroup(chunkiter, csmap, trp) is None and not emptyok:
1980 raise util.Abort(_("received changelog group is empty"))
1983 raise util.Abort(_("received changelog group is empty"))
1981 cnr = cl.count() - 1
1984 cnr = cl.count() - 1
1982 changesets = cnr - cor
1985 changesets = cnr - cor
1983
1986
1984 # pull off the manifest group
1987 # pull off the manifest group
1985 self.ui.status(_("adding manifests\n"))
1988 self.ui.status(_("adding manifests\n"))
1986 chunkiter = changegroup.chunkiter(source)
1989 chunkiter = changegroup.chunkiter(source)
1987 # no need to check for empty manifest group here:
1990 # no need to check for empty manifest group here:
1988 # if the result of the merge of 1 and 2 is the same in 3 and 4,
1991 # if the result of the merge of 1 and 2 is the same in 3 and 4,
1989 # no new manifest will be created and the manifest group will
1992 # no new manifest will be created and the manifest group will
1990 # be empty during the pull
1993 # be empty during the pull
1991 self.manifest.addgroup(chunkiter, revmap, trp)
1994 self.manifest.addgroup(chunkiter, revmap, trp)
1992
1995
1993 # process the files
1996 # process the files
1994 self.ui.status(_("adding file changes\n"))
1997 self.ui.status(_("adding file changes\n"))
1995 while 1:
1998 while 1:
1996 f = changegroup.getchunk(source)
1999 f = changegroup.getchunk(source)
1997 if not f:
2000 if not f:
1998 break
2001 break
1999 self.ui.debug(_("adding %s revisions\n") % f)
2002 self.ui.debug(_("adding %s revisions\n") % f)
2000 fl = self.file(f)
2003 fl = self.file(f)
2001 o = fl.count()
2004 o = fl.count()
2002 chunkiter = changegroup.chunkiter(source)
2005 chunkiter = changegroup.chunkiter(source)
2003 if fl.addgroup(chunkiter, revmap, trp) is None:
2006 if fl.addgroup(chunkiter, revmap, trp) is None:
2004 raise util.Abort(_("received file revlog group is empty"))
2007 raise util.Abort(_("received file revlog group is empty"))
2005 revisions += fl.count() - o
2008 revisions += fl.count() - o
2006 files += 1
2009 files += 1
2007
2010
2008 # make changelog see real files again
2011 # make changelog see real files again
2009 cl.finalize(trp)
2012 cl.finalize(trp)
2010
2013
2011 newheads = len(self.changelog.heads())
2014 newheads = len(self.changelog.heads())
2012 heads = ""
2015 heads = ""
2013 if oldheads and newheads != oldheads:
2016 if oldheads and newheads != oldheads:
2014 heads = _(" (%+d heads)") % (newheads - oldheads)
2017 heads = _(" (%+d heads)") % (newheads - oldheads)
2015
2018
2016 self.ui.status(_("added %d changesets"
2019 self.ui.status(_("added %d changesets"
2017 " with %d changes to %d files%s\n")
2020 " with %d changes to %d files%s\n")
2018 % (changesets, revisions, files, heads))
2021 % (changesets, revisions, files, heads))
2019
2022
2020 if changesets > 0:
2023 if changesets > 0:
2021 self.hook('pretxnchangegroup', throw=True,
2024 self.hook('pretxnchangegroup', throw=True,
2022 node=hex(self.changelog.node(cor+1)), source=srctype,
2025 node=hex(self.changelog.node(cor+1)), source=srctype,
2023 url=url)
2026 url=url)
2024
2027
2025 tr.close()
2028 tr.close()
2026 finally:
2029 finally:
2027 del tr
2030 del tr
2028
2031
2029 if changesets > 0:
2032 if changesets > 0:
2030 # forcefully update the on-disk branch cache
2033 # forcefully update the on-disk branch cache
2031 self.ui.debug(_("updating the branch cache\n"))
2034 self.ui.debug(_("updating the branch cache\n"))
2032 self.branchtags()
2035 self.branchtags()
2033 self.hook("changegroup", node=hex(self.changelog.node(cor+1)),
2036 self.hook("changegroup", node=hex(self.changelog.node(cor+1)),
2034 source=srctype, url=url)
2037 source=srctype, url=url)
2035
2038
2036 for i in xrange(cor + 1, cnr + 1):
2039 for i in xrange(cor + 1, cnr + 1):
2037 self.hook("incoming", node=hex(self.changelog.node(i)),
2040 self.hook("incoming", node=hex(self.changelog.node(i)),
2038 source=srctype, url=url)
2041 source=srctype, url=url)
2039
2042
2040 # never return 0 here:
2043 # never return 0 here:
2041 if newheads < oldheads:
2044 if newheads < oldheads:
2042 return newheads - oldheads - 1
2045 return newheads - oldheads - 1
2043 else:
2046 else:
2044 return newheads - oldheads + 1
2047 return newheads - oldheads + 1
2045
2048
2046
2049
2047 def stream_in(self, remote):
2050 def stream_in(self, remote):
2048 fp = remote.stream_out()
2051 fp = remote.stream_out()
2049 l = fp.readline()
2052 l = fp.readline()
2050 try:
2053 try:
2051 resp = int(l)
2054 resp = int(l)
2052 except ValueError:
2055 except ValueError:
2053 raise util.UnexpectedOutput(
2056 raise util.UnexpectedOutput(
2054 _('Unexpected response from remote server:'), l)
2057 _('Unexpected response from remote server:'), l)
2055 if resp == 1:
2058 if resp == 1:
2056 raise util.Abort(_('operation forbidden by server'))
2059 raise util.Abort(_('operation forbidden by server'))
2057 elif resp == 2:
2060 elif resp == 2:
2058 raise util.Abort(_('locking the remote repository failed'))
2061 raise util.Abort(_('locking the remote repository failed'))
2059 elif resp != 0:
2062 elif resp != 0:
2060 raise util.Abort(_('the server sent an unknown error code'))
2063 raise util.Abort(_('the server sent an unknown error code'))
2061 self.ui.status(_('streaming all changes\n'))
2064 self.ui.status(_('streaming all changes\n'))
2062 l = fp.readline()
2065 l = fp.readline()
2063 try:
2066 try:
2064 total_files, total_bytes = map(int, l.split(' ', 1))
2067 total_files, total_bytes = map(int, l.split(' ', 1))
2065 except (ValueError, TypeError):
2068 except (ValueError, TypeError):
2066 raise util.UnexpectedOutput(
2069 raise util.UnexpectedOutput(
2067 _('Unexpected response from remote server:'), l)
2070 _('Unexpected response from remote server:'), l)
2068 self.ui.status(_('%d files to transfer, %s of data\n') %
2071 self.ui.status(_('%d files to transfer, %s of data\n') %
2069 (total_files, util.bytecount(total_bytes)))
2072 (total_files, util.bytecount(total_bytes)))
2070 start = time.time()
2073 start = time.time()
2071 for i in xrange(total_files):
2074 for i in xrange(total_files):
2072 # XXX doesn't support '\n' or '\r' in filenames
2075 # XXX doesn't support '\n' or '\r' in filenames
2073 l = fp.readline()
2076 l = fp.readline()
2074 try:
2077 try:
2075 name, size = l.split('\0', 1)
2078 name, size = l.split('\0', 1)
2076 size = int(size)
2079 size = int(size)
2077 except ValueError, TypeError:
2080 except ValueError, TypeError:
2078 raise util.UnexpectedOutput(
2081 raise util.UnexpectedOutput(
2079 _('Unexpected response from remote server:'), l)
2082 _('Unexpected response from remote server:'), l)
2080 self.ui.debug('adding %s (%s)\n' % (name, util.bytecount(size)))
2083 self.ui.debug('adding %s (%s)\n' % (name, util.bytecount(size)))
2081 ofp = self.sopener(name, 'w')
2084 ofp = self.sopener(name, 'w')
2082 for chunk in util.filechunkiter(fp, limit=size):
2085 for chunk in util.filechunkiter(fp, limit=size):
2083 ofp.write(chunk)
2086 ofp.write(chunk)
2084 ofp.close()
2087 ofp.close()
2085 elapsed = time.time() - start
2088 elapsed = time.time() - start
2086 if elapsed <= 0:
2089 if elapsed <= 0:
2087 elapsed = 0.001
2090 elapsed = 0.001
2088 self.ui.status(_('transferred %s in %.1f seconds (%s/sec)\n') %
2091 self.ui.status(_('transferred %s in %.1f seconds (%s/sec)\n') %
2089 (util.bytecount(total_bytes), elapsed,
2092 (util.bytecount(total_bytes), elapsed,
2090 util.bytecount(total_bytes / elapsed)))
2093 util.bytecount(total_bytes / elapsed)))
2091 self.invalidate()
2094 self.invalidate()
2092 return len(self.heads()) + 1
2095 return len(self.heads()) + 1
2093
2096
2094 def clone(self, remote, heads=[], stream=False):
2097 def clone(self, remote, heads=[], stream=False):
2095 '''clone remote repository.
2098 '''clone remote repository.
2096
2099
2097 keyword arguments:
2100 keyword arguments:
2098 heads: list of revs to clone (forces use of pull)
2101 heads: list of revs to clone (forces use of pull)
2099 stream: use streaming clone if possible'''
2102 stream: use streaming clone if possible'''
2100
2103
2101 # now, all clients that can request uncompressed clones can
2104 # now, all clients that can request uncompressed clones can
2102 # read repo formats supported by all servers that can serve
2105 # read repo formats supported by all servers that can serve
2103 # them.
2106 # them.
2104
2107
2105 # if revlog format changes, client will have to check version
2108 # if revlog format changes, client will have to check version
2106 # and format flags on "stream" capability, and use
2109 # and format flags on "stream" capability, and use
2107 # uncompressed only if compatible.
2110 # uncompressed only if compatible.
2108
2111
2109 if stream and not heads and remote.capable('stream'):
2112 if stream and not heads and remote.capable('stream'):
2110 return self.stream_in(remote)
2113 return self.stream_in(remote)
2111 return self.pull(remote, heads)
2114 return self.pull(remote, heads)
2112
2115
2113 # used to avoid circular references so destructors work
2116 # used to avoid circular references so destructors work
2114 def aftertrans(files):
2117 def aftertrans(files):
2115 renamefiles = [tuple(t) for t in files]
2118 renamefiles = [tuple(t) for t in files]
2116 def a():
2119 def a():
2117 for src, dest in renamefiles:
2120 for src, dest in renamefiles:
2118 util.rename(src, dest)
2121 util.rename(src, dest)
2119 return a
2122 return a
2120
2123
2121 def instance(ui, path, create):
2124 def instance(ui, path, create):
2122 return localrepository(ui, util.drop_scheme('file', path), create)
2125 return localrepository(ui, util.drop_scheme('file', path), create)
2123
2126
2124 def islocal(path):
2127 def islocal(path):
2125 return True
2128 return True
@@ -1,28 +1,26 b''
1 changeset: 0:9426b370c206
1 changeset: 0:9426b370c206
2 tag: tip
2 tag: tip
3 user: My Name <myname@example.com>
3 user: My Name <myname@example.com>
4 date: Mon Jan 12 13:46:40 1970 +0000
4 date: Mon Jan 12 13:46:40 1970 +0000
5 summary: commit-1
5 summary: commit-1
6
6
7 changeset: 1:4997f15a1b24
7 changeset: 1:4997f15a1b24
8 tag: tip
8 tag: tip
9 user: foo@bar.com
9 user: foo@bar.com
10 date: Mon Jan 12 13:46:40 1970 +0000
10 date: Mon Jan 12 13:46:40 1970 +0000
11 summary: commit-1
11 summary: commit-1
12
12
13 changeset: 2:72b8012b424e
13 changeset: 2:72b8012b424e
14 tag: tip
14 tag: tip
15 user: foobar <foo@bar.com>
15 user: foobar <foo@bar.com>
16 date: Mon Jan 12 13:46:40 1970 +0000
16 date: Mon Jan 12 13:46:40 1970 +0000
17 summary: commit-1
17 summary: commit-1
18
18
19 changeset: 3:35ff3067bedd
19 changeset: 3:35ff3067bedd
20 tag: tip
20 tag: tip
21 user: foo@bar.com
21 user: foo@bar.com
22 date: Mon Jan 12 13:46:40 1970 +0000
22 date: Mon Jan 12 13:46:40 1970 +0000
23 summary: commit-1
23 summary: commit-1
24
24
25 transaction abort!
26 rollback completed
27 abort: Please specify a username.
25 abort: Please specify a username.
28 No username found, using user@host instead
26 No username found, using user@host instead
General Comments 0
You need to be logged in to leave comments. Login now