##// END OF EJS Templates
kill some trailing spaces
Dirkjan Ochtman -
r6721:521c6c6f default
parent child Browse files
Show More
@@ -1,761 +1,761 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.
449 date - any valid date string or (unixtime, offset), or None.
450 user - username string, or None.
450 user - username string, or None.
451 extra - a dictionary of extra values, or None.
451 extra - a dictionary of extra values, or None.
452 changes - a list of file lists as returned by localrepo.status()
452 changes - a list of file lists as returned by localrepo.status()
453 or None to use the repository status.
453 or None to use the repository status.
454 """
454 """
455 def __init__(self, repo, parents=None, text="", user=None, date=None,
455 def __init__(self, repo, parents=None, text="", user=None, date=None,
456 extra=None, changes=None):
456 extra=None, changes=None):
457 self._repo = repo
457 self._repo = repo
458 self._rev = None
458 self._rev = None
459 self._node = None
459 self._node = None
460 self._text = text
460 self._text = text
461 if date:
461 if date:
462 self._date = util.parsedate(date)
462 self._date = util.parsedate(date)
463 else:
463 else:
464 self._date = util.makedate()
464 self._date = util.makedate()
465 if user:
465 if user:
466 self._user = user
466 self._user = user
467 else:
467 else:
468 self._user = self._repo.ui.username()
468 self._user = self._repo.ui.username()
469 if parents:
469 if parents:
470 p1, p2 = parents
470 p1, p2 = parents
471 self._parents = [self._repo.changectx(p) for p in (p1, p2)]
471 self._parents = [self._repo.changectx(p) for p in (p1, p2)]
472 if changes:
472 if changes:
473 self._status = list(changes)
473 self._status = list(changes)
474
474
475 self._extra = {}
475 self._extra = {}
476 if extra:
476 if extra:
477 self._extra = extra.copy()
477 self._extra = extra.copy()
478 if 'branch' not in self._extra:
478 if 'branch' not in self._extra:
479 branch = self._repo.dirstate.branch()
479 branch = self._repo.dirstate.branch()
480 try:
480 try:
481 branch = branch.decode('UTF-8').encode('UTF-8')
481 branch = branch.decode('UTF-8').encode('UTF-8')
482 except UnicodeDecodeError:
482 except UnicodeDecodeError:
483 raise util.Abort(_('branch name not in UTF-8!'))
483 raise util.Abort(_('branch name not in UTF-8!'))
484 self._extra['branch'] = branch
484 self._extra['branch'] = branch
485 if self._extra['branch'] == '':
485 if self._extra['branch'] == '':
486 self._extra['branch'] = 'default'
486 self._extra['branch'] = 'default'
487
487
488 def __str__(self):
488 def __str__(self):
489 return str(self._parents[0]) + "+"
489 return str(self._parents[0]) + "+"
490
490
491 def __nonzero__(self):
491 def __nonzero__(self):
492 return True
492 return True
493
493
494 def __getattr__(self, name):
494 def __getattr__(self, name):
495 if name == '_parents':
495 if name == '_parents':
496 self._parents = self._repo.parents()
496 self._parents = self._repo.parents()
497 return self._parents
497 return self._parents
498 if name == '_status':
498 if name == '_status':
499 self._status = self._repo.status()
499 self._status = self._repo.status()
500 return self._status
500 return self._status
501 if name == '_manifest':
501 if name == '_manifest':
502 self._buildmanifest()
502 self._buildmanifest()
503 return self._manifest
503 return self._manifest
504 else:
504 else:
505 raise AttributeError, name
505 raise AttributeError, name
506
506
507 def _buildmanifest(self):
507 def _buildmanifest(self):
508 """generate a manifest corresponding to the working directory"""
508 """generate a manifest corresponding to the working directory"""
509
509
510 man = self._parents[0].manifest().copy()
510 man = self._parents[0].manifest().copy()
511 copied = self._repo.dirstate.copies()
511 copied = self._repo.dirstate.copies()
512 is_exec = util.execfunc(self._repo.root,
512 is_exec = util.execfunc(self._repo.root,
513 lambda p: man.execf(copied.get(p,p)))
513 lambda p: man.execf(copied.get(p,p)))
514 is_link = util.linkfunc(self._repo.root,
514 is_link = util.linkfunc(self._repo.root,
515 lambda p: man.linkf(copied.get(p,p)))
515 lambda p: man.linkf(copied.get(p,p)))
516 modified, added, removed, deleted, unknown = self._status[:5]
516 modified, added, removed, deleted, unknown = self._status[:5]
517 for i, l in (("a", added), ("m", modified), ("u", unknown)):
517 for i, l in (("a", added), ("m", modified), ("u", unknown)):
518 for f in l:
518 for f in l:
519 man[f] = man.get(copied.get(f, f), nullid) + i
519 man[f] = man.get(copied.get(f, f), nullid) + i
520 try:
520 try:
521 man.set(f, is_exec(f), is_link(f))
521 man.set(f, is_exec(f), is_link(f))
522 except OSError:
522 except OSError:
523 pass
523 pass
524
524
525 for f in deleted + removed:
525 for f in deleted + removed:
526 if f in man:
526 if f in man:
527 del man[f]
527 del man[f]
528
528
529 self._manifest = man
529 self._manifest = man
530
530
531 def manifest(self): return self._manifest
531 def manifest(self): return self._manifest
532
532
533 def user(self): return self._user
533 def user(self): return self._user
534 def date(self): return self._date
534 def date(self): return self._date
535 def description(self): return self._text
535 def description(self): return self._text
536 def files(self):
536 def files(self):
537 f = self.modified() + self.added() + self.removed()
537 f = self.modified() + self.added() + self.removed()
538 f.sort()
538 f.sort()
539 return f
539 return f
540
540
541 def modified(self): return self._status[0]
541 def modified(self): return self._status[0]
542 def added(self): return self._status[1]
542 def added(self): return self._status[1]
543 def removed(self): return self._status[2]
543 def removed(self): return self._status[2]
544 def deleted(self): return self._status[3]
544 def deleted(self): return self._status[3]
545 def unknown(self): return self._status[4]
545 def unknown(self): return self._status[4]
546 def clean(self): return self._status[5]
546 def clean(self): return self._status[5]
547 def branch(self): return self._extra['branch']
547 def branch(self): return self._extra['branch']
548 def extra(self): return self._extra
548 def extra(self): return self._extra
549
549
550 def tags(self):
550 def tags(self):
551 t = []
551 t = []
552 [t.extend(p.tags()) for p in self.parents()]
552 [t.extend(p.tags()) for p in self.parents()]
553 return t
553 return t
554
554
555 def parents(self):
555 def parents(self):
556 """return contexts for each parent changeset"""
556 """return contexts for each parent changeset"""
557 return self._parents
557 return self._parents
558
558
559 def children(self):
559 def children(self):
560 return []
560 return []
561
561
562 def fileflags(self, path):
562 def fileflags(self, path):
563 if '_manifest' in self.__dict__:
563 if '_manifest' in self.__dict__:
564 try:
564 try:
565 return self._manifest.flags(path)
565 return self._manifest.flags(path)
566 except KeyError:
566 except KeyError:
567 return ''
567 return ''
568
568
569 pnode = self._parents[0].changeset()[0]
569 pnode = self._parents[0].changeset()[0]
570 orig = self._repo.dirstate.copies().get(path, path)
570 orig = self._repo.dirstate.copies().get(path, path)
571 node, flag = self._repo.manifest.find(pnode, orig)
571 node, flag = self._repo.manifest.find(pnode, orig)
572 is_link = util.linkfunc(self._repo.root,
572 is_link = util.linkfunc(self._repo.root,
573 lambda p: flag and 'l' in flag)
573 lambda p: flag and 'l' in flag)
574 is_exec = util.execfunc(self._repo.root,
574 is_exec = util.execfunc(self._repo.root,
575 lambda p: flag and 'x' in flag)
575 lambda p: flag and 'x' in flag)
576 try:
576 try:
577 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 '')
578 except OSError:
578 except OSError:
579 pass
579 pass
580
580
581 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():
582 return ''
582 return ''
583 return flag
583 return flag
584
584
585 def filectx(self, path, filelog=None):
585 def filectx(self, path, filelog=None):
586 """get a file context from the working directory"""
586 """get a file context from the working directory"""
587 return workingfilectx(self._repo, path, workingctx=self,
587 return workingfilectx(self._repo, path, workingctx=self,
588 filelog=filelog)
588 filelog=filelog)
589
589
590 def ancestor(self, c2):
590 def ancestor(self, c2):
591 """return the ancestor context of self and c2"""
591 """return the ancestor context of self and c2"""
592 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
593
593
594 class workingfilectx(filectx):
594 class workingfilectx(filectx):
595 """A workingfilectx object makes access to data related to a particular
595 """A workingfilectx object makes access to data related to a particular
596 file in the working directory convenient."""
596 file in the working directory convenient."""
597 def __init__(self, repo, path, filelog=None, workingctx=None):
597 def __init__(self, repo, path, filelog=None, workingctx=None):
598 """changeid can be a changeset revision, node, or tag.
598 """changeid can be a changeset revision, node, or tag.
599 fileid can be a file revision or node."""
599 fileid can be a file revision or node."""
600 self._repo = repo
600 self._repo = repo
601 self._path = path
601 self._path = path
602 self._changeid = None
602 self._changeid = None
603 self._filerev = self._filenode = None
603 self._filerev = self._filenode = None
604
604
605 if filelog:
605 if filelog:
606 self._filelog = filelog
606 self._filelog = filelog
607 if workingctx:
607 if workingctx:
608 self._changectx = workingctx
608 self._changectx = workingctx
609
609
610 def __getattr__(self, name):
610 def __getattr__(self, name):
611 if name == '_changectx':
611 if name == '_changectx':
612 self._changectx = workingctx(self._repo)
612 self._changectx = workingctx(self._repo)
613 return self._changectx
613 return self._changectx
614 elif name == '_repopath':
614 elif name == '_repopath':
615 self._repopath = (self._repo.dirstate.copied(self._path)
615 self._repopath = (self._repo.dirstate.copied(self._path)
616 or self._path)
616 or self._path)
617 return self._repopath
617 return self._repopath
618 elif name == '_filelog':
618 elif name == '_filelog':
619 self._filelog = self._repo.file(self._repopath)
619 self._filelog = self._repo.file(self._repopath)
620 return self._filelog
620 return self._filelog
621 else:
621 else:
622 raise AttributeError, name
622 raise AttributeError, name
623
623
624 def __nonzero__(self):
624 def __nonzero__(self):
625 return True
625 return True
626
626
627 def __str__(self):
627 def __str__(self):
628 return "%s@%s" % (self.path(), self._changectx)
628 return "%s@%s" % (self.path(), self._changectx)
629
629
630 def filectx(self, fileid):
630 def filectx(self, fileid):
631 '''opens an arbitrary revision of the file without
631 '''opens an arbitrary revision of the file without
632 opening a new filelog'''
632 opening a new filelog'''
633 return filectx(self._repo, self._repopath, fileid=fileid,
633 return filectx(self._repo, self._repopath, fileid=fileid,
634 filelog=self._filelog)
634 filelog=self._filelog)
635
635
636 def rev(self):
636 def rev(self):
637 if '_changectx' in self.__dict__:
637 if '_changectx' in self.__dict__:
638 return self._changectx.rev()
638 return self._changectx.rev()
639 return self._filelog.linkrev(self._filenode)
639 return self._filelog.linkrev(self._filenode)
640
640
641 def data(self): return self._repo.wread(self._path)
641 def data(self): return self._repo.wread(self._path)
642 def renamed(self):
642 def renamed(self):
643 rp = self._repopath
643 rp = self._repopath
644 if rp == self._path:
644 if rp == self._path:
645 return None
645 return None
646 return rp, self._changectx._parents[0]._manifest.get(rp, nullid)
646 return rp, self._changectx._parents[0]._manifest.get(rp, nullid)
647
647
648 def parents(self):
648 def parents(self):
649 '''return parent filectxs, following copies if necessary'''
649 '''return parent filectxs, following copies if necessary'''
650 p = self._path
650 p = self._path
651 rp = self._repopath
651 rp = self._repopath
652 pcl = self._changectx._parents
652 pcl = self._changectx._parents
653 fl = self._filelog
653 fl = self._filelog
654 pl = [(rp, pcl[0]._manifest.get(rp, nullid), fl)]
654 pl = [(rp, pcl[0]._manifest.get(rp, nullid), fl)]
655 if len(pcl) > 1:
655 if len(pcl) > 1:
656 if rp != p:
656 if rp != p:
657 fl = None
657 fl = None
658 pl.append((p, pcl[1]._manifest.get(p, nullid), fl))
658 pl.append((p, pcl[1]._manifest.get(p, nullid), fl))
659
659
660 return [filectx(self._repo, p, fileid=n, filelog=l)
660 return [filectx(self._repo, p, fileid=n, filelog=l)
661 for p,n,l in pl if n != nullid]
661 for p,n,l in pl if n != nullid]
662
662
663 def children(self):
663 def children(self):
664 return []
664 return []
665
665
666 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
667 def date(self):
667 def date(self):
668 t, tz = self._changectx.date()
668 t, tz = self._changectx.date()
669 try:
669 try:
670 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)
671 except OSError, err:
671 except OSError, err:
672 if err.errno != errno.ENOENT: raise
672 if err.errno != errno.ENOENT: raise
673 return (t, tz)
673 return (t, tz)
674
674
675 def cmp(self, text): return self._repo.wread(self._path) == text
675 def cmp(self, text): return self._repo.wread(self._path) == text
676
676
677 class memctx(object):
677 class memctx(object):
678 """A memctx is a subset of changectx supposed to be built on memory
678 """A memctx is a subset of changectx supposed to be built on memory
679 and passed to commit functions.
679 and passed to commit functions.
680
680
681 NOTE: this interface and the related memfilectx are experimental and
681 NOTE: this interface and the related memfilectx are experimental and
682 may change without notice.
682 may change without notice.
683
683
684 parents - a pair of parent nodeids.
684 parents - a pair of parent nodeids.
685 filectxfn - a callable taking (repo, memctx, path) arguments and
685 filectxfn - a callable taking (repo, memctx, path) arguments and
686 returning a memctx object.
686 returning a memctx object.
687 date - any valid date string or (unixtime, offset), or None.
687 date - any valid date string or (unixtime, offset), or None.
688 user - username string, or None.
688 user - username string, or None.
689 extra - a dictionary of extra values, or None.
689 extra - a dictionary of extra values, or None.
690 """
690 """
691 def __init__(self, repo, parents, text, files, filectxfn, user=None,
691 def __init__(self, repo, parents, text, files, filectxfn, user=None,
692 date=None, extra=None):
692 date=None, extra=None):
693 self._repo = repo
693 self._repo = repo
694 self._rev = None
694 self._rev = None
695 self._node = None
695 self._node = None
696 self._text = text
696 self._text = text
697 self._date = date and util.parsedate(date) or util.makedate()
697 self._date = date and util.parsedate(date) or util.makedate()
698 self._user = user or self._repo.ui.username()
698 self._user = user or self._repo.ui.username()
699 parents = [(p or nullid) for p in parents]
699 parents = [(p or nullid) for p in parents]
700 p1, p2 = parents
700 p1, p2 = parents
701 self._parents = [self._repo.changectx(p) for p in (p1, p2)]
701 self._parents = [self._repo.changectx(p) for p in (p1, p2)]
702 files = list(files)
702 files = list(files)
703 files.sort()
703 files.sort()
704 self._status = [files, [], [], [], []]
704 self._status = [files, [], [], [], []]
705 self._filectxfn = filectxfn
705 self._filectxfn = filectxfn
706
706
707 self._extra = extra and extra.copy() or {}
707 self._extra = extra and extra.copy() or {}
708 if 'branch' not in self._extra:
708 if 'branch' not in self._extra:
709 self._extra['branch'] = 'default'
709 self._extra['branch'] = 'default'
710 elif self._extra.get('branch') == '':
710 elif self._extra.get('branch') == '':
711 self._extra['branch'] = 'default'
711 self._extra['branch'] = 'default'
712
712
713 def __str__(self):
713 def __str__(self):
714 return str(self._parents[0]) + "+"
714 return str(self._parents[0]) + "+"
715
715
716 def __nonzero__(self):
716 def __nonzero__(self):
717 return True
717 return True
718
718
719 def user(self): return self._user
719 def user(self): return self._user
720 def date(self): return self._date
720 def date(self): return self._date
721 def description(self): return self._text
721 def description(self): return self._text
722 def files(self): return self.modified()
722 def files(self): return self.modified()
723 def modified(self): return self._status[0]
723 def modified(self): return self._status[0]
724 def added(self): return self._status[1]
724 def added(self): return self._status[1]
725 def removed(self): return self._status[2]
725 def removed(self): return self._status[2]
726 def deleted(self): return self._status[3]
726 def deleted(self): return self._status[3]
727 def unknown(self): return self._status[4]
727 def unknown(self): return self._status[4]
728 def clean(self): return self._status[5]
728 def clean(self): return self._status[5]
729 def branch(self): return self._extra['branch']
729 def branch(self): return self._extra['branch']
730 def extra(self): return self._extra
730 def extra(self): return self._extra
731
731
732 def parents(self):
732 def parents(self):
733 """return contexts for each parent changeset"""
733 """return contexts for each parent changeset"""
734 return self._parents
734 return self._parents
735
735
736 def filectx(self, path, filelog=None):
736 def filectx(self, path, filelog=None):
737 """get a file context from the working directory"""
737 """get a file context from the working directory"""
738 return self._filectxfn(self._repo, self, path)
738 return self._filectxfn(self._repo, self, path)
739
739
740 class memfilectx(object):
740 class memfilectx(object):
741 """A memfilectx is a subset of filectx supposed to be built by client
741 """A memfilectx is a subset of filectx supposed to be built by client
742 code and passed to commit functions.
742 code and passed to commit functions.
743 """
743 """
744 def __init__(self, path, data, islink, isexec, copied):
744 def __init__(self, path, data, islink, isexec, copied):
745 """copied is the source file path, or None."""
745 """copied is the source file path, or None."""
746 self._path = path
746 self._path = path
747 self._data = data
747 self._data = data
748 self._flags = (islink and 'l' or '') + (isexec and 'x' or '')
748 self._flags = (islink and 'l' or '') + (isexec and 'x' or '')
749 self._copied = None
749 self._copied = None
750 if copied:
750 if copied:
751 self._copied = (copied, nullid)
751 self._copied = (copied, nullid)
752
752
753 def __nonzero__(self): return True
753 def __nonzero__(self): return True
754 def __str__(self): return "%s@%s" % (self.path(), self._changectx)
754 def __str__(self): return "%s@%s" % (self.path(), self._changectx)
755 def path(self): return self._path
755 def path(self): return self._path
756 def data(self): return self._data
756 def data(self): return self._data
757 def fileflags(self): return self._flags
757 def fileflags(self): return self._flags
758 def isexec(self): return 'x' in self._flags
758 def isexec(self): return 'x' in self._flags
759 def islink(self): return 'l' in self._flags
759 def islink(self): return 'l' in self._flags
760 def renamed(self): return self._copied
760 def renamed(self): return self._copied
761
761
@@ -1,2146 +1,2146 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):
494 def workingctx(self):
495 return context.workingctx(self)
495 return context.workingctx(self)
496
496
497 def parents(self, changeid=None):
497 def parents(self, changeid=None):
498 '''
498 '''
499 get list of changectxs for parents of changeid or working directory
499 get list of changectxs for parents of changeid or working directory
500 '''
500 '''
501 if changeid is None:
501 if changeid is None:
502 pl = self.dirstate.parents()
502 pl = self.dirstate.parents()
503 else:
503 else:
504 n = self.changelog.lookup(changeid)
504 n = self.changelog.lookup(changeid)
505 pl = self.changelog.parents(n)
505 pl = self.changelog.parents(n)
506 if pl[1] == nullid:
506 if pl[1] == nullid:
507 return [self.changectx(pl[0])]
507 return [self.changectx(pl[0])]
508 return [self.changectx(pl[0]), self.changectx(pl[1])]
508 return [self.changectx(pl[0]), self.changectx(pl[1])]
509
509
510 def filectx(self, path, changeid=None, fileid=None):
510 def filectx(self, path, changeid=None, fileid=None):
511 """changeid can be a changeset revision, node, or tag.
511 """changeid can be a changeset revision, node, or tag.
512 fileid can be a file revision or node."""
512 fileid can be a file revision or node."""
513 return context.filectx(self, path, changeid, fileid)
513 return context.filectx(self, path, changeid, fileid)
514
514
515 def getcwd(self):
515 def getcwd(self):
516 return self.dirstate.getcwd()
516 return self.dirstate.getcwd()
517
517
518 def pathto(self, f, cwd=None):
518 def pathto(self, f, cwd=None):
519 return self.dirstate.pathto(f, cwd)
519 return self.dirstate.pathto(f, cwd)
520
520
521 def wfile(self, f, mode='r'):
521 def wfile(self, f, mode='r'):
522 return self.wopener(f, mode)
522 return self.wopener(f, mode)
523
523
524 def _link(self, f):
524 def _link(self, f):
525 return os.path.islink(self.wjoin(f))
525 return os.path.islink(self.wjoin(f))
526
526
527 def _filter(self, filter, filename, data):
527 def _filter(self, filter, filename, data):
528 if filter not in self.filterpats:
528 if filter not in self.filterpats:
529 l = []
529 l = []
530 for pat, cmd in self.ui.configitems(filter):
530 for pat, cmd in self.ui.configitems(filter):
531 mf = util.matcher(self.root, "", [pat], [], [])[1]
531 mf = util.matcher(self.root, "", [pat], [], [])[1]
532 fn = None
532 fn = None
533 params = cmd
533 params = cmd
534 for name, filterfn in self._datafilters.iteritems():
534 for name, filterfn in self._datafilters.iteritems():
535 if cmd.startswith(name):
535 if cmd.startswith(name):
536 fn = filterfn
536 fn = filterfn
537 params = cmd[len(name):].lstrip()
537 params = cmd[len(name):].lstrip()
538 break
538 break
539 if not fn:
539 if not fn:
540 fn = lambda s, c, **kwargs: util.filter(s, c)
540 fn = lambda s, c, **kwargs: util.filter(s, c)
541 # Wrap old filters not supporting keyword arguments
541 # Wrap old filters not supporting keyword arguments
542 if not inspect.getargspec(fn)[2]:
542 if not inspect.getargspec(fn)[2]:
543 oldfn = fn
543 oldfn = fn
544 fn = lambda s, c, **kwargs: oldfn(s, c)
544 fn = lambda s, c, **kwargs: oldfn(s, c)
545 l.append((mf, fn, params))
545 l.append((mf, fn, params))
546 self.filterpats[filter] = l
546 self.filterpats[filter] = l
547
547
548 for mf, fn, cmd in self.filterpats[filter]:
548 for mf, fn, cmd in self.filterpats[filter]:
549 if mf(filename):
549 if mf(filename):
550 self.ui.debug(_("filtering %s through %s\n") % (filename, cmd))
550 self.ui.debug(_("filtering %s through %s\n") % (filename, cmd))
551 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
551 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
552 break
552 break
553
553
554 return data
554 return data
555
555
556 def adddatafilter(self, name, filter):
556 def adddatafilter(self, name, filter):
557 self._datafilters[name] = filter
557 self._datafilters[name] = filter
558
558
559 def wread(self, filename):
559 def wread(self, filename):
560 if self._link(filename):
560 if self._link(filename):
561 data = os.readlink(self.wjoin(filename))
561 data = os.readlink(self.wjoin(filename))
562 else:
562 else:
563 data = self.wopener(filename, 'r').read()
563 data = self.wopener(filename, 'r').read()
564 return self._filter("encode", filename, data)
564 return self._filter("encode", filename, data)
565
565
566 def wwrite(self, filename, data, flags):
566 def wwrite(self, filename, data, flags):
567 data = self._filter("decode", filename, data)
567 data = self._filter("decode", filename, data)
568 try:
568 try:
569 os.unlink(self.wjoin(filename))
569 os.unlink(self.wjoin(filename))
570 except OSError:
570 except OSError:
571 pass
571 pass
572 self.wopener(filename, 'w').write(data)
572 self.wopener(filename, 'w').write(data)
573 util.set_flags(self.wjoin(filename), flags)
573 util.set_flags(self.wjoin(filename), flags)
574
574
575 def wwritedata(self, filename, data):
575 def wwritedata(self, filename, data):
576 return self._filter("decode", filename, data)
576 return self._filter("decode", filename, data)
577
577
578 def transaction(self):
578 def transaction(self):
579 if self._transref and self._transref():
579 if self._transref and self._transref():
580 return self._transref().nest()
580 return self._transref().nest()
581
581
582 # abort here if the journal already exists
582 # abort here if the journal already exists
583 if os.path.exists(self.sjoin("journal")):
583 if os.path.exists(self.sjoin("journal")):
584 raise repo.RepoError(_("journal already exists - run hg recover"))
584 raise repo.RepoError(_("journal already exists - run hg recover"))
585
585
586 # save dirstate for rollback
586 # save dirstate for rollback
587 try:
587 try:
588 ds = self.opener("dirstate").read()
588 ds = self.opener("dirstate").read()
589 except IOError:
589 except IOError:
590 ds = ""
590 ds = ""
591 self.opener("journal.dirstate", "w").write(ds)
591 self.opener("journal.dirstate", "w").write(ds)
592 self.opener("journal.branch", "w").write(self.dirstate.branch())
592 self.opener("journal.branch", "w").write(self.dirstate.branch())
593
593
594 renames = [(self.sjoin("journal"), self.sjoin("undo")),
594 renames = [(self.sjoin("journal"), self.sjoin("undo")),
595 (self.join("journal.dirstate"), self.join("undo.dirstate")),
595 (self.join("journal.dirstate"), self.join("undo.dirstate")),
596 (self.join("journal.branch"), self.join("undo.branch"))]
596 (self.join("journal.branch"), self.join("undo.branch"))]
597 tr = transaction.transaction(self.ui.warn, self.sopener,
597 tr = transaction.transaction(self.ui.warn, self.sopener,
598 self.sjoin("journal"),
598 self.sjoin("journal"),
599 aftertrans(renames),
599 aftertrans(renames),
600 self._createmode)
600 self._createmode)
601 self._transref = weakref.ref(tr)
601 self._transref = weakref.ref(tr)
602 return tr
602 return tr
603
603
604 def recover(self):
604 def recover(self):
605 l = self.lock()
605 l = self.lock()
606 try:
606 try:
607 if os.path.exists(self.sjoin("journal")):
607 if os.path.exists(self.sjoin("journal")):
608 self.ui.status(_("rolling back interrupted transaction\n"))
608 self.ui.status(_("rolling back interrupted transaction\n"))
609 transaction.rollback(self.sopener, self.sjoin("journal"))
609 transaction.rollback(self.sopener, self.sjoin("journal"))
610 self.invalidate()
610 self.invalidate()
611 return True
611 return True
612 else:
612 else:
613 self.ui.warn(_("no interrupted transaction available\n"))
613 self.ui.warn(_("no interrupted transaction available\n"))
614 return False
614 return False
615 finally:
615 finally:
616 del l
616 del l
617
617
618 def rollback(self):
618 def rollback(self):
619 wlock = lock = None
619 wlock = lock = None
620 try:
620 try:
621 wlock = self.wlock()
621 wlock = self.wlock()
622 lock = self.lock()
622 lock = self.lock()
623 if os.path.exists(self.sjoin("undo")):
623 if os.path.exists(self.sjoin("undo")):
624 self.ui.status(_("rolling back last transaction\n"))
624 self.ui.status(_("rolling back last transaction\n"))
625 transaction.rollback(self.sopener, self.sjoin("undo"))
625 transaction.rollback(self.sopener, self.sjoin("undo"))
626 util.rename(self.join("undo.dirstate"), self.join("dirstate"))
626 util.rename(self.join("undo.dirstate"), self.join("dirstate"))
627 try:
627 try:
628 branch = self.opener("undo.branch").read()
628 branch = self.opener("undo.branch").read()
629 self.dirstate.setbranch(branch)
629 self.dirstate.setbranch(branch)
630 except IOError:
630 except IOError:
631 self.ui.warn(_("Named branch could not be reset, "
631 self.ui.warn(_("Named branch could not be reset, "
632 "current branch still is: %s\n")
632 "current branch still is: %s\n")
633 % util.tolocal(self.dirstate.branch()))
633 % util.tolocal(self.dirstate.branch()))
634 self.invalidate()
634 self.invalidate()
635 self.dirstate.invalidate()
635 self.dirstate.invalidate()
636 else:
636 else:
637 self.ui.warn(_("no rollback information available\n"))
637 self.ui.warn(_("no rollback information available\n"))
638 finally:
638 finally:
639 del lock, wlock
639 del lock, wlock
640
640
641 def invalidate(self):
641 def invalidate(self):
642 for a in "changelog manifest".split():
642 for a in "changelog manifest".split():
643 if a in self.__dict__:
643 if a in self.__dict__:
644 delattr(self, a)
644 delattr(self, a)
645 self.tagscache = None
645 self.tagscache = None
646 self._tagstypecache = None
646 self._tagstypecache = None
647 self.nodetagscache = None
647 self.nodetagscache = None
648 self.branchcache = None
648 self.branchcache = None
649 self._ubranchcache = None
649 self._ubranchcache = None
650 self._branchcachetip = None
650 self._branchcachetip = None
651
651
652 def _lock(self, lockname, wait, releasefn, acquirefn, desc):
652 def _lock(self, lockname, wait, releasefn, acquirefn, desc):
653 try:
653 try:
654 l = lock.lock(lockname, 0, releasefn, desc=desc)
654 l = lock.lock(lockname, 0, releasefn, desc=desc)
655 except lock.LockHeld, inst:
655 except lock.LockHeld, inst:
656 if not wait:
656 if not wait:
657 raise
657 raise
658 self.ui.warn(_("waiting for lock on %s held by %r\n") %
658 self.ui.warn(_("waiting for lock on %s held by %r\n") %
659 (desc, inst.locker))
659 (desc, inst.locker))
660 # default to 600 seconds timeout
660 # default to 600 seconds timeout
661 l = lock.lock(lockname, int(self.ui.config("ui", "timeout", "600")),
661 l = lock.lock(lockname, int(self.ui.config("ui", "timeout", "600")),
662 releasefn, desc=desc)
662 releasefn, desc=desc)
663 if acquirefn:
663 if acquirefn:
664 acquirefn()
664 acquirefn()
665 return l
665 return l
666
666
667 def lock(self, wait=True):
667 def lock(self, wait=True):
668 if self._lockref and self._lockref():
668 if self._lockref and self._lockref():
669 return self._lockref()
669 return self._lockref()
670
670
671 l = self._lock(self.sjoin("lock"), wait, None, self.invalidate,
671 l = self._lock(self.sjoin("lock"), wait, None, self.invalidate,
672 _('repository %s') % self.origroot)
672 _('repository %s') % self.origroot)
673 self._lockref = weakref.ref(l)
673 self._lockref = weakref.ref(l)
674 return l
674 return l
675
675
676 def wlock(self, wait=True):
676 def wlock(self, wait=True):
677 if self._wlockref and self._wlockref():
677 if self._wlockref and self._wlockref():
678 return self._wlockref()
678 return self._wlockref()
679
679
680 l = self._lock(self.join("wlock"), wait, self.dirstate.write,
680 l = self._lock(self.join("wlock"), wait, self.dirstate.write,
681 self.dirstate.invalidate, _('working directory of %s') %
681 self.dirstate.invalidate, _('working directory of %s') %
682 self.origroot)
682 self.origroot)
683 self._wlockref = weakref.ref(l)
683 self._wlockref = weakref.ref(l)
684 return l
684 return l
685
685
686 def filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
686 def filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
687 """
687 """
688 commit an individual file as part of a larger transaction
688 commit an individual file as part of a larger transaction
689 """
689 """
690
690
691 fn = fctx.path()
691 fn = fctx.path()
692 t = fctx.data()
692 t = fctx.data()
693 fl = self.file(fn)
693 fl = self.file(fn)
694 fp1 = manifest1.get(fn, nullid)
694 fp1 = manifest1.get(fn, nullid)
695 fp2 = manifest2.get(fn, nullid)
695 fp2 = manifest2.get(fn, nullid)
696
696
697 meta = {}
697 meta = {}
698 cp = fctx.renamed()
698 cp = fctx.renamed()
699 if cp and cp[0] != fn:
699 if cp and cp[0] != fn:
700 cp = cp[0]
700 cp = cp[0]
701 # Mark the new revision of this file as a copy of another
701 # Mark the new revision of this file as a copy of another
702 # file. This copy data will effectively act as a parent
702 # file. This copy data will effectively act as a parent
703 # of this new revision. If this is a merge, the first
703 # of this new revision. If this is a merge, the first
704 # parent will be the nullid (meaning "look up the copy data")
704 # parent will be the nullid (meaning "look up the copy data")
705 # and the second one will be the other parent. For example:
705 # and the second one will be the other parent. For example:
706 #
706 #
707 # 0 --- 1 --- 3 rev1 changes file foo
707 # 0 --- 1 --- 3 rev1 changes file foo
708 # \ / rev2 renames foo to bar and changes it
708 # \ / rev2 renames foo to bar and changes it
709 # \- 2 -/ rev3 should have bar with all changes and
709 # \- 2 -/ rev3 should have bar with all changes and
710 # should record that bar descends from
710 # should record that bar descends from
711 # bar in rev2 and foo in rev1
711 # bar in rev2 and foo in rev1
712 #
712 #
713 # this allows this merge to succeed:
713 # this allows this merge to succeed:
714 #
714 #
715 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
715 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
716 # \ / merging rev3 and rev4 should use bar@rev2
716 # \ / merging rev3 and rev4 should use bar@rev2
717 # \- 2 --- 4 as the merge base
717 # \- 2 --- 4 as the merge base
718 #
718 #
719 meta["copy"] = cp
719 meta["copy"] = cp
720 if not manifest2: # not a branch merge
720 if not manifest2: # not a branch merge
721 meta["copyrev"] = hex(manifest1[cp])
721 meta["copyrev"] = hex(manifest1[cp])
722 fp2 = nullid
722 fp2 = nullid
723 elif fp2 != nullid: # copied on remote side
723 elif fp2 != nullid: # copied on remote side
724 meta["copyrev"] = hex(manifest1[cp])
724 meta["copyrev"] = hex(manifest1[cp])
725 elif fp1 != nullid: # copied on local side, reversed
725 elif fp1 != nullid: # copied on local side, reversed
726 meta["copyrev"] = hex(manifest2[cp])
726 meta["copyrev"] = hex(manifest2[cp])
727 fp2 = fp1
727 fp2 = fp1
728 elif cp in manifest2: # directory rename on local side
728 elif cp in manifest2: # directory rename on local side
729 meta["copyrev"] = hex(manifest2[cp])
729 meta["copyrev"] = hex(manifest2[cp])
730 else: # directory rename on remote side
730 else: # directory rename on remote side
731 meta["copyrev"] = hex(manifest1[cp])
731 meta["copyrev"] = hex(manifest1[cp])
732 self.ui.debug(_(" %s: copy %s:%s\n") %
732 self.ui.debug(_(" %s: copy %s:%s\n") %
733 (fn, cp, meta["copyrev"]))
733 (fn, cp, meta["copyrev"]))
734 fp1 = nullid
734 fp1 = nullid
735 elif fp2 != nullid:
735 elif fp2 != nullid:
736 # is one parent an ancestor of the other?
736 # is one parent an ancestor of the other?
737 fpa = fl.ancestor(fp1, fp2)
737 fpa = fl.ancestor(fp1, fp2)
738 if fpa == fp1:
738 if fpa == fp1:
739 fp1, fp2 = fp2, nullid
739 fp1, fp2 = fp2, nullid
740 elif fpa == fp2:
740 elif fpa == fp2:
741 fp2 = nullid
741 fp2 = nullid
742
742
743 # is the file unmodified from the parent? report existing entry
743 # is the file unmodified from the parent? report existing entry
744 if fp2 == nullid and not fl.cmp(fp1, t) and not meta:
744 if fp2 == nullid and not fl.cmp(fp1, t) and not meta:
745 return fp1
745 return fp1
746
746
747 changelist.append(fn)
747 changelist.append(fn)
748 return fl.add(t, meta, tr, linkrev, fp1, fp2)
748 return fl.add(t, meta, tr, linkrev, fp1, fp2)
749
749
750 def rawcommit(self, files, text, user, date, p1=None, p2=None, extra={}):
750 def rawcommit(self, files, text, user, date, p1=None, p2=None, extra={}):
751 if p1 is None:
751 if p1 is None:
752 p1, p2 = self.dirstate.parents()
752 p1, p2 = self.dirstate.parents()
753 return self.commit(files=files, text=text, user=user, date=date,
753 return self.commit(files=files, text=text, user=user, date=date,
754 p1=p1, p2=p2, extra=extra, empty_ok=True)
754 p1=p1, p2=p2, extra=extra, empty_ok=True)
755
755
756 def commit(self, files=None, text="", user=None, date=None,
756 def commit(self, files=None, text="", user=None, date=None,
757 match=None, force=False, force_editor=False,
757 match=None, force=False, force_editor=False,
758 p1=None, p2=None, extra={}, empty_ok=False):
758 p1=None, p2=None, extra={}, empty_ok=False):
759 wlock = lock = None
759 wlock = lock = None
760 if files:
760 if files:
761 files = util.unique(files)
761 files = util.unique(files)
762 try:
762 try:
763 wlock = self.wlock()
763 wlock = self.wlock()
764 lock = self.lock()
764 lock = self.lock()
765 use_dirstate = (p1 is None) # not rawcommit
765 use_dirstate = (p1 is None) # not rawcommit
766
766
767 if use_dirstate:
767 if use_dirstate:
768 p1, p2 = self.dirstate.parents()
768 p1, p2 = self.dirstate.parents()
769 update_dirstate = True
769 update_dirstate = True
770
770
771 if (not force and p2 != nullid and
771 if (not force and p2 != nullid and
772 (match and (match.files() or match.anypats()))):
772 (match and (match.files() or match.anypats()))):
773 raise util.Abort(_('cannot partially commit a merge '
773 raise util.Abort(_('cannot partially commit a merge '
774 '(do not specify files or patterns)'))
774 '(do not specify files or patterns)'))
775
775
776 if files:
776 if files:
777 modified, removed = [], []
777 modified, removed = [], []
778 for f in files:
778 for f in files:
779 s = self.dirstate[f]
779 s = self.dirstate[f]
780 if s in 'nma':
780 if s in 'nma':
781 modified.append(f)
781 modified.append(f)
782 elif s == 'r':
782 elif s == 'r':
783 removed.append(f)
783 removed.append(f)
784 else:
784 else:
785 self.ui.warn(_("%s not tracked!\n") % f)
785 self.ui.warn(_("%s not tracked!\n") % f)
786 changes = [modified, [], removed, [], []]
786 changes = [modified, [], removed, [], []]
787 else:
787 else:
788 changes = self.status(match=match)
788 changes = self.status(match=match)
789 else:
789 else:
790 p1, p2 = p1, p2 or nullid
790 p1, p2 = p1, p2 or nullid
791 update_dirstate = (self.dirstate.parents()[0] == p1)
791 update_dirstate = (self.dirstate.parents()[0] == p1)
792 changes = [files, [], [], [], []]
792 changes = [files, [], [], [], []]
793
793
794 wctx = context.workingctx(self, (p1, p2), text, user, date,
794 wctx = context.workingctx(self, (p1, p2), text, user, date,
795 extra, changes)
795 extra, changes)
796 return self._commitctx(wctx, force, force_editor, empty_ok,
796 return self._commitctx(wctx, force, force_editor, empty_ok,
797 use_dirstate, update_dirstate)
797 use_dirstate, update_dirstate)
798 finally:
798 finally:
799 del lock, wlock
799 del lock, wlock
800
800
801 def commitctx(self, ctx):
801 def commitctx(self, ctx):
802 wlock = lock = None
802 wlock = lock = None
803 try:
803 try:
804 wlock = self.wlock()
804 wlock = self.wlock()
805 lock = self.lock()
805 lock = self.lock()
806 return self._commitctx(ctx, force=True, force_editor=False,
806 return self._commitctx(ctx, force=True, force_editor=False,
807 empty_ok=True, use_dirstate=False,
807 empty_ok=True, use_dirstate=False,
808 update_dirstate=False)
808 update_dirstate=False)
809 finally:
809 finally:
810 del lock, wlock
810 del lock, wlock
811
811
812 def _commitctx(self, wctx, force=False, force_editor=False, empty_ok=False,
812 def _commitctx(self, wctx, force=False, force_editor=False, empty_ok=False,
813 use_dirstate=True, update_dirstate=True):
813 use_dirstate=True, update_dirstate=True):
814 tr = None
814 tr = None
815 valid = 0 # don't save the dirstate if this isn't set
815 valid = 0 # don't save the dirstate if this isn't set
816 try:
816 try:
817 commit = wctx.modified() + wctx.added()
817 commit = wctx.modified() + wctx.added()
818 remove = wctx.removed()
818 remove = wctx.removed()
819 extra = wctx.extra().copy()
819 extra = wctx.extra().copy()
820 branchname = extra['branch']
820 branchname = extra['branch']
821 user = wctx.user()
821 user = wctx.user()
822 text = wctx.description()
822 text = wctx.description()
823
823
824 p1, p2 = [p.node() for p in wctx.parents()]
824 p1, p2 = [p.node() for p in wctx.parents()]
825 c1 = self.changelog.read(p1)
825 c1 = self.changelog.read(p1)
826 c2 = self.changelog.read(p2)
826 c2 = self.changelog.read(p2)
827 m1 = self.manifest.read(c1[0]).copy()
827 m1 = self.manifest.read(c1[0]).copy()
828 m2 = self.manifest.read(c2[0])
828 m2 = self.manifest.read(c2[0])
829
829
830 if use_dirstate:
830 if use_dirstate:
831 oldname = c1[5].get("branch") # stored in UTF-8
831 oldname = c1[5].get("branch") # stored in UTF-8
832 if (not commit and not remove and not force and p2 == nullid
832 if (not commit and not remove and not force and p2 == nullid
833 and branchname == oldname):
833 and branchname == oldname):
834 self.ui.status(_("nothing changed\n"))
834 self.ui.status(_("nothing changed\n"))
835 return None
835 return None
836
836
837 xp1 = hex(p1)
837 xp1 = hex(p1)
838 if p2 == nullid: xp2 = ''
838 if p2 == nullid: xp2 = ''
839 else: xp2 = hex(p2)
839 else: xp2 = hex(p2)
840
840
841 self.hook("precommit", throw=True, parent1=xp1, parent2=xp2)
841 self.hook("precommit", throw=True, parent1=xp1, parent2=xp2)
842
842
843 tr = self.transaction()
843 tr = self.transaction()
844 trp = weakref.proxy(tr)
844 trp = weakref.proxy(tr)
845
845
846 # check in files
846 # check in files
847 new = {}
847 new = {}
848 changed = []
848 changed = []
849 linkrev = self.changelog.count()
849 linkrev = self.changelog.count()
850 commit.sort()
850 commit.sort()
851 for f in commit:
851 for f in commit:
852 self.ui.note(f + "\n")
852 self.ui.note(f + "\n")
853 try:
853 try:
854 fctx = wctx.filectx(f)
854 fctx = wctx.filectx(f)
855 new[f] = self.filecommit(fctx, m1, m2, linkrev, trp, changed)
855 new[f] = self.filecommit(fctx, m1, m2, linkrev, trp, changed)
856 new_exec = fctx.isexec()
856 new_exec = fctx.isexec()
857 new_link = fctx.islink()
857 new_link = fctx.islink()
858 if ((not changed or changed[-1] != f) and
858 if ((not changed or changed[-1] != f) and
859 m2.get(f) != new[f]):
859 m2.get(f) != new[f]):
860 # mention the file in the changelog if some
860 # mention the file in the changelog if some
861 # flag changed, even if there was no content
861 # flag changed, even if there was no content
862 # change.
862 # change.
863 old_exec = m1.execf(f)
863 old_exec = m1.execf(f)
864 old_link = m1.linkf(f)
864 old_link = m1.linkf(f)
865 if old_exec != new_exec or old_link != new_link:
865 if old_exec != new_exec or old_link != new_link:
866 changed.append(f)
866 changed.append(f)
867 m1.set(f, new_exec, new_link)
867 m1.set(f, new_exec, new_link)
868 if use_dirstate:
868 if use_dirstate:
869 self.dirstate.normal(f)
869 self.dirstate.normal(f)
870
870
871 except (OSError, IOError):
871 except (OSError, IOError):
872 if use_dirstate:
872 if use_dirstate:
873 self.ui.warn(_("trouble committing %s!\n") % f)
873 self.ui.warn(_("trouble committing %s!\n") % f)
874 raise
874 raise
875 else:
875 else:
876 remove.append(f)
876 remove.append(f)
877
877
878 # update manifest
878 # update manifest
879 m1.update(new)
879 m1.update(new)
880 remove.sort()
880 remove.sort()
881 removed = []
881 removed = []
882
882
883 for f in remove:
883 for f in remove:
884 if f in m1:
884 if f in m1:
885 del m1[f]
885 del m1[f]
886 removed.append(f)
886 removed.append(f)
887 elif f in m2:
887 elif f in m2:
888 removed.append(f)
888 removed.append(f)
889 mn = self.manifest.add(m1, trp, linkrev, c1[0], c2[0],
889 mn = self.manifest.add(m1, trp, linkrev, c1[0], c2[0],
890 (new, removed))
890 (new, removed))
891
891
892 # add changeset
892 # add changeset
893 if (not empty_ok and not text) or force_editor:
893 if (not empty_ok and not text) or force_editor:
894 edittext = []
894 edittext = []
895 if text:
895 if text:
896 edittext.append(text)
896 edittext.append(text)
897 edittext.append("")
897 edittext.append("")
898 edittext.append(_("HG: Enter commit message."
898 edittext.append(_("HG: Enter commit message."
899 " Lines beginning with 'HG:' are removed."))
899 " Lines beginning with 'HG:' are removed."))
900 edittext.append("HG: --")
900 edittext.append("HG: --")
901 edittext.append("HG: user: %s" % user)
901 edittext.append("HG: user: %s" % user)
902 if p2 != nullid:
902 if p2 != nullid:
903 edittext.append("HG: branch merge")
903 edittext.append("HG: branch merge")
904 if branchname:
904 if branchname:
905 edittext.append("HG: branch '%s'" % util.tolocal(branchname))
905 edittext.append("HG: branch '%s'" % util.tolocal(branchname))
906 edittext.extend(["HG: changed %s" % f for f in changed])
906 edittext.extend(["HG: changed %s" % f for f in changed])
907 edittext.extend(["HG: removed %s" % f for f in removed])
907 edittext.extend(["HG: removed %s" % f for f in removed])
908 if not changed and not remove:
908 if not changed and not remove:
909 edittext.append("HG: no files changed")
909 edittext.append("HG: no files changed")
910 edittext.append("")
910 edittext.append("")
911 # run editor in the repository root
911 # run editor in the repository root
912 olddir = os.getcwd()
912 olddir = os.getcwd()
913 os.chdir(self.root)
913 os.chdir(self.root)
914 text = self.ui.edit("\n".join(edittext), user)
914 text = self.ui.edit("\n".join(edittext), user)
915 os.chdir(olddir)
915 os.chdir(olddir)
916
916
917 lines = [line.rstrip() for line in text.rstrip().splitlines()]
917 lines = [line.rstrip() for line in text.rstrip().splitlines()]
918 while lines and not lines[0]:
918 while lines and not lines[0]:
919 del lines[0]
919 del lines[0]
920 if not lines and use_dirstate:
920 if not lines and use_dirstate:
921 raise util.Abort(_("empty commit message"))
921 raise util.Abort(_("empty commit message"))
922 text = '\n'.join(lines)
922 text = '\n'.join(lines)
923
923
924 n = self.changelog.add(mn, changed + removed, text, trp, p1, p2,
924 n = self.changelog.add(mn, changed + removed, text, trp, p1, p2,
925 user, wctx.date(), extra)
925 user, wctx.date(), extra)
926 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
926 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
927 parent2=xp2)
927 parent2=xp2)
928 tr.close()
928 tr.close()
929
929
930 if self.branchcache:
930 if self.branchcache:
931 self.branchtags()
931 self.branchtags()
932
932
933 if use_dirstate or update_dirstate:
933 if use_dirstate or update_dirstate:
934 self.dirstate.setparents(n)
934 self.dirstate.setparents(n)
935 if use_dirstate:
935 if use_dirstate:
936 for f in removed:
936 for f in removed:
937 self.dirstate.forget(f)
937 self.dirstate.forget(f)
938 valid = 1 # our dirstate updates are complete
938 valid = 1 # our dirstate updates are complete
939
939
940 self.hook("commit", node=hex(n), parent1=xp1, parent2=xp2)
940 self.hook("commit", node=hex(n), parent1=xp1, parent2=xp2)
941 return n
941 return n
942 finally:
942 finally:
943 if not valid: # don't save our updated dirstate
943 if not valid: # don't save our updated dirstate
944 self.dirstate.invalidate()
944 self.dirstate.invalidate()
945 del tr
945 del tr
946
946
947 def walk(self, match, node=None):
947 def walk(self, match, node=None):
948 '''
948 '''
949 walk recursively through the directory tree or a given
949 walk recursively through the directory tree or a given
950 changeset, finding all files matched by the match
950 changeset, finding all files matched by the match
951 function
951 function
952 '''
952 '''
953
953
954 if node:
954 if node:
955 fdict = dict.fromkeys(match.files())
955 fdict = dict.fromkeys(match.files())
956 # for dirstate.walk, files=['.'] means "walk the whole tree".
956 # for dirstate.walk, files=['.'] means "walk the whole tree".
957 # follow that here, too
957 # follow that here, too
958 fdict.pop('.', None)
958 fdict.pop('.', None)
959 mdict = self.manifest.read(self.changelog.read(node)[0])
959 mdict = self.manifest.read(self.changelog.read(node)[0])
960 mfiles = mdict.keys()
960 mfiles = mdict.keys()
961 mfiles.sort()
961 mfiles.sort()
962 for fn in mfiles:
962 for fn in mfiles:
963 for ffn in fdict:
963 for ffn in fdict:
964 # match if the file is the exact name or a directory
964 # match if the file is the exact name or a directory
965 if ffn == fn or fn.startswith("%s/" % ffn):
965 if ffn == fn or fn.startswith("%s/" % ffn):
966 del fdict[ffn]
966 del fdict[ffn]
967 break
967 break
968 if match(fn):
968 if match(fn):
969 yield fn
969 yield fn
970 ffiles = fdict.keys()
970 ffiles = fdict.keys()
971 ffiles.sort()
971 ffiles.sort()
972 for fn in ffiles:
972 for fn in ffiles:
973 if match.bad(fn, 'No such file in rev ' + short(node)) \
973 if match.bad(fn, 'No such file in rev ' + short(node)) \
974 and match(fn):
974 and match(fn):
975 yield fn
975 yield fn
976 else:
976 else:
977 for fn in self.dirstate.walk(match):
977 for fn in self.dirstate.walk(match):
978 yield fn
978 yield fn
979
979
980 def status(self, node1=None, node2=None, match=None,
980 def status(self, node1=None, node2=None, match=None,
981 list_ignored=False, list_clean=False, list_unknown=True):
981 list_ignored=False, list_clean=False, list_unknown=True):
982 """return status of files between two nodes or node and working directory
982 """return status of files between two nodes or node and working directory
983
983
984 If node1 is None, use the first dirstate parent instead.
984 If node1 is None, use the first dirstate parent instead.
985 If node2 is None, compare node1 with working directory.
985 If node2 is None, compare node1 with working directory.
986 """
986 """
987
987
988 def fcmp(fn, getnode):
988 def fcmp(fn, getnode):
989 t1 = self.wread(fn)
989 t1 = self.wread(fn)
990 return self.file(fn).cmp(getnode(fn), t1)
990 return self.file(fn).cmp(getnode(fn), t1)
991
991
992 def mfmatches(node):
992 def mfmatches(node):
993 change = self.changelog.read(node)
993 change = self.changelog.read(node)
994 mf = self.manifest.read(change[0]).copy()
994 mf = self.manifest.read(change[0]).copy()
995 for fn in mf.keys():
995 for fn in mf.keys():
996 if not match(fn):
996 if not match(fn):
997 del mf[fn]
997 del mf[fn]
998 return mf
998 return mf
999
999
1000 if not match:
1000 if not match:
1001 match = match_.always(self.root, self.getcwd())
1001 match = match_.always(self.root, self.getcwd())
1002
1002
1003 modified, added, removed, deleted, unknown = [], [], [], [], []
1003 modified, added, removed, deleted, unknown = [], [], [], [], []
1004 ignored, clean = [], []
1004 ignored, clean = [], []
1005
1005
1006 compareworking = False
1006 compareworking = False
1007 if not node1 or (not node2 and node1 == self.dirstate.parents()[0]):
1007 if not node1 or (not node2 and node1 == self.dirstate.parents()[0]):
1008 compareworking = True
1008 compareworking = True
1009
1009
1010 if not compareworking:
1010 if not compareworking:
1011 # read the manifest from node1 before the manifest from node2,
1011 # read the manifest from node1 before the manifest from node2,
1012 # so that we'll hit the manifest cache if we're going through
1012 # so that we'll hit the manifest cache if we're going through
1013 # all the revisions in parent->child order.
1013 # all the revisions in parent->child order.
1014 mf1 = mfmatches(node1)
1014 mf1 = mfmatches(node1)
1015
1015
1016 # are we comparing the working directory?
1016 # are we comparing the working directory?
1017 if not node2:
1017 if not node2:
1018 (lookup, modified, added, removed, deleted, unknown,
1018 (lookup, modified, added, removed, deleted, unknown,
1019 ignored, clean) = self.dirstate.status(match, list_ignored,
1019 ignored, clean) = self.dirstate.status(match, list_ignored,
1020 list_clean, list_unknown)
1020 list_clean, list_unknown)
1021 # are we comparing working dir against its parent?
1021 # are we comparing working dir against its parent?
1022 if compareworking:
1022 if compareworking:
1023 if lookup:
1023 if lookup:
1024 fixup = []
1024 fixup = []
1025 # do a full compare of any files that might have changed
1025 # do a full compare of any files that might have changed
1026 ctx = self.changectx()
1026 ctx = self.changectx()
1027 mexec = lambda f: 'x' in ctx.fileflags(f)
1027 mexec = lambda f: 'x' in ctx.fileflags(f)
1028 mlink = lambda f: 'l' in ctx.fileflags(f)
1028 mlink = lambda f: 'l' in ctx.fileflags(f)
1029 is_exec = util.execfunc(self.root, mexec)
1029 is_exec = util.execfunc(self.root, mexec)
1030 is_link = util.linkfunc(self.root, mlink)
1030 is_link = util.linkfunc(self.root, mlink)
1031 def flags(f):
1031 def flags(f):
1032 return is_link(f) and 'l' or is_exec(f) and 'x' or ''
1032 return is_link(f) and 'l' or is_exec(f) and 'x' or ''
1033 for f in lookup:
1033 for f in lookup:
1034 if (f not in ctx or flags(f) != ctx.fileflags(f)
1034 if (f not in ctx or flags(f) != ctx.fileflags(f)
1035 or ctx[f].cmp(self.wread(f))):
1035 or ctx[f].cmp(self.wread(f))):
1036 modified.append(f)
1036 modified.append(f)
1037 else:
1037 else:
1038 fixup.append(f)
1038 fixup.append(f)
1039 if list_clean:
1039 if list_clean:
1040 clean.append(f)
1040 clean.append(f)
1041
1041
1042 # update dirstate for files that are actually clean
1042 # update dirstate for files that are actually clean
1043 if fixup:
1043 if fixup:
1044 wlock = None
1044 wlock = None
1045 try:
1045 try:
1046 try:
1046 try:
1047 wlock = self.wlock(False)
1047 wlock = self.wlock(False)
1048 except lock.LockException:
1048 except lock.LockException:
1049 pass
1049 pass
1050 if wlock:
1050 if wlock:
1051 for f in fixup:
1051 for f in fixup:
1052 self.dirstate.normal(f)
1052 self.dirstate.normal(f)
1053 finally:
1053 finally:
1054 del wlock
1054 del wlock
1055 else:
1055 else:
1056 # we are comparing working dir against non-parent
1056 # we are comparing working dir against non-parent
1057 # generate a pseudo-manifest for the working dir
1057 # generate a pseudo-manifest for the working dir
1058 # XXX: create it in dirstate.py ?
1058 # XXX: create it in dirstate.py ?
1059 mf2 = mfmatches(self.dirstate.parents()[0])
1059 mf2 = mfmatches(self.dirstate.parents()[0])
1060 is_exec = util.execfunc(self.root, mf2.execf)
1060 is_exec = util.execfunc(self.root, mf2.execf)
1061 is_link = util.linkfunc(self.root, mf2.linkf)
1061 is_link = util.linkfunc(self.root, mf2.linkf)
1062 for f in lookup + modified + added:
1062 for f in lookup + modified + added:
1063 mf2[f] = ""
1063 mf2[f] = ""
1064 mf2.set(f, is_exec(f), is_link(f))
1064 mf2.set(f, is_exec(f), is_link(f))
1065 for f in removed:
1065 for f in removed:
1066 if f in mf2:
1066 if f in mf2:
1067 del mf2[f]
1067 del mf2[f]
1068
1068
1069 else:
1069 else:
1070 # we are comparing two revisions
1070 # we are comparing two revisions
1071 mf2 = mfmatches(node2)
1071 mf2 = mfmatches(node2)
1072
1072
1073 if not compareworking:
1073 if not compareworking:
1074 # flush lists from dirstate before comparing manifests
1074 # flush lists from dirstate before comparing manifests
1075 modified, added, clean = [], [], []
1075 modified, added, clean = [], [], []
1076
1076
1077 # make sure to sort the files so we talk to the disk in a
1077 # make sure to sort the files so we talk to the disk in a
1078 # reasonable order
1078 # reasonable order
1079 mf2keys = mf2.keys()
1079 mf2keys = mf2.keys()
1080 mf2keys.sort()
1080 mf2keys.sort()
1081 getnode = lambda fn: mf1.get(fn, nullid)
1081 getnode = lambda fn: mf1.get(fn, nullid)
1082 for fn in mf2keys:
1082 for fn in mf2keys:
1083 if fn in mf1:
1083 if fn in mf1:
1084 if (mf1.flags(fn) != mf2.flags(fn) or
1084 if (mf1.flags(fn) != mf2.flags(fn) or
1085 (mf1[fn] != mf2[fn] and
1085 (mf1[fn] != mf2[fn] and
1086 (mf2[fn] != "" or fcmp(fn, getnode)))):
1086 (mf2[fn] != "" or fcmp(fn, getnode)))):
1087 modified.append(fn)
1087 modified.append(fn)
1088 elif list_clean:
1088 elif list_clean:
1089 clean.append(fn)
1089 clean.append(fn)
1090 del mf1[fn]
1090 del mf1[fn]
1091 else:
1091 else:
1092 added.append(fn)
1092 added.append(fn)
1093
1093
1094 removed = mf1.keys()
1094 removed = mf1.keys()
1095
1095
1096 # sort and return results:
1096 # sort and return results:
1097 for l in modified, added, removed, deleted, unknown, ignored, clean:
1097 for l in modified, added, removed, deleted, unknown, ignored, clean:
1098 l.sort()
1098 l.sort()
1099 return (modified, added, removed, deleted, unknown, ignored, clean)
1099 return (modified, added, removed, deleted, unknown, ignored, clean)
1100
1100
1101 def add(self, list):
1101 def add(self, list):
1102 wlock = self.wlock()
1102 wlock = self.wlock()
1103 try:
1103 try:
1104 rejected = []
1104 rejected = []
1105 for f in list:
1105 for f in list:
1106 p = self.wjoin(f)
1106 p = self.wjoin(f)
1107 try:
1107 try:
1108 st = os.lstat(p)
1108 st = os.lstat(p)
1109 except:
1109 except:
1110 self.ui.warn(_("%s does not exist!\n") % f)
1110 self.ui.warn(_("%s does not exist!\n") % f)
1111 rejected.append(f)
1111 rejected.append(f)
1112 continue
1112 continue
1113 if st.st_size > 10000000:
1113 if st.st_size > 10000000:
1114 self.ui.warn(_("%s: files over 10MB may cause memory and"
1114 self.ui.warn(_("%s: files over 10MB may cause memory and"
1115 " performance problems\n"
1115 " performance problems\n"
1116 "(use 'hg revert %s' to unadd the file)\n")
1116 "(use 'hg revert %s' to unadd the file)\n")
1117 % (f, f))
1117 % (f, f))
1118 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1118 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1119 self.ui.warn(_("%s not added: only files and symlinks "
1119 self.ui.warn(_("%s not added: only files and symlinks "
1120 "supported currently\n") % f)
1120 "supported currently\n") % f)
1121 rejected.append(p)
1121 rejected.append(p)
1122 elif self.dirstate[f] in 'amn':
1122 elif self.dirstate[f] in 'amn':
1123 self.ui.warn(_("%s already tracked!\n") % f)
1123 self.ui.warn(_("%s already tracked!\n") % f)
1124 elif self.dirstate[f] == 'r':
1124 elif self.dirstate[f] == 'r':
1125 self.dirstate.normallookup(f)
1125 self.dirstate.normallookup(f)
1126 else:
1126 else:
1127 self.dirstate.add(f)
1127 self.dirstate.add(f)
1128 return rejected
1128 return rejected
1129 finally:
1129 finally:
1130 del wlock
1130 del wlock
1131
1131
1132 def forget(self, list):
1132 def forget(self, list):
1133 wlock = self.wlock()
1133 wlock = self.wlock()
1134 try:
1134 try:
1135 for f in list:
1135 for f in list:
1136 if self.dirstate[f] != 'a':
1136 if self.dirstate[f] != 'a':
1137 self.ui.warn(_("%s not added!\n") % f)
1137 self.ui.warn(_("%s not added!\n") % f)
1138 else:
1138 else:
1139 self.dirstate.forget(f)
1139 self.dirstate.forget(f)
1140 finally:
1140 finally:
1141 del wlock
1141 del wlock
1142
1142
1143 def remove(self, list, unlink=False):
1143 def remove(self, list, unlink=False):
1144 wlock = None
1144 wlock = None
1145 try:
1145 try:
1146 if unlink:
1146 if unlink:
1147 for f in list:
1147 for f in list:
1148 try:
1148 try:
1149 util.unlink(self.wjoin(f))
1149 util.unlink(self.wjoin(f))
1150 except OSError, inst:
1150 except OSError, inst:
1151 if inst.errno != errno.ENOENT:
1151 if inst.errno != errno.ENOENT:
1152 raise
1152 raise
1153 wlock = self.wlock()
1153 wlock = self.wlock()
1154 for f in list:
1154 for f in list:
1155 if unlink and os.path.exists(self.wjoin(f)):
1155 if unlink and os.path.exists(self.wjoin(f)):
1156 self.ui.warn(_("%s still exists!\n") % f)
1156 self.ui.warn(_("%s still exists!\n") % f)
1157 elif self.dirstate[f] == 'a':
1157 elif self.dirstate[f] == 'a':
1158 self.dirstate.forget(f)
1158 self.dirstate.forget(f)
1159 elif f not in self.dirstate:
1159 elif f not in self.dirstate:
1160 self.ui.warn(_("%s not tracked!\n") % f)
1160 self.ui.warn(_("%s not tracked!\n") % f)
1161 else:
1161 else:
1162 self.dirstate.remove(f)
1162 self.dirstate.remove(f)
1163 finally:
1163 finally:
1164 del wlock
1164 del wlock
1165
1165
1166 def undelete(self, list):
1166 def undelete(self, list):
1167 wlock = None
1167 wlock = None
1168 try:
1168 try:
1169 manifests = [self.manifest.read(self.changelog.read(p)[0])
1169 manifests = [self.manifest.read(self.changelog.read(p)[0])
1170 for p in self.dirstate.parents() if p != nullid]
1170 for p in self.dirstate.parents() if p != nullid]
1171 wlock = self.wlock()
1171 wlock = self.wlock()
1172 for f in list:
1172 for f in list:
1173 if self.dirstate[f] != 'r':
1173 if self.dirstate[f] != 'r':
1174 self.ui.warn("%s not removed!\n" % f)
1174 self.ui.warn("%s not removed!\n" % f)
1175 else:
1175 else:
1176 m = f in manifests[0] and manifests[0] or manifests[1]
1176 m = f in manifests[0] and manifests[0] or manifests[1]
1177 t = self.file(f).read(m[f])
1177 t = self.file(f).read(m[f])
1178 self.wwrite(f, t, m.flags(f))
1178 self.wwrite(f, t, m.flags(f))
1179 self.dirstate.normal(f)
1179 self.dirstate.normal(f)
1180 finally:
1180 finally:
1181 del wlock
1181 del wlock
1182
1182
1183 def copy(self, source, dest):
1183 def copy(self, source, dest):
1184 wlock = None
1184 wlock = None
1185 try:
1185 try:
1186 p = self.wjoin(dest)
1186 p = self.wjoin(dest)
1187 if not (os.path.exists(p) or os.path.islink(p)):
1187 if not (os.path.exists(p) or os.path.islink(p)):
1188 self.ui.warn(_("%s does not exist!\n") % dest)
1188 self.ui.warn(_("%s does not exist!\n") % dest)
1189 elif not (os.path.isfile(p) or os.path.islink(p)):
1189 elif not (os.path.isfile(p) or os.path.islink(p)):
1190 self.ui.warn(_("copy failed: %s is not a file or a "
1190 self.ui.warn(_("copy failed: %s is not a file or a "
1191 "symbolic link\n") % dest)
1191 "symbolic link\n") % dest)
1192 else:
1192 else:
1193 wlock = self.wlock()
1193 wlock = self.wlock()
1194 if dest not in self.dirstate:
1194 if dest not in self.dirstate:
1195 self.dirstate.add(dest)
1195 self.dirstate.add(dest)
1196 self.dirstate.copy(source, dest)
1196 self.dirstate.copy(source, dest)
1197 finally:
1197 finally:
1198 del wlock
1198 del wlock
1199
1199
1200 def heads(self, start=None):
1200 def heads(self, start=None):
1201 heads = self.changelog.heads(start)
1201 heads = self.changelog.heads(start)
1202 # sort the output in rev descending order
1202 # sort the output in rev descending order
1203 heads = [(-self.changelog.rev(h), h) for h in heads]
1203 heads = [(-self.changelog.rev(h), h) for h in heads]
1204 heads.sort()
1204 heads.sort()
1205 return [n for (r, n) in heads]
1205 return [n for (r, n) in heads]
1206
1206
1207 def branchheads(self, branch, start=None):
1207 def branchheads(self, branch, start=None):
1208 branches = self.branchtags()
1208 branches = self.branchtags()
1209 if branch not in branches:
1209 if branch not in branches:
1210 return []
1210 return []
1211 # The basic algorithm is this:
1211 # The basic algorithm is this:
1212 #
1212 #
1213 # Start from the branch tip since there are no later revisions that can
1213 # Start from the branch tip since there are no later revisions that can
1214 # possibly be in this branch, and the tip is a guaranteed head.
1214 # possibly be in this branch, and the tip is a guaranteed head.
1215 #
1215 #
1216 # Remember the tip's parents as the first ancestors, since these by
1216 # Remember the tip's parents as the first ancestors, since these by
1217 # definition are not heads.
1217 # definition are not heads.
1218 #
1218 #
1219 # Step backwards from the brach tip through all the revisions. We are
1219 # Step backwards from the brach tip through all the revisions. We are
1220 # guaranteed by the rules of Mercurial that we will now be visiting the
1220 # guaranteed by the rules of Mercurial that we will now be visiting the
1221 # nodes in reverse topological order (children before parents).
1221 # nodes in reverse topological order (children before parents).
1222 #
1222 #
1223 # If a revision is one of the ancestors of a head then we can toss it
1223 # If a revision is one of the ancestors of a head then we can toss it
1224 # out of the ancestors set (we've already found it and won't be
1224 # out of the ancestors set (we've already found it and won't be
1225 # visiting it again) and put its parents in the ancestors set.
1225 # visiting it again) and put its parents in the ancestors set.
1226 #
1226 #
1227 # Otherwise, if a revision is in the branch it's another head, since it
1227 # Otherwise, if a revision is in the branch it's another head, since it
1228 # wasn't in the ancestor list of an existing head. So add it to the
1228 # wasn't in the ancestor list of an existing head. So add it to the
1229 # head list, and add its parents to the ancestor list.
1229 # head list, and add its parents to the ancestor list.
1230 #
1230 #
1231 # If it is not in the branch ignore it.
1231 # If it is not in the branch ignore it.
1232 #
1232 #
1233 # Once we have a list of heads, use nodesbetween to filter out all the
1233 # Once we have a list of heads, use nodesbetween to filter out all the
1234 # heads that cannot be reached from startrev. There may be a more
1234 # heads that cannot be reached from startrev. There may be a more
1235 # efficient way to do this as part of the previous algorithm.
1235 # efficient way to do this as part of the previous algorithm.
1236
1236
1237 set = util.set
1237 set = util.set
1238 heads = [self.changelog.rev(branches[branch])]
1238 heads = [self.changelog.rev(branches[branch])]
1239 # Don't care if ancestors contains nullrev or not.
1239 # Don't care if ancestors contains nullrev or not.
1240 ancestors = set(self.changelog.parentrevs(heads[0]))
1240 ancestors = set(self.changelog.parentrevs(heads[0]))
1241 for rev in xrange(heads[0] - 1, nullrev, -1):
1241 for rev in xrange(heads[0] - 1, nullrev, -1):
1242 if rev in ancestors:
1242 if rev in ancestors:
1243 ancestors.update(self.changelog.parentrevs(rev))
1243 ancestors.update(self.changelog.parentrevs(rev))
1244 ancestors.remove(rev)
1244 ancestors.remove(rev)
1245 elif self.changectx(rev).branch() == branch:
1245 elif self.changectx(rev).branch() == branch:
1246 heads.append(rev)
1246 heads.append(rev)
1247 ancestors.update(self.changelog.parentrevs(rev))
1247 ancestors.update(self.changelog.parentrevs(rev))
1248 heads = [self.changelog.node(rev) for rev in heads]
1248 heads = [self.changelog.node(rev) for rev in heads]
1249 if start is not None:
1249 if start is not None:
1250 heads = self.changelog.nodesbetween([start], heads)[2]
1250 heads = self.changelog.nodesbetween([start], heads)[2]
1251 return heads
1251 return heads
1252
1252
1253 def branches(self, nodes):
1253 def branches(self, nodes):
1254 if not nodes:
1254 if not nodes:
1255 nodes = [self.changelog.tip()]
1255 nodes = [self.changelog.tip()]
1256 b = []
1256 b = []
1257 for n in nodes:
1257 for n in nodes:
1258 t = n
1258 t = n
1259 while 1:
1259 while 1:
1260 p = self.changelog.parents(n)
1260 p = self.changelog.parents(n)
1261 if p[1] != nullid or p[0] == nullid:
1261 if p[1] != nullid or p[0] == nullid:
1262 b.append((t, n, p[0], p[1]))
1262 b.append((t, n, p[0], p[1]))
1263 break
1263 break
1264 n = p[0]
1264 n = p[0]
1265 return b
1265 return b
1266
1266
1267 def between(self, pairs):
1267 def between(self, pairs):
1268 r = []
1268 r = []
1269
1269
1270 for top, bottom in pairs:
1270 for top, bottom in pairs:
1271 n, l, i = top, [], 0
1271 n, l, i = top, [], 0
1272 f = 1
1272 f = 1
1273
1273
1274 while n != bottom:
1274 while n != bottom:
1275 p = self.changelog.parents(n)[0]
1275 p = self.changelog.parents(n)[0]
1276 if i == f:
1276 if i == f:
1277 l.append(n)
1277 l.append(n)
1278 f = f * 2
1278 f = f * 2
1279 n = p
1279 n = p
1280 i += 1
1280 i += 1
1281
1281
1282 r.append(l)
1282 r.append(l)
1283
1283
1284 return r
1284 return r
1285
1285
1286 def findincoming(self, remote, base=None, heads=None, force=False):
1286 def findincoming(self, remote, base=None, heads=None, force=False):
1287 """Return list of roots of the subsets of missing nodes from remote
1287 """Return list of roots of the subsets of missing nodes from remote
1288
1288
1289 If base dict is specified, assume that these nodes and their parents
1289 If base dict is specified, assume that these nodes and their parents
1290 exist on the remote side and that no child of a node of base exists
1290 exist on the remote side and that no child of a node of base exists
1291 in both remote and self.
1291 in both remote and self.
1292 Furthermore base will be updated to include the nodes that exists
1292 Furthermore base will be updated to include the nodes that exists
1293 in self and remote but no children exists in self and remote.
1293 in self and remote but no children exists in self and remote.
1294 If a list of heads is specified, return only nodes which are heads
1294 If a list of heads is specified, return only nodes which are heads
1295 or ancestors of these heads.
1295 or ancestors of these heads.
1296
1296
1297 All the ancestors of base are in self and in remote.
1297 All the ancestors of base are in self and in remote.
1298 All the descendants of the list returned are missing in self.
1298 All the descendants of the list returned are missing in self.
1299 (and so we know that the rest of the nodes are missing in remote, see
1299 (and so we know that the rest of the nodes are missing in remote, see
1300 outgoing)
1300 outgoing)
1301 """
1301 """
1302 m = self.changelog.nodemap
1302 m = self.changelog.nodemap
1303 search = []
1303 search = []
1304 fetch = {}
1304 fetch = {}
1305 seen = {}
1305 seen = {}
1306 seenbranch = {}
1306 seenbranch = {}
1307 if base == None:
1307 if base == None:
1308 base = {}
1308 base = {}
1309
1309
1310 if not heads:
1310 if not heads:
1311 heads = remote.heads()
1311 heads = remote.heads()
1312
1312
1313 if self.changelog.tip() == nullid:
1313 if self.changelog.tip() == nullid:
1314 base[nullid] = 1
1314 base[nullid] = 1
1315 if heads != [nullid]:
1315 if heads != [nullid]:
1316 return [nullid]
1316 return [nullid]
1317 return []
1317 return []
1318
1318
1319 # assume we're closer to the tip than the root
1319 # assume we're closer to the tip than the root
1320 # and start by examining the heads
1320 # and start by examining the heads
1321 self.ui.status(_("searching for changes\n"))
1321 self.ui.status(_("searching for changes\n"))
1322
1322
1323 unknown = []
1323 unknown = []
1324 for h in heads:
1324 for h in heads:
1325 if h not in m:
1325 if h not in m:
1326 unknown.append(h)
1326 unknown.append(h)
1327 else:
1327 else:
1328 base[h] = 1
1328 base[h] = 1
1329
1329
1330 if not unknown:
1330 if not unknown:
1331 return []
1331 return []
1332
1332
1333 req = dict.fromkeys(unknown)
1333 req = dict.fromkeys(unknown)
1334 reqcnt = 0
1334 reqcnt = 0
1335
1335
1336 # search through remote branches
1336 # search through remote branches
1337 # a 'branch' here is a linear segment of history, with four parts:
1337 # a 'branch' here is a linear segment of history, with four parts:
1338 # head, root, first parent, second parent
1338 # head, root, first parent, second parent
1339 # (a branch always has two parents (or none) by definition)
1339 # (a branch always has two parents (or none) by definition)
1340 unknown = remote.branches(unknown)
1340 unknown = remote.branches(unknown)
1341 while unknown:
1341 while unknown:
1342 r = []
1342 r = []
1343 while unknown:
1343 while unknown:
1344 n = unknown.pop(0)
1344 n = unknown.pop(0)
1345 if n[0] in seen:
1345 if n[0] in seen:
1346 continue
1346 continue
1347
1347
1348 self.ui.debug(_("examining %s:%s\n")
1348 self.ui.debug(_("examining %s:%s\n")
1349 % (short(n[0]), short(n[1])))
1349 % (short(n[0]), short(n[1])))
1350 if n[0] == nullid: # found the end of the branch
1350 if n[0] == nullid: # found the end of the branch
1351 pass
1351 pass
1352 elif n in seenbranch:
1352 elif n in seenbranch:
1353 self.ui.debug(_("branch already found\n"))
1353 self.ui.debug(_("branch already found\n"))
1354 continue
1354 continue
1355 elif n[1] and n[1] in m: # do we know the base?
1355 elif n[1] and n[1] in m: # do we know the base?
1356 self.ui.debug(_("found incomplete branch %s:%s\n")
1356 self.ui.debug(_("found incomplete branch %s:%s\n")
1357 % (short(n[0]), short(n[1])))
1357 % (short(n[0]), short(n[1])))
1358 search.append(n) # schedule branch range for scanning
1358 search.append(n) # schedule branch range for scanning
1359 seenbranch[n] = 1
1359 seenbranch[n] = 1
1360 else:
1360 else:
1361 if n[1] not in seen and n[1] not in fetch:
1361 if n[1] not in seen and n[1] not in fetch:
1362 if n[2] in m and n[3] in m:
1362 if n[2] in m and n[3] in m:
1363 self.ui.debug(_("found new changeset %s\n") %
1363 self.ui.debug(_("found new changeset %s\n") %
1364 short(n[1]))
1364 short(n[1]))
1365 fetch[n[1]] = 1 # earliest unknown
1365 fetch[n[1]] = 1 # earliest unknown
1366 for p in n[2:4]:
1366 for p in n[2:4]:
1367 if p in m:
1367 if p in m:
1368 base[p] = 1 # latest known
1368 base[p] = 1 # latest known
1369
1369
1370 for p in n[2:4]:
1370 for p in n[2:4]:
1371 if p not in req and p not in m:
1371 if p not in req and p not in m:
1372 r.append(p)
1372 r.append(p)
1373 req[p] = 1
1373 req[p] = 1
1374 seen[n[0]] = 1
1374 seen[n[0]] = 1
1375
1375
1376 if r:
1376 if r:
1377 reqcnt += 1
1377 reqcnt += 1
1378 self.ui.debug(_("request %d: %s\n") %
1378 self.ui.debug(_("request %d: %s\n") %
1379 (reqcnt, " ".join(map(short, r))))
1379 (reqcnt, " ".join(map(short, r))))
1380 for p in xrange(0, len(r), 10):
1380 for p in xrange(0, len(r), 10):
1381 for b in remote.branches(r[p:p+10]):
1381 for b in remote.branches(r[p:p+10]):
1382 self.ui.debug(_("received %s:%s\n") %
1382 self.ui.debug(_("received %s:%s\n") %
1383 (short(b[0]), short(b[1])))
1383 (short(b[0]), short(b[1])))
1384 unknown.append(b)
1384 unknown.append(b)
1385
1385
1386 # do binary search on the branches we found
1386 # do binary search on the branches we found
1387 while search:
1387 while search:
1388 n = search.pop(0)
1388 n = search.pop(0)
1389 reqcnt += 1
1389 reqcnt += 1
1390 l = remote.between([(n[0], n[1])])[0]
1390 l = remote.between([(n[0], n[1])])[0]
1391 l.append(n[1])
1391 l.append(n[1])
1392 p = n[0]
1392 p = n[0]
1393 f = 1
1393 f = 1
1394 for i in l:
1394 for i in l:
1395 self.ui.debug(_("narrowing %d:%d %s\n") % (f, len(l), short(i)))
1395 self.ui.debug(_("narrowing %d:%d %s\n") % (f, len(l), short(i)))
1396 if i in m:
1396 if i in m:
1397 if f <= 2:
1397 if f <= 2:
1398 self.ui.debug(_("found new branch changeset %s\n") %
1398 self.ui.debug(_("found new branch changeset %s\n") %
1399 short(p))
1399 short(p))
1400 fetch[p] = 1
1400 fetch[p] = 1
1401 base[i] = 1
1401 base[i] = 1
1402 else:
1402 else:
1403 self.ui.debug(_("narrowed branch search to %s:%s\n")
1403 self.ui.debug(_("narrowed branch search to %s:%s\n")
1404 % (short(p), short(i)))
1404 % (short(p), short(i)))
1405 search.append((p, i))
1405 search.append((p, i))
1406 break
1406 break
1407 p, f = i, f * 2
1407 p, f = i, f * 2
1408
1408
1409 # sanity check our fetch list
1409 # sanity check our fetch list
1410 for f in fetch.keys():
1410 for f in fetch.keys():
1411 if f in m:
1411 if f in m:
1412 raise repo.RepoError(_("already have changeset ") + short(f[:4]))
1412 raise repo.RepoError(_("already have changeset ") + short(f[:4]))
1413
1413
1414 if base.keys() == [nullid]:
1414 if base.keys() == [nullid]:
1415 if force:
1415 if force:
1416 self.ui.warn(_("warning: repository is unrelated\n"))
1416 self.ui.warn(_("warning: repository is unrelated\n"))
1417 else:
1417 else:
1418 raise util.Abort(_("repository is unrelated"))
1418 raise util.Abort(_("repository is unrelated"))
1419
1419
1420 self.ui.debug(_("found new changesets starting at ") +
1420 self.ui.debug(_("found new changesets starting at ") +
1421 " ".join([short(f) for f in fetch]) + "\n")
1421 " ".join([short(f) for f in fetch]) + "\n")
1422
1422
1423 self.ui.debug(_("%d total queries\n") % reqcnt)
1423 self.ui.debug(_("%d total queries\n") % reqcnt)
1424
1424
1425 return fetch.keys()
1425 return fetch.keys()
1426
1426
1427 def findoutgoing(self, remote, base=None, heads=None, force=False):
1427 def findoutgoing(self, remote, base=None, heads=None, force=False):
1428 """Return list of nodes that are roots of subsets not in remote
1428 """Return list of nodes that are roots of subsets not in remote
1429
1429
1430 If base dict is specified, assume that these nodes and their parents
1430 If base dict is specified, assume that these nodes and their parents
1431 exist on the remote side.
1431 exist on the remote side.
1432 If a list of heads is specified, return only nodes which are heads
1432 If a list of heads is specified, return only nodes which are heads
1433 or ancestors of these heads, and return a second element which
1433 or ancestors of these heads, and return a second element which
1434 contains all remote heads which get new children.
1434 contains all remote heads which get new children.
1435 """
1435 """
1436 if base == None:
1436 if base == None:
1437 base = {}
1437 base = {}
1438 self.findincoming(remote, base, heads, force=force)
1438 self.findincoming(remote, base, heads, force=force)
1439
1439
1440 self.ui.debug(_("common changesets up to ")
1440 self.ui.debug(_("common changesets up to ")
1441 + " ".join(map(short, base.keys())) + "\n")
1441 + " ".join(map(short, base.keys())) + "\n")
1442
1442
1443 remain = dict.fromkeys(self.changelog.nodemap)
1443 remain = dict.fromkeys(self.changelog.nodemap)
1444
1444
1445 # prune everything remote has from the tree
1445 # prune everything remote has from the tree
1446 del remain[nullid]
1446 del remain[nullid]
1447 remove = base.keys()
1447 remove = base.keys()
1448 while remove:
1448 while remove:
1449 n = remove.pop(0)
1449 n = remove.pop(0)
1450 if n in remain:
1450 if n in remain:
1451 del remain[n]
1451 del remain[n]
1452 for p in self.changelog.parents(n):
1452 for p in self.changelog.parents(n):
1453 remove.append(p)
1453 remove.append(p)
1454
1454
1455 # find every node whose parents have been pruned
1455 # find every node whose parents have been pruned
1456 subset = []
1456 subset = []
1457 # find every remote head that will get new children
1457 # find every remote head that will get new children
1458 updated_heads = {}
1458 updated_heads = {}
1459 for n in remain:
1459 for n in remain:
1460 p1, p2 = self.changelog.parents(n)
1460 p1, p2 = self.changelog.parents(n)
1461 if p1 not in remain and p2 not in remain:
1461 if p1 not in remain and p2 not in remain:
1462 subset.append(n)
1462 subset.append(n)
1463 if heads:
1463 if heads:
1464 if p1 in heads:
1464 if p1 in heads:
1465 updated_heads[p1] = True
1465 updated_heads[p1] = True
1466 if p2 in heads:
1466 if p2 in heads:
1467 updated_heads[p2] = True
1467 updated_heads[p2] = True
1468
1468
1469 # this is the set of all roots we have to push
1469 # this is the set of all roots we have to push
1470 if heads:
1470 if heads:
1471 return subset, updated_heads.keys()
1471 return subset, updated_heads.keys()
1472 else:
1472 else:
1473 return subset
1473 return subset
1474
1474
1475 def pull(self, remote, heads=None, force=False):
1475 def pull(self, remote, heads=None, force=False):
1476 lock = self.lock()
1476 lock = self.lock()
1477 try:
1477 try:
1478 fetch = self.findincoming(remote, heads=heads, force=force)
1478 fetch = self.findincoming(remote, heads=heads, force=force)
1479 if fetch == [nullid]:
1479 if fetch == [nullid]:
1480 self.ui.status(_("requesting all changes\n"))
1480 self.ui.status(_("requesting all changes\n"))
1481
1481
1482 if not fetch:
1482 if not fetch:
1483 self.ui.status(_("no changes found\n"))
1483 self.ui.status(_("no changes found\n"))
1484 return 0
1484 return 0
1485
1485
1486 if heads is None:
1486 if heads is None:
1487 cg = remote.changegroup(fetch, 'pull')
1487 cg = remote.changegroup(fetch, 'pull')
1488 else:
1488 else:
1489 if 'changegroupsubset' not in remote.capabilities:
1489 if 'changegroupsubset' not in remote.capabilities:
1490 raise util.Abort(_("Partial pull cannot be done because other repository doesn't support changegroupsubset."))
1490 raise util.Abort(_("Partial pull cannot be done because other repository doesn't support changegroupsubset."))
1491 cg = remote.changegroupsubset(fetch, heads, 'pull')
1491 cg = remote.changegroupsubset(fetch, heads, 'pull')
1492 return self.addchangegroup(cg, 'pull', remote.url())
1492 return self.addchangegroup(cg, 'pull', remote.url())
1493 finally:
1493 finally:
1494 del lock
1494 del lock
1495
1495
1496 def push(self, remote, force=False, revs=None):
1496 def push(self, remote, force=False, revs=None):
1497 # there are two ways to push to remote repo:
1497 # there are two ways to push to remote repo:
1498 #
1498 #
1499 # addchangegroup assumes local user can lock remote
1499 # addchangegroup assumes local user can lock remote
1500 # repo (local filesystem, old ssh servers).
1500 # repo (local filesystem, old ssh servers).
1501 #
1501 #
1502 # unbundle assumes local user cannot lock remote repo (new ssh
1502 # unbundle assumes local user cannot lock remote repo (new ssh
1503 # servers, http servers).
1503 # servers, http servers).
1504
1504
1505 if remote.capable('unbundle'):
1505 if remote.capable('unbundle'):
1506 return self.push_unbundle(remote, force, revs)
1506 return self.push_unbundle(remote, force, revs)
1507 return self.push_addchangegroup(remote, force, revs)
1507 return self.push_addchangegroup(remote, force, revs)
1508
1508
1509 def prepush(self, remote, force, revs):
1509 def prepush(self, remote, force, revs):
1510 base = {}
1510 base = {}
1511 remote_heads = remote.heads()
1511 remote_heads = remote.heads()
1512 inc = self.findincoming(remote, base, remote_heads, force=force)
1512 inc = self.findincoming(remote, base, remote_heads, force=force)
1513
1513
1514 update, updated_heads = self.findoutgoing(remote, base, remote_heads)
1514 update, updated_heads = self.findoutgoing(remote, base, remote_heads)
1515 if revs is not None:
1515 if revs is not None:
1516 msng_cl, bases, heads = self.changelog.nodesbetween(update, revs)
1516 msng_cl, bases, heads = self.changelog.nodesbetween(update, revs)
1517 else:
1517 else:
1518 bases, heads = update, self.changelog.heads()
1518 bases, heads = update, self.changelog.heads()
1519
1519
1520 if not bases:
1520 if not bases:
1521 self.ui.status(_("no changes found\n"))
1521 self.ui.status(_("no changes found\n"))
1522 return None, 1
1522 return None, 1
1523 elif not force:
1523 elif not force:
1524 # check if we're creating new remote heads
1524 # check if we're creating new remote heads
1525 # to be a remote head after push, node must be either
1525 # to be a remote head after push, node must be either
1526 # - unknown locally
1526 # - unknown locally
1527 # - a local outgoing head descended from update
1527 # - a local outgoing head descended from update
1528 # - a remote head that's known locally and not
1528 # - a remote head that's known locally and not
1529 # ancestral to an outgoing head
1529 # ancestral to an outgoing head
1530
1530
1531 warn = 0
1531 warn = 0
1532
1532
1533 if remote_heads == [nullid]:
1533 if remote_heads == [nullid]:
1534 warn = 0
1534 warn = 0
1535 elif not revs and len(heads) > len(remote_heads):
1535 elif not revs and len(heads) > len(remote_heads):
1536 warn = 1
1536 warn = 1
1537 else:
1537 else:
1538 newheads = list(heads)
1538 newheads = list(heads)
1539 for r in remote_heads:
1539 for r in remote_heads:
1540 if r in self.changelog.nodemap:
1540 if r in self.changelog.nodemap:
1541 desc = self.changelog.heads(r, heads)
1541 desc = self.changelog.heads(r, heads)
1542 l = [h for h in heads if h in desc]
1542 l = [h for h in heads if h in desc]
1543 if not l:
1543 if not l:
1544 newheads.append(r)
1544 newheads.append(r)
1545 else:
1545 else:
1546 newheads.append(r)
1546 newheads.append(r)
1547 if len(newheads) > len(remote_heads):
1547 if len(newheads) > len(remote_heads):
1548 warn = 1
1548 warn = 1
1549
1549
1550 if warn:
1550 if warn:
1551 self.ui.warn(_("abort: push creates new remote heads!\n"))
1551 self.ui.warn(_("abort: push creates new remote heads!\n"))
1552 self.ui.status(_("(did you forget to merge?"
1552 self.ui.status(_("(did you forget to merge?"
1553 " use push -f to force)\n"))
1553 " use push -f to force)\n"))
1554 return None, 0
1554 return None, 0
1555 elif inc:
1555 elif inc:
1556 self.ui.warn(_("note: unsynced remote changes!\n"))
1556 self.ui.warn(_("note: unsynced remote changes!\n"))
1557
1557
1558
1558
1559 if revs is None:
1559 if revs is None:
1560 cg = self.changegroup(update, 'push')
1560 cg = self.changegroup(update, 'push')
1561 else:
1561 else:
1562 cg = self.changegroupsubset(update, revs, 'push')
1562 cg = self.changegroupsubset(update, revs, 'push')
1563 return cg, remote_heads
1563 return cg, remote_heads
1564
1564
1565 def push_addchangegroup(self, remote, force, revs):
1565 def push_addchangegroup(self, remote, force, revs):
1566 lock = remote.lock()
1566 lock = remote.lock()
1567 try:
1567 try:
1568 ret = self.prepush(remote, force, revs)
1568 ret = self.prepush(remote, force, revs)
1569 if ret[0] is not None:
1569 if ret[0] is not None:
1570 cg, remote_heads = ret
1570 cg, remote_heads = ret
1571 return remote.addchangegroup(cg, 'push', self.url())
1571 return remote.addchangegroup(cg, 'push', self.url())
1572 return ret[1]
1572 return ret[1]
1573 finally:
1573 finally:
1574 del lock
1574 del lock
1575
1575
1576 def push_unbundle(self, remote, force, revs):
1576 def push_unbundle(self, remote, force, revs):
1577 # local repo finds heads on server, finds out what revs it
1577 # local repo finds heads on server, finds out what revs it
1578 # must push. once revs transferred, if server finds it has
1578 # must push. once revs transferred, if server finds it has
1579 # different heads (someone else won commit/push race), server
1579 # different heads (someone else won commit/push race), server
1580 # aborts.
1580 # aborts.
1581
1581
1582 ret = self.prepush(remote, force, revs)
1582 ret = self.prepush(remote, force, revs)
1583 if ret[0] is not None:
1583 if ret[0] is not None:
1584 cg, remote_heads = ret
1584 cg, remote_heads = ret
1585 if force: remote_heads = ['force']
1585 if force: remote_heads = ['force']
1586 return remote.unbundle(cg, remote_heads, 'push')
1586 return remote.unbundle(cg, remote_heads, 'push')
1587 return ret[1]
1587 return ret[1]
1588
1588
1589 def changegroupinfo(self, nodes, source):
1589 def changegroupinfo(self, nodes, source):
1590 if self.ui.verbose or source == 'bundle':
1590 if self.ui.verbose or source == 'bundle':
1591 self.ui.status(_("%d changesets found\n") % len(nodes))
1591 self.ui.status(_("%d changesets found\n") % len(nodes))
1592 if self.ui.debugflag:
1592 if self.ui.debugflag:
1593 self.ui.debug(_("List of changesets:\n"))
1593 self.ui.debug(_("List of changesets:\n"))
1594 for node in nodes:
1594 for node in nodes:
1595 self.ui.debug("%s\n" % hex(node))
1595 self.ui.debug("%s\n" % hex(node))
1596
1596
1597 def changegroupsubset(self, bases, heads, source, extranodes=None):
1597 def changegroupsubset(self, bases, heads, source, extranodes=None):
1598 """This function generates a changegroup consisting of all the nodes
1598 """This function generates a changegroup consisting of all the nodes
1599 that are descendents of any of the bases, and ancestors of any of
1599 that are descendents of any of the bases, and ancestors of any of
1600 the heads.
1600 the heads.
1601
1601
1602 It is fairly complex as determining which filenodes and which
1602 It is fairly complex as determining which filenodes and which
1603 manifest nodes need to be included for the changeset to be complete
1603 manifest nodes need to be included for the changeset to be complete
1604 is non-trivial.
1604 is non-trivial.
1605
1605
1606 Another wrinkle is doing the reverse, figuring out which changeset in
1606 Another wrinkle is doing the reverse, figuring out which changeset in
1607 the changegroup a particular filenode or manifestnode belongs to.
1607 the changegroup a particular filenode or manifestnode belongs to.
1608
1608
1609 The caller can specify some nodes that must be included in the
1609 The caller can specify some nodes that must be included in the
1610 changegroup using the extranodes argument. It should be a dict
1610 changegroup using the extranodes argument. It should be a dict
1611 where the keys are the filenames (or 1 for the manifest), and the
1611 where the keys are the filenames (or 1 for the manifest), and the
1612 values are lists of (node, linknode) tuples, where node is a wanted
1612 values are lists of (node, linknode) tuples, where node is a wanted
1613 node and linknode is the changelog node that should be transmitted as
1613 node and linknode is the changelog node that should be transmitted as
1614 the linkrev.
1614 the linkrev.
1615 """
1615 """
1616
1616
1617 self.hook('preoutgoing', throw=True, source=source)
1617 self.hook('preoutgoing', throw=True, source=source)
1618
1618
1619 # Set up some initial variables
1619 # Set up some initial variables
1620 # Make it easy to refer to self.changelog
1620 # Make it easy to refer to self.changelog
1621 cl = self.changelog
1621 cl = self.changelog
1622 # msng is short for missing - compute the list of changesets in this
1622 # msng is short for missing - compute the list of changesets in this
1623 # changegroup.
1623 # changegroup.
1624 msng_cl_lst, bases, heads = cl.nodesbetween(bases, heads)
1624 msng_cl_lst, bases, heads = cl.nodesbetween(bases, heads)
1625 self.changegroupinfo(msng_cl_lst, source)
1625 self.changegroupinfo(msng_cl_lst, source)
1626 # Some bases may turn out to be superfluous, and some heads may be
1626 # Some bases may turn out to be superfluous, and some heads may be
1627 # too. nodesbetween will return the minimal set of bases and heads
1627 # too. nodesbetween will return the minimal set of bases and heads
1628 # necessary to re-create the changegroup.
1628 # necessary to re-create the changegroup.
1629
1629
1630 # Known heads are the list of heads that it is assumed the recipient
1630 # Known heads are the list of heads that it is assumed the recipient
1631 # of this changegroup will know about.
1631 # of this changegroup will know about.
1632 knownheads = {}
1632 knownheads = {}
1633 # We assume that all parents of bases are known heads.
1633 # We assume that all parents of bases are known heads.
1634 for n in bases:
1634 for n in bases:
1635 for p in cl.parents(n):
1635 for p in cl.parents(n):
1636 if p != nullid:
1636 if p != nullid:
1637 knownheads[p] = 1
1637 knownheads[p] = 1
1638 knownheads = knownheads.keys()
1638 knownheads = knownheads.keys()
1639 if knownheads:
1639 if knownheads:
1640 # Now that we know what heads are known, we can compute which
1640 # Now that we know what heads are known, we can compute which
1641 # changesets are known. The recipient must know about all
1641 # changesets are known. The recipient must know about all
1642 # changesets required to reach the known heads from the null
1642 # changesets required to reach the known heads from the null
1643 # changeset.
1643 # changeset.
1644 has_cl_set, junk, junk = cl.nodesbetween(None, knownheads)
1644 has_cl_set, junk, junk = cl.nodesbetween(None, knownheads)
1645 junk = None
1645 junk = None
1646 # Transform the list into an ersatz set.
1646 # Transform the list into an ersatz set.
1647 has_cl_set = dict.fromkeys(has_cl_set)
1647 has_cl_set = dict.fromkeys(has_cl_set)
1648 else:
1648 else:
1649 # If there were no known heads, the recipient cannot be assumed to
1649 # If there were no known heads, the recipient cannot be assumed to
1650 # know about any changesets.
1650 # know about any changesets.
1651 has_cl_set = {}
1651 has_cl_set = {}
1652
1652
1653 # Make it easy to refer to self.manifest
1653 # Make it easy to refer to self.manifest
1654 mnfst = self.manifest
1654 mnfst = self.manifest
1655 # We don't know which manifests are missing yet
1655 # We don't know which manifests are missing yet
1656 msng_mnfst_set = {}
1656 msng_mnfst_set = {}
1657 # Nor do we know which filenodes are missing.
1657 # Nor do we know which filenodes are missing.
1658 msng_filenode_set = {}
1658 msng_filenode_set = {}
1659
1659
1660 junk = mnfst.index[mnfst.count() - 1] # Get around a bug in lazyindex
1660 junk = mnfst.index[mnfst.count() - 1] # Get around a bug in lazyindex
1661 junk = None
1661 junk = None
1662
1662
1663 # A changeset always belongs to itself, so the changenode lookup
1663 # A changeset always belongs to itself, so the changenode lookup
1664 # function for a changenode is identity.
1664 # function for a changenode is identity.
1665 def identity(x):
1665 def identity(x):
1666 return x
1666 return x
1667
1667
1668 # A function generating function. Sets up an environment for the
1668 # A function generating function. Sets up an environment for the
1669 # inner function.
1669 # inner function.
1670 def cmp_by_rev_func(revlog):
1670 def cmp_by_rev_func(revlog):
1671 # Compare two nodes by their revision number in the environment's
1671 # Compare two nodes by their revision number in the environment's
1672 # revision history. Since the revision number both represents the
1672 # revision history. Since the revision number both represents the
1673 # most efficient order to read the nodes in, and represents a
1673 # most efficient order to read the nodes in, and represents a
1674 # topological sorting of the nodes, this function is often useful.
1674 # topological sorting of the nodes, this function is often useful.
1675 def cmp_by_rev(a, b):
1675 def cmp_by_rev(a, b):
1676 return cmp(revlog.rev(a), revlog.rev(b))
1676 return cmp(revlog.rev(a), revlog.rev(b))
1677 return cmp_by_rev
1677 return cmp_by_rev
1678
1678
1679 # If we determine that a particular file or manifest node must be a
1679 # If we determine that a particular file or manifest node must be a
1680 # node that the recipient of the changegroup will already have, we can
1680 # node that the recipient of the changegroup will already have, we can
1681 # also assume the recipient will have all the parents. This function
1681 # also assume the recipient will have all the parents. This function
1682 # prunes them from the set of missing nodes.
1682 # prunes them from the set of missing nodes.
1683 def prune_parents(revlog, hasset, msngset):
1683 def prune_parents(revlog, hasset, msngset):
1684 haslst = hasset.keys()
1684 haslst = hasset.keys()
1685 haslst.sort(cmp_by_rev_func(revlog))
1685 haslst.sort(cmp_by_rev_func(revlog))
1686 for node in haslst:
1686 for node in haslst:
1687 parentlst = [p for p in revlog.parents(node) if p != nullid]
1687 parentlst = [p for p in revlog.parents(node) if p != nullid]
1688 while parentlst:
1688 while parentlst:
1689 n = parentlst.pop()
1689 n = parentlst.pop()
1690 if n not in hasset:
1690 if n not in hasset:
1691 hasset[n] = 1
1691 hasset[n] = 1
1692 p = [p for p in revlog.parents(n) if p != nullid]
1692 p = [p for p in revlog.parents(n) if p != nullid]
1693 parentlst.extend(p)
1693 parentlst.extend(p)
1694 for n in hasset:
1694 for n in hasset:
1695 msngset.pop(n, None)
1695 msngset.pop(n, None)
1696
1696
1697 # This is a function generating function used to set up an environment
1697 # This is a function generating function used to set up an environment
1698 # for the inner function to execute in.
1698 # for the inner function to execute in.
1699 def manifest_and_file_collector(changedfileset):
1699 def manifest_and_file_collector(changedfileset):
1700 # This is an information gathering function that gathers
1700 # This is an information gathering function that gathers
1701 # information from each changeset node that goes out as part of
1701 # information from each changeset node that goes out as part of
1702 # the changegroup. The information gathered is a list of which
1702 # the changegroup. The information gathered is a list of which
1703 # manifest nodes are potentially required (the recipient may
1703 # manifest nodes are potentially required (the recipient may
1704 # already have them) and total list of all files which were
1704 # already have them) and total list of all files which were
1705 # changed in any changeset in the changegroup.
1705 # changed in any changeset in the changegroup.
1706 #
1706 #
1707 # We also remember the first changenode we saw any manifest
1707 # We also remember the first changenode we saw any manifest
1708 # referenced by so we can later determine which changenode 'owns'
1708 # referenced by so we can later determine which changenode 'owns'
1709 # the manifest.
1709 # the manifest.
1710 def collect_manifests_and_files(clnode):
1710 def collect_manifests_and_files(clnode):
1711 c = cl.read(clnode)
1711 c = cl.read(clnode)
1712 for f in c[3]:
1712 for f in c[3]:
1713 # This is to make sure we only have one instance of each
1713 # This is to make sure we only have one instance of each
1714 # filename string for each filename.
1714 # filename string for each filename.
1715 changedfileset.setdefault(f, f)
1715 changedfileset.setdefault(f, f)
1716 msng_mnfst_set.setdefault(c[0], clnode)
1716 msng_mnfst_set.setdefault(c[0], clnode)
1717 return collect_manifests_and_files
1717 return collect_manifests_and_files
1718
1718
1719 # Figure out which manifest nodes (of the ones we think might be part
1719 # Figure out which manifest nodes (of the ones we think might be part
1720 # of the changegroup) the recipient must know about and remove them
1720 # of the changegroup) the recipient must know about and remove them
1721 # from the changegroup.
1721 # from the changegroup.
1722 def prune_manifests():
1722 def prune_manifests():
1723 has_mnfst_set = {}
1723 has_mnfst_set = {}
1724 for n in msng_mnfst_set:
1724 for n in msng_mnfst_set:
1725 # If a 'missing' manifest thinks it belongs to a changenode
1725 # If a 'missing' manifest thinks it belongs to a changenode
1726 # the recipient is assumed to have, obviously the recipient
1726 # the recipient is assumed to have, obviously the recipient
1727 # must have that manifest.
1727 # must have that manifest.
1728 linknode = cl.node(mnfst.linkrev(n))
1728 linknode = cl.node(mnfst.linkrev(n))
1729 if linknode in has_cl_set:
1729 if linknode in has_cl_set:
1730 has_mnfst_set[n] = 1
1730 has_mnfst_set[n] = 1
1731 prune_parents(mnfst, has_mnfst_set, msng_mnfst_set)
1731 prune_parents(mnfst, has_mnfst_set, msng_mnfst_set)
1732
1732
1733 # Use the information collected in collect_manifests_and_files to say
1733 # Use the information collected in collect_manifests_and_files to say
1734 # which changenode any manifestnode belongs to.
1734 # which changenode any manifestnode belongs to.
1735 def lookup_manifest_link(mnfstnode):
1735 def lookup_manifest_link(mnfstnode):
1736 return msng_mnfst_set[mnfstnode]
1736 return msng_mnfst_set[mnfstnode]
1737
1737
1738 # A function generating function that sets up the initial environment
1738 # A function generating function that sets up the initial environment
1739 # the inner function.
1739 # the inner function.
1740 def filenode_collector(changedfiles):
1740 def filenode_collector(changedfiles):
1741 next_rev = [0]
1741 next_rev = [0]
1742 # This gathers information from each manifestnode included in the
1742 # This gathers information from each manifestnode included in the
1743 # changegroup about which filenodes the manifest node references
1743 # changegroup about which filenodes the manifest node references
1744 # so we can include those in the changegroup too.
1744 # so we can include those in the changegroup too.
1745 #
1745 #
1746 # It also remembers which changenode each filenode belongs to. It
1746 # It also remembers which changenode each filenode belongs to. It
1747 # does this by assuming the a filenode belongs to the changenode
1747 # does this by assuming the a filenode belongs to the changenode
1748 # the first manifest that references it belongs to.
1748 # the first manifest that references it belongs to.
1749 def collect_msng_filenodes(mnfstnode):
1749 def collect_msng_filenodes(mnfstnode):
1750 r = mnfst.rev(mnfstnode)
1750 r = mnfst.rev(mnfstnode)
1751 if r == next_rev[0]:
1751 if r == next_rev[0]:
1752 # If the last rev we looked at was the one just previous,
1752 # If the last rev we looked at was the one just previous,
1753 # we only need to see a diff.
1753 # we only need to see a diff.
1754 deltamf = mnfst.readdelta(mnfstnode)
1754 deltamf = mnfst.readdelta(mnfstnode)
1755 # For each line in the delta
1755 # For each line in the delta
1756 for f, fnode in deltamf.items():
1756 for f, fnode in deltamf.items():
1757 f = changedfiles.get(f, None)
1757 f = changedfiles.get(f, None)
1758 # And if the file is in the list of files we care
1758 # And if the file is in the list of files we care
1759 # about.
1759 # about.
1760 if f is not None:
1760 if f is not None:
1761 # Get the changenode this manifest belongs to
1761 # Get the changenode this manifest belongs to
1762 clnode = msng_mnfst_set[mnfstnode]
1762 clnode = msng_mnfst_set[mnfstnode]
1763 # Create the set of filenodes for the file if
1763 # Create the set of filenodes for the file if
1764 # there isn't one already.
1764 # there isn't one already.
1765 ndset = msng_filenode_set.setdefault(f, {})
1765 ndset = msng_filenode_set.setdefault(f, {})
1766 # And set the filenode's changelog node to the
1766 # And set the filenode's changelog node to the
1767 # manifest's if it hasn't been set already.
1767 # manifest's if it hasn't been set already.
1768 ndset.setdefault(fnode, clnode)
1768 ndset.setdefault(fnode, clnode)
1769 else:
1769 else:
1770 # Otherwise we need a full manifest.
1770 # Otherwise we need a full manifest.
1771 m = mnfst.read(mnfstnode)
1771 m = mnfst.read(mnfstnode)
1772 # For every file in we care about.
1772 # For every file in we care about.
1773 for f in changedfiles:
1773 for f in changedfiles:
1774 fnode = m.get(f, None)
1774 fnode = m.get(f, None)
1775 # If it's in the manifest
1775 # If it's in the manifest
1776 if fnode is not None:
1776 if fnode is not None:
1777 # See comments above.
1777 # See comments above.
1778 clnode = msng_mnfst_set[mnfstnode]
1778 clnode = msng_mnfst_set[mnfstnode]
1779 ndset = msng_filenode_set.setdefault(f, {})
1779 ndset = msng_filenode_set.setdefault(f, {})
1780 ndset.setdefault(fnode, clnode)
1780 ndset.setdefault(fnode, clnode)
1781 # Remember the revision we hope to see next.
1781 # Remember the revision we hope to see next.
1782 next_rev[0] = r + 1
1782 next_rev[0] = r + 1
1783 return collect_msng_filenodes
1783 return collect_msng_filenodes
1784
1784
1785 # We have a list of filenodes we think we need for a file, lets remove
1785 # We have a list of filenodes we think we need for a file, lets remove
1786 # all those we now the recipient must have.
1786 # all those we now the recipient must have.
1787 def prune_filenodes(f, filerevlog):
1787 def prune_filenodes(f, filerevlog):
1788 msngset = msng_filenode_set[f]
1788 msngset = msng_filenode_set[f]
1789 hasset = {}
1789 hasset = {}
1790 # If a 'missing' filenode thinks it belongs to a changenode we
1790 # If a 'missing' filenode thinks it belongs to a changenode we
1791 # assume the recipient must have, then the recipient must have
1791 # assume the recipient must have, then the recipient must have
1792 # that filenode.
1792 # that filenode.
1793 for n in msngset:
1793 for n in msngset:
1794 clnode = cl.node(filerevlog.linkrev(n))
1794 clnode = cl.node(filerevlog.linkrev(n))
1795 if clnode in has_cl_set:
1795 if clnode in has_cl_set:
1796 hasset[n] = 1
1796 hasset[n] = 1
1797 prune_parents(filerevlog, hasset, msngset)
1797 prune_parents(filerevlog, hasset, msngset)
1798
1798
1799 # A function generator function that sets up the a context for the
1799 # A function generator function that sets up the a context for the
1800 # inner function.
1800 # inner function.
1801 def lookup_filenode_link_func(fname):
1801 def lookup_filenode_link_func(fname):
1802 msngset = msng_filenode_set[fname]
1802 msngset = msng_filenode_set[fname]
1803 # Lookup the changenode the filenode belongs to.
1803 # Lookup the changenode the filenode belongs to.
1804 def lookup_filenode_link(fnode):
1804 def lookup_filenode_link(fnode):
1805 return msngset[fnode]
1805 return msngset[fnode]
1806 return lookup_filenode_link
1806 return lookup_filenode_link
1807
1807
1808 # Add the nodes that were explicitly requested.
1808 # Add the nodes that were explicitly requested.
1809 def add_extra_nodes(name, nodes):
1809 def add_extra_nodes(name, nodes):
1810 if not extranodes or name not in extranodes:
1810 if not extranodes or name not in extranodes:
1811 return
1811 return
1812
1812
1813 for node, linknode in extranodes[name]:
1813 for node, linknode in extranodes[name]:
1814 if node not in nodes:
1814 if node not in nodes:
1815 nodes[node] = linknode
1815 nodes[node] = linknode
1816
1816
1817 # Now that we have all theses utility functions to help out and
1817 # Now that we have all theses utility functions to help out and
1818 # logically divide up the task, generate the group.
1818 # logically divide up the task, generate the group.
1819 def gengroup():
1819 def gengroup():
1820 # The set of changed files starts empty.
1820 # The set of changed files starts empty.
1821 changedfiles = {}
1821 changedfiles = {}
1822 # Create a changenode group generator that will call our functions
1822 # Create a changenode group generator that will call our functions
1823 # back to lookup the owning changenode and collect information.
1823 # back to lookup the owning changenode and collect information.
1824 group = cl.group(msng_cl_lst, identity,
1824 group = cl.group(msng_cl_lst, identity,
1825 manifest_and_file_collector(changedfiles))
1825 manifest_and_file_collector(changedfiles))
1826 for chnk in group:
1826 for chnk in group:
1827 yield chnk
1827 yield chnk
1828
1828
1829 # The list of manifests has been collected by the generator
1829 # The list of manifests has been collected by the generator
1830 # calling our functions back.
1830 # calling our functions back.
1831 prune_manifests()
1831 prune_manifests()
1832 add_extra_nodes(1, msng_mnfst_set)
1832 add_extra_nodes(1, msng_mnfst_set)
1833 msng_mnfst_lst = msng_mnfst_set.keys()
1833 msng_mnfst_lst = msng_mnfst_set.keys()
1834 # Sort the manifestnodes by revision number.
1834 # Sort the manifestnodes by revision number.
1835 msng_mnfst_lst.sort(cmp_by_rev_func(mnfst))
1835 msng_mnfst_lst.sort(cmp_by_rev_func(mnfst))
1836 # Create a generator for the manifestnodes that calls our lookup
1836 # Create a generator for the manifestnodes that calls our lookup
1837 # and data collection functions back.
1837 # and data collection functions back.
1838 group = mnfst.group(msng_mnfst_lst, lookup_manifest_link,
1838 group = mnfst.group(msng_mnfst_lst, lookup_manifest_link,
1839 filenode_collector(changedfiles))
1839 filenode_collector(changedfiles))
1840 for chnk in group:
1840 for chnk in group:
1841 yield chnk
1841 yield chnk
1842
1842
1843 # These are no longer needed, dereference and toss the memory for
1843 # These are no longer needed, dereference and toss the memory for
1844 # them.
1844 # them.
1845 msng_mnfst_lst = None
1845 msng_mnfst_lst = None
1846 msng_mnfst_set.clear()
1846 msng_mnfst_set.clear()
1847
1847
1848 if extranodes:
1848 if extranodes:
1849 for fname in extranodes:
1849 for fname in extranodes:
1850 if isinstance(fname, int):
1850 if isinstance(fname, int):
1851 continue
1851 continue
1852 add_extra_nodes(fname,
1852 add_extra_nodes(fname,
1853 msng_filenode_set.setdefault(fname, {}))
1853 msng_filenode_set.setdefault(fname, {}))
1854 changedfiles[fname] = 1
1854 changedfiles[fname] = 1
1855 changedfiles = changedfiles.keys()
1855 changedfiles = changedfiles.keys()
1856 changedfiles.sort()
1856 changedfiles.sort()
1857 # Go through all our files in order sorted by name.
1857 # Go through all our files in order sorted by name.
1858 for fname in changedfiles:
1858 for fname in changedfiles:
1859 filerevlog = self.file(fname)
1859 filerevlog = self.file(fname)
1860 if filerevlog.count() == 0:
1860 if filerevlog.count() == 0:
1861 raise util.Abort(_("empty or missing revlog for %s") % fname)
1861 raise util.Abort(_("empty or missing revlog for %s") % fname)
1862 # Toss out the filenodes that the recipient isn't really
1862 # Toss out the filenodes that the recipient isn't really
1863 # missing.
1863 # missing.
1864 if fname in msng_filenode_set:
1864 if fname in msng_filenode_set:
1865 prune_filenodes(fname, filerevlog)
1865 prune_filenodes(fname, filerevlog)
1866 msng_filenode_lst = msng_filenode_set[fname].keys()
1866 msng_filenode_lst = msng_filenode_set[fname].keys()
1867 else:
1867 else:
1868 msng_filenode_lst = []
1868 msng_filenode_lst = []
1869 # If any filenodes are left, generate the group for them,
1869 # If any filenodes are left, generate the group for them,
1870 # otherwise don't bother.
1870 # otherwise don't bother.
1871 if len(msng_filenode_lst) > 0:
1871 if len(msng_filenode_lst) > 0:
1872 yield changegroup.chunkheader(len(fname))
1872 yield changegroup.chunkheader(len(fname))
1873 yield fname
1873 yield fname
1874 # Sort the filenodes by their revision #
1874 # Sort the filenodes by their revision #
1875 msng_filenode_lst.sort(cmp_by_rev_func(filerevlog))
1875 msng_filenode_lst.sort(cmp_by_rev_func(filerevlog))
1876 # Create a group generator and only pass in a changenode
1876 # Create a group generator and only pass in a changenode
1877 # lookup function as we need to collect no information
1877 # lookup function as we need to collect no information
1878 # from filenodes.
1878 # from filenodes.
1879 group = filerevlog.group(msng_filenode_lst,
1879 group = filerevlog.group(msng_filenode_lst,
1880 lookup_filenode_link_func(fname))
1880 lookup_filenode_link_func(fname))
1881 for chnk in group:
1881 for chnk in group:
1882 yield chnk
1882 yield chnk
1883 if fname in msng_filenode_set:
1883 if fname in msng_filenode_set:
1884 # Don't need this anymore, toss it to free memory.
1884 # Don't need this anymore, toss it to free memory.
1885 del msng_filenode_set[fname]
1885 del msng_filenode_set[fname]
1886 # Signal that no more groups are left.
1886 # Signal that no more groups are left.
1887 yield changegroup.closechunk()
1887 yield changegroup.closechunk()
1888
1888
1889 if msng_cl_lst:
1889 if msng_cl_lst:
1890 self.hook('outgoing', node=hex(msng_cl_lst[0]), source=source)
1890 self.hook('outgoing', node=hex(msng_cl_lst[0]), source=source)
1891
1891
1892 return util.chunkbuffer(gengroup())
1892 return util.chunkbuffer(gengroup())
1893
1893
1894 def changegroup(self, basenodes, source):
1894 def changegroup(self, basenodes, source):
1895 """Generate a changegroup of all nodes that we have that a recipient
1895 """Generate a changegroup of all nodes that we have that a recipient
1896 doesn't.
1896 doesn't.
1897
1897
1898 This is much easier than the previous function as we can assume that
1898 This is much easier than the previous function as we can assume that
1899 the recipient has any changenode we aren't sending them."""
1899 the recipient has any changenode we aren't sending them."""
1900
1900
1901 self.hook('preoutgoing', throw=True, source=source)
1901 self.hook('preoutgoing', throw=True, source=source)
1902
1902
1903 cl = self.changelog
1903 cl = self.changelog
1904 nodes = cl.nodesbetween(basenodes, None)[0]
1904 nodes = cl.nodesbetween(basenodes, None)[0]
1905 revset = dict.fromkeys([cl.rev(n) for n in nodes])
1905 revset = dict.fromkeys([cl.rev(n) for n in nodes])
1906 self.changegroupinfo(nodes, source)
1906 self.changegroupinfo(nodes, source)
1907
1907
1908 def identity(x):
1908 def identity(x):
1909 return x
1909 return x
1910
1910
1911 def gennodelst(revlog):
1911 def gennodelst(revlog):
1912 for r in xrange(0, revlog.count()):
1912 for r in xrange(0, revlog.count()):
1913 n = revlog.node(r)
1913 n = revlog.node(r)
1914 if revlog.linkrev(n) in revset:
1914 if revlog.linkrev(n) in revset:
1915 yield n
1915 yield n
1916
1916
1917 def changed_file_collector(changedfileset):
1917 def changed_file_collector(changedfileset):
1918 def collect_changed_files(clnode):
1918 def collect_changed_files(clnode):
1919 c = cl.read(clnode)
1919 c = cl.read(clnode)
1920 for fname in c[3]:
1920 for fname in c[3]:
1921 changedfileset[fname] = 1
1921 changedfileset[fname] = 1
1922 return collect_changed_files
1922 return collect_changed_files
1923
1923
1924 def lookuprevlink_func(revlog):
1924 def lookuprevlink_func(revlog):
1925 def lookuprevlink(n):
1925 def lookuprevlink(n):
1926 return cl.node(revlog.linkrev(n))
1926 return cl.node(revlog.linkrev(n))
1927 return lookuprevlink
1927 return lookuprevlink
1928
1928
1929 def gengroup():
1929 def gengroup():
1930 # construct a list of all changed files
1930 # construct a list of all changed files
1931 changedfiles = {}
1931 changedfiles = {}
1932
1932
1933 for chnk in cl.group(nodes, identity,
1933 for chnk in cl.group(nodes, identity,
1934 changed_file_collector(changedfiles)):
1934 changed_file_collector(changedfiles)):
1935 yield chnk
1935 yield chnk
1936 changedfiles = changedfiles.keys()
1936 changedfiles = changedfiles.keys()
1937 changedfiles.sort()
1937 changedfiles.sort()
1938
1938
1939 mnfst = self.manifest
1939 mnfst = self.manifest
1940 nodeiter = gennodelst(mnfst)
1940 nodeiter = gennodelst(mnfst)
1941 for chnk in mnfst.group(nodeiter, lookuprevlink_func(mnfst)):
1941 for chnk in mnfst.group(nodeiter, lookuprevlink_func(mnfst)):
1942 yield chnk
1942 yield chnk
1943
1943
1944 for fname in changedfiles:
1944 for fname in changedfiles:
1945 filerevlog = self.file(fname)
1945 filerevlog = self.file(fname)
1946 if filerevlog.count() == 0:
1946 if filerevlog.count() == 0:
1947 raise util.Abort(_("empty or missing revlog for %s") % fname)
1947 raise util.Abort(_("empty or missing revlog for %s") % fname)
1948 nodeiter = gennodelst(filerevlog)
1948 nodeiter = gennodelst(filerevlog)
1949 nodeiter = list(nodeiter)
1949 nodeiter = list(nodeiter)
1950 if nodeiter:
1950 if nodeiter:
1951 yield changegroup.chunkheader(len(fname))
1951 yield changegroup.chunkheader(len(fname))
1952 yield fname
1952 yield fname
1953 lookup = lookuprevlink_func(filerevlog)
1953 lookup = lookuprevlink_func(filerevlog)
1954 for chnk in filerevlog.group(nodeiter, lookup):
1954 for chnk in filerevlog.group(nodeiter, lookup):
1955 yield chnk
1955 yield chnk
1956
1956
1957 yield changegroup.closechunk()
1957 yield changegroup.closechunk()
1958
1958
1959 if nodes:
1959 if nodes:
1960 self.hook('outgoing', node=hex(nodes[0]), source=source)
1960 self.hook('outgoing', node=hex(nodes[0]), source=source)
1961
1961
1962 return util.chunkbuffer(gengroup())
1962 return util.chunkbuffer(gengroup())
1963
1963
1964 def addchangegroup(self, source, srctype, url, emptyok=False):
1964 def addchangegroup(self, source, srctype, url, emptyok=False):
1965 """add changegroup to repo.
1965 """add changegroup to repo.
1966
1966
1967 return values:
1967 return values:
1968 - nothing changed or no source: 0
1968 - nothing changed or no source: 0
1969 - more heads than before: 1+added heads (2..n)
1969 - more heads than before: 1+added heads (2..n)
1970 - less heads than before: -1-removed heads (-2..-n)
1970 - less heads than before: -1-removed heads (-2..-n)
1971 - number of heads stays the same: 1
1971 - number of heads stays the same: 1
1972 """
1972 """
1973 def csmap(x):
1973 def csmap(x):
1974 self.ui.debug(_("add changeset %s\n") % short(x))
1974 self.ui.debug(_("add changeset %s\n") % short(x))
1975 return cl.count()
1975 return cl.count()
1976
1976
1977 def revmap(x):
1977 def revmap(x):
1978 return cl.rev(x)
1978 return cl.rev(x)
1979
1979
1980 if not source:
1980 if not source:
1981 return 0
1981 return 0
1982
1982
1983 self.hook('prechangegroup', throw=True, source=srctype, url=url)
1983 self.hook('prechangegroup', throw=True, source=srctype, url=url)
1984
1984
1985 changesets = files = revisions = 0
1985 changesets = files = revisions = 0
1986
1986
1987 # write changelog data to temp files so concurrent readers will not see
1987 # write changelog data to temp files so concurrent readers will not see
1988 # inconsistent view
1988 # inconsistent view
1989 cl = self.changelog
1989 cl = self.changelog
1990 cl.delayupdate()
1990 cl.delayupdate()
1991 oldheads = len(cl.heads())
1991 oldheads = len(cl.heads())
1992
1992
1993 tr = self.transaction()
1993 tr = self.transaction()
1994 try:
1994 try:
1995 trp = weakref.proxy(tr)
1995 trp = weakref.proxy(tr)
1996 # pull off the changeset group
1996 # pull off the changeset group
1997 self.ui.status(_("adding changesets\n"))
1997 self.ui.status(_("adding changesets\n"))
1998 cor = cl.count() - 1
1998 cor = cl.count() - 1
1999 chunkiter = changegroup.chunkiter(source)
1999 chunkiter = changegroup.chunkiter(source)
2000 if cl.addgroup(chunkiter, csmap, trp) is None and not emptyok:
2000 if cl.addgroup(chunkiter, csmap, trp) is None and not emptyok:
2001 raise util.Abort(_("received changelog group is empty"))
2001 raise util.Abort(_("received changelog group is empty"))
2002 cnr = cl.count() - 1
2002 cnr = cl.count() - 1
2003 changesets = cnr - cor
2003 changesets = cnr - cor
2004
2004
2005 # pull off the manifest group
2005 # pull off the manifest group
2006 self.ui.status(_("adding manifests\n"))
2006 self.ui.status(_("adding manifests\n"))
2007 chunkiter = changegroup.chunkiter(source)
2007 chunkiter = changegroup.chunkiter(source)
2008 # no need to check for empty manifest group here:
2008 # no need to check for empty manifest group here:
2009 # if the result of the merge of 1 and 2 is the same in 3 and 4,
2009 # if the result of the merge of 1 and 2 is the same in 3 and 4,
2010 # no new manifest will be created and the manifest group will
2010 # no new manifest will be created and the manifest group will
2011 # be empty during the pull
2011 # be empty during the pull
2012 self.manifest.addgroup(chunkiter, revmap, trp)
2012 self.manifest.addgroup(chunkiter, revmap, trp)
2013
2013
2014 # process the files
2014 # process the files
2015 self.ui.status(_("adding file changes\n"))
2015 self.ui.status(_("adding file changes\n"))
2016 while 1:
2016 while 1:
2017 f = changegroup.getchunk(source)
2017 f = changegroup.getchunk(source)
2018 if not f:
2018 if not f:
2019 break
2019 break
2020 self.ui.debug(_("adding %s revisions\n") % f)
2020 self.ui.debug(_("adding %s revisions\n") % f)
2021 fl = self.file(f)
2021 fl = self.file(f)
2022 o = fl.count()
2022 o = fl.count()
2023 chunkiter = changegroup.chunkiter(source)
2023 chunkiter = changegroup.chunkiter(source)
2024 if fl.addgroup(chunkiter, revmap, trp) is None:
2024 if fl.addgroup(chunkiter, revmap, trp) is None:
2025 raise util.Abort(_("received file revlog group is empty"))
2025 raise util.Abort(_("received file revlog group is empty"))
2026 revisions += fl.count() - o
2026 revisions += fl.count() - o
2027 files += 1
2027 files += 1
2028
2028
2029 # make changelog see real files again
2029 # make changelog see real files again
2030 cl.finalize(trp)
2030 cl.finalize(trp)
2031
2031
2032 newheads = len(self.changelog.heads())
2032 newheads = len(self.changelog.heads())
2033 heads = ""
2033 heads = ""
2034 if oldheads and newheads != oldheads:
2034 if oldheads and newheads != oldheads:
2035 heads = _(" (%+d heads)") % (newheads - oldheads)
2035 heads = _(" (%+d heads)") % (newheads - oldheads)
2036
2036
2037 self.ui.status(_("added %d changesets"
2037 self.ui.status(_("added %d changesets"
2038 " with %d changes to %d files%s\n")
2038 " with %d changes to %d files%s\n")
2039 % (changesets, revisions, files, heads))
2039 % (changesets, revisions, files, heads))
2040
2040
2041 if changesets > 0:
2041 if changesets > 0:
2042 self.hook('pretxnchangegroup', throw=True,
2042 self.hook('pretxnchangegroup', throw=True,
2043 node=hex(self.changelog.node(cor+1)), source=srctype,
2043 node=hex(self.changelog.node(cor+1)), source=srctype,
2044 url=url)
2044 url=url)
2045
2045
2046 tr.close()
2046 tr.close()
2047 finally:
2047 finally:
2048 del tr
2048 del tr
2049
2049
2050 if changesets > 0:
2050 if changesets > 0:
2051 # forcefully update the on-disk branch cache
2051 # forcefully update the on-disk branch cache
2052 self.ui.debug(_("updating the branch cache\n"))
2052 self.ui.debug(_("updating the branch cache\n"))
2053 self.branchtags()
2053 self.branchtags()
2054 self.hook("changegroup", node=hex(self.changelog.node(cor+1)),
2054 self.hook("changegroup", node=hex(self.changelog.node(cor+1)),
2055 source=srctype, url=url)
2055 source=srctype, url=url)
2056
2056
2057 for i in xrange(cor + 1, cnr + 1):
2057 for i in xrange(cor + 1, cnr + 1):
2058 self.hook("incoming", node=hex(self.changelog.node(i)),
2058 self.hook("incoming", node=hex(self.changelog.node(i)),
2059 source=srctype, url=url)
2059 source=srctype, url=url)
2060
2060
2061 # never return 0 here:
2061 # never return 0 here:
2062 if newheads < oldheads:
2062 if newheads < oldheads:
2063 return newheads - oldheads - 1
2063 return newheads - oldheads - 1
2064 else:
2064 else:
2065 return newheads - oldheads + 1
2065 return newheads - oldheads + 1
2066
2066
2067
2067
2068 def stream_in(self, remote):
2068 def stream_in(self, remote):
2069 fp = remote.stream_out()
2069 fp = remote.stream_out()
2070 l = fp.readline()
2070 l = fp.readline()
2071 try:
2071 try:
2072 resp = int(l)
2072 resp = int(l)
2073 except ValueError:
2073 except ValueError:
2074 raise util.UnexpectedOutput(
2074 raise util.UnexpectedOutput(
2075 _('Unexpected response from remote server:'), l)
2075 _('Unexpected response from remote server:'), l)
2076 if resp == 1:
2076 if resp == 1:
2077 raise util.Abort(_('operation forbidden by server'))
2077 raise util.Abort(_('operation forbidden by server'))
2078 elif resp == 2:
2078 elif resp == 2:
2079 raise util.Abort(_('locking the remote repository failed'))
2079 raise util.Abort(_('locking the remote repository failed'))
2080 elif resp != 0:
2080 elif resp != 0:
2081 raise util.Abort(_('the server sent an unknown error code'))
2081 raise util.Abort(_('the server sent an unknown error code'))
2082 self.ui.status(_('streaming all changes\n'))
2082 self.ui.status(_('streaming all changes\n'))
2083 l = fp.readline()
2083 l = fp.readline()
2084 try:
2084 try:
2085 total_files, total_bytes = map(int, l.split(' ', 1))
2085 total_files, total_bytes = map(int, l.split(' ', 1))
2086 except (ValueError, TypeError):
2086 except (ValueError, TypeError):
2087 raise util.UnexpectedOutput(
2087 raise util.UnexpectedOutput(
2088 _('Unexpected response from remote server:'), l)
2088 _('Unexpected response from remote server:'), l)
2089 self.ui.status(_('%d files to transfer, %s of data\n') %
2089 self.ui.status(_('%d files to transfer, %s of data\n') %
2090 (total_files, util.bytecount(total_bytes)))
2090 (total_files, util.bytecount(total_bytes)))
2091 start = time.time()
2091 start = time.time()
2092 for i in xrange(total_files):
2092 for i in xrange(total_files):
2093 # XXX doesn't support '\n' or '\r' in filenames
2093 # XXX doesn't support '\n' or '\r' in filenames
2094 l = fp.readline()
2094 l = fp.readline()
2095 try:
2095 try:
2096 name, size = l.split('\0', 1)
2096 name, size = l.split('\0', 1)
2097 size = int(size)
2097 size = int(size)
2098 except ValueError, TypeError:
2098 except ValueError, TypeError:
2099 raise util.UnexpectedOutput(
2099 raise util.UnexpectedOutput(
2100 _('Unexpected response from remote server:'), l)
2100 _('Unexpected response from remote server:'), l)
2101 self.ui.debug('adding %s (%s)\n' % (name, util.bytecount(size)))
2101 self.ui.debug('adding %s (%s)\n' % (name, util.bytecount(size)))
2102 ofp = self.sopener(name, 'w')
2102 ofp = self.sopener(name, 'w')
2103 for chunk in util.filechunkiter(fp, limit=size):
2103 for chunk in util.filechunkiter(fp, limit=size):
2104 ofp.write(chunk)
2104 ofp.write(chunk)
2105 ofp.close()
2105 ofp.close()
2106 elapsed = time.time() - start
2106 elapsed = time.time() - start
2107 if elapsed <= 0:
2107 if elapsed <= 0:
2108 elapsed = 0.001
2108 elapsed = 0.001
2109 self.ui.status(_('transferred %s in %.1f seconds (%s/sec)\n') %
2109 self.ui.status(_('transferred %s in %.1f seconds (%s/sec)\n') %
2110 (util.bytecount(total_bytes), elapsed,
2110 (util.bytecount(total_bytes), elapsed,
2111 util.bytecount(total_bytes / elapsed)))
2111 util.bytecount(total_bytes / elapsed)))
2112 self.invalidate()
2112 self.invalidate()
2113 return len(self.heads()) + 1
2113 return len(self.heads()) + 1
2114
2114
2115 def clone(self, remote, heads=[], stream=False):
2115 def clone(self, remote, heads=[], stream=False):
2116 '''clone remote repository.
2116 '''clone remote repository.
2117
2117
2118 keyword arguments:
2118 keyword arguments:
2119 heads: list of revs to clone (forces use of pull)
2119 heads: list of revs to clone (forces use of pull)
2120 stream: use streaming clone if possible'''
2120 stream: use streaming clone if possible'''
2121
2121
2122 # now, all clients that can request uncompressed clones can
2122 # now, all clients that can request uncompressed clones can
2123 # read repo formats supported by all servers that can serve
2123 # read repo formats supported by all servers that can serve
2124 # them.
2124 # them.
2125
2125
2126 # if revlog format changes, client will have to check version
2126 # if revlog format changes, client will have to check version
2127 # and format flags on "stream" capability, and use
2127 # and format flags on "stream" capability, and use
2128 # uncompressed only if compatible.
2128 # uncompressed only if compatible.
2129
2129
2130 if stream and not heads and remote.capable('stream'):
2130 if stream and not heads and remote.capable('stream'):
2131 return self.stream_in(remote)
2131 return self.stream_in(remote)
2132 return self.pull(remote, heads)
2132 return self.pull(remote, heads)
2133
2133
2134 # used to avoid circular references so destructors work
2134 # used to avoid circular references so destructors work
2135 def aftertrans(files):
2135 def aftertrans(files):
2136 renamefiles = [tuple(t) for t in files]
2136 renamefiles = [tuple(t) for t in files]
2137 def a():
2137 def a():
2138 for src, dest in renamefiles:
2138 for src, dest in renamefiles:
2139 util.rename(src, dest)
2139 util.rename(src, dest)
2140 return a
2140 return a
2141
2141
2142 def instance(ui, path, create):
2142 def instance(ui, path, create):
2143 return localrepository(ui, util.drop_scheme('file', path), create)
2143 return localrepository(ui, util.drop_scheme('file', path), create)
2144
2144
2145 def islocal(path):
2145 def islocal(path):
2146 return True
2146 return True
General Comments 0
You need to be logged in to leave comments. Login now