##// END OF EJS Templates
From: Thomas Arendsen Hein <thomas@intevation.de>...
mpm@selenic.com -
r19:12360c04 default
parent child Browse files
Show More
@@ -1,578 +1,578 b''
1 1 # hg.py - repository classes for mercurial
2 2 #
3 3 # Copyright 2005 Matt Mackall <mpm@selenic.com>
4 4 #
5 5 # This software may be used and distributed according to the terms
6 6 # of the GNU General Public License, incorporated herein by reference.
7 7
8 8 import sys, struct, sha, socket, os, time, base64, re, urllib2, binascii
9 9 import urllib
10 10 from mercurial import byterange
11 11 from mercurial.transaction import *
12 12 from mercurial.revlog import *
13 13
14 14 def hex(node): return binascii.hexlify(node)
15 15 def bin(node): return binascii.unhexlify(node)
16 16
17 17 class filelog(revlog):
18 18 def __init__(self, opener, path):
19 19 s = self.encodepath(path)
20 20 revlog.__init__(self, opener, os.path.join("data", s + "i"),
21 21 os.path.join("data", s))
22 22
23 23 def encodepath(self, path):
24 24 s = sha.sha(path).digest()
25 25 s = base64.encodestring(s)[:-3]
26 26 s = re.sub("\+", "%", s)
27 27 s = re.sub("/", "_", s)
28 28 return s
29 29
30 30 def read(self, node):
31 31 return self.revision(node)
32 32 def add(self, text, transaction, link, p1=None, p2=None):
33 33 return self.addrevision(text, transaction, link, p1, p2)
34 34
35 35 def resolvedag(self, old, new, transaction, link):
36 36 """resolve unmerged heads in our DAG"""
37 37 if old == new: return None
38 38 a = self.ancestor(old, new)
39 39 if old == a: return new
40 40 return self.merge3(old, new, a, transaction, link)
41 41
42 42 def merge3(self, my, other, base, transaction, link):
43 43 """perform a 3-way merge and append the result"""
44 44 def temp(prefix, node):
45 45 (fd, name) = tempfile.mkstemp(prefix)
46 46 f = os.fdopen(fd, "w")
47 47 f.write(self.revision(node))
48 48 f.close()
49 49 return name
50 50
51 51 a = temp("local", my)
52 52 b = temp("remote", other)
53 53 c = temp("parent", base)
54 54
55 55 cmd = os.environ["HGMERGE"]
56 56 r = os.system("%s %s %s %s" % (cmd, a, b, c))
57 57 if r:
58 58 raise "Merge failed, implement rollback!"
59 59
60 60 t = open(a).read()
61 61 os.unlink(a)
62 62 os.unlink(b)
63 63 os.unlink(c)
64 64 return self.addrevision(t, transaction, link, my, other)
65 65
66 66 def merge(self, other, transaction, linkseq, link):
67 67 """perform a merge and resolve resulting heads"""
68 68 (o, n) = self.mergedag(other, transaction, linkseq)
69 69 return self.resolvedag(o, n, transaction, link)
70 70
71 71 class manifest(revlog):
72 72 def __init__(self, opener):
73 73 self.mapcache = None
74 74 self.listcache = None
75 75 self.addlist = None
76 76 revlog.__init__(self, opener, "00manifest.i", "00manifest.d")
77 77
78 78 def read(self, node):
79 79 if self.mapcache and self.mapcache[0] == node:
80 80 return self.mapcache[1]
81 81 text = self.revision(node)
82 82 map = {}
83 83 self.listcache = text.splitlines(1)
84 84 for l in self.listcache:
85 85 (f, n) = l.split('\0')
86 86 map[f] = bin(n[:40])
87 87 self.mapcache = (node, map)
88 88 return map
89 89
90 90 def diff(self, a, b):
91 91 # this is sneaky, as we're not actually using a and b
92 92 if self.listcache:
93 93 return mdiff.diff(self.listcache, self.addlist, 1)
94 94 else:
95 95 return mdiff.diff(a, b)
96 96
97 97 def add(self, map, transaction, link, p1=None, p2=None):
98 98 files = map.keys()
99 99 files.sort()
100 100
101 101 self.addlist = ["%s\000%s\n" % (f, hex(map[f])) for f in files]
102 102 text = "".join(self.addlist)
103 103
104 104 n = self.addrevision(text, transaction, link, p1, p2)
105 105 self.mapcache = (n, map)
106 106 self.listcache = self.addlist
107 107
108 108 return n
109 109
110 110 class changelog(revlog):
111 111 def __init__(self, opener):
112 112 revlog.__init__(self, opener, "00changelog.i", "00changelog.d")
113 113
114 114 def extract(self, text):
115 115 last = text.index("\n\n")
116 116 desc = text[last + 2:]
117 117 l = text[:last].splitlines()
118 118 manifest = bin(l[0])
119 119 user = l[1]
120 120 date = l[2]
121 121 files = l[3:]
122 122 return (manifest, user, date, files, desc)
123 123
124 124 def read(self, node):
125 125 return self.extract(self.revision(node))
126 126
127 127 def add(self, manifest, list, desc, transaction, p1=None, p2=None):
128 128 try: user = os.environ["HGUSER"]
129 129 except: user = os.environ["LOGNAME"] + '@' + socket.getfqdn()
130 130 date = "%d %d" % (time.time(), time.timezone)
131 131 list.sort()
132 132 l = [hex(manifest), user, date] + list + ["", desc]
133 133 text = "\n".join(l)
134 134 return self.addrevision(text, transaction, self.count(), p1, p2)
135 135
136 136 def merge3(self, my, other, base):
137 137 pass
138 138
139 139 class dircache:
140 140 def __init__(self, opener):
141 141 self.opener = opener
142 142 self.dirty = 0
143 143 self.map = None
144 144 def __del__(self):
145 145 if self.dirty: self.write()
146 146 def __getitem__(self, key):
147 147 try:
148 148 return self.map[key]
149 149 except TypeError:
150 150 self.read()
151 151 return self[key]
152 152
153 153 def read(self):
154 154 if self.map is not None: return self.map
155 155
156 156 self.map = {}
157 157 try:
158 158 st = self.opener("dircache").read()
159 159 except: return
160 160
161 161 pos = 0
162 162 while pos < len(st):
163 163 e = struct.unpack(">llll", st[pos:pos+16])
164 164 l = e[3]
165 165 pos += 16
166 166 f = st[pos:pos + l]
167 167 self.map[f] = e[:3]
168 168 pos += l
169 169
170 170 def update(self, files):
171 171 if not files: return
172 172 self.read()
173 173 self.dirty = 1
174 174 for f in files:
175 175 try:
176 176 s = os.stat(f)
177 177 self.map[f] = (s.st_mode, s.st_size, s.st_mtime)
178 178 except IOError:
179 179 self.remove(f)
180 180
181 181 def taint(self, files):
182 182 if not files: return
183 183 self.read()
184 184 self.dirty = 1
185 185 for f in files:
186 186 self.map[f] = (0, -1, 0)
187 187
188 188 def remove(self, files):
189 189 if not files: return
190 190 self.read()
191 191 self.dirty = 1
192 192 for f in files:
193 try: del self[f]
194 except: pass
193 try: del self.map[f]
194 except KeyError: pass
195 195
196 196 def clear(self):
197 197 self.map = {}
198 198 self.dirty = 1
199 199
200 200 def write(self):
201 201 st = self.opener("dircache", "w")
202 202 for f, e in self.map.items():
203 203 e = struct.pack(">llll", e[0], e[1], e[2], len(f))
204 204 st.write(e + f)
205 205 self.dirty = 0
206 206
207 207 def copy(self):
208 208 self.read()
209 209 return self.map.copy()
210 210
211 211 # used to avoid circular references so destructors work
212 212 def opener(base):
213 213 p = base
214 214 def o(path, mode="r"):
215 215 if p[:7] == "http://":
216 216 f = os.path.join(p, urllib.quote(path))
217 217 return httprangereader(f)
218 218
219 219 f = os.path.join(p, path)
220 220
221 221 if mode != "r" and os.path.isfile(f):
222 222 s = os.stat(f)
223 223 if s.st_nlink > 1:
224 224 file(f + ".tmp", "w").write(file(f).read())
225 225 os.rename(f+".tmp", f)
226 226
227 227 return file(f, mode)
228 228
229 229 return o
230 230
231 231 class repository:
232 232 def __init__(self, ui, path=None, create=0):
233 233 self.remote = 0
234 234 if path and path[:7] == "http://":
235 235 self.remote = 1
236 236 self.path = path
237 237 else:
238 238 if not path:
239 239 p = os.getcwd()
240 240 while not os.path.isdir(os.path.join(p, ".hg")):
241 241 p = os.path.dirname(p)
242 242 if p == "/": raise "No repo found"
243 243 path = p
244 244 self.path = os.path.join(path, ".hg")
245 245
246 246 self.root = path
247 247 self.ui = ui
248 248
249 249 if create:
250 250 os.mkdir(self.path)
251 251 os.mkdir(self.join("data"))
252 252
253 253 self.opener = opener(self.path)
254 254 self.manifest = manifest(self.opener)
255 255 self.changelog = changelog(self.opener)
256 256 self.ignorelist = None
257 257
258 258 if not self.remote:
259 259 self.dircache = dircache(self.opener)
260 260 try:
261 261 self.current = bin(self.opener("current").read())
262 262 except IOError:
263 263 self.current = None
264 264
265 265 def setcurrent(self, node):
266 266 self.current = node
267 267 self.opener("current", "w").write(hex(node))
268 268
269 269 def ignore(self, f):
270 270 if self.ignorelist is None:
271 271 self.ignorelist = []
272 272 try:
273 273 l = open(os.path.join(self.root, ".hgignore")).readlines()
274 274 for pat in l:
275 275 if pat != "\n":
276 276 self.ignorelist.append(re.compile(pat[:-1]))
277 277 except IOError: pass
278 278 for pat in self.ignorelist:
279 279 if pat.search(f): return True
280 280 return False
281 281
282 282 def join(self, f):
283 283 return os.path.join(self.path, f)
284 284
285 285 def file(self, f):
286 286 return filelog(self.opener, f)
287 287
288 288 def transaction(self):
289 289 return transaction(self.opener, self.join("journal"))
290 290
291 291 def merge(self, other):
292 292 tr = self.transaction()
293 293 changed = {}
294 294 new = {}
295 295 seqrev = self.changelog.count()
296 296 # some magic to allow fiddling in nested scope
297 297 nextrev = [seqrev]
298 298
299 299 # helpers for back-linking file revisions to local changeset
300 300 # revisions so we can immediately get to changeset from annotate
301 301 def accumulate(text):
302 302 # track which files are added in which changeset and the
303 303 # corresponding _local_ changeset revision
304 304 files = self.changelog.extract(text)[3]
305 305 for f in files:
306 306 changed.setdefault(f, []).append(nextrev[0])
307 307 nextrev[0] += 1
308 308
309 309 def seq(start):
310 310 while 1:
311 311 yield start
312 312 start += 1
313 313
314 314 def lseq(l):
315 315 for r in l:
316 316 yield r
317 317
318 318 # begin the import/merge of changesets
319 319 self.ui.status("merging new changesets\n")
320 320 (co, cn) = self.changelog.mergedag(other.changelog, tr,
321 321 seq(seqrev), accumulate)
322 322 resolverev = self.changelog.count()
323 323
324 324 # is there anything to do?
325 325 if co == cn:
326 326 tr.close()
327 327 return
328 328
329 329 # do we need to resolve?
330 330 simple = (co == self.changelog.ancestor(co, cn))
331 331
332 332 # merge all files changed by the changesets,
333 333 # keeping track of the new tips
334 334 changelist = changed.keys()
335 335 changelist.sort()
336 336 for f in changelist:
337 337 sys.stdout.write(".")
338 338 sys.stdout.flush()
339 339 r = self.file(f)
340 340 node = r.merge(other.file(f), tr, lseq(changed[f]), resolverev)
341 341 if node:
342 342 new[f] = node
343 343 sys.stdout.write("\n")
344 344
345 345 # begin the merge of the manifest
346 346 self.ui.status("merging manifests\n")
347 347 (mm, mo) = self.manifest.mergedag(other.manifest, tr, seq(seqrev))
348 348
349 349 # For simple merges, we don't need to resolve manifests or changesets
350 350 if simple:
351 351 tr.close()
352 352 return
353 353
354 354 ma = self.manifest.ancestor(mm, mo)
355 355
356 356 # resolve the manifest to point to all the merged files
357 357 self.ui.status("resolving manifests\n")
358 358 mmap = self.manifest.read(mm) # mine
359 359 omap = self.manifest.read(mo) # other
360 360 amap = self.manifest.read(ma) # ancestor
361 361 nmap = {}
362 362
363 363 for f, mid in mmap.iteritems():
364 364 if f in omap:
365 365 if mid != omap[f]:
366 366 nmap[f] = new.get(f, mid) # use merged version
367 367 else:
368 368 nmap[f] = new.get(f, mid) # they're the same
369 369 del omap[f]
370 370 elif f in amap:
371 371 if mid != amap[f]:
372 372 pass # we should prompt here
373 373 else:
374 374 pass # other deleted it
375 375 else:
376 376 nmap[f] = new.get(f, mid) # we created it
377 377
378 378 del mmap
379 379
380 380 for f, oid in omap.iteritems():
381 381 if f in amap:
382 382 if oid != amap[f]:
383 383 pass # this is the nasty case, we should prompt
384 384 else:
385 385 pass # probably safe
386 386 else:
387 387 nmap[f] = new.get(f, oid) # remote created it
388 388
389 389 del omap
390 390 del amap
391 391
392 392 node = self.manifest.add(nmap, tr, resolverev, mm, mo)
393 393
394 394 # Now all files and manifests are merged, we add the changed files
395 395 # and manifest id to the changelog
396 396 self.ui.status("committing merge changeset\n")
397 397 new = new.keys()
398 398 new.sort()
399 399 if co == cn: cn = -1
400 400
401 401 edittext = "\n"+"".join(["HG: changed %s\n" % f for f in new])
402 402 edittext = self.ui.edit(edittext)
403 403 n = self.changelog.add(node, new, edittext, tr, co, cn)
404 404
405 405 tr.close()
406 406
407 407 def commit(self, update = None, text = ""):
408 408 tr = self.transaction()
409 409
410 410 try:
411 411 remove = [ l[:-1] for l in self.opener("to-remove") ]
412 412 os.unlink(self.join("to-remove"))
413 413
414 414 except IOError:
415 415 remove = []
416 416
417 417 if update == None:
418 418 update = self.diffdir(self.root)[0]
419 419
420 420 # check in files
421 421 new = {}
422 422 linkrev = self.changelog.count()
423 423 for f in update:
424 424 try:
425 425 t = file(f).read()
426 426 except IOError:
427 427 remove.append(f)
428 428 continue
429 429 r = self.file(f)
430 430 new[f] = r.add(t, tr, linkrev)
431 431
432 432 # update manifest
433 433 mmap = self.manifest.read(self.manifest.tip())
434 434 mmap.update(new)
435 435 for f in remove:
436 436 del mmap[f]
437 437 mnode = self.manifest.add(mmap, tr, linkrev)
438 438
439 439 # add changeset
440 440 new = new.keys()
441 441 new.sort()
442 442
443 443 edittext = text + "\n"+"".join(["HG: changed %s\n" % f for f in new])
444 444 edittext = self.ui.edit(edittext)
445 445
446 446 n = self.changelog.add(mnode, new, edittext, tr)
447 447 tr.close()
448 448
449 449 self.setcurrent(n)
450 450 self.dircache.update(new)
451 451 self.dircache.remove(remove)
452 452
453 453 def checkdir(self, path):
454 454 d = os.path.dirname(path)
455 455 if not d: return
456 456 if not os.path.isdir(d):
457 457 self.checkdir(d)
458 458 os.mkdir(d)
459 459
460 460 def checkout(self, node):
461 461 # checkout is really dumb at the moment
462 462 # it ought to basically merge
463 463 change = self.changelog.read(node)
464 464 mmap = self.manifest.read(change[0])
465 465
466 466 l = mmap.keys()
467 467 l.sort()
468 468 stats = []
469 469 for f in l:
470 470 r = self.file(f)
471 471 t = r.revision(mmap[f])
472 472 try:
473 473 file(f, "w").write(t)
474 474 except:
475 475 self.checkdir(f)
476 476 file(f, "w").write(t)
477 477
478 478 self.setcurrent(node)
479 479 self.dircache.clear()
480 480 self.dircache.update(l)
481 481
482 482 def diffdir(self, path):
483 483 dc = self.dircache.copy()
484 484 changed = []
485 485 mf = {}
486 486 added = []
487 487
488 488 if self.current:
489 489 change = self.changelog.read(self.current)
490 490 mf = self.manifest.read(change[0])
491 491
492 492 for dir, subdirs, files in os.walk(self.root):
493 493 d = dir[len(self.root)+1:]
494 494 if ".hg" in subdirs: subdirs.remove(".hg")
495 495
496 496 for f in files:
497 497 fn = os.path.join(d, f)
498 498 try: s = os.stat(fn)
499 499 except: continue
500 500 if fn in dc:
501 501 c = dc[fn]
502 502 del dc[fn]
503 503 if c[1] != s.st_size:
504 504 changed.append(fn)
505 505 elif c[0] != s.st_mode or c[2] != s.st_mtime:
506 506 t1 = file(fn).read()
507 507 t2 = self.file(fn).revision(mf[fn])
508 508 if t1 != t2:
509 509 changed.append(fn)
510 510 else:
511 511 if self.ignore(fn): continue
512 512 added.append(fn)
513 513
514 514 deleted = dc.keys()
515 515 deleted.sort()
516 516
517 517 return (changed, added, deleted)
518 518
519 519 def add(self, list):
520 520 self.dircache.taint(list)
521 521
522 522 def remove(self, list):
523 523 dl = self.opener("to-remove", "a")
524 524 for f in list:
525 525 dl.write(f + "\n")
526 526
527 527 class ui:
528 528 def __init__(self, verbose=False, debug=False):
529 529 self.verbose = verbose
530 530 def write(self, *args):
531 531 for a in args:
532 532 sys.stdout.write(str(a))
533 533 def prompt(self, msg, pat):
534 534 while 1:
535 535 sys.stdout.write(msg)
536 536 r = sys.stdin.readline()[:-1]
537 537 if re.match(pat, r):
538 538 return r
539 539 def status(self, *msg):
540 540 self.write(*msg)
541 541 def warn(self, msg):
542 542 self.write(*msg)
543 543 def note(self, msg):
544 544 if self.verbose: self.write(*msg)
545 545 def debug(self, msg):
546 546 if self.debug: self.write(*msg)
547 547 def edit(self, text):
548 548 (fd, name) = tempfile.mkstemp("hg")
549 549 f = os.fdopen(fd, "w")
550 550 f.write(text)
551 551 f.close()
552 552
553 553 editor = os.environ.get("EDITOR", "vi")
554 554 r = os.system("%s %s" % (editor, name))
555 555 if r:
556 556 raise "Edit failed!"
557 557
558 558 t = open(name).read()
559 559 t = re.sub("(?m)^HG:.*\n", "", t)
560 560
561 561 return t
562 562
563 563
564 564 class httprangereader:
565 565 def __init__(self, url):
566 566 self.url = url
567 567 self.pos = 0
568 568 def seek(self, pos):
569 569 self.pos = pos
570 570 def read(self, bytes=None):
571 571 opener = urllib2.build_opener(byterange.HTTPRangeHandler())
572 572 urllib2.install_opener(opener)
573 573 req = urllib2.Request(self.url)
574 574 end = ''
575 575 if bytes: end = self.pos + bytes
576 576 req.add_header('Range', 'bytes=%d-%s' % (self.pos, end))
577 577 f = urllib2.urlopen(req)
578 578 return f.read()
General Comments 0
You need to be logged in to leave comments. Login now