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