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