]> arthur.barton.de Git - bup.git/blob - git.py
cmd-margin: work correctly in python 2.4 when a midx is present.
[bup.git] / git.py
1 import os, errno, zlib, time, sha, subprocess, struct, stat, re, tempfile
2 import heapq
3 from helpers import *
4
5 verbose = 0
6 ignore_midx = 0
7 home_repodir = os.path.expanduser('~/.bup')
8 repodir = None
9
10 _typemap =  { 'blob':3, 'tree':2, 'commit':1, 'tag':4 }
11 _typermap = { 3:'blob', 2:'tree', 1:'commit', 4:'tag' }
12
13
14 class GitError(Exception):
15     pass
16
17
18 def repo(sub = ''):
19     global repodir
20     if not repodir:
21         raise GitError('You should call check_repo_or_die()')
22     gd = os.path.join(repodir, '.git')
23     if os.path.exists(gd):
24         repodir = gd
25     return os.path.join(repodir, sub)
26
27
28 def _encode_packobj(type, content):
29     szout = ''
30     sz = len(content)
31     szbits = (sz & 0x0f) | (_typemap[type]<<4)
32     sz >>= 4
33     while 1:
34         if sz: szbits |= 0x80
35         szout += chr(szbits)
36         if not sz:
37             break
38         szbits = sz & 0x7f
39         sz >>= 7
40     z = zlib.compressobj(1)
41     yield szout
42     yield z.compress(content)
43     yield z.flush()
44
45
46 def _encode_looseobj(type, content):
47     z = zlib.compressobj(1)
48     yield z.compress('%s %d\0' % (type, len(content)))
49     yield z.compress(content)
50     yield z.flush()
51
52
53 def _decode_looseobj(buf):
54     assert(buf);
55     s = zlib.decompress(buf)
56     i = s.find('\0')
57     assert(i > 0)
58     l = s[:i].split(' ')
59     type = l[0]
60     sz = int(l[1])
61     content = s[i+1:]
62     assert(type in _typemap)
63     assert(sz == len(content))
64     return (type, content)
65
66
67 def _decode_packobj(buf):
68     assert(buf)
69     c = ord(buf[0])
70     type = _typermap[(c & 0x70) >> 4]
71     sz = c & 0x0f
72     shift = 4
73     i = 0
74     while c & 0x80:
75         i += 1
76         c = ord(buf[i])
77         sz |= (c & 0x7f) << shift
78         shift += 7
79         if not (c & 0x80):
80             break
81     return (type, zlib.decompress(buf[i+1:]))
82
83
84 class PackIndex:
85     def __init__(self, filename):
86         self.name = filename
87         self.map = mmap_read(open(filename))
88         assert(str(self.map[0:8]) == '\377tOc\0\0\0\2')
89         self.fanout = list(struct.unpack('!256I',
90                                          str(buffer(self.map, 8, 256*4))))
91         self.fanout.append(0)  # entry "-1"
92         nsha = self.fanout[255]
93         self.ofstable = buffer(self.map,
94                                8 + 256*4 + nsha*20 + nsha*4,
95                                nsha*4)
96         self.ofs64table = buffer(self.map,
97                                  8 + 256*4 + nsha*20 + nsha*4 + nsha*4)
98
99     def _ofs_from_idx(self, idx):
100         ofs = struct.unpack('!I', str(buffer(self.ofstable, idx*4, 4)))[0]
101         if ofs & 0x80000000:
102             idx64 = ofs & 0x7fffffff
103             ofs = struct.unpack('!I',
104                                 str(buffer(self.ofs64table, idx64*8, 8)))[0]
105         return ofs
106
107     def _idx_from_hash(self, hash):
108         assert(len(hash) == 20)
109         b1 = ord(hash[0])
110         start = self.fanout[b1-1] # range -1..254
111         end = self.fanout[b1] # range 0..255
112         buf = buffer(self.map, 8 + 256*4, end*20)
113         want = str(hash)
114         while start < end:
115             mid = start + (end-start)/2
116             v = str(buf[mid*20:(mid+1)*20])
117             if v < want:
118                 start = mid+1
119             elif v > want:
120                 end = mid
121             else: # got it!
122                 return mid
123         return None
124         
125     def find_offset(self, hash):
126         idx = self._idx_from_hash(hash)
127         if idx != None:
128             return self._ofs_from_idx(idx)
129         return None
130
131     def exists(self, hash):
132         return hash and (self._idx_from_hash(hash) != None) and True or None
133
134     def __iter__(self):
135         for i in xrange(self.fanout[255]):
136             yield buffer(self.map, 8 + 256*4 + 20*i, 20)
137
138     def __len__(self):
139         return int(self.fanout[255])
140
141
142 def extract_bits(buf, bits):
143     mask = (1<<bits) - 1
144     v = struct.unpack('!I', buf[0:4])[0]
145     v = (v >> (32-bits)) & mask
146     return v
147
148
149 class PackMidx:
150     def __init__(self, filename):
151         self.name = filename
152         assert(filename.endswith('.midx'))
153         self.map = mmap_read(open(filename))
154         if str(self.map[0:8]) == 'MIDX\0\0\0\1':
155             log('Warning: ignoring old-style midx %r\n' % filename)
156             self.bits = 0
157             self.entries = 1
158             self.fanout = buffer('\0\0\0\0')
159             self.shalist = buffer('\0'*20)
160             self.idxnames = []
161         else:
162             assert(str(self.map[0:8]) == 'MIDX\0\0\0\2')
163             self.bits = struct.unpack('!I', self.map[8:12])[0]
164             self.entries = 2**self.bits
165             self.fanout = buffer(self.map, 12, self.entries*4)
166             shaofs = 12 + self.entries*4
167             nsha = self._fanget(self.entries-1)
168             self.shalist = buffer(self.map, shaofs, nsha*20)
169             self.idxnames = str(self.map[shaofs + 20*nsha:]).split('\0')
170
171     def _fanget(self, i):
172         start = i*4
173         s = self.fanout[start:start+4]
174         return struct.unpack('!I', s)[0]
175     
176     def exists(self, hash):
177         want = str(hash)
178         el = extract_bits(want, self.bits)
179         if el:
180             start = self._fanget(el-1)
181         else:
182             start = 0
183         end = self._fanget(el)
184         while start < end:
185             mid = start + (end-start)/2
186             v = str(self.shalist[mid*20:(mid+1)*20])
187             if v < want:
188                 start = mid+1
189             elif v > want:
190                 end = mid
191             else: # got it!
192                 return True
193         return None
194     
195     def __iter__(self):
196         for i in xrange(self._fanget(self.entries-1)):
197             yield buffer(self.shalist, i*20, 20)
198     
199     def __len__(self):
200         return int(self._fanget(self.entries-1))
201
202
203 _mpi_count = 0
204 class MultiPackIndex:
205     def __init__(self, dir):
206         global _mpi_count
207         assert(_mpi_count == 0)
208         _mpi_count += 1
209         self.dir = dir
210         self.also = {}
211         self.packs = []
212         self.refresh()
213
214     def __del__(self):
215         global _mpi_count
216         _mpi_count -= 1
217         assert(_mpi_count == 0)
218
219     def __iter__(self):
220         return iter(idxmerge(self.packs))
221
222     def exists(self, hash):
223         if hash in self.also:
224             return True
225         for i in range(len(self.packs)):
226             p = self.packs[i]
227             if p.exists(hash):
228                 # reorder so most recently used packs are searched first
229                 self.packs = [p] + self.packs[:i] + self.packs[i+1:]
230                 return p.name
231         return None
232
233     def refresh(self, skip_midx = False, forget_packs = False):
234         if forget_packs:
235             self.packs = []
236         skip_midx = skip_midx or ignore_midx
237         d = dict([(p.name, 1) for p in self.packs])
238         if os.path.exists(self.dir):
239             if not skip_midx:
240                 midxl = []
241                 for f in os.listdir(self.dir):
242                     full = os.path.join(self.dir, f)
243                     if f.endswith('.midx') and not d.get(full):
244                         midxl.append(PackMidx(full))
245                 midxl.sort(lambda x,y: -cmp(len(x),len(y)))
246                 for ix in midxl:
247                     any = 0
248                     for sub in ix.idxnames:
249                         if not d.get(os.path.join(self.dir, sub)):
250                             self.packs.append(ix)
251                             d[ix.name] = 1
252                             for name in ix.idxnames:
253                                 d[os.path.join(self.dir, name)] = 1
254                             break
255             for f in os.listdir(self.dir):
256                 full = os.path.join(self.dir, f)
257                 if f.endswith('.idx') and not d.get(full):
258                     self.packs.append(PackIndex(full))
259                     d[full] = 1
260         #log('MultiPackIndex: using %d packs.\n' % len(self.packs))
261
262     def add(self, hash):
263         self.also[hash] = 1
264
265     def zap_also(self):
266         self.also = {}
267
268
269 def calc_hash(type, content):
270     header = '%s %d\0' % (type, len(content))
271     sum = sha.sha(header)
272     sum.update(content)
273     return sum.digest()
274
275
276 def _shalist_sort_key(ent):
277     (mode, name, id) = ent
278     if stat.S_ISDIR(int(mode, 8)):
279         return name + '/'
280     else:
281         return name
282
283
284 def idxmerge(idxlist):
285     total = sum([len(i) for i in idxlist])
286     iters = [iter(i) for i in idxlist]
287     heap = [(next(it), it) for it in iters]
288     heapq.heapify(heap)
289     count = 0
290     while heap:
291         if (count % 10024) == 0:
292             progress('Creating midx: %.2f%% (%d/%d)\r'
293                      % (count*100.0/total, count, total))
294         (e, it) = heap[0]
295         yield e
296         count += 1
297         e = next(it)
298         if e:
299             heapq.heapreplace(heap, (e, it))
300         else:
301             heapq.heappop(heap)
302     log('Creating midx: %.2f%% (%d/%d), done.\n' % (100, total, total))
303
304     
305 class PackWriter:
306     def __init__(self, objcache_maker=None):
307         self.count = 0
308         self.outbytes = 0
309         self.filename = None
310         self.file = None
311         self.objcache_maker = objcache_maker
312         self.objcache = None
313
314     def __del__(self):
315         self.close()
316
317     def _make_objcache(self):
318         if not self.objcache:
319             if self.objcache_maker:
320                 self.objcache = self.objcache_maker()
321             else:
322                 self.objcache = MultiPackIndex(repo('objects/pack'))
323
324     def _open(self):
325         if not self.file:
326             self._make_objcache()
327             (fd,name) = tempfile.mkstemp(suffix='.pack', dir=repo('objects'))
328             self.file = os.fdopen(fd, 'w+b')
329             assert(name.endswith('.pack'))
330             self.filename = name[:-5]
331             self.file.write('PACK\0\0\0\2\0\0\0\0')
332
333     def _raw_write(self, datalist):
334         self._open()
335         f = self.file
336         for d in datalist:
337             f.write(d)
338             self.outbytes += len(d)
339         self.count += 1
340
341     def _write(self, bin, type, content):
342         if verbose:
343             log('>')
344         self._raw_write(_encode_packobj(type, content))
345         return bin
346
347     def breakpoint(self):
348         id = self._end()
349         self.outbytes = self.count = 0
350         return id
351
352     def write(self, type, content):
353         return self._write(calc_hash(type, content), type, content)
354
355     def exists(self, id):
356         if not self.objcache:
357             self._make_objcache()
358         return self.objcache.exists(id)
359
360     def maybe_write(self, type, content):
361         bin = calc_hash(type, content)
362         if not self.exists(bin):
363             self._write(bin, type, content)
364             self.objcache.add(bin)
365         return bin
366
367     def new_blob(self, blob):
368         return self.maybe_write('blob', blob)
369
370     def new_tree(self, shalist):
371         shalist = sorted(shalist, key = _shalist_sort_key)
372         l = []
373         for (mode,name,bin) in shalist:
374             assert(mode)
375             assert(mode[0] != '0')
376             assert(name)
377             assert(len(bin) == 20)
378             l.append('%s %s\0%s' % (mode,name,bin))
379         return self.maybe_write('tree', ''.join(l))
380
381     def _new_commit(self, tree, parent, author, adate, committer, cdate, msg):
382         l = []
383         if tree: l.append('tree %s' % tree.encode('hex'))
384         if parent: l.append('parent %s' % parent.encode('hex'))
385         if author: l.append('author %s %s' % (author, _git_date(adate)))
386         if committer: l.append('committer %s %s' % (committer, _git_date(cdate)))
387         l.append('')
388         l.append(msg)
389         return self.maybe_write('commit', '\n'.join(l))
390
391     def new_commit(self, parent, tree, msg):
392         now = time.time()
393         userline = '%s <%s@%s>' % (userfullname(), username(), hostname())
394         commit = self._new_commit(tree, parent,
395                                   userline, now, userline, now,
396                                   msg)
397         return commit
398
399     def abort(self):
400         f = self.file
401         if f:
402             self.file = None
403             f.close()
404             os.unlink(self.filename + '.pack')
405
406     def _end(self):
407         f = self.file
408         if not f: return None
409         self.file = None
410         self.objcache = None
411
412         # update object count
413         f.seek(8)
414         cp = struct.pack('!i', self.count)
415         assert(len(cp) == 4)
416         f.write(cp)
417
418         # calculate the pack sha1sum
419         f.seek(0)
420         sum = sha.sha()
421         while 1:
422             b = f.read(65536)
423             sum.update(b)
424             if not b: break
425         f.write(sum.digest())
426         
427         f.close()
428
429         p = subprocess.Popen(['git', 'index-pack', '-v',
430                               '--index-version=2',
431                               self.filename + '.pack'],
432                              preexec_fn = _gitenv,
433                              stdout = subprocess.PIPE)
434         out = p.stdout.read().strip()
435         _git_wait('git index-pack', p)
436         if not out:
437             raise GitError('git index-pack produced no output')
438         nameprefix = repo('objects/pack/%s' % out)
439         if os.path.exists(self.filename + '.map'):
440             os.unlink(self.filename + '.map')
441         os.rename(self.filename + '.pack', nameprefix + '.pack')
442         os.rename(self.filename + '.idx', nameprefix + '.idx')
443         return nameprefix
444
445     def close(self):
446         return self._end()
447
448
449 def _git_date(date):
450     return time.strftime('%s %z', time.localtime(date))
451
452
453 def _gitenv():
454     os.environ['GIT_DIR'] = os.path.abspath(repo())
455
456
457 def list_refs(refname = None):
458     argv = ['git', 'show-ref', '--']
459     if refname:
460         argv += [refname]
461     p = subprocess.Popen(argv, preexec_fn = _gitenv, stdout = subprocess.PIPE)
462     out = p.stdout.read().strip()
463     rv = p.wait()  # not fatal
464     if rv:
465         assert(not out)
466     if out:
467         for d in out.split('\n'):
468             (sha, name) = d.split(' ', 1)
469             yield (name, sha.decode('hex'))
470
471
472 def read_ref(refname):
473     l = list(list_refs(refname))
474     if l:
475         assert(len(l) == 1)
476         return l[0][1]
477     else:
478         return None
479
480
481 def rev_list(ref):
482     assert(not ref.startswith('-'))
483     argv = ['git', 'rev-list', '--pretty=format:%ct', ref, '--']
484     p = subprocess.Popen(argv, preexec_fn = _gitenv, stdout = subprocess.PIPE)
485     commit = None
486     for row in p.stdout:
487         s = row.strip()
488         if s.startswith('commit '):
489             commit = s[7:].decode('hex')
490         else:
491             date = int(s)
492             yield (date, commit)
493     rv = p.wait()  # not fatal
494     if rv:
495         raise GitError, 'git rev-list returned error %d' % rv
496
497
498 def update_ref(refname, newval, oldval):
499     if not oldval:
500         oldval = ''
501     assert(refname.startswith('refs/heads/'))
502     p = subprocess.Popen(['git', 'update-ref', refname,
503                           newval.encode('hex'), oldval.encode('hex')],
504                          preexec_fn = _gitenv)
505     _git_wait('git update-ref', p)
506
507
508 def guess_repo(path=None):
509     global repodir
510     if path:
511         repodir = path
512     if not repodir:
513         repodir = os.environ.get('BUP_DIR')
514         if not repodir:
515             repodir = os.path.expanduser('~/.bup')
516
517
518 def init_repo(path=None):
519     guess_repo(path)
520     d = repo()
521     if os.path.exists(d) and not os.path.isdir(os.path.join(d, '.')):
522         raise GitError('"%d" exists but is not a directory\n' % d)
523     p = subprocess.Popen(['git', '--bare', 'init'], stdout=sys.stderr,
524                          preexec_fn = _gitenv)
525     _git_wait('git init', p)
526     p = subprocess.Popen(['git', 'config', 'pack.indexVersion', '2'],
527                          stdout=sys.stderr, preexec_fn = _gitenv)
528     _git_wait('git config', p)
529
530
531 def check_repo_or_die(path=None):
532     guess_repo(path)
533     if not os.path.isdir(repo('objects/pack/.')):
534         if repodir == home_repodir:
535             init_repo()
536         else:
537             log('error: %r is not a bup/git repository\n' % repo())
538             sys.exit(15)
539
540
541 def _treeparse(buf):
542     ofs = 0
543     while ofs < len(buf):
544         z = buf[ofs:].find('\0')
545         assert(z > 0)
546         spl = buf[ofs:ofs+z].split(' ', 1)
547         assert(len(spl) == 2)
548         sha = buf[ofs+z+1:ofs+z+1+20]
549         ofs += z+1+20
550         yield (spl[0], spl[1], sha)
551
552
553 _ver = None
554 def ver():
555     global _ver
556     if not _ver:
557         p = subprocess.Popen(['git', '--version'],
558                              stdout=subprocess.PIPE)
559         gvs = p.stdout.read()
560         _git_wait('git --version', p)
561         m = re.match(r'git version (\S+.\S+)', gvs)
562         if not m:
563             raise GitError('git --version weird output: %r' % gvs)
564         _ver = tuple(m.group(1).split('.'))
565     needed = ('1','5', '3', '1')
566     if _ver < needed:
567         raise GitError('git version %s or higher is required; you have %s'
568                        % ('.'.join(needed), '.'.join(_ver)))
569     return _ver
570
571
572 def _git_wait(cmd, p):
573     rv = p.wait()
574     if rv != 0:
575         raise GitError('%s returned %d' % (cmd, rv))
576
577
578 def _git_capture(argv):
579     p = subprocess.Popen(argv, stdout=subprocess.PIPE, preexec_fn = _gitenv)
580     r = p.stdout.read()
581     _git_wait(repr(argv), p)
582     return r
583
584
585 _ver_warned = 0
586 class CatPipe:
587     def __init__(self):
588         global _ver_warned
589         wanted = ('1','5','6')
590         if ver() < wanted:
591             if not _ver_warned:
592                 log('warning: git version < %s; bup will be slow.\n'
593                     % '.'.join(wanted))
594                 _ver_warned = 1
595             self.get = self._slow_get
596         else:
597             self.p = subprocess.Popen(['git', 'cat-file', '--batch'],
598                                       stdin=subprocess.PIPE, 
599                                       stdout=subprocess.PIPE,
600                                       preexec_fn = _gitenv)
601             self.get = self._fast_get
602
603     def _fast_get(self, id):
604         assert(id.find('\n') < 0)
605         assert(id.find('\r') < 0)
606         assert(id[0] != '-')
607         self.p.stdin.write('%s\n' % id)
608         hdr = self.p.stdout.readline()
609         if hdr.endswith(' missing\n'):
610             raise KeyError('blob %r is missing' % id)
611         spl = hdr.split(' ')
612         if len(spl) != 3 or len(spl[0]) != 40:
613             raise GitError('expected blob, got %r' % spl)
614         (hex, type, size) = spl
615         it = iter(chunkyreader(self.p.stdout, int(spl[2])))
616         try:
617             yield type
618             for blob in it:
619                 yield blob
620         except StopIteration:
621             while 1:
622                 it.next()
623         assert(self.p.stdout.readline() == '\n')
624
625     def _slow_get(self, id):
626         assert(id.find('\n') < 0)
627         assert(id.find('\r') < 0)
628         assert(id[0] != '-')
629         type = _git_capture(['git', 'cat-file', '-t', id]).strip()
630         yield type
631
632         p = subprocess.Popen(['git', 'cat-file', type, id],
633                              stdout=subprocess.PIPE,
634                              preexec_fn = _gitenv)
635         for blob in chunkyreader(p.stdout):
636             yield blob
637         _git_wait('git cat-file', p)
638
639     def _join(self, it):
640         type = it.next()
641         if type == 'blob':
642             for blob in it:
643                 yield blob
644         elif type == 'tree':
645             treefile = ''.join(it)
646             for (mode, name, sha) in _treeparse(treefile):
647                 for blob in self.join(sha.encode('hex')):
648                     yield blob
649         elif type == 'commit':
650             treeline = ''.join(it).split('\n')[0]
651             assert(treeline.startswith('tree '))
652             for blob in self.join(treeline[5:]):
653                 yield blob
654         else:
655             raise GitError('invalid object type %r: expected blob/tree/commit'
656                            % type)
657
658     def join(self, id):
659         for d in self._join(self.get(id)):
660             yield d
661         
662
663 def cat(id):
664     c = CatPipe()
665     for d in c.join(id):
666         yield d