##// END OF EJS Templates
make hook code nicer....
Vadim Gelfer -
r1718:c1996b84 default
parent child Browse files
Show More
@@ -1,1840 +1,1843 b''
1 # localrepo.py - read/write repository class for mercurial
1 # localrepo.py - read/write repository class for mercurial
2 #
2 #
3 # Copyright 2005 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005 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 import struct, os, util
8 import struct, os, util
9 import filelog, manifest, changelog, dirstate, repo
9 import filelog, manifest, changelog, dirstate, repo
10 from node import *
10 from node import *
11 from i18n import gettext as _
11 from i18n import gettext as _
12 from demandload import *
12 from demandload import *
13 demandload(globals(), "re lock transaction tempfile stat mdiff errno")
13 demandload(globals(), "re lock transaction tempfile stat mdiff errno")
14
14
15 class localrepository(object):
15 class localrepository(object):
16 def __init__(self, ui, path=None, create=0):
16 def __init__(self, ui, path=None, create=0):
17 if not path:
17 if not path:
18 p = os.getcwd()
18 p = os.getcwd()
19 while not os.path.isdir(os.path.join(p, ".hg")):
19 while not os.path.isdir(os.path.join(p, ".hg")):
20 oldp = p
20 oldp = p
21 p = os.path.dirname(p)
21 p = os.path.dirname(p)
22 if p == oldp:
22 if p == oldp:
23 raise repo.RepoError(_("no repo found"))
23 raise repo.RepoError(_("no repo found"))
24 path = p
24 path = p
25 self.path = os.path.join(path, ".hg")
25 self.path = os.path.join(path, ".hg")
26
26
27 if not create and not os.path.isdir(self.path):
27 if not create and not os.path.isdir(self.path):
28 raise repo.RepoError(_("repository %s not found") % path)
28 raise repo.RepoError(_("repository %s not found") % path)
29
29
30 self.root = os.path.abspath(path)
30 self.root = os.path.abspath(path)
31 self.ui = ui
31 self.ui = ui
32 self.opener = util.opener(self.path)
32 self.opener = util.opener(self.path)
33 self.wopener = util.opener(self.root)
33 self.wopener = util.opener(self.root)
34 self.manifest = manifest.manifest(self.opener)
34 self.manifest = manifest.manifest(self.opener)
35 self.changelog = changelog.changelog(self.opener)
35 self.changelog = changelog.changelog(self.opener)
36 self.tagscache = None
36 self.tagscache = None
37 self.nodetagscache = None
37 self.nodetagscache = None
38 self.encodepats = None
38 self.encodepats = None
39 self.decodepats = None
39 self.decodepats = None
40
40
41 if create:
41 if create:
42 os.mkdir(self.path)
42 os.mkdir(self.path)
43 os.mkdir(self.join("data"))
43 os.mkdir(self.join("data"))
44
44
45 self.dirstate = dirstate.dirstate(self.opener, ui, self.root)
45 self.dirstate = dirstate.dirstate(self.opener, ui, self.root)
46 try:
46 try:
47 self.ui.readconfig(self.join("hgrc"))
47 self.ui.readconfig(self.join("hgrc"))
48 except IOError:
48 except IOError:
49 pass
49 pass
50
50
51 def hook(self, name, **args):
51 def hook(self, name, throw=False, **args):
52 def runhook(name, cmd):
52 def runhook(name, cmd):
53 self.ui.note(_("running hook %s: %s\n") % (name, cmd))
53 self.ui.note(_("running hook %s: %s\n") % (name, cmd))
54 old = {}
54 old = {}
55 for k, v in args.items():
55 for k, v in args.items():
56 k = k.upper()
56 k = k.upper()
57 old[k] = os.environ.get(k, None)
57 old[k] = os.environ.get(k, None)
58 os.environ[k] = v
58 os.environ[k] = v
59
59
60 # Hooks run in the repository root
60 try:
61 olddir = os.getcwd()
61 # Hooks run in the repository root
62 os.chdir(self.root)
62 olddir = os.getcwd()
63 r = os.system(cmd)
63 os.chdir(self.root)
64 os.chdir(olddir)
64 r = os.system(cmd)
65 finally:
66 for k, v in old.items():
67 if v != None:
68 os.environ[k] = v
69 else:
70 del os.environ[k]
65
71
66 for k, v in old.items():
72 os.chdir(olddir)
67 if v != None:
68 os.environ[k] = v
69 else:
70 del os.environ[k]
71
73
72 if r:
74 if r:
73 self.ui.warn(_("abort: %s hook failed with status %d!\n") %
75 desc, r = util.explain_exit(r)
74 (name, r))
76 if throw:
77 raise util.Abort(_('%s hook %s') % (name, desc))
78 self.ui.warn(_('error: %s hook %s\n') % (name, desc))
75 return False
79 return False
76 return True
80 return True
77
81
78 r = True
82 r = True
79 for hname, cmd in self.ui.configitems("hooks"):
83 for hname, cmd in self.ui.configitems("hooks"):
80 s = hname.split(".")
84 s = hname.split(".")
81 if s[0] == name and cmd:
85 if s[0] == name and cmd:
82 r = runhook(hname, cmd) and r
86 r = runhook(hname, cmd) and r
83 return r
87 return r
84
88
85 def tags(self):
89 def tags(self):
86 '''return a mapping of tag to node'''
90 '''return a mapping of tag to node'''
87 if not self.tagscache:
91 if not self.tagscache:
88 self.tagscache = {}
92 self.tagscache = {}
89 def addtag(self, k, n):
93 def addtag(self, k, n):
90 try:
94 try:
91 bin_n = bin(n)
95 bin_n = bin(n)
92 except TypeError:
96 except TypeError:
93 bin_n = ''
97 bin_n = ''
94 self.tagscache[k.strip()] = bin_n
98 self.tagscache[k.strip()] = bin_n
95
99
96 try:
100 try:
97 # read each head of the tags file, ending with the tip
101 # read each head of the tags file, ending with the tip
98 # and add each tag found to the map, with "newer" ones
102 # and add each tag found to the map, with "newer" ones
99 # taking precedence
103 # taking precedence
100 fl = self.file(".hgtags")
104 fl = self.file(".hgtags")
101 h = fl.heads()
105 h = fl.heads()
102 h.reverse()
106 h.reverse()
103 for r in h:
107 for r in h:
104 for l in fl.read(r).splitlines():
108 for l in fl.read(r).splitlines():
105 if l:
109 if l:
106 n, k = l.split(" ", 1)
110 n, k = l.split(" ", 1)
107 addtag(self, k, n)
111 addtag(self, k, n)
108 except KeyError:
112 except KeyError:
109 pass
113 pass
110
114
111 try:
115 try:
112 f = self.opener("localtags")
116 f = self.opener("localtags")
113 for l in f:
117 for l in f:
114 n, k = l.split(" ", 1)
118 n, k = l.split(" ", 1)
115 addtag(self, k, n)
119 addtag(self, k, n)
116 except IOError:
120 except IOError:
117 pass
121 pass
118
122
119 self.tagscache['tip'] = self.changelog.tip()
123 self.tagscache['tip'] = self.changelog.tip()
120
124
121 return self.tagscache
125 return self.tagscache
122
126
123 def tagslist(self):
127 def tagslist(self):
124 '''return a list of tags ordered by revision'''
128 '''return a list of tags ordered by revision'''
125 l = []
129 l = []
126 for t, n in self.tags().items():
130 for t, n in self.tags().items():
127 try:
131 try:
128 r = self.changelog.rev(n)
132 r = self.changelog.rev(n)
129 except:
133 except:
130 r = -2 # sort to the beginning of the list if unknown
134 r = -2 # sort to the beginning of the list if unknown
131 l.append((r, t, n))
135 l.append((r, t, n))
132 l.sort()
136 l.sort()
133 return [(t, n) for r, t, n in l]
137 return [(t, n) for r, t, n in l]
134
138
135 def nodetags(self, node):
139 def nodetags(self, node):
136 '''return the tags associated with a node'''
140 '''return the tags associated with a node'''
137 if not self.nodetagscache:
141 if not self.nodetagscache:
138 self.nodetagscache = {}
142 self.nodetagscache = {}
139 for t, n in self.tags().items():
143 for t, n in self.tags().items():
140 self.nodetagscache.setdefault(n, []).append(t)
144 self.nodetagscache.setdefault(n, []).append(t)
141 return self.nodetagscache.get(node, [])
145 return self.nodetagscache.get(node, [])
142
146
143 def lookup(self, key):
147 def lookup(self, key):
144 try:
148 try:
145 return self.tags()[key]
149 return self.tags()[key]
146 except KeyError:
150 except KeyError:
147 try:
151 try:
148 return self.changelog.lookup(key)
152 return self.changelog.lookup(key)
149 except:
153 except:
150 raise repo.RepoError(_("unknown revision '%s'") % key)
154 raise repo.RepoError(_("unknown revision '%s'") % key)
151
155
152 def dev(self):
156 def dev(self):
153 return os.stat(self.path).st_dev
157 return os.stat(self.path).st_dev
154
158
155 def local(self):
159 def local(self):
156 return True
160 return True
157
161
158 def join(self, f):
162 def join(self, f):
159 return os.path.join(self.path, f)
163 return os.path.join(self.path, f)
160
164
161 def wjoin(self, f):
165 def wjoin(self, f):
162 return os.path.join(self.root, f)
166 return os.path.join(self.root, f)
163
167
164 def file(self, f):
168 def file(self, f):
165 if f[0] == '/':
169 if f[0] == '/':
166 f = f[1:]
170 f = f[1:]
167 return filelog.filelog(self.opener, f)
171 return filelog.filelog(self.opener, f)
168
172
169 def getcwd(self):
173 def getcwd(self):
170 return self.dirstate.getcwd()
174 return self.dirstate.getcwd()
171
175
172 def wfile(self, f, mode='r'):
176 def wfile(self, f, mode='r'):
173 return self.wopener(f, mode)
177 return self.wopener(f, mode)
174
178
175 def wread(self, filename):
179 def wread(self, filename):
176 if self.encodepats == None:
180 if self.encodepats == None:
177 l = []
181 l = []
178 for pat, cmd in self.ui.configitems("encode"):
182 for pat, cmd in self.ui.configitems("encode"):
179 mf = util.matcher("", "/", [pat], [], [])[1]
183 mf = util.matcher("", "/", [pat], [], [])[1]
180 l.append((mf, cmd))
184 l.append((mf, cmd))
181 self.encodepats = l
185 self.encodepats = l
182
186
183 data = self.wopener(filename, 'r').read()
187 data = self.wopener(filename, 'r').read()
184
188
185 for mf, cmd in self.encodepats:
189 for mf, cmd in self.encodepats:
186 if mf(filename):
190 if mf(filename):
187 self.ui.debug(_("filtering %s through %s\n") % (filename, cmd))
191 self.ui.debug(_("filtering %s through %s\n") % (filename, cmd))
188 data = util.filter(data, cmd)
192 data = util.filter(data, cmd)
189 break
193 break
190
194
191 return data
195 return data
192
196
193 def wwrite(self, filename, data, fd=None):
197 def wwrite(self, filename, data, fd=None):
194 if self.decodepats == None:
198 if self.decodepats == None:
195 l = []
199 l = []
196 for pat, cmd in self.ui.configitems("decode"):
200 for pat, cmd in self.ui.configitems("decode"):
197 mf = util.matcher("", "/", [pat], [], [])[1]
201 mf = util.matcher("", "/", [pat], [], [])[1]
198 l.append((mf, cmd))
202 l.append((mf, cmd))
199 self.decodepats = l
203 self.decodepats = l
200
204
201 for mf, cmd in self.decodepats:
205 for mf, cmd in self.decodepats:
202 if mf(filename):
206 if mf(filename):
203 self.ui.debug(_("filtering %s through %s\n") % (filename, cmd))
207 self.ui.debug(_("filtering %s through %s\n") % (filename, cmd))
204 data = util.filter(data, cmd)
208 data = util.filter(data, cmd)
205 break
209 break
206
210
207 if fd:
211 if fd:
208 return fd.write(data)
212 return fd.write(data)
209 return self.wopener(filename, 'w').write(data)
213 return self.wopener(filename, 'w').write(data)
210
214
211 def transaction(self):
215 def transaction(self):
212 # save dirstate for undo
216 # save dirstate for undo
213 try:
217 try:
214 ds = self.opener("dirstate").read()
218 ds = self.opener("dirstate").read()
215 except IOError:
219 except IOError:
216 ds = ""
220 ds = ""
217 self.opener("journal.dirstate", "w").write(ds)
221 self.opener("journal.dirstate", "w").write(ds)
218
222
219 def after():
223 def after():
220 util.rename(self.join("journal"), self.join("undo"))
224 util.rename(self.join("journal"), self.join("undo"))
221 util.rename(self.join("journal.dirstate"),
225 util.rename(self.join("journal.dirstate"),
222 self.join("undo.dirstate"))
226 self.join("undo.dirstate"))
223
227
224 return transaction.transaction(self.ui.warn, self.opener,
228 return transaction.transaction(self.ui.warn, self.opener,
225 self.join("journal"), after)
229 self.join("journal"), after)
226
230
227 def recover(self):
231 def recover(self):
228 lock = self.lock()
232 lock = self.lock()
229 if os.path.exists(self.join("journal")):
233 if os.path.exists(self.join("journal")):
230 self.ui.status(_("rolling back interrupted transaction\n"))
234 self.ui.status(_("rolling back interrupted transaction\n"))
231 transaction.rollback(self.opener, self.join("journal"))
235 transaction.rollback(self.opener, self.join("journal"))
232 self.manifest = manifest.manifest(self.opener)
236 self.manifest = manifest.manifest(self.opener)
233 self.changelog = changelog.changelog(self.opener)
237 self.changelog = changelog.changelog(self.opener)
234 return True
238 return True
235 else:
239 else:
236 self.ui.warn(_("no interrupted transaction available\n"))
240 self.ui.warn(_("no interrupted transaction available\n"))
237 return False
241 return False
238
242
239 def undo(self, wlock=None):
243 def undo(self, wlock=None):
240 if not wlock:
244 if not wlock:
241 wlock = self.wlock()
245 wlock = self.wlock()
242 lock = self.lock()
246 lock = self.lock()
243 if os.path.exists(self.join("undo")):
247 if os.path.exists(self.join("undo")):
244 self.ui.status(_("rolling back last transaction\n"))
248 self.ui.status(_("rolling back last transaction\n"))
245 transaction.rollback(self.opener, self.join("undo"))
249 transaction.rollback(self.opener, self.join("undo"))
246 util.rename(self.join("undo.dirstate"), self.join("dirstate"))
250 util.rename(self.join("undo.dirstate"), self.join("dirstate"))
247 self.dirstate.read()
251 self.dirstate.read()
248 else:
252 else:
249 self.ui.warn(_("no undo information available\n"))
253 self.ui.warn(_("no undo information available\n"))
250
254
251 def lock(self, wait=1):
255 def lock(self, wait=1):
252 try:
256 try:
253 return lock.lock(self.join("lock"), 0)
257 return lock.lock(self.join("lock"), 0)
254 except lock.LockHeld, inst:
258 except lock.LockHeld, inst:
255 if wait:
259 if wait:
256 self.ui.warn(_("waiting for lock held by %s\n") % inst.args[0])
260 self.ui.warn(_("waiting for lock held by %s\n") % inst.args[0])
257 return lock.lock(self.join("lock"), wait)
261 return lock.lock(self.join("lock"), wait)
258 raise inst
262 raise inst
259
263
260 def wlock(self, wait=1):
264 def wlock(self, wait=1):
261 try:
265 try:
262 wlock = lock.lock(self.join("wlock"), 0, self.dirstate.write)
266 wlock = lock.lock(self.join("wlock"), 0, self.dirstate.write)
263 except lock.LockHeld, inst:
267 except lock.LockHeld, inst:
264 if not wait:
268 if not wait:
265 raise inst
269 raise inst
266 self.ui.warn(_("waiting for lock held by %s\n") % inst.args[0])
270 self.ui.warn(_("waiting for lock held by %s\n") % inst.args[0])
267 wlock = lock.lock(self.join("wlock"), wait, self.dirstate.write)
271 wlock = lock.lock(self.join("wlock"), wait, self.dirstate.write)
268 self.dirstate.read()
272 self.dirstate.read()
269 return wlock
273 return wlock
270
274
271 def rawcommit(self, files, text, user, date, p1=None, p2=None, wlock=None):
275 def rawcommit(self, files, text, user, date, p1=None, p2=None, wlock=None):
272 orig_parent = self.dirstate.parents()[0] or nullid
276 orig_parent = self.dirstate.parents()[0] or nullid
273 p1 = p1 or self.dirstate.parents()[0] or nullid
277 p1 = p1 or self.dirstate.parents()[0] or nullid
274 p2 = p2 or self.dirstate.parents()[1] or nullid
278 p2 = p2 or self.dirstate.parents()[1] or nullid
275 c1 = self.changelog.read(p1)
279 c1 = self.changelog.read(p1)
276 c2 = self.changelog.read(p2)
280 c2 = self.changelog.read(p2)
277 m1 = self.manifest.read(c1[0])
281 m1 = self.manifest.read(c1[0])
278 mf1 = self.manifest.readflags(c1[0])
282 mf1 = self.manifest.readflags(c1[0])
279 m2 = self.manifest.read(c2[0])
283 m2 = self.manifest.read(c2[0])
280 changed = []
284 changed = []
281
285
282 if orig_parent == p1:
286 if orig_parent == p1:
283 update_dirstate = 1
287 update_dirstate = 1
284 else:
288 else:
285 update_dirstate = 0
289 update_dirstate = 0
286
290
287 if not wlock:
291 if not wlock:
288 wlock = self.wlock()
292 wlock = self.wlock()
289 lock = self.lock()
293 lock = self.lock()
290 tr = self.transaction()
294 tr = self.transaction()
291 mm = m1.copy()
295 mm = m1.copy()
292 mfm = mf1.copy()
296 mfm = mf1.copy()
293 linkrev = self.changelog.count()
297 linkrev = self.changelog.count()
294 for f in files:
298 for f in files:
295 try:
299 try:
296 t = self.wread(f)
300 t = self.wread(f)
297 tm = util.is_exec(self.wjoin(f), mfm.get(f, False))
301 tm = util.is_exec(self.wjoin(f), mfm.get(f, False))
298 r = self.file(f)
302 r = self.file(f)
299 mfm[f] = tm
303 mfm[f] = tm
300
304
301 fp1 = m1.get(f, nullid)
305 fp1 = m1.get(f, nullid)
302 fp2 = m2.get(f, nullid)
306 fp2 = m2.get(f, nullid)
303
307
304 # is the same revision on two branches of a merge?
308 # is the same revision on two branches of a merge?
305 if fp2 == fp1:
309 if fp2 == fp1:
306 fp2 = nullid
310 fp2 = nullid
307
311
308 if fp2 != nullid:
312 if fp2 != nullid:
309 # is one parent an ancestor of the other?
313 # is one parent an ancestor of the other?
310 fpa = r.ancestor(fp1, fp2)
314 fpa = r.ancestor(fp1, fp2)
311 if fpa == fp1:
315 if fpa == fp1:
312 fp1, fp2 = fp2, nullid
316 fp1, fp2 = fp2, nullid
313 elif fpa == fp2:
317 elif fpa == fp2:
314 fp2 = nullid
318 fp2 = nullid
315
319
316 # is the file unmodified from the parent?
320 # is the file unmodified from the parent?
317 if t == r.read(fp1):
321 if t == r.read(fp1):
318 # record the proper existing parent in manifest
322 # record the proper existing parent in manifest
319 # no need to add a revision
323 # no need to add a revision
320 mm[f] = fp1
324 mm[f] = fp1
321 continue
325 continue
322
326
323 mm[f] = r.add(t, {}, tr, linkrev, fp1, fp2)
327 mm[f] = r.add(t, {}, tr, linkrev, fp1, fp2)
324 changed.append(f)
328 changed.append(f)
325 if update_dirstate:
329 if update_dirstate:
326 self.dirstate.update([f], "n")
330 self.dirstate.update([f], "n")
327 except IOError:
331 except IOError:
328 try:
332 try:
329 del mm[f]
333 del mm[f]
330 del mfm[f]
334 del mfm[f]
331 if update_dirstate:
335 if update_dirstate:
332 self.dirstate.forget([f])
336 self.dirstate.forget([f])
333 except:
337 except:
334 # deleted from p2?
338 # deleted from p2?
335 pass
339 pass
336
340
337 mnode = self.manifest.add(mm, mfm, tr, linkrev, c1[0], c2[0])
341 mnode = self.manifest.add(mm, mfm, tr, linkrev, c1[0], c2[0])
338 user = user or self.ui.username()
342 user = user or self.ui.username()
339 n = self.changelog.add(mnode, changed, text, tr, p1, p2, user, date)
343 n = self.changelog.add(mnode, changed, text, tr, p1, p2, user, date)
340 tr.close()
344 tr.close()
341 if update_dirstate:
345 if update_dirstate:
342 self.dirstate.setparents(n, nullid)
346 self.dirstate.setparents(n, nullid)
343
347
344 def commit(self, files=None, text="", user=None, date=None,
348 def commit(self, files=None, text="", user=None, date=None,
345 match=util.always, force=False, wlock=None):
349 match=util.always, force=False, wlock=None):
346 commit = []
350 commit = []
347 remove = []
351 remove = []
348 changed = []
352 changed = []
349
353
350 if files:
354 if files:
351 for f in files:
355 for f in files:
352 s = self.dirstate.state(f)
356 s = self.dirstate.state(f)
353 if s in 'nmai':
357 if s in 'nmai':
354 commit.append(f)
358 commit.append(f)
355 elif s == 'r':
359 elif s == 'r':
356 remove.append(f)
360 remove.append(f)
357 else:
361 else:
358 self.ui.warn(_("%s not tracked!\n") % f)
362 self.ui.warn(_("%s not tracked!\n") % f)
359 else:
363 else:
360 modified, added, removed, deleted, unknown = self.changes(match=match)
364 modified, added, removed, deleted, unknown = self.changes(match=match)
361 commit = modified + added
365 commit = modified + added
362 remove = removed
366 remove = removed
363
367
364 p1, p2 = self.dirstate.parents()
368 p1, p2 = self.dirstate.parents()
365 c1 = self.changelog.read(p1)
369 c1 = self.changelog.read(p1)
366 c2 = self.changelog.read(p2)
370 c2 = self.changelog.read(p2)
367 m1 = self.manifest.read(c1[0])
371 m1 = self.manifest.read(c1[0])
368 mf1 = self.manifest.readflags(c1[0])
372 mf1 = self.manifest.readflags(c1[0])
369 m2 = self.manifest.read(c2[0])
373 m2 = self.manifest.read(c2[0])
370
374
371 if not commit and not remove and not force and p2 == nullid:
375 if not commit and not remove and not force and p2 == nullid:
372 self.ui.status(_("nothing changed\n"))
376 self.ui.status(_("nothing changed\n"))
373 return None
377 return None
374
378
375 if not self.hook("precommit"):
379 self.hook("precommit", throw=True)
376 return None
377
380
378 if not wlock:
381 if not wlock:
379 wlock = self.wlock()
382 wlock = self.wlock()
380 lock = self.lock()
383 lock = self.lock()
381 tr = self.transaction()
384 tr = self.transaction()
382
385
383 # check in files
386 # check in files
384 new = {}
387 new = {}
385 linkrev = self.changelog.count()
388 linkrev = self.changelog.count()
386 commit.sort()
389 commit.sort()
387 for f in commit:
390 for f in commit:
388 self.ui.note(f + "\n")
391 self.ui.note(f + "\n")
389 try:
392 try:
390 mf1[f] = util.is_exec(self.wjoin(f), mf1.get(f, False))
393 mf1[f] = util.is_exec(self.wjoin(f), mf1.get(f, False))
391 t = self.wread(f)
394 t = self.wread(f)
392 except IOError:
395 except IOError:
393 self.ui.warn(_("trouble committing %s!\n") % f)
396 self.ui.warn(_("trouble committing %s!\n") % f)
394 raise
397 raise
395
398
396 r = self.file(f)
399 r = self.file(f)
397
400
398 meta = {}
401 meta = {}
399 cp = self.dirstate.copied(f)
402 cp = self.dirstate.copied(f)
400 if cp:
403 if cp:
401 meta["copy"] = cp
404 meta["copy"] = cp
402 meta["copyrev"] = hex(m1.get(cp, m2.get(cp, nullid)))
405 meta["copyrev"] = hex(m1.get(cp, m2.get(cp, nullid)))
403 self.ui.debug(_(" %s: copy %s:%s\n") % (f, cp, meta["copyrev"]))
406 self.ui.debug(_(" %s: copy %s:%s\n") % (f, cp, meta["copyrev"]))
404 fp1, fp2 = nullid, nullid
407 fp1, fp2 = nullid, nullid
405 else:
408 else:
406 fp1 = m1.get(f, nullid)
409 fp1 = m1.get(f, nullid)
407 fp2 = m2.get(f, nullid)
410 fp2 = m2.get(f, nullid)
408
411
409 if fp2 != nullid:
412 if fp2 != nullid:
410 # is one parent an ancestor of the other?
413 # is one parent an ancestor of the other?
411 fpa = r.ancestor(fp1, fp2)
414 fpa = r.ancestor(fp1, fp2)
412 if fpa == fp1:
415 if fpa == fp1:
413 fp1, fp2 = fp2, nullid
416 fp1, fp2 = fp2, nullid
414 elif fpa == fp2:
417 elif fpa == fp2:
415 fp2 = nullid
418 fp2 = nullid
416
419
417 # is the file unmodified from the parent?
420 # is the file unmodified from the parent?
418 if not meta and t == r.read(fp1) and fp2 == nullid:
421 if not meta and t == r.read(fp1) and fp2 == nullid:
419 # record the proper existing parent in manifest
422 # record the proper existing parent in manifest
420 # no need to add a revision
423 # no need to add a revision
421 new[f] = fp1
424 new[f] = fp1
422 continue
425 continue
423
426
424 new[f] = r.add(t, meta, tr, linkrev, fp1, fp2)
427 new[f] = r.add(t, meta, tr, linkrev, fp1, fp2)
425 # remember what we've added so that we can later calculate
428 # remember what we've added so that we can later calculate
426 # the files to pull from a set of changesets
429 # the files to pull from a set of changesets
427 changed.append(f)
430 changed.append(f)
428
431
429 # update manifest
432 # update manifest
430 m1 = m1.copy()
433 m1 = m1.copy()
431 m1.update(new)
434 m1.update(new)
432 for f in remove:
435 for f in remove:
433 if f in m1:
436 if f in m1:
434 del m1[f]
437 del m1[f]
435 mn = self.manifest.add(m1, mf1, tr, linkrev, c1[0], c2[0],
438 mn = self.manifest.add(m1, mf1, tr, linkrev, c1[0], c2[0],
436 (new, remove))
439 (new, remove))
437
440
438 # add changeset
441 # add changeset
439 new = new.keys()
442 new = new.keys()
440 new.sort()
443 new.sort()
441
444
442 if not text:
445 if not text:
443 edittext = [""]
446 edittext = [""]
444 if p2 != nullid:
447 if p2 != nullid:
445 edittext.append("HG: branch merge")
448 edittext.append("HG: branch merge")
446 edittext.extend(["HG: changed %s" % f for f in changed])
449 edittext.extend(["HG: changed %s" % f for f in changed])
447 edittext.extend(["HG: removed %s" % f for f in remove])
450 edittext.extend(["HG: removed %s" % f for f in remove])
448 if not changed and not remove:
451 if not changed and not remove:
449 edittext.append("HG: no files changed")
452 edittext.append("HG: no files changed")
450 edittext.append("")
453 edittext.append("")
451 # run editor in the repository root
454 # run editor in the repository root
452 olddir = os.getcwd()
455 olddir = os.getcwd()
453 os.chdir(self.root)
456 os.chdir(self.root)
454 edittext = self.ui.edit("\n".join(edittext))
457 edittext = self.ui.edit("\n".join(edittext))
455 os.chdir(olddir)
458 os.chdir(olddir)
456 if not edittext.rstrip():
459 if not edittext.rstrip():
457 return None
460 return None
458 text = edittext
461 text = edittext
459
462
460 user = user or self.ui.username()
463 user = user or self.ui.username()
461 n = self.changelog.add(mn, changed + remove, text, tr, p1, p2, user, date)
464 n = self.changelog.add(mn, changed + remove, text, tr, p1, p2, user, date)
462 tr.close()
465 tr.close()
463
466
464 self.dirstate.setparents(n)
467 self.dirstate.setparents(n)
465 self.dirstate.update(new, "n")
468 self.dirstate.update(new, "n")
466 self.dirstate.forget(remove)
469 self.dirstate.forget(remove)
467
470
468 self.hook("commit", node=hex(n))
471 self.hook("commit", node=hex(n))
469 return n
472 return n
470
473
471 def walk(self, node=None, files=[], match=util.always):
474 def walk(self, node=None, files=[], match=util.always):
472 if node:
475 if node:
473 fdict = dict.fromkeys(files)
476 fdict = dict.fromkeys(files)
474 for fn in self.manifest.read(self.changelog.read(node)[0]):
477 for fn in self.manifest.read(self.changelog.read(node)[0]):
475 fdict.pop(fn, None)
478 fdict.pop(fn, None)
476 if match(fn):
479 if match(fn):
477 yield 'm', fn
480 yield 'm', fn
478 for fn in fdict:
481 for fn in fdict:
479 self.ui.warn(_('%s: No such file in rev %s\n') % (
482 self.ui.warn(_('%s: No such file in rev %s\n') % (
480 util.pathto(self.getcwd(), fn), short(node)))
483 util.pathto(self.getcwd(), fn), short(node)))
481 else:
484 else:
482 for src, fn in self.dirstate.walk(files, match):
485 for src, fn in self.dirstate.walk(files, match):
483 yield src, fn
486 yield src, fn
484
487
485 def changes(self, node1=None, node2=None, files=[], match=util.always,
488 def changes(self, node1=None, node2=None, files=[], match=util.always,
486 wlock=None):
489 wlock=None):
487 """return changes between two nodes or node and working directory
490 """return changes between two nodes or node and working directory
488
491
489 If node1 is None, use the first dirstate parent instead.
492 If node1 is None, use the first dirstate parent instead.
490 If node2 is None, compare node1 with working directory.
493 If node2 is None, compare node1 with working directory.
491 """
494 """
492
495
493 def fcmp(fn, mf):
496 def fcmp(fn, mf):
494 t1 = self.wread(fn)
497 t1 = self.wread(fn)
495 t2 = self.file(fn).read(mf.get(fn, nullid))
498 t2 = self.file(fn).read(mf.get(fn, nullid))
496 return cmp(t1, t2)
499 return cmp(t1, t2)
497
500
498 def mfmatches(node):
501 def mfmatches(node):
499 change = self.changelog.read(node)
502 change = self.changelog.read(node)
500 mf = dict(self.manifest.read(change[0]))
503 mf = dict(self.manifest.read(change[0]))
501 for fn in mf.keys():
504 for fn in mf.keys():
502 if not match(fn):
505 if not match(fn):
503 del mf[fn]
506 del mf[fn]
504 return mf
507 return mf
505
508
506 # are we comparing the working directory?
509 # are we comparing the working directory?
507 if not node2:
510 if not node2:
508 if not wlock:
511 if not wlock:
509 try:
512 try:
510 wlock = self.wlock(wait=0)
513 wlock = self.wlock(wait=0)
511 except lock.LockHeld:
514 except lock.LockHeld:
512 wlock = None
515 wlock = None
513 lookup, modified, added, removed, deleted, unknown = (
516 lookup, modified, added, removed, deleted, unknown = (
514 self.dirstate.changes(files, match))
517 self.dirstate.changes(files, match))
515
518
516 # are we comparing working dir against its parent?
519 # are we comparing working dir against its parent?
517 if not node1:
520 if not node1:
518 if lookup:
521 if lookup:
519 # do a full compare of any files that might have changed
522 # do a full compare of any files that might have changed
520 mf2 = mfmatches(self.dirstate.parents()[0])
523 mf2 = mfmatches(self.dirstate.parents()[0])
521 for f in lookup:
524 for f in lookup:
522 if fcmp(f, mf2):
525 if fcmp(f, mf2):
523 modified.append(f)
526 modified.append(f)
524 elif wlock is not None:
527 elif wlock is not None:
525 self.dirstate.update([f], "n")
528 self.dirstate.update([f], "n")
526 else:
529 else:
527 # we are comparing working dir against non-parent
530 # we are comparing working dir against non-parent
528 # generate a pseudo-manifest for the working dir
531 # generate a pseudo-manifest for the working dir
529 mf2 = mfmatches(self.dirstate.parents()[0])
532 mf2 = mfmatches(self.dirstate.parents()[0])
530 for f in lookup + modified + added:
533 for f in lookup + modified + added:
531 mf2[f] = ""
534 mf2[f] = ""
532 for f in removed:
535 for f in removed:
533 if f in mf2:
536 if f in mf2:
534 del mf2[f]
537 del mf2[f]
535 else:
538 else:
536 # we are comparing two revisions
539 # we are comparing two revisions
537 deleted, unknown = [], []
540 deleted, unknown = [], []
538 mf2 = mfmatches(node2)
541 mf2 = mfmatches(node2)
539
542
540 if node1:
543 if node1:
541 # flush lists from dirstate before comparing manifests
544 # flush lists from dirstate before comparing manifests
542 modified, added = [], []
545 modified, added = [], []
543
546
544 mf1 = mfmatches(node1)
547 mf1 = mfmatches(node1)
545
548
546 for fn in mf2:
549 for fn in mf2:
547 if mf1.has_key(fn):
550 if mf1.has_key(fn):
548 if mf1[fn] != mf2[fn] and (mf2[fn] != "" or fcmp(fn, mf1)):
551 if mf1[fn] != mf2[fn] and (mf2[fn] != "" or fcmp(fn, mf1)):
549 modified.append(fn)
552 modified.append(fn)
550 del mf1[fn]
553 del mf1[fn]
551 else:
554 else:
552 added.append(fn)
555 added.append(fn)
553
556
554 removed = mf1.keys()
557 removed = mf1.keys()
555
558
556 # sort and return results:
559 # sort and return results:
557 for l in modified, added, removed, deleted, unknown:
560 for l in modified, added, removed, deleted, unknown:
558 l.sort()
561 l.sort()
559 return (modified, added, removed, deleted, unknown)
562 return (modified, added, removed, deleted, unknown)
560
563
561 def add(self, list, wlock=None):
564 def add(self, list, wlock=None):
562 if not wlock:
565 if not wlock:
563 wlock = self.wlock()
566 wlock = self.wlock()
564 for f in list:
567 for f in list:
565 p = self.wjoin(f)
568 p = self.wjoin(f)
566 if not os.path.exists(p):
569 if not os.path.exists(p):
567 self.ui.warn(_("%s does not exist!\n") % f)
570 self.ui.warn(_("%s does not exist!\n") % f)
568 elif not os.path.isfile(p):
571 elif not os.path.isfile(p):
569 self.ui.warn(_("%s not added: only files supported currently\n")
572 self.ui.warn(_("%s not added: only files supported currently\n")
570 % f)
573 % f)
571 elif self.dirstate.state(f) in 'an':
574 elif self.dirstate.state(f) in 'an':
572 self.ui.warn(_("%s already tracked!\n") % f)
575 self.ui.warn(_("%s already tracked!\n") % f)
573 else:
576 else:
574 self.dirstate.update([f], "a")
577 self.dirstate.update([f], "a")
575
578
576 def forget(self, list, wlock=None):
579 def forget(self, list, wlock=None):
577 if not wlock:
580 if not wlock:
578 wlock = self.wlock()
581 wlock = self.wlock()
579 for f in list:
582 for f in list:
580 if self.dirstate.state(f) not in 'ai':
583 if self.dirstate.state(f) not in 'ai':
581 self.ui.warn(_("%s not added!\n") % f)
584 self.ui.warn(_("%s not added!\n") % f)
582 else:
585 else:
583 self.dirstate.forget([f])
586 self.dirstate.forget([f])
584
587
585 def remove(self, list, unlink=False, wlock=None):
588 def remove(self, list, unlink=False, wlock=None):
586 if unlink:
589 if unlink:
587 for f in list:
590 for f in list:
588 try:
591 try:
589 util.unlink(self.wjoin(f))
592 util.unlink(self.wjoin(f))
590 except OSError, inst:
593 except OSError, inst:
591 if inst.errno != errno.ENOENT:
594 if inst.errno != errno.ENOENT:
592 raise
595 raise
593 if not wlock:
596 if not wlock:
594 wlock = self.wlock()
597 wlock = self.wlock()
595 for f in list:
598 for f in list:
596 p = self.wjoin(f)
599 p = self.wjoin(f)
597 if os.path.exists(p):
600 if os.path.exists(p):
598 self.ui.warn(_("%s still exists!\n") % f)
601 self.ui.warn(_("%s still exists!\n") % f)
599 elif self.dirstate.state(f) == 'a':
602 elif self.dirstate.state(f) == 'a':
600 self.ui.warn(_("%s never committed!\n") % f)
603 self.ui.warn(_("%s never committed!\n") % f)
601 self.dirstate.forget([f])
604 self.dirstate.forget([f])
602 elif f not in self.dirstate:
605 elif f not in self.dirstate:
603 self.ui.warn(_("%s not tracked!\n") % f)
606 self.ui.warn(_("%s not tracked!\n") % f)
604 else:
607 else:
605 self.dirstate.update([f], "r")
608 self.dirstate.update([f], "r")
606
609
607 def undelete(self, list, wlock=None):
610 def undelete(self, list, wlock=None):
608 p = self.dirstate.parents()[0]
611 p = self.dirstate.parents()[0]
609 mn = self.changelog.read(p)[0]
612 mn = self.changelog.read(p)[0]
610 mf = self.manifest.readflags(mn)
613 mf = self.manifest.readflags(mn)
611 m = self.manifest.read(mn)
614 m = self.manifest.read(mn)
612 if not wlock:
615 if not wlock:
613 wlock = self.wlock()
616 wlock = self.wlock()
614 for f in list:
617 for f in list:
615 if self.dirstate.state(f) not in "r":
618 if self.dirstate.state(f) not in "r":
616 self.ui.warn("%s not removed!\n" % f)
619 self.ui.warn("%s not removed!\n" % f)
617 else:
620 else:
618 t = self.file(f).read(m[f])
621 t = self.file(f).read(m[f])
619 self.wwrite(f, t)
622 self.wwrite(f, t)
620 util.set_exec(self.wjoin(f), mf[f])
623 util.set_exec(self.wjoin(f), mf[f])
621 self.dirstate.update([f], "n")
624 self.dirstate.update([f], "n")
622
625
623 def copy(self, source, dest, wlock=None):
626 def copy(self, source, dest, wlock=None):
624 p = self.wjoin(dest)
627 p = self.wjoin(dest)
625 if not os.path.exists(p):
628 if not os.path.exists(p):
626 self.ui.warn(_("%s does not exist!\n") % dest)
629 self.ui.warn(_("%s does not exist!\n") % dest)
627 elif not os.path.isfile(p):
630 elif not os.path.isfile(p):
628 self.ui.warn(_("copy failed: %s is not a file\n") % dest)
631 self.ui.warn(_("copy failed: %s is not a file\n") % dest)
629 else:
632 else:
630 if not wlock:
633 if not wlock:
631 wlock = self.wlock()
634 wlock = self.wlock()
632 if self.dirstate.state(dest) == '?':
635 if self.dirstate.state(dest) == '?':
633 self.dirstate.update([dest], "a")
636 self.dirstate.update([dest], "a")
634 self.dirstate.copy(source, dest)
637 self.dirstate.copy(source, dest)
635
638
636 def heads(self, start=None):
639 def heads(self, start=None):
637 heads = self.changelog.heads(start)
640 heads = self.changelog.heads(start)
638 # sort the output in rev descending order
641 # sort the output in rev descending order
639 heads = [(-self.changelog.rev(h), h) for h in heads]
642 heads = [(-self.changelog.rev(h), h) for h in heads]
640 heads.sort()
643 heads.sort()
641 return [n for (r, n) in heads]
644 return [n for (r, n) in heads]
642
645
643 # branchlookup returns a dict giving a list of branches for
646 # branchlookup returns a dict giving a list of branches for
644 # each head. A branch is defined as the tag of a node or
647 # each head. A branch is defined as the tag of a node or
645 # the branch of the node's parents. If a node has multiple
648 # the branch of the node's parents. If a node has multiple
646 # branch tags, tags are eliminated if they are visible from other
649 # branch tags, tags are eliminated if they are visible from other
647 # branch tags.
650 # branch tags.
648 #
651 #
649 # So, for this graph: a->b->c->d->e
652 # So, for this graph: a->b->c->d->e
650 # \ /
653 # \ /
651 # aa -----/
654 # aa -----/
652 # a has tag 2.6.12
655 # a has tag 2.6.12
653 # d has tag 2.6.13
656 # d has tag 2.6.13
654 # e would have branch tags for 2.6.12 and 2.6.13. Because the node
657 # e would have branch tags for 2.6.12 and 2.6.13. Because the node
655 # for 2.6.12 can be reached from the node 2.6.13, that is eliminated
658 # for 2.6.12 can be reached from the node 2.6.13, that is eliminated
656 # from the list.
659 # from the list.
657 #
660 #
658 # It is possible that more than one head will have the same branch tag.
661 # It is possible that more than one head will have the same branch tag.
659 # callers need to check the result for multiple heads under the same
662 # callers need to check the result for multiple heads under the same
660 # branch tag if that is a problem for them (ie checkout of a specific
663 # branch tag if that is a problem for them (ie checkout of a specific
661 # branch).
664 # branch).
662 #
665 #
663 # passing in a specific branch will limit the depth of the search
666 # passing in a specific branch will limit the depth of the search
664 # through the parents. It won't limit the branches returned in the
667 # through the parents. It won't limit the branches returned in the
665 # result though.
668 # result though.
666 def branchlookup(self, heads=None, branch=None):
669 def branchlookup(self, heads=None, branch=None):
667 if not heads:
670 if not heads:
668 heads = self.heads()
671 heads = self.heads()
669 headt = [ h for h in heads ]
672 headt = [ h for h in heads ]
670 chlog = self.changelog
673 chlog = self.changelog
671 branches = {}
674 branches = {}
672 merges = []
675 merges = []
673 seenmerge = {}
676 seenmerge = {}
674
677
675 # traverse the tree once for each head, recording in the branches
678 # traverse the tree once for each head, recording in the branches
676 # dict which tags are visible from this head. The branches
679 # dict which tags are visible from this head. The branches
677 # dict also records which tags are visible from each tag
680 # dict also records which tags are visible from each tag
678 # while we traverse.
681 # while we traverse.
679 while headt or merges:
682 while headt or merges:
680 if merges:
683 if merges:
681 n, found = merges.pop()
684 n, found = merges.pop()
682 visit = [n]
685 visit = [n]
683 else:
686 else:
684 h = headt.pop()
687 h = headt.pop()
685 visit = [h]
688 visit = [h]
686 found = [h]
689 found = [h]
687 seen = {}
690 seen = {}
688 while visit:
691 while visit:
689 n = visit.pop()
692 n = visit.pop()
690 if n in seen:
693 if n in seen:
691 continue
694 continue
692 pp = chlog.parents(n)
695 pp = chlog.parents(n)
693 tags = self.nodetags(n)
696 tags = self.nodetags(n)
694 if tags:
697 if tags:
695 for x in tags:
698 for x in tags:
696 if x == 'tip':
699 if x == 'tip':
697 continue
700 continue
698 for f in found:
701 for f in found:
699 branches.setdefault(f, {})[n] = 1
702 branches.setdefault(f, {})[n] = 1
700 branches.setdefault(n, {})[n] = 1
703 branches.setdefault(n, {})[n] = 1
701 break
704 break
702 if n not in found:
705 if n not in found:
703 found.append(n)
706 found.append(n)
704 if branch in tags:
707 if branch in tags:
705 continue
708 continue
706 seen[n] = 1
709 seen[n] = 1
707 if pp[1] != nullid and n not in seenmerge:
710 if pp[1] != nullid and n not in seenmerge:
708 merges.append((pp[1], [x for x in found]))
711 merges.append((pp[1], [x for x in found]))
709 seenmerge[n] = 1
712 seenmerge[n] = 1
710 if pp[0] != nullid:
713 if pp[0] != nullid:
711 visit.append(pp[0])
714 visit.append(pp[0])
712 # traverse the branches dict, eliminating branch tags from each
715 # traverse the branches dict, eliminating branch tags from each
713 # head that are visible from another branch tag for that head.
716 # head that are visible from another branch tag for that head.
714 out = {}
717 out = {}
715 viscache = {}
718 viscache = {}
716 for h in heads:
719 for h in heads:
717 def visible(node):
720 def visible(node):
718 if node in viscache:
721 if node in viscache:
719 return viscache[node]
722 return viscache[node]
720 ret = {}
723 ret = {}
721 visit = [node]
724 visit = [node]
722 while visit:
725 while visit:
723 x = visit.pop()
726 x = visit.pop()
724 if x in viscache:
727 if x in viscache:
725 ret.update(viscache[x])
728 ret.update(viscache[x])
726 elif x not in ret:
729 elif x not in ret:
727 ret[x] = 1
730 ret[x] = 1
728 if x in branches:
731 if x in branches:
729 visit[len(visit):] = branches[x].keys()
732 visit[len(visit):] = branches[x].keys()
730 viscache[node] = ret
733 viscache[node] = ret
731 return ret
734 return ret
732 if h not in branches:
735 if h not in branches:
733 continue
736 continue
734 # O(n^2), but somewhat limited. This only searches the
737 # O(n^2), but somewhat limited. This only searches the
735 # tags visible from a specific head, not all the tags in the
738 # tags visible from a specific head, not all the tags in the
736 # whole repo.
739 # whole repo.
737 for b in branches[h]:
740 for b in branches[h]:
738 vis = False
741 vis = False
739 for bb in branches[h].keys():
742 for bb in branches[h].keys():
740 if b != bb:
743 if b != bb:
741 if b in visible(bb):
744 if b in visible(bb):
742 vis = True
745 vis = True
743 break
746 break
744 if not vis:
747 if not vis:
745 l = out.setdefault(h, [])
748 l = out.setdefault(h, [])
746 l[len(l):] = self.nodetags(b)
749 l[len(l):] = self.nodetags(b)
747 return out
750 return out
748
751
749 def branches(self, nodes):
752 def branches(self, nodes):
750 if not nodes:
753 if not nodes:
751 nodes = [self.changelog.tip()]
754 nodes = [self.changelog.tip()]
752 b = []
755 b = []
753 for n in nodes:
756 for n in nodes:
754 t = n
757 t = n
755 while n:
758 while n:
756 p = self.changelog.parents(n)
759 p = self.changelog.parents(n)
757 if p[1] != nullid or p[0] == nullid:
760 if p[1] != nullid or p[0] == nullid:
758 b.append((t, n, p[0], p[1]))
761 b.append((t, n, p[0], p[1]))
759 break
762 break
760 n = p[0]
763 n = p[0]
761 return b
764 return b
762
765
763 def between(self, pairs):
766 def between(self, pairs):
764 r = []
767 r = []
765
768
766 for top, bottom in pairs:
769 for top, bottom in pairs:
767 n, l, i = top, [], 0
770 n, l, i = top, [], 0
768 f = 1
771 f = 1
769
772
770 while n != bottom:
773 while n != bottom:
771 p = self.changelog.parents(n)[0]
774 p = self.changelog.parents(n)[0]
772 if i == f:
775 if i == f:
773 l.append(n)
776 l.append(n)
774 f = f * 2
777 f = f * 2
775 n = p
778 n = p
776 i += 1
779 i += 1
777
780
778 r.append(l)
781 r.append(l)
779
782
780 return r
783 return r
781
784
782 def findincoming(self, remote, base=None, heads=None):
785 def findincoming(self, remote, base=None, heads=None):
783 m = self.changelog.nodemap
786 m = self.changelog.nodemap
784 search = []
787 search = []
785 fetch = {}
788 fetch = {}
786 seen = {}
789 seen = {}
787 seenbranch = {}
790 seenbranch = {}
788 if base == None:
791 if base == None:
789 base = {}
792 base = {}
790
793
791 # assume we're closer to the tip than the root
794 # assume we're closer to the tip than the root
792 # and start by examining the heads
795 # and start by examining the heads
793 self.ui.status(_("searching for changes\n"))
796 self.ui.status(_("searching for changes\n"))
794
797
795 if not heads:
798 if not heads:
796 heads = remote.heads()
799 heads = remote.heads()
797
800
798 unknown = []
801 unknown = []
799 for h in heads:
802 for h in heads:
800 if h not in m:
803 if h not in m:
801 unknown.append(h)
804 unknown.append(h)
802 else:
805 else:
803 base[h] = 1
806 base[h] = 1
804
807
805 if not unknown:
808 if not unknown:
806 return None
809 return None
807
810
808 rep = {}
811 rep = {}
809 reqcnt = 0
812 reqcnt = 0
810
813
811 # search through remote branches
814 # search through remote branches
812 # a 'branch' here is a linear segment of history, with four parts:
815 # a 'branch' here is a linear segment of history, with four parts:
813 # head, root, first parent, second parent
816 # head, root, first parent, second parent
814 # (a branch always has two parents (or none) by definition)
817 # (a branch always has two parents (or none) by definition)
815 unknown = remote.branches(unknown)
818 unknown = remote.branches(unknown)
816 while unknown:
819 while unknown:
817 r = []
820 r = []
818 while unknown:
821 while unknown:
819 n = unknown.pop(0)
822 n = unknown.pop(0)
820 if n[0] in seen:
823 if n[0] in seen:
821 continue
824 continue
822
825
823 self.ui.debug(_("examining %s:%s\n")
826 self.ui.debug(_("examining %s:%s\n")
824 % (short(n[0]), short(n[1])))
827 % (short(n[0]), short(n[1])))
825 if n[0] == nullid:
828 if n[0] == nullid:
826 break
829 break
827 if n in seenbranch:
830 if n in seenbranch:
828 self.ui.debug(_("branch already found\n"))
831 self.ui.debug(_("branch already found\n"))
829 continue
832 continue
830 if n[1] and n[1] in m: # do we know the base?
833 if n[1] and n[1] in m: # do we know the base?
831 self.ui.debug(_("found incomplete branch %s:%s\n")
834 self.ui.debug(_("found incomplete branch %s:%s\n")
832 % (short(n[0]), short(n[1])))
835 % (short(n[0]), short(n[1])))
833 search.append(n) # schedule branch range for scanning
836 search.append(n) # schedule branch range for scanning
834 seenbranch[n] = 1
837 seenbranch[n] = 1
835 else:
838 else:
836 if n[1] not in seen and n[1] not in fetch:
839 if n[1] not in seen and n[1] not in fetch:
837 if n[2] in m and n[3] in m:
840 if n[2] in m and n[3] in m:
838 self.ui.debug(_("found new changeset %s\n") %
841 self.ui.debug(_("found new changeset %s\n") %
839 short(n[1]))
842 short(n[1]))
840 fetch[n[1]] = 1 # earliest unknown
843 fetch[n[1]] = 1 # earliest unknown
841 base[n[2]] = 1 # latest known
844 base[n[2]] = 1 # latest known
842 continue
845 continue
843
846
844 for a in n[2:4]:
847 for a in n[2:4]:
845 if a not in rep:
848 if a not in rep:
846 r.append(a)
849 r.append(a)
847 rep[a] = 1
850 rep[a] = 1
848
851
849 seen[n[0]] = 1
852 seen[n[0]] = 1
850
853
851 if r:
854 if r:
852 reqcnt += 1
855 reqcnt += 1
853 self.ui.debug(_("request %d: %s\n") %
856 self.ui.debug(_("request %d: %s\n") %
854 (reqcnt, " ".join(map(short, r))))
857 (reqcnt, " ".join(map(short, r))))
855 for p in range(0, len(r), 10):
858 for p in range(0, len(r), 10):
856 for b in remote.branches(r[p:p+10]):
859 for b in remote.branches(r[p:p+10]):
857 self.ui.debug(_("received %s:%s\n") %
860 self.ui.debug(_("received %s:%s\n") %
858 (short(b[0]), short(b[1])))
861 (short(b[0]), short(b[1])))
859 if b[0] in m:
862 if b[0] in m:
860 self.ui.debug(_("found base node %s\n")
863 self.ui.debug(_("found base node %s\n")
861 % short(b[0]))
864 % short(b[0]))
862 base[b[0]] = 1
865 base[b[0]] = 1
863 elif b[0] not in seen:
866 elif b[0] not in seen:
864 unknown.append(b)
867 unknown.append(b)
865
868
866 # do binary search on the branches we found
869 # do binary search on the branches we found
867 while search:
870 while search:
868 n = search.pop(0)
871 n = search.pop(0)
869 reqcnt += 1
872 reqcnt += 1
870 l = remote.between([(n[0], n[1])])[0]
873 l = remote.between([(n[0], n[1])])[0]
871 l.append(n[1])
874 l.append(n[1])
872 p = n[0]
875 p = n[0]
873 f = 1
876 f = 1
874 for i in l:
877 for i in l:
875 self.ui.debug(_("narrowing %d:%d %s\n") % (f, len(l), short(i)))
878 self.ui.debug(_("narrowing %d:%d %s\n") % (f, len(l), short(i)))
876 if i in m:
879 if i in m:
877 if f <= 2:
880 if f <= 2:
878 self.ui.debug(_("found new branch changeset %s\n") %
881 self.ui.debug(_("found new branch changeset %s\n") %
879 short(p))
882 short(p))
880 fetch[p] = 1
883 fetch[p] = 1
881 base[i] = 1
884 base[i] = 1
882 else:
885 else:
883 self.ui.debug(_("narrowed branch search to %s:%s\n")
886 self.ui.debug(_("narrowed branch search to %s:%s\n")
884 % (short(p), short(i)))
887 % (short(p), short(i)))
885 search.append((p, i))
888 search.append((p, i))
886 break
889 break
887 p, f = i, f * 2
890 p, f = i, f * 2
888
891
889 # sanity check our fetch list
892 # sanity check our fetch list
890 for f in fetch.keys():
893 for f in fetch.keys():
891 if f in m:
894 if f in m:
892 raise repo.RepoError(_("already have changeset ") + short(f[:4]))
895 raise repo.RepoError(_("already have changeset ") + short(f[:4]))
893
896
894 if base.keys() == [nullid]:
897 if base.keys() == [nullid]:
895 self.ui.warn(_("warning: pulling from an unrelated repository!\n"))
898 self.ui.warn(_("warning: pulling from an unrelated repository!\n"))
896
899
897 self.ui.note(_("found new changesets starting at ") +
900 self.ui.note(_("found new changesets starting at ") +
898 " ".join([short(f) for f in fetch]) + "\n")
901 " ".join([short(f) for f in fetch]) + "\n")
899
902
900 self.ui.debug(_("%d total queries\n") % reqcnt)
903 self.ui.debug(_("%d total queries\n") % reqcnt)
901
904
902 return fetch.keys()
905 return fetch.keys()
903
906
904 def findoutgoing(self, remote, base=None, heads=None):
907 def findoutgoing(self, remote, base=None, heads=None):
905 if base == None:
908 if base == None:
906 base = {}
909 base = {}
907 self.findincoming(remote, base, heads)
910 self.findincoming(remote, base, heads)
908
911
909 self.ui.debug(_("common changesets up to ")
912 self.ui.debug(_("common changesets up to ")
910 + " ".join(map(short, base.keys())) + "\n")
913 + " ".join(map(short, base.keys())) + "\n")
911
914
912 remain = dict.fromkeys(self.changelog.nodemap)
915 remain = dict.fromkeys(self.changelog.nodemap)
913
916
914 # prune everything remote has from the tree
917 # prune everything remote has from the tree
915 del remain[nullid]
918 del remain[nullid]
916 remove = base.keys()
919 remove = base.keys()
917 while remove:
920 while remove:
918 n = remove.pop(0)
921 n = remove.pop(0)
919 if n in remain:
922 if n in remain:
920 del remain[n]
923 del remain[n]
921 for p in self.changelog.parents(n):
924 for p in self.changelog.parents(n):
922 remove.append(p)
925 remove.append(p)
923
926
924 # find every node whose parents have been pruned
927 # find every node whose parents have been pruned
925 subset = []
928 subset = []
926 for n in remain:
929 for n in remain:
927 p1, p2 = self.changelog.parents(n)
930 p1, p2 = self.changelog.parents(n)
928 if p1 not in remain and p2 not in remain:
931 if p1 not in remain and p2 not in remain:
929 subset.append(n)
932 subset.append(n)
930
933
931 # this is the set of all roots we have to push
934 # this is the set of all roots we have to push
932 return subset
935 return subset
933
936
934 def pull(self, remote, heads=None):
937 def pull(self, remote, heads=None):
935 lock = self.lock()
938 lock = self.lock()
936
939
937 # if we have an empty repo, fetch everything
940 # if we have an empty repo, fetch everything
938 if self.changelog.tip() == nullid:
941 if self.changelog.tip() == nullid:
939 self.ui.status(_("requesting all changes\n"))
942 self.ui.status(_("requesting all changes\n"))
940 fetch = [nullid]
943 fetch = [nullid]
941 else:
944 else:
942 fetch = self.findincoming(remote)
945 fetch = self.findincoming(remote)
943
946
944 if not fetch:
947 if not fetch:
945 self.ui.status(_("no changes found\n"))
948 self.ui.status(_("no changes found\n"))
946 return 1
949 return 1
947
950
948 if heads is None:
951 if heads is None:
949 cg = remote.changegroup(fetch)
952 cg = remote.changegroup(fetch)
950 else:
953 else:
951 cg = remote.changegroupsubset(fetch, heads)
954 cg = remote.changegroupsubset(fetch, heads)
952 return self.addchangegroup(cg)
955 return self.addchangegroup(cg)
953
956
954 def push(self, remote, force=False):
957 def push(self, remote, force=False):
955 lock = remote.lock()
958 lock = remote.lock()
956
959
957 base = {}
960 base = {}
958 heads = remote.heads()
961 heads = remote.heads()
959 inc = self.findincoming(remote, base, heads)
962 inc = self.findincoming(remote, base, heads)
960 if not force and inc:
963 if not force and inc:
961 self.ui.warn(_("abort: unsynced remote changes!\n"))
964 self.ui.warn(_("abort: unsynced remote changes!\n"))
962 self.ui.status(_("(did you forget to sync? use push -f to force)\n"))
965 self.ui.status(_("(did you forget to sync? use push -f to force)\n"))
963 return 1
966 return 1
964
967
965 update = self.findoutgoing(remote, base)
968 update = self.findoutgoing(remote, base)
966 if not update:
969 if not update:
967 self.ui.status(_("no changes found\n"))
970 self.ui.status(_("no changes found\n"))
968 return 1
971 return 1
969 elif not force:
972 elif not force:
970 if len(heads) < len(self.changelog.heads()):
973 if len(heads) < len(self.changelog.heads()):
971 self.ui.warn(_("abort: push creates new remote branches!\n"))
974 self.ui.warn(_("abort: push creates new remote branches!\n"))
972 self.ui.status(_("(did you forget to merge?"
975 self.ui.status(_("(did you forget to merge?"
973 " use push -f to force)\n"))
976 " use push -f to force)\n"))
974 return 1
977 return 1
975
978
976 cg = self.changegroup(update)
979 cg = self.changegroup(update)
977 return remote.addchangegroup(cg)
980 return remote.addchangegroup(cg)
978
981
979 def changegroupsubset(self, bases, heads):
982 def changegroupsubset(self, bases, heads):
980 """This function generates a changegroup consisting of all the nodes
983 """This function generates a changegroup consisting of all the nodes
981 that are descendents of any of the bases, and ancestors of any of
984 that are descendents of any of the bases, and ancestors of any of
982 the heads.
985 the heads.
983
986
984 It is fairly complex as determining which filenodes and which
987 It is fairly complex as determining which filenodes and which
985 manifest nodes need to be included for the changeset to be complete
988 manifest nodes need to be included for the changeset to be complete
986 is non-trivial.
989 is non-trivial.
987
990
988 Another wrinkle is doing the reverse, figuring out which changeset in
991 Another wrinkle is doing the reverse, figuring out which changeset in
989 the changegroup a particular filenode or manifestnode belongs to."""
992 the changegroup a particular filenode or manifestnode belongs to."""
990
993
991 # Set up some initial variables
994 # Set up some initial variables
992 # Make it easy to refer to self.changelog
995 # Make it easy to refer to self.changelog
993 cl = self.changelog
996 cl = self.changelog
994 # msng is short for missing - compute the list of changesets in this
997 # msng is short for missing - compute the list of changesets in this
995 # changegroup.
998 # changegroup.
996 msng_cl_lst, bases, heads = cl.nodesbetween(bases, heads)
999 msng_cl_lst, bases, heads = cl.nodesbetween(bases, heads)
997 # Some bases may turn out to be superfluous, and some heads may be
1000 # Some bases may turn out to be superfluous, and some heads may be
998 # too. nodesbetween will return the minimal set of bases and heads
1001 # too. nodesbetween will return the minimal set of bases and heads
999 # necessary to re-create the changegroup.
1002 # necessary to re-create the changegroup.
1000
1003
1001 # Known heads are the list of heads that it is assumed the recipient
1004 # Known heads are the list of heads that it is assumed the recipient
1002 # of this changegroup will know about.
1005 # of this changegroup will know about.
1003 knownheads = {}
1006 knownheads = {}
1004 # We assume that all parents of bases are known heads.
1007 # We assume that all parents of bases are known heads.
1005 for n in bases:
1008 for n in bases:
1006 for p in cl.parents(n):
1009 for p in cl.parents(n):
1007 if p != nullid:
1010 if p != nullid:
1008 knownheads[p] = 1
1011 knownheads[p] = 1
1009 knownheads = knownheads.keys()
1012 knownheads = knownheads.keys()
1010 if knownheads:
1013 if knownheads:
1011 # Now that we know what heads are known, we can compute which
1014 # Now that we know what heads are known, we can compute which
1012 # changesets are known. The recipient must know about all
1015 # changesets are known. The recipient must know about all
1013 # changesets required to reach the known heads from the null
1016 # changesets required to reach the known heads from the null
1014 # changeset.
1017 # changeset.
1015 has_cl_set, junk, junk = cl.nodesbetween(None, knownheads)
1018 has_cl_set, junk, junk = cl.nodesbetween(None, knownheads)
1016 junk = None
1019 junk = None
1017 # Transform the list into an ersatz set.
1020 # Transform the list into an ersatz set.
1018 has_cl_set = dict.fromkeys(has_cl_set)
1021 has_cl_set = dict.fromkeys(has_cl_set)
1019 else:
1022 else:
1020 # If there were no known heads, the recipient cannot be assumed to
1023 # If there were no known heads, the recipient cannot be assumed to
1021 # know about any changesets.
1024 # know about any changesets.
1022 has_cl_set = {}
1025 has_cl_set = {}
1023
1026
1024 # Make it easy to refer to self.manifest
1027 # Make it easy to refer to self.manifest
1025 mnfst = self.manifest
1028 mnfst = self.manifest
1026 # We don't know which manifests are missing yet
1029 # We don't know which manifests are missing yet
1027 msng_mnfst_set = {}
1030 msng_mnfst_set = {}
1028 # Nor do we know which filenodes are missing.
1031 # Nor do we know which filenodes are missing.
1029 msng_filenode_set = {}
1032 msng_filenode_set = {}
1030
1033
1031 junk = mnfst.index[mnfst.count() - 1] # Get around a bug in lazyindex
1034 junk = mnfst.index[mnfst.count() - 1] # Get around a bug in lazyindex
1032 junk = None
1035 junk = None
1033
1036
1034 # A changeset always belongs to itself, so the changenode lookup
1037 # A changeset always belongs to itself, so the changenode lookup
1035 # function for a changenode is identity.
1038 # function for a changenode is identity.
1036 def identity(x):
1039 def identity(x):
1037 return x
1040 return x
1038
1041
1039 # A function generating function. Sets up an environment for the
1042 # A function generating function. Sets up an environment for the
1040 # inner function.
1043 # inner function.
1041 def cmp_by_rev_func(revlog):
1044 def cmp_by_rev_func(revlog):
1042 # Compare two nodes by their revision number in the environment's
1045 # Compare two nodes by their revision number in the environment's
1043 # revision history. Since the revision number both represents the
1046 # revision history. Since the revision number both represents the
1044 # most efficient order to read the nodes in, and represents a
1047 # most efficient order to read the nodes in, and represents a
1045 # topological sorting of the nodes, this function is often useful.
1048 # topological sorting of the nodes, this function is often useful.
1046 def cmp_by_rev(a, b):
1049 def cmp_by_rev(a, b):
1047 return cmp(revlog.rev(a), revlog.rev(b))
1050 return cmp(revlog.rev(a), revlog.rev(b))
1048 return cmp_by_rev
1051 return cmp_by_rev
1049
1052
1050 # If we determine that a particular file or manifest node must be a
1053 # If we determine that a particular file or manifest node must be a
1051 # node that the recipient of the changegroup will already have, we can
1054 # node that the recipient of the changegroup will already have, we can
1052 # also assume the recipient will have all the parents. This function
1055 # also assume the recipient will have all the parents. This function
1053 # prunes them from the set of missing nodes.
1056 # prunes them from the set of missing nodes.
1054 def prune_parents(revlog, hasset, msngset):
1057 def prune_parents(revlog, hasset, msngset):
1055 haslst = hasset.keys()
1058 haslst = hasset.keys()
1056 haslst.sort(cmp_by_rev_func(revlog))
1059 haslst.sort(cmp_by_rev_func(revlog))
1057 for node in haslst:
1060 for node in haslst:
1058 parentlst = [p for p in revlog.parents(node) if p != nullid]
1061 parentlst = [p for p in revlog.parents(node) if p != nullid]
1059 while parentlst:
1062 while parentlst:
1060 n = parentlst.pop()
1063 n = parentlst.pop()
1061 if n not in hasset:
1064 if n not in hasset:
1062 hasset[n] = 1
1065 hasset[n] = 1
1063 p = [p for p in revlog.parents(n) if p != nullid]
1066 p = [p for p in revlog.parents(n) if p != nullid]
1064 parentlst.extend(p)
1067 parentlst.extend(p)
1065 for n in hasset:
1068 for n in hasset:
1066 msngset.pop(n, None)
1069 msngset.pop(n, None)
1067
1070
1068 # This is a function generating function used to set up an environment
1071 # This is a function generating function used to set up an environment
1069 # for the inner function to execute in.
1072 # for the inner function to execute in.
1070 def manifest_and_file_collector(changedfileset):
1073 def manifest_and_file_collector(changedfileset):
1071 # This is an information gathering function that gathers
1074 # This is an information gathering function that gathers
1072 # information from each changeset node that goes out as part of
1075 # information from each changeset node that goes out as part of
1073 # the changegroup. The information gathered is a list of which
1076 # the changegroup. The information gathered is a list of which
1074 # manifest nodes are potentially required (the recipient may
1077 # manifest nodes are potentially required (the recipient may
1075 # already have them) and total list of all files which were
1078 # already have them) and total list of all files which were
1076 # changed in any changeset in the changegroup.
1079 # changed in any changeset in the changegroup.
1077 #
1080 #
1078 # We also remember the first changenode we saw any manifest
1081 # We also remember the first changenode we saw any manifest
1079 # referenced by so we can later determine which changenode 'owns'
1082 # referenced by so we can later determine which changenode 'owns'
1080 # the manifest.
1083 # the manifest.
1081 def collect_manifests_and_files(clnode):
1084 def collect_manifests_and_files(clnode):
1082 c = cl.read(clnode)
1085 c = cl.read(clnode)
1083 for f in c[3]:
1086 for f in c[3]:
1084 # This is to make sure we only have one instance of each
1087 # This is to make sure we only have one instance of each
1085 # filename string for each filename.
1088 # filename string for each filename.
1086 changedfileset.setdefault(f, f)
1089 changedfileset.setdefault(f, f)
1087 msng_mnfst_set.setdefault(c[0], clnode)
1090 msng_mnfst_set.setdefault(c[0], clnode)
1088 return collect_manifests_and_files
1091 return collect_manifests_and_files
1089
1092
1090 # Figure out which manifest nodes (of the ones we think might be part
1093 # Figure out which manifest nodes (of the ones we think might be part
1091 # of the changegroup) the recipient must know about and remove them
1094 # of the changegroup) the recipient must know about and remove them
1092 # from the changegroup.
1095 # from the changegroup.
1093 def prune_manifests():
1096 def prune_manifests():
1094 has_mnfst_set = {}
1097 has_mnfst_set = {}
1095 for n in msng_mnfst_set:
1098 for n in msng_mnfst_set:
1096 # If a 'missing' manifest thinks it belongs to a changenode
1099 # If a 'missing' manifest thinks it belongs to a changenode
1097 # the recipient is assumed to have, obviously the recipient
1100 # the recipient is assumed to have, obviously the recipient
1098 # must have that manifest.
1101 # must have that manifest.
1099 linknode = cl.node(mnfst.linkrev(n))
1102 linknode = cl.node(mnfst.linkrev(n))
1100 if linknode in has_cl_set:
1103 if linknode in has_cl_set:
1101 has_mnfst_set[n] = 1
1104 has_mnfst_set[n] = 1
1102 prune_parents(mnfst, has_mnfst_set, msng_mnfst_set)
1105 prune_parents(mnfst, has_mnfst_set, msng_mnfst_set)
1103
1106
1104 # Use the information collected in collect_manifests_and_files to say
1107 # Use the information collected in collect_manifests_and_files to say
1105 # which changenode any manifestnode belongs to.
1108 # which changenode any manifestnode belongs to.
1106 def lookup_manifest_link(mnfstnode):
1109 def lookup_manifest_link(mnfstnode):
1107 return msng_mnfst_set[mnfstnode]
1110 return msng_mnfst_set[mnfstnode]
1108
1111
1109 # A function generating function that sets up the initial environment
1112 # A function generating function that sets up the initial environment
1110 # the inner function.
1113 # the inner function.
1111 def filenode_collector(changedfiles):
1114 def filenode_collector(changedfiles):
1112 next_rev = [0]
1115 next_rev = [0]
1113 # This gathers information from each manifestnode included in the
1116 # This gathers information from each manifestnode included in the
1114 # changegroup about which filenodes the manifest node references
1117 # changegroup about which filenodes the manifest node references
1115 # so we can include those in the changegroup too.
1118 # so we can include those in the changegroup too.
1116 #
1119 #
1117 # It also remembers which changenode each filenode belongs to. It
1120 # It also remembers which changenode each filenode belongs to. It
1118 # does this by assuming the a filenode belongs to the changenode
1121 # does this by assuming the a filenode belongs to the changenode
1119 # the first manifest that references it belongs to.
1122 # the first manifest that references it belongs to.
1120 def collect_msng_filenodes(mnfstnode):
1123 def collect_msng_filenodes(mnfstnode):
1121 r = mnfst.rev(mnfstnode)
1124 r = mnfst.rev(mnfstnode)
1122 if r == next_rev[0]:
1125 if r == next_rev[0]:
1123 # If the last rev we looked at was the one just previous,
1126 # If the last rev we looked at was the one just previous,
1124 # we only need to see a diff.
1127 # we only need to see a diff.
1125 delta = mdiff.patchtext(mnfst.delta(mnfstnode))
1128 delta = mdiff.patchtext(mnfst.delta(mnfstnode))
1126 # For each line in the delta
1129 # For each line in the delta
1127 for dline in delta.splitlines():
1130 for dline in delta.splitlines():
1128 # get the filename and filenode for that line
1131 # get the filename and filenode for that line
1129 f, fnode = dline.split('\0')
1132 f, fnode = dline.split('\0')
1130 fnode = bin(fnode[:40])
1133 fnode = bin(fnode[:40])
1131 f = changedfiles.get(f, None)
1134 f = changedfiles.get(f, None)
1132 # And if the file is in the list of files we care
1135 # And if the file is in the list of files we care
1133 # about.
1136 # about.
1134 if f is not None:
1137 if f is not None:
1135 # Get the changenode this manifest belongs to
1138 # Get the changenode this manifest belongs to
1136 clnode = msng_mnfst_set[mnfstnode]
1139 clnode = msng_mnfst_set[mnfstnode]
1137 # Create the set of filenodes for the file if
1140 # Create the set of filenodes for the file if
1138 # there isn't one already.
1141 # there isn't one already.
1139 ndset = msng_filenode_set.setdefault(f, {})
1142 ndset = msng_filenode_set.setdefault(f, {})
1140 # And set the filenode's changelog node to the
1143 # And set the filenode's changelog node to the
1141 # manifest's if it hasn't been set already.
1144 # manifest's if it hasn't been set already.
1142 ndset.setdefault(fnode, clnode)
1145 ndset.setdefault(fnode, clnode)
1143 else:
1146 else:
1144 # Otherwise we need a full manifest.
1147 # Otherwise we need a full manifest.
1145 m = mnfst.read(mnfstnode)
1148 m = mnfst.read(mnfstnode)
1146 # For every file in we care about.
1149 # For every file in we care about.
1147 for f in changedfiles:
1150 for f in changedfiles:
1148 fnode = m.get(f, None)
1151 fnode = m.get(f, None)
1149 # If it's in the manifest
1152 # If it's in the manifest
1150 if fnode is not None:
1153 if fnode is not None:
1151 # See comments above.
1154 # See comments above.
1152 clnode = msng_mnfst_set[mnfstnode]
1155 clnode = msng_mnfst_set[mnfstnode]
1153 ndset = msng_filenode_set.setdefault(f, {})
1156 ndset = msng_filenode_set.setdefault(f, {})
1154 ndset.setdefault(fnode, clnode)
1157 ndset.setdefault(fnode, clnode)
1155 # Remember the revision we hope to see next.
1158 # Remember the revision we hope to see next.
1156 next_rev[0] = r + 1
1159 next_rev[0] = r + 1
1157 return collect_msng_filenodes
1160 return collect_msng_filenodes
1158
1161
1159 # We have a list of filenodes we think we need for a file, lets remove
1162 # We have a list of filenodes we think we need for a file, lets remove
1160 # all those we now the recipient must have.
1163 # all those we now the recipient must have.
1161 def prune_filenodes(f, filerevlog):
1164 def prune_filenodes(f, filerevlog):
1162 msngset = msng_filenode_set[f]
1165 msngset = msng_filenode_set[f]
1163 hasset = {}
1166 hasset = {}
1164 # If a 'missing' filenode thinks it belongs to a changenode we
1167 # If a 'missing' filenode thinks it belongs to a changenode we
1165 # assume the recipient must have, then the recipient must have
1168 # assume the recipient must have, then the recipient must have
1166 # that filenode.
1169 # that filenode.
1167 for n in msngset:
1170 for n in msngset:
1168 clnode = cl.node(filerevlog.linkrev(n))
1171 clnode = cl.node(filerevlog.linkrev(n))
1169 if clnode in has_cl_set:
1172 if clnode in has_cl_set:
1170 hasset[n] = 1
1173 hasset[n] = 1
1171 prune_parents(filerevlog, hasset, msngset)
1174 prune_parents(filerevlog, hasset, msngset)
1172
1175
1173 # A function generator function that sets up the a context for the
1176 # A function generator function that sets up the a context for the
1174 # inner function.
1177 # inner function.
1175 def lookup_filenode_link_func(fname):
1178 def lookup_filenode_link_func(fname):
1176 msngset = msng_filenode_set[fname]
1179 msngset = msng_filenode_set[fname]
1177 # Lookup the changenode the filenode belongs to.
1180 # Lookup the changenode the filenode belongs to.
1178 def lookup_filenode_link(fnode):
1181 def lookup_filenode_link(fnode):
1179 return msngset[fnode]
1182 return msngset[fnode]
1180 return lookup_filenode_link
1183 return lookup_filenode_link
1181
1184
1182 # Now that we have all theses utility functions to help out and
1185 # Now that we have all theses utility functions to help out and
1183 # logically divide up the task, generate the group.
1186 # logically divide up the task, generate the group.
1184 def gengroup():
1187 def gengroup():
1185 # The set of changed files starts empty.
1188 # The set of changed files starts empty.
1186 changedfiles = {}
1189 changedfiles = {}
1187 # Create a changenode group generator that will call our functions
1190 # Create a changenode group generator that will call our functions
1188 # back to lookup the owning changenode and collect information.
1191 # back to lookup the owning changenode and collect information.
1189 group = cl.group(msng_cl_lst, identity,
1192 group = cl.group(msng_cl_lst, identity,
1190 manifest_and_file_collector(changedfiles))
1193 manifest_and_file_collector(changedfiles))
1191 for chnk in group:
1194 for chnk in group:
1192 yield chnk
1195 yield chnk
1193
1196
1194 # The list of manifests has been collected by the generator
1197 # The list of manifests has been collected by the generator
1195 # calling our functions back.
1198 # calling our functions back.
1196 prune_manifests()
1199 prune_manifests()
1197 msng_mnfst_lst = msng_mnfst_set.keys()
1200 msng_mnfst_lst = msng_mnfst_set.keys()
1198 # Sort the manifestnodes by revision number.
1201 # Sort the manifestnodes by revision number.
1199 msng_mnfst_lst.sort(cmp_by_rev_func(mnfst))
1202 msng_mnfst_lst.sort(cmp_by_rev_func(mnfst))
1200 # Create a generator for the manifestnodes that calls our lookup
1203 # Create a generator for the manifestnodes that calls our lookup
1201 # and data collection functions back.
1204 # and data collection functions back.
1202 group = mnfst.group(msng_mnfst_lst, lookup_manifest_link,
1205 group = mnfst.group(msng_mnfst_lst, lookup_manifest_link,
1203 filenode_collector(changedfiles))
1206 filenode_collector(changedfiles))
1204 for chnk in group:
1207 for chnk in group:
1205 yield chnk
1208 yield chnk
1206
1209
1207 # These are no longer needed, dereference and toss the memory for
1210 # These are no longer needed, dereference and toss the memory for
1208 # them.
1211 # them.
1209 msng_mnfst_lst = None
1212 msng_mnfst_lst = None
1210 msng_mnfst_set.clear()
1213 msng_mnfst_set.clear()
1211
1214
1212 changedfiles = changedfiles.keys()
1215 changedfiles = changedfiles.keys()
1213 changedfiles.sort()
1216 changedfiles.sort()
1214 # Go through all our files in order sorted by name.
1217 # Go through all our files in order sorted by name.
1215 for fname in changedfiles:
1218 for fname in changedfiles:
1216 filerevlog = self.file(fname)
1219 filerevlog = self.file(fname)
1217 # Toss out the filenodes that the recipient isn't really
1220 # Toss out the filenodes that the recipient isn't really
1218 # missing.
1221 # missing.
1219 if msng_filenode_set.has_key(fname):
1222 if msng_filenode_set.has_key(fname):
1220 prune_filenodes(fname, filerevlog)
1223 prune_filenodes(fname, filerevlog)
1221 msng_filenode_lst = msng_filenode_set[fname].keys()
1224 msng_filenode_lst = msng_filenode_set[fname].keys()
1222 else:
1225 else:
1223 msng_filenode_lst = []
1226 msng_filenode_lst = []
1224 # If any filenodes are left, generate the group for them,
1227 # If any filenodes are left, generate the group for them,
1225 # otherwise don't bother.
1228 # otherwise don't bother.
1226 if len(msng_filenode_lst) > 0:
1229 if len(msng_filenode_lst) > 0:
1227 yield struct.pack(">l", len(fname) + 4) + fname
1230 yield struct.pack(">l", len(fname) + 4) + fname
1228 # Sort the filenodes by their revision #
1231 # Sort the filenodes by their revision #
1229 msng_filenode_lst.sort(cmp_by_rev_func(filerevlog))
1232 msng_filenode_lst.sort(cmp_by_rev_func(filerevlog))
1230 # Create a group generator and only pass in a changenode
1233 # Create a group generator and only pass in a changenode
1231 # lookup function as we need to collect no information
1234 # lookup function as we need to collect no information
1232 # from filenodes.
1235 # from filenodes.
1233 group = filerevlog.group(msng_filenode_lst,
1236 group = filerevlog.group(msng_filenode_lst,
1234 lookup_filenode_link_func(fname))
1237 lookup_filenode_link_func(fname))
1235 for chnk in group:
1238 for chnk in group:
1236 yield chnk
1239 yield chnk
1237 if msng_filenode_set.has_key(fname):
1240 if msng_filenode_set.has_key(fname):
1238 # Don't need this anymore, toss it to free memory.
1241 # Don't need this anymore, toss it to free memory.
1239 del msng_filenode_set[fname]
1242 del msng_filenode_set[fname]
1240 # Signal that no more groups are left.
1243 # Signal that no more groups are left.
1241 yield struct.pack(">l", 0)
1244 yield struct.pack(">l", 0)
1242
1245
1243 return util.chunkbuffer(gengroup())
1246 return util.chunkbuffer(gengroup())
1244
1247
1245 def changegroup(self, basenodes):
1248 def changegroup(self, basenodes):
1246 """Generate a changegroup of all nodes that we have that a recipient
1249 """Generate a changegroup of all nodes that we have that a recipient
1247 doesn't.
1250 doesn't.
1248
1251
1249 This is much easier than the previous function as we can assume that
1252 This is much easier than the previous function as we can assume that
1250 the recipient has any changenode we aren't sending them."""
1253 the recipient has any changenode we aren't sending them."""
1251 cl = self.changelog
1254 cl = self.changelog
1252 nodes = cl.nodesbetween(basenodes, None)[0]
1255 nodes = cl.nodesbetween(basenodes, None)[0]
1253 revset = dict.fromkeys([cl.rev(n) for n in nodes])
1256 revset = dict.fromkeys([cl.rev(n) for n in nodes])
1254
1257
1255 def identity(x):
1258 def identity(x):
1256 return x
1259 return x
1257
1260
1258 def gennodelst(revlog):
1261 def gennodelst(revlog):
1259 for r in xrange(0, revlog.count()):
1262 for r in xrange(0, revlog.count()):
1260 n = revlog.node(r)
1263 n = revlog.node(r)
1261 if revlog.linkrev(n) in revset:
1264 if revlog.linkrev(n) in revset:
1262 yield n
1265 yield n
1263
1266
1264 def changed_file_collector(changedfileset):
1267 def changed_file_collector(changedfileset):
1265 def collect_changed_files(clnode):
1268 def collect_changed_files(clnode):
1266 c = cl.read(clnode)
1269 c = cl.read(clnode)
1267 for fname in c[3]:
1270 for fname in c[3]:
1268 changedfileset[fname] = 1
1271 changedfileset[fname] = 1
1269 return collect_changed_files
1272 return collect_changed_files
1270
1273
1271 def lookuprevlink_func(revlog):
1274 def lookuprevlink_func(revlog):
1272 def lookuprevlink(n):
1275 def lookuprevlink(n):
1273 return cl.node(revlog.linkrev(n))
1276 return cl.node(revlog.linkrev(n))
1274 return lookuprevlink
1277 return lookuprevlink
1275
1278
1276 def gengroup():
1279 def gengroup():
1277 # construct a list of all changed files
1280 # construct a list of all changed files
1278 changedfiles = {}
1281 changedfiles = {}
1279
1282
1280 for chnk in cl.group(nodes, identity,
1283 for chnk in cl.group(nodes, identity,
1281 changed_file_collector(changedfiles)):
1284 changed_file_collector(changedfiles)):
1282 yield chnk
1285 yield chnk
1283 changedfiles = changedfiles.keys()
1286 changedfiles = changedfiles.keys()
1284 changedfiles.sort()
1287 changedfiles.sort()
1285
1288
1286 mnfst = self.manifest
1289 mnfst = self.manifest
1287 nodeiter = gennodelst(mnfst)
1290 nodeiter = gennodelst(mnfst)
1288 for chnk in mnfst.group(nodeiter, lookuprevlink_func(mnfst)):
1291 for chnk in mnfst.group(nodeiter, lookuprevlink_func(mnfst)):
1289 yield chnk
1292 yield chnk
1290
1293
1291 for fname in changedfiles:
1294 for fname in changedfiles:
1292 filerevlog = self.file(fname)
1295 filerevlog = self.file(fname)
1293 nodeiter = gennodelst(filerevlog)
1296 nodeiter = gennodelst(filerevlog)
1294 nodeiter = list(nodeiter)
1297 nodeiter = list(nodeiter)
1295 if nodeiter:
1298 if nodeiter:
1296 yield struct.pack(">l", len(fname) + 4) + fname
1299 yield struct.pack(">l", len(fname) + 4) + fname
1297 lookup = lookuprevlink_func(filerevlog)
1300 lookup = lookuprevlink_func(filerevlog)
1298 for chnk in filerevlog.group(nodeiter, lookup):
1301 for chnk in filerevlog.group(nodeiter, lookup):
1299 yield chnk
1302 yield chnk
1300
1303
1301 yield struct.pack(">l", 0)
1304 yield struct.pack(">l", 0)
1302
1305
1303 return util.chunkbuffer(gengroup())
1306 return util.chunkbuffer(gengroup())
1304
1307
1305 def addchangegroup(self, source):
1308 def addchangegroup(self, source):
1306
1309
1307 def getchunk():
1310 def getchunk():
1308 d = source.read(4)
1311 d = source.read(4)
1309 if not d:
1312 if not d:
1310 return ""
1313 return ""
1311 l = struct.unpack(">l", d)[0]
1314 l = struct.unpack(">l", d)[0]
1312 if l <= 4:
1315 if l <= 4:
1313 return ""
1316 return ""
1314 d = source.read(l - 4)
1317 d = source.read(l - 4)
1315 if len(d) < l - 4:
1318 if len(d) < l - 4:
1316 raise repo.RepoError(_("premature EOF reading chunk"
1319 raise repo.RepoError(_("premature EOF reading chunk"
1317 " (got %d bytes, expected %d)")
1320 " (got %d bytes, expected %d)")
1318 % (len(d), l - 4))
1321 % (len(d), l - 4))
1319 return d
1322 return d
1320
1323
1321 def getgroup():
1324 def getgroup():
1322 while 1:
1325 while 1:
1323 c = getchunk()
1326 c = getchunk()
1324 if not c:
1327 if not c:
1325 break
1328 break
1326 yield c
1329 yield c
1327
1330
1328 def csmap(x):
1331 def csmap(x):
1329 self.ui.debug(_("add changeset %s\n") % short(x))
1332 self.ui.debug(_("add changeset %s\n") % short(x))
1330 return self.changelog.count()
1333 return self.changelog.count()
1331
1334
1332 def revmap(x):
1335 def revmap(x):
1333 return self.changelog.rev(x)
1336 return self.changelog.rev(x)
1334
1337
1335 if not source:
1338 if not source:
1336 return
1339 return
1337 changesets = files = revisions = 0
1340 changesets = files = revisions = 0
1338
1341
1339 tr = self.transaction()
1342 tr = self.transaction()
1340
1343
1341 oldheads = len(self.changelog.heads())
1344 oldheads = len(self.changelog.heads())
1342
1345
1343 # pull off the changeset group
1346 # pull off the changeset group
1344 self.ui.status(_("adding changesets\n"))
1347 self.ui.status(_("adding changesets\n"))
1345 co = self.changelog.tip()
1348 co = self.changelog.tip()
1346 cn = self.changelog.addgroup(getgroup(), csmap, tr, 1) # unique
1349 cn = self.changelog.addgroup(getgroup(), csmap, tr, 1) # unique
1347 cnr, cor = map(self.changelog.rev, (cn, co))
1350 cnr, cor = map(self.changelog.rev, (cn, co))
1348 if cn == nullid:
1351 if cn == nullid:
1349 cnr = cor
1352 cnr = cor
1350 changesets = cnr - cor
1353 changesets = cnr - cor
1351
1354
1352 # pull off the manifest group
1355 # pull off the manifest group
1353 self.ui.status(_("adding manifests\n"))
1356 self.ui.status(_("adding manifests\n"))
1354 mm = self.manifest.tip()
1357 mm = self.manifest.tip()
1355 mo = self.manifest.addgroup(getgroup(), revmap, tr)
1358 mo = self.manifest.addgroup(getgroup(), revmap, tr)
1356
1359
1357 # process the files
1360 # process the files
1358 self.ui.status(_("adding file changes\n"))
1361 self.ui.status(_("adding file changes\n"))
1359 while 1:
1362 while 1:
1360 f = getchunk()
1363 f = getchunk()
1361 if not f:
1364 if not f:
1362 break
1365 break
1363 self.ui.debug(_("adding %s revisions\n") % f)
1366 self.ui.debug(_("adding %s revisions\n") % f)
1364 fl = self.file(f)
1367 fl = self.file(f)
1365 o = fl.count()
1368 o = fl.count()
1366 n = fl.addgroup(getgroup(), revmap, tr)
1369 n = fl.addgroup(getgroup(), revmap, tr)
1367 revisions += fl.count() - o
1370 revisions += fl.count() - o
1368 files += 1
1371 files += 1
1369
1372
1370 newheads = len(self.changelog.heads())
1373 newheads = len(self.changelog.heads())
1371 heads = ""
1374 heads = ""
1372 if oldheads and newheads > oldheads:
1375 if oldheads and newheads > oldheads:
1373 heads = _(" (+%d heads)") % (newheads - oldheads)
1376 heads = _(" (+%d heads)") % (newheads - oldheads)
1374
1377
1375 self.ui.status(_("added %d changesets"
1378 self.ui.status(_("added %d changesets"
1376 " with %d changes to %d files%s\n")
1379 " with %d changes to %d files%s\n")
1377 % (changesets, revisions, files, heads))
1380 % (changesets, revisions, files, heads))
1378
1381
1379 tr.close()
1382 tr.close()
1380
1383
1381 if changesets > 0:
1384 if changesets > 0:
1382 self.hook("changegroup", node=hex(self.changelog.node(cor+1)))
1385 self.hook("changegroup", node=hex(self.changelog.node(cor+1)))
1383
1386
1384 for i in range(cor + 1, cnr + 1):
1387 for i in range(cor + 1, cnr + 1):
1385 self.hook("incoming", node=hex(self.changelog.node(i)))
1388 self.hook("incoming", node=hex(self.changelog.node(i)))
1386
1389
1387 def update(self, node, allow=False, force=False, choose=None,
1390 def update(self, node, allow=False, force=False, choose=None,
1388 moddirstate=True, forcemerge=False, wlock=None):
1391 moddirstate=True, forcemerge=False, wlock=None):
1389 pl = self.dirstate.parents()
1392 pl = self.dirstate.parents()
1390 if not force and pl[1] != nullid:
1393 if not force and pl[1] != nullid:
1391 self.ui.warn(_("aborting: outstanding uncommitted merges\n"))
1394 self.ui.warn(_("aborting: outstanding uncommitted merges\n"))
1392 return 1
1395 return 1
1393
1396
1394 err = False
1397 err = False
1395
1398
1396 p1, p2 = pl[0], node
1399 p1, p2 = pl[0], node
1397 pa = self.changelog.ancestor(p1, p2)
1400 pa = self.changelog.ancestor(p1, p2)
1398 m1n = self.changelog.read(p1)[0]
1401 m1n = self.changelog.read(p1)[0]
1399 m2n = self.changelog.read(p2)[0]
1402 m2n = self.changelog.read(p2)[0]
1400 man = self.manifest.ancestor(m1n, m2n)
1403 man = self.manifest.ancestor(m1n, m2n)
1401 m1 = self.manifest.read(m1n)
1404 m1 = self.manifest.read(m1n)
1402 mf1 = self.manifest.readflags(m1n)
1405 mf1 = self.manifest.readflags(m1n)
1403 m2 = self.manifest.read(m2n).copy()
1406 m2 = self.manifest.read(m2n).copy()
1404 mf2 = self.manifest.readflags(m2n)
1407 mf2 = self.manifest.readflags(m2n)
1405 ma = self.manifest.read(man)
1408 ma = self.manifest.read(man)
1406 mfa = self.manifest.readflags(man)
1409 mfa = self.manifest.readflags(man)
1407
1410
1408 modified, added, removed, deleted, unknown = self.changes()
1411 modified, added, removed, deleted, unknown = self.changes()
1409
1412
1410 # is this a jump, or a merge? i.e. is there a linear path
1413 # is this a jump, or a merge? i.e. is there a linear path
1411 # from p1 to p2?
1414 # from p1 to p2?
1412 linear_path = (pa == p1 or pa == p2)
1415 linear_path = (pa == p1 or pa == p2)
1413
1416
1414 if allow and linear_path:
1417 if allow and linear_path:
1415 raise util.Abort(_("there is nothing to merge, "
1418 raise util.Abort(_("there is nothing to merge, "
1416 "just use 'hg update'"))
1419 "just use 'hg update'"))
1417 if allow and not forcemerge:
1420 if allow and not forcemerge:
1418 if modified or added or removed:
1421 if modified or added or removed:
1419 raise util.Abort(_("outstanding uncommited changes"))
1422 raise util.Abort(_("outstanding uncommited changes"))
1420 if not forcemerge and not force:
1423 if not forcemerge and not force:
1421 for f in unknown:
1424 for f in unknown:
1422 if f in m2:
1425 if f in m2:
1423 t1 = self.wread(f)
1426 t1 = self.wread(f)
1424 t2 = self.file(f).read(m2[f])
1427 t2 = self.file(f).read(m2[f])
1425 if cmp(t1, t2) != 0:
1428 if cmp(t1, t2) != 0:
1426 raise util.Abort(_("'%s' already exists in the working"
1429 raise util.Abort(_("'%s' already exists in the working"
1427 " dir and differs from remote") % f)
1430 " dir and differs from remote") % f)
1428
1431
1429 # resolve the manifest to determine which files
1432 # resolve the manifest to determine which files
1430 # we care about merging
1433 # we care about merging
1431 self.ui.note(_("resolving manifests\n"))
1434 self.ui.note(_("resolving manifests\n"))
1432 self.ui.debug(_(" force %s allow %s moddirstate %s linear %s\n") %
1435 self.ui.debug(_(" force %s allow %s moddirstate %s linear %s\n") %
1433 (force, allow, moddirstate, linear_path))
1436 (force, allow, moddirstate, linear_path))
1434 self.ui.debug(_(" ancestor %s local %s remote %s\n") %
1437 self.ui.debug(_(" ancestor %s local %s remote %s\n") %
1435 (short(man), short(m1n), short(m2n)))
1438 (short(man), short(m1n), short(m2n)))
1436
1439
1437 merge = {}
1440 merge = {}
1438 get = {}
1441 get = {}
1439 remove = []
1442 remove = []
1440
1443
1441 # construct a working dir manifest
1444 # construct a working dir manifest
1442 mw = m1.copy()
1445 mw = m1.copy()
1443 mfw = mf1.copy()
1446 mfw = mf1.copy()
1444 umap = dict.fromkeys(unknown)
1447 umap = dict.fromkeys(unknown)
1445
1448
1446 for f in added + modified + unknown:
1449 for f in added + modified + unknown:
1447 mw[f] = ""
1450 mw[f] = ""
1448 mfw[f] = util.is_exec(self.wjoin(f), mfw.get(f, False))
1451 mfw[f] = util.is_exec(self.wjoin(f), mfw.get(f, False))
1449
1452
1450 if moddirstate and not wlock:
1453 if moddirstate and not wlock:
1451 wlock = self.wlock()
1454 wlock = self.wlock()
1452
1455
1453 for f in deleted + removed:
1456 for f in deleted + removed:
1454 if f in mw:
1457 if f in mw:
1455 del mw[f]
1458 del mw[f]
1456
1459
1457 # If we're jumping between revisions (as opposed to merging),
1460 # If we're jumping between revisions (as opposed to merging),
1458 # and if neither the working directory nor the target rev has
1461 # and if neither the working directory nor the target rev has
1459 # the file, then we need to remove it from the dirstate, to
1462 # the file, then we need to remove it from the dirstate, to
1460 # prevent the dirstate from listing the file when it is no
1463 # prevent the dirstate from listing the file when it is no
1461 # longer in the manifest.
1464 # longer in the manifest.
1462 if moddirstate and linear_path and f not in m2:
1465 if moddirstate and linear_path and f not in m2:
1463 self.dirstate.forget((f,))
1466 self.dirstate.forget((f,))
1464
1467
1465 # Compare manifests
1468 # Compare manifests
1466 for f, n in mw.iteritems():
1469 for f, n in mw.iteritems():
1467 if choose and not choose(f):
1470 if choose and not choose(f):
1468 continue
1471 continue
1469 if f in m2:
1472 if f in m2:
1470 s = 0
1473 s = 0
1471
1474
1472 # is the wfile new since m1, and match m2?
1475 # is the wfile new since m1, and match m2?
1473 if f not in m1:
1476 if f not in m1:
1474 t1 = self.wread(f)
1477 t1 = self.wread(f)
1475 t2 = self.file(f).read(m2[f])
1478 t2 = self.file(f).read(m2[f])
1476 if cmp(t1, t2) == 0:
1479 if cmp(t1, t2) == 0:
1477 n = m2[f]
1480 n = m2[f]
1478 del t1, t2
1481 del t1, t2
1479
1482
1480 # are files different?
1483 # are files different?
1481 if n != m2[f]:
1484 if n != m2[f]:
1482 a = ma.get(f, nullid)
1485 a = ma.get(f, nullid)
1483 # are both different from the ancestor?
1486 # are both different from the ancestor?
1484 if n != a and m2[f] != a:
1487 if n != a and m2[f] != a:
1485 self.ui.debug(_(" %s versions differ, resolve\n") % f)
1488 self.ui.debug(_(" %s versions differ, resolve\n") % f)
1486 # merge executable bits
1489 # merge executable bits
1487 # "if we changed or they changed, change in merge"
1490 # "if we changed or they changed, change in merge"
1488 a, b, c = mfa.get(f, 0), mfw[f], mf2[f]
1491 a, b, c = mfa.get(f, 0), mfw[f], mf2[f]
1489 mode = ((a^b) | (a^c)) ^ a
1492 mode = ((a^b) | (a^c)) ^ a
1490 merge[f] = (m1.get(f, nullid), m2[f], mode)
1493 merge[f] = (m1.get(f, nullid), m2[f], mode)
1491 s = 1
1494 s = 1
1492 # are we clobbering?
1495 # are we clobbering?
1493 # is remote's version newer?
1496 # is remote's version newer?
1494 # or are we going back in time?
1497 # or are we going back in time?
1495 elif force or m2[f] != a or (p2 == pa and mw[f] == m1[f]):
1498 elif force or m2[f] != a or (p2 == pa and mw[f] == m1[f]):
1496 self.ui.debug(_(" remote %s is newer, get\n") % f)
1499 self.ui.debug(_(" remote %s is newer, get\n") % f)
1497 get[f] = m2[f]
1500 get[f] = m2[f]
1498 s = 1
1501 s = 1
1499 elif f in umap:
1502 elif f in umap:
1500 # this unknown file is the same as the checkout
1503 # this unknown file is the same as the checkout
1501 get[f] = m2[f]
1504 get[f] = m2[f]
1502
1505
1503 if not s and mfw[f] != mf2[f]:
1506 if not s and mfw[f] != mf2[f]:
1504 if force:
1507 if force:
1505 self.ui.debug(_(" updating permissions for %s\n") % f)
1508 self.ui.debug(_(" updating permissions for %s\n") % f)
1506 util.set_exec(self.wjoin(f), mf2[f])
1509 util.set_exec(self.wjoin(f), mf2[f])
1507 else:
1510 else:
1508 a, b, c = mfa.get(f, 0), mfw[f], mf2[f]
1511 a, b, c = mfa.get(f, 0), mfw[f], mf2[f]
1509 mode = ((a^b) | (a^c)) ^ a
1512 mode = ((a^b) | (a^c)) ^ a
1510 if mode != b:
1513 if mode != b:
1511 self.ui.debug(_(" updating permissions for %s\n")
1514 self.ui.debug(_(" updating permissions for %s\n")
1512 % f)
1515 % f)
1513 util.set_exec(self.wjoin(f), mode)
1516 util.set_exec(self.wjoin(f), mode)
1514 del m2[f]
1517 del m2[f]
1515 elif f in ma:
1518 elif f in ma:
1516 if n != ma[f]:
1519 if n != ma[f]:
1517 r = _("d")
1520 r = _("d")
1518 if not force and (linear_path or allow):
1521 if not force and (linear_path or allow):
1519 r = self.ui.prompt(
1522 r = self.ui.prompt(
1520 (_(" local changed %s which remote deleted\n") % f) +
1523 (_(" local changed %s which remote deleted\n") % f) +
1521 _("(k)eep or (d)elete?"), _("[kd]"), _("k"))
1524 _("(k)eep or (d)elete?"), _("[kd]"), _("k"))
1522 if r == _("d"):
1525 if r == _("d"):
1523 remove.append(f)
1526 remove.append(f)
1524 else:
1527 else:
1525 self.ui.debug(_("other deleted %s\n") % f)
1528 self.ui.debug(_("other deleted %s\n") % f)
1526 remove.append(f) # other deleted it
1529 remove.append(f) # other deleted it
1527 else:
1530 else:
1528 # file is created on branch or in working directory
1531 # file is created on branch or in working directory
1529 if force and f not in umap:
1532 if force and f not in umap:
1530 self.ui.debug(_("remote deleted %s, clobbering\n") % f)
1533 self.ui.debug(_("remote deleted %s, clobbering\n") % f)
1531 remove.append(f)
1534 remove.append(f)
1532 elif n == m1.get(f, nullid): # same as parent
1535 elif n == m1.get(f, nullid): # same as parent
1533 if p2 == pa: # going backwards?
1536 if p2 == pa: # going backwards?
1534 self.ui.debug(_("remote deleted %s\n") % f)
1537 self.ui.debug(_("remote deleted %s\n") % f)
1535 remove.append(f)
1538 remove.append(f)
1536 else:
1539 else:
1537 self.ui.debug(_("local modified %s, keeping\n") % f)
1540 self.ui.debug(_("local modified %s, keeping\n") % f)
1538 else:
1541 else:
1539 self.ui.debug(_("working dir created %s, keeping\n") % f)
1542 self.ui.debug(_("working dir created %s, keeping\n") % f)
1540
1543
1541 for f, n in m2.iteritems():
1544 for f, n in m2.iteritems():
1542 if choose and not choose(f):
1545 if choose and not choose(f):
1543 continue
1546 continue
1544 if f[0] == "/":
1547 if f[0] == "/":
1545 continue
1548 continue
1546 if f in ma and n != ma[f]:
1549 if f in ma and n != ma[f]:
1547 r = _("k")
1550 r = _("k")
1548 if not force and (linear_path or allow):
1551 if not force and (linear_path or allow):
1549 r = self.ui.prompt(
1552 r = self.ui.prompt(
1550 (_("remote changed %s which local deleted\n") % f) +
1553 (_("remote changed %s which local deleted\n") % f) +
1551 _("(k)eep or (d)elete?"), _("[kd]"), _("k"))
1554 _("(k)eep or (d)elete?"), _("[kd]"), _("k"))
1552 if r == _("k"):
1555 if r == _("k"):
1553 get[f] = n
1556 get[f] = n
1554 elif f not in ma:
1557 elif f not in ma:
1555 self.ui.debug(_("remote created %s\n") % f)
1558 self.ui.debug(_("remote created %s\n") % f)
1556 get[f] = n
1559 get[f] = n
1557 else:
1560 else:
1558 if force or p2 == pa: # going backwards?
1561 if force or p2 == pa: # going backwards?
1559 self.ui.debug(_("local deleted %s, recreating\n") % f)
1562 self.ui.debug(_("local deleted %s, recreating\n") % f)
1560 get[f] = n
1563 get[f] = n
1561 else:
1564 else:
1562 self.ui.debug(_("local deleted %s\n") % f)
1565 self.ui.debug(_("local deleted %s\n") % f)
1563
1566
1564 del mw, m1, m2, ma
1567 del mw, m1, m2, ma
1565
1568
1566 if force:
1569 if force:
1567 for f in merge:
1570 for f in merge:
1568 get[f] = merge[f][1]
1571 get[f] = merge[f][1]
1569 merge = {}
1572 merge = {}
1570
1573
1571 if linear_path or force:
1574 if linear_path or force:
1572 # we don't need to do any magic, just jump to the new rev
1575 # we don't need to do any magic, just jump to the new rev
1573 branch_merge = False
1576 branch_merge = False
1574 p1, p2 = p2, nullid
1577 p1, p2 = p2, nullid
1575 else:
1578 else:
1576 if not allow:
1579 if not allow:
1577 self.ui.status(_("this update spans a branch"
1580 self.ui.status(_("this update spans a branch"
1578 " affecting the following files:\n"))
1581 " affecting the following files:\n"))
1579 fl = merge.keys() + get.keys()
1582 fl = merge.keys() + get.keys()
1580 fl.sort()
1583 fl.sort()
1581 for f in fl:
1584 for f in fl:
1582 cf = ""
1585 cf = ""
1583 if f in merge:
1586 if f in merge:
1584 cf = _(" (resolve)")
1587 cf = _(" (resolve)")
1585 self.ui.status(" %s%s\n" % (f, cf))
1588 self.ui.status(" %s%s\n" % (f, cf))
1586 self.ui.warn(_("aborting update spanning branches!\n"))
1589 self.ui.warn(_("aborting update spanning branches!\n"))
1587 self.ui.status(_("(use update -m to merge across branches"
1590 self.ui.status(_("(use update -m to merge across branches"
1588 " or -C to lose changes)\n"))
1591 " or -C to lose changes)\n"))
1589 return 1
1592 return 1
1590 branch_merge = True
1593 branch_merge = True
1591
1594
1592 # get the files we don't need to change
1595 # get the files we don't need to change
1593 files = get.keys()
1596 files = get.keys()
1594 files.sort()
1597 files.sort()
1595 for f in files:
1598 for f in files:
1596 if f[0] == "/":
1599 if f[0] == "/":
1597 continue
1600 continue
1598 self.ui.note(_("getting %s\n") % f)
1601 self.ui.note(_("getting %s\n") % f)
1599 t = self.file(f).read(get[f])
1602 t = self.file(f).read(get[f])
1600 self.wwrite(f, t)
1603 self.wwrite(f, t)
1601 util.set_exec(self.wjoin(f), mf2[f])
1604 util.set_exec(self.wjoin(f), mf2[f])
1602 if moddirstate:
1605 if moddirstate:
1603 if branch_merge:
1606 if branch_merge:
1604 self.dirstate.update([f], 'n', st_mtime=-1)
1607 self.dirstate.update([f], 'n', st_mtime=-1)
1605 else:
1608 else:
1606 self.dirstate.update([f], 'n')
1609 self.dirstate.update([f], 'n')
1607
1610
1608 # merge the tricky bits
1611 # merge the tricky bits
1609 files = merge.keys()
1612 files = merge.keys()
1610 files.sort()
1613 files.sort()
1611 for f in files:
1614 for f in files:
1612 self.ui.status(_("merging %s\n") % f)
1615 self.ui.status(_("merging %s\n") % f)
1613 my, other, flag = merge[f]
1616 my, other, flag = merge[f]
1614 ret = self.merge3(f, my, other)
1617 ret = self.merge3(f, my, other)
1615 if ret:
1618 if ret:
1616 err = True
1619 err = True
1617 util.set_exec(self.wjoin(f), flag)
1620 util.set_exec(self.wjoin(f), flag)
1618 if moddirstate:
1621 if moddirstate:
1619 if branch_merge:
1622 if branch_merge:
1620 # We've done a branch merge, mark this file as merged
1623 # We've done a branch merge, mark this file as merged
1621 # so that we properly record the merger later
1624 # so that we properly record the merger later
1622 self.dirstate.update([f], 'm')
1625 self.dirstate.update([f], 'm')
1623 else:
1626 else:
1624 # We've update-merged a locally modified file, so
1627 # We've update-merged a locally modified file, so
1625 # we set the dirstate to emulate a normal checkout
1628 # we set the dirstate to emulate a normal checkout
1626 # of that file some time in the past. Thus our
1629 # of that file some time in the past. Thus our
1627 # merge will appear as a normal local file
1630 # merge will appear as a normal local file
1628 # modification.
1631 # modification.
1629 f_len = len(self.file(f).read(other))
1632 f_len = len(self.file(f).read(other))
1630 self.dirstate.update([f], 'n', st_size=f_len, st_mtime=-1)
1633 self.dirstate.update([f], 'n', st_size=f_len, st_mtime=-1)
1631
1634
1632 remove.sort()
1635 remove.sort()
1633 for f in remove:
1636 for f in remove:
1634 self.ui.note(_("removing %s\n") % f)
1637 self.ui.note(_("removing %s\n") % f)
1635 try:
1638 try:
1636 util.unlink(self.wjoin(f))
1639 util.unlink(self.wjoin(f))
1637 except OSError, inst:
1640 except OSError, inst:
1638 if inst.errno != errno.ENOENT:
1641 if inst.errno != errno.ENOENT:
1639 self.ui.warn(_("update failed to remove %s: %s!\n") %
1642 self.ui.warn(_("update failed to remove %s: %s!\n") %
1640 (f, inst.strerror))
1643 (f, inst.strerror))
1641 if moddirstate:
1644 if moddirstate:
1642 if branch_merge:
1645 if branch_merge:
1643 self.dirstate.update(remove, 'r')
1646 self.dirstate.update(remove, 'r')
1644 else:
1647 else:
1645 self.dirstate.forget(remove)
1648 self.dirstate.forget(remove)
1646
1649
1647 if moddirstate:
1650 if moddirstate:
1648 self.dirstate.setparents(p1, p2)
1651 self.dirstate.setparents(p1, p2)
1649 return err
1652 return err
1650
1653
1651 def merge3(self, fn, my, other):
1654 def merge3(self, fn, my, other):
1652 """perform a 3-way merge in the working directory"""
1655 """perform a 3-way merge in the working directory"""
1653
1656
1654 def temp(prefix, node):
1657 def temp(prefix, node):
1655 pre = "%s~%s." % (os.path.basename(fn), prefix)
1658 pre = "%s~%s." % (os.path.basename(fn), prefix)
1656 (fd, name) = tempfile.mkstemp("", pre)
1659 (fd, name) = tempfile.mkstemp("", pre)
1657 f = os.fdopen(fd, "wb")
1660 f = os.fdopen(fd, "wb")
1658 self.wwrite(fn, fl.read(node), f)
1661 self.wwrite(fn, fl.read(node), f)
1659 f.close()
1662 f.close()
1660 return name
1663 return name
1661
1664
1662 fl = self.file(fn)
1665 fl = self.file(fn)
1663 base = fl.ancestor(my, other)
1666 base = fl.ancestor(my, other)
1664 a = self.wjoin(fn)
1667 a = self.wjoin(fn)
1665 b = temp("base", base)
1668 b = temp("base", base)
1666 c = temp("other", other)
1669 c = temp("other", other)
1667
1670
1668 self.ui.note(_("resolving %s\n") % fn)
1671 self.ui.note(_("resolving %s\n") % fn)
1669 self.ui.debug(_("file %s: my %s other %s ancestor %s\n") %
1672 self.ui.debug(_("file %s: my %s other %s ancestor %s\n") %
1670 (fn, short(my), short(other), short(base)))
1673 (fn, short(my), short(other), short(base)))
1671
1674
1672 cmd = (os.environ.get("HGMERGE") or self.ui.config("ui", "merge")
1675 cmd = (os.environ.get("HGMERGE") or self.ui.config("ui", "merge")
1673 or "hgmerge")
1676 or "hgmerge")
1674 r = os.system('%s "%s" "%s" "%s"' % (cmd, a, b, c))
1677 r = os.system('%s "%s" "%s" "%s"' % (cmd, a, b, c))
1675 if r:
1678 if r:
1676 self.ui.warn(_("merging %s failed!\n") % fn)
1679 self.ui.warn(_("merging %s failed!\n") % fn)
1677
1680
1678 os.unlink(b)
1681 os.unlink(b)
1679 os.unlink(c)
1682 os.unlink(c)
1680 return r
1683 return r
1681
1684
1682 def verify(self):
1685 def verify(self):
1683 filelinkrevs = {}
1686 filelinkrevs = {}
1684 filenodes = {}
1687 filenodes = {}
1685 changesets = revisions = files = 0
1688 changesets = revisions = files = 0
1686 errors = [0]
1689 errors = [0]
1687 neededmanifests = {}
1690 neededmanifests = {}
1688
1691
1689 def err(msg):
1692 def err(msg):
1690 self.ui.warn(msg + "\n")
1693 self.ui.warn(msg + "\n")
1691 errors[0] += 1
1694 errors[0] += 1
1692
1695
1693 def checksize(obj, name):
1696 def checksize(obj, name):
1694 d = obj.checksize()
1697 d = obj.checksize()
1695 if d[0]:
1698 if d[0]:
1696 err(_("%s data length off by %d bytes") % (name, d[0]))
1699 err(_("%s data length off by %d bytes") % (name, d[0]))
1697 if d[1]:
1700 if d[1]:
1698 err(_("%s index contains %d extra bytes") % (name, d[1]))
1701 err(_("%s index contains %d extra bytes") % (name, d[1]))
1699
1702
1700 seen = {}
1703 seen = {}
1701 self.ui.status(_("checking changesets\n"))
1704 self.ui.status(_("checking changesets\n"))
1702 checksize(self.changelog, "changelog")
1705 checksize(self.changelog, "changelog")
1703
1706
1704 for i in range(self.changelog.count()):
1707 for i in range(self.changelog.count()):
1705 changesets += 1
1708 changesets += 1
1706 n = self.changelog.node(i)
1709 n = self.changelog.node(i)
1707 l = self.changelog.linkrev(n)
1710 l = self.changelog.linkrev(n)
1708 if l != i:
1711 if l != i:
1709 err(_("incorrect link (%d) for changeset revision %d") %(l, i))
1712 err(_("incorrect link (%d) for changeset revision %d") %(l, i))
1710 if n in seen:
1713 if n in seen:
1711 err(_("duplicate changeset at revision %d") % i)
1714 err(_("duplicate changeset at revision %d") % i)
1712 seen[n] = 1
1715 seen[n] = 1
1713
1716
1714 for p in self.changelog.parents(n):
1717 for p in self.changelog.parents(n):
1715 if p not in self.changelog.nodemap:
1718 if p not in self.changelog.nodemap:
1716 err(_("changeset %s has unknown parent %s") %
1719 err(_("changeset %s has unknown parent %s") %
1717 (short(n), short(p)))
1720 (short(n), short(p)))
1718 try:
1721 try:
1719 changes = self.changelog.read(n)
1722 changes = self.changelog.read(n)
1720 except KeyboardInterrupt:
1723 except KeyboardInterrupt:
1721 self.ui.warn(_("interrupted"))
1724 self.ui.warn(_("interrupted"))
1722 raise
1725 raise
1723 except Exception, inst:
1726 except Exception, inst:
1724 err(_("unpacking changeset %s: %s") % (short(n), inst))
1727 err(_("unpacking changeset %s: %s") % (short(n), inst))
1725
1728
1726 neededmanifests[changes[0]] = n
1729 neededmanifests[changes[0]] = n
1727
1730
1728 for f in changes[3]:
1731 for f in changes[3]:
1729 filelinkrevs.setdefault(f, []).append(i)
1732 filelinkrevs.setdefault(f, []).append(i)
1730
1733
1731 seen = {}
1734 seen = {}
1732 self.ui.status(_("checking manifests\n"))
1735 self.ui.status(_("checking manifests\n"))
1733 checksize(self.manifest, "manifest")
1736 checksize(self.manifest, "manifest")
1734
1737
1735 for i in range(self.manifest.count()):
1738 for i in range(self.manifest.count()):
1736 n = self.manifest.node(i)
1739 n = self.manifest.node(i)
1737 l = self.manifest.linkrev(n)
1740 l = self.manifest.linkrev(n)
1738
1741
1739 if l < 0 or l >= self.changelog.count():
1742 if l < 0 or l >= self.changelog.count():
1740 err(_("bad manifest link (%d) at revision %d") % (l, i))
1743 err(_("bad manifest link (%d) at revision %d") % (l, i))
1741
1744
1742 if n in neededmanifests:
1745 if n in neededmanifests:
1743 del neededmanifests[n]
1746 del neededmanifests[n]
1744
1747
1745 if n in seen:
1748 if n in seen:
1746 err(_("duplicate manifest at revision %d") % i)
1749 err(_("duplicate manifest at revision %d") % i)
1747
1750
1748 seen[n] = 1
1751 seen[n] = 1
1749
1752
1750 for p in self.manifest.parents(n):
1753 for p in self.manifest.parents(n):
1751 if p not in self.manifest.nodemap:
1754 if p not in self.manifest.nodemap:
1752 err(_("manifest %s has unknown parent %s") %
1755 err(_("manifest %s has unknown parent %s") %
1753 (short(n), short(p)))
1756 (short(n), short(p)))
1754
1757
1755 try:
1758 try:
1756 delta = mdiff.patchtext(self.manifest.delta(n))
1759 delta = mdiff.patchtext(self.manifest.delta(n))
1757 except KeyboardInterrupt:
1760 except KeyboardInterrupt:
1758 self.ui.warn(_("interrupted"))
1761 self.ui.warn(_("interrupted"))
1759 raise
1762 raise
1760 except Exception, inst:
1763 except Exception, inst:
1761 err(_("unpacking manifest %s: %s") % (short(n), inst))
1764 err(_("unpacking manifest %s: %s") % (short(n), inst))
1762
1765
1763 ff = [ l.split('\0') for l in delta.splitlines() ]
1766 ff = [ l.split('\0') for l in delta.splitlines() ]
1764 for f, fn in ff:
1767 for f, fn in ff:
1765 filenodes.setdefault(f, {})[bin(fn[:40])] = 1
1768 filenodes.setdefault(f, {})[bin(fn[:40])] = 1
1766
1769
1767 self.ui.status(_("crosschecking files in changesets and manifests\n"))
1770 self.ui.status(_("crosschecking files in changesets and manifests\n"))
1768
1771
1769 for m, c in neededmanifests.items():
1772 for m, c in neededmanifests.items():
1770 err(_("Changeset %s refers to unknown manifest %s") %
1773 err(_("Changeset %s refers to unknown manifest %s") %
1771 (short(m), short(c)))
1774 (short(m), short(c)))
1772 del neededmanifests
1775 del neededmanifests
1773
1776
1774 for f in filenodes:
1777 for f in filenodes:
1775 if f not in filelinkrevs:
1778 if f not in filelinkrevs:
1776 err(_("file %s in manifest but not in changesets") % f)
1779 err(_("file %s in manifest but not in changesets") % f)
1777
1780
1778 for f in filelinkrevs:
1781 for f in filelinkrevs:
1779 if f not in filenodes:
1782 if f not in filenodes:
1780 err(_("file %s in changeset but not in manifest") % f)
1783 err(_("file %s in changeset but not in manifest") % f)
1781
1784
1782 self.ui.status(_("checking files\n"))
1785 self.ui.status(_("checking files\n"))
1783 ff = filenodes.keys()
1786 ff = filenodes.keys()
1784 ff.sort()
1787 ff.sort()
1785 for f in ff:
1788 for f in ff:
1786 if f == "/dev/null":
1789 if f == "/dev/null":
1787 continue
1790 continue
1788 files += 1
1791 files += 1
1789 fl = self.file(f)
1792 fl = self.file(f)
1790 checksize(fl, f)
1793 checksize(fl, f)
1791
1794
1792 nodes = {nullid: 1}
1795 nodes = {nullid: 1}
1793 seen = {}
1796 seen = {}
1794 for i in range(fl.count()):
1797 for i in range(fl.count()):
1795 revisions += 1
1798 revisions += 1
1796 n = fl.node(i)
1799 n = fl.node(i)
1797
1800
1798 if n in seen:
1801 if n in seen:
1799 err(_("%s: duplicate revision %d") % (f, i))
1802 err(_("%s: duplicate revision %d") % (f, i))
1800 if n not in filenodes[f]:
1803 if n not in filenodes[f]:
1801 err(_("%s: %d:%s not in manifests") % (f, i, short(n)))
1804 err(_("%s: %d:%s not in manifests") % (f, i, short(n)))
1802 else:
1805 else:
1803 del filenodes[f][n]
1806 del filenodes[f][n]
1804
1807
1805 flr = fl.linkrev(n)
1808 flr = fl.linkrev(n)
1806 if flr not in filelinkrevs[f]:
1809 if flr not in filelinkrevs[f]:
1807 err(_("%s:%s points to unexpected changeset %d")
1810 err(_("%s:%s points to unexpected changeset %d")
1808 % (f, short(n), flr))
1811 % (f, short(n), flr))
1809 else:
1812 else:
1810 filelinkrevs[f].remove(flr)
1813 filelinkrevs[f].remove(flr)
1811
1814
1812 # verify contents
1815 # verify contents
1813 try:
1816 try:
1814 t = fl.read(n)
1817 t = fl.read(n)
1815 except KeyboardInterrupt:
1818 except KeyboardInterrupt:
1816 self.ui.warn(_("interrupted"))
1819 self.ui.warn(_("interrupted"))
1817 raise
1820 raise
1818 except Exception, inst:
1821 except Exception, inst:
1819 err(_("unpacking file %s %s: %s") % (f, short(n), inst))
1822 err(_("unpacking file %s %s: %s") % (f, short(n), inst))
1820
1823
1821 # verify parents
1824 # verify parents
1822 (p1, p2) = fl.parents(n)
1825 (p1, p2) = fl.parents(n)
1823 if p1 not in nodes:
1826 if p1 not in nodes:
1824 err(_("file %s:%s unknown parent 1 %s") %
1827 err(_("file %s:%s unknown parent 1 %s") %
1825 (f, short(n), short(p1)))
1828 (f, short(n), short(p1)))
1826 if p2 not in nodes:
1829 if p2 not in nodes:
1827 err(_("file %s:%s unknown parent 2 %s") %
1830 err(_("file %s:%s unknown parent 2 %s") %
1828 (f, short(n), short(p1)))
1831 (f, short(n), short(p1)))
1829 nodes[n] = 1
1832 nodes[n] = 1
1830
1833
1831 # cross-check
1834 # cross-check
1832 for node in filenodes[f]:
1835 for node in filenodes[f]:
1833 err(_("node %s in manifests not in %s") % (hex(node), f))
1836 err(_("node %s in manifests not in %s") % (hex(node), f))
1834
1837
1835 self.ui.status(_("%d files, %d changesets, %d total revisions\n") %
1838 self.ui.status(_("%d files, %d changesets, %d total revisions\n") %
1836 (files, changesets, revisions))
1839 (files, changesets, revisions))
1837
1840
1838 if errors[0]:
1841 if errors[0]:
1839 self.ui.warn(_("%d integrity errors encountered!\n") % errors[0])
1842 self.ui.warn(_("%d integrity errors encountered!\n") % errors[0])
1840 return 1
1843 return 1
General Comments 0
You need to be logged in to leave comments. Login now