1 import os, errno, zlib, time, sha, subprocess, struct, stat, re, tempfile
7 home_repodir = os.path.expanduser('~/.bup')
10 _typemap = { 'blob':3, 'tree':2, 'commit':1, 'tag':4 }
11 _typermap = { 3:'blob', 2:'tree', 1:'commit', 4:'tag' }
14 class GitError(Exception):
21 raise GitError('You should call check_repo_or_die()')
22 gd = os.path.join(repodir, '.git')
23 if os.path.exists(gd):
25 return os.path.join(repodir, sub)
28 def _encode_packobj(type, content):
31 szbits = (sz & 0x0f) | (_typemap[type]<<4)
40 z = zlib.compressobj(1)
42 yield z.compress(content)
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)
53 def _decode_looseobj(buf):
55 s = zlib.decompress(buf)
62 assert(type in _typemap)
63 assert(sz == len(content))
64 return (type, content)
67 def _decode_packobj(buf):
70 type = _typermap[(c & 0x70) >> 4]
77 sz |= (c & 0x7f) << shift
81 return (type, zlib.decompress(buf[i+1:]))
85 def __init__(self, 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,
96 self.ofs64table = buffer(self.map,
97 8 + 256*4 + nsha*20 + nsha*4 + nsha*4)
99 def _ofs_from_idx(self, idx):
100 ofs = struct.unpack('!I', str(buffer(self.ofstable, idx*4, 4)))[0]
102 idx64 = ofs & 0x7fffffff
103 ofs = struct.unpack('!I',
104 str(buffer(self.ofs64table, idx64*8, 8)))[0]
107 def _idx_from_hash(self, hash):
108 assert(len(hash) == 20)
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)
115 mid = start + (end-start)/2
116 v = str(buf[mid*20:(mid+1)*20])
125 def find_offset(self, hash):
126 idx = self._idx_from_hash(hash)
128 return self._ofs_from_idx(idx)
131 def exists(self, hash):
132 return hash and (self._idx_from_hash(hash) != None) and True or None
135 for i in xrange(self.fanout[255]):
136 yield buffer(self.map, 8 + 256*4 + 20*i, 20)
139 return int(self.fanout[255])
142 def extract_bits(buf, bits):
144 v = struct.unpack('!I', buf[0:4])[0]
145 v = (v >> (32-bits)) & mask
150 def __init__(self, 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)
158 self.fanout = buffer('\0\0\0\0')
159 self.shalist = buffer('\0'*20)
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')
171 def _fanget(self, i):
173 s = self.fanout[start:start+4]
174 return struct.unpack('!I', s)[0]
176 def exists(self, hash):
178 el = extract_bits(want, self.bits)
180 start = self._fanget(el-1)
183 end = self._fanget(el)
185 mid = start + (end-start)/2
186 v = str(self.shalist[mid*20:(mid+1)*20])
196 for i in xrange(self._fanget(self.entries-1)):
197 yield buffer(self.shalist, i*20, 20)
200 return int(self._fanget(self.entries-1))
204 class MultiPackIndex:
205 def __init__(self, dir):
207 assert(_mpi_count == 0)
217 assert(_mpi_count == 0)
220 return iter(idxmerge(self.packs))
222 def exists(self, hash):
223 if hash in self.also:
225 for i in range(len(self.packs)):
228 # reorder so most recently used packs are searched first
229 self.packs = [p] + self.packs[:i] + self.packs[i+1:]
233 def refresh(self, skip_midx = False, forget_packs = False):
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):
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)))
248 for sub in ix.idxnames:
249 if not d.get(os.path.join(self.dir, sub)):
250 self.packs.append(ix)
252 for name in ix.idxnames:
253 d[os.path.join(self.dir, name)] = 1
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))
260 #log('MultiPackIndex: using %d packs.\n' % len(self.packs))
269 def calc_hash(type, content):
270 header = '%s %d\0' % (type, len(content))
271 sum = sha.sha(header)
276 def _shalist_sort_key(ent):
277 (mode, name, id) = ent
278 if stat.S_ISDIR(int(mode, 8)):
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]
291 if (count % 10024) == 0:
292 progress('Creating midx: %.2f%% (%d/%d)\r'
293 % (count*100.0/total, count, total))
299 heapq.heapreplace(heap, (e, it))
302 log('Creating midx: %.2f%% (%d/%d), done.\n' % (100, total, total))
306 def __init__(self, objcache_maker=None):
311 self.objcache_maker = objcache_maker
317 def _make_objcache(self):
318 if not self.objcache:
319 if self.objcache_maker:
320 self.objcache = self.objcache_maker()
322 self.objcache = MultiPackIndex(repo('objects/pack'))
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')
333 def _raw_write(self, datalist):
338 self.outbytes += len(d)
341 def _write(self, bin, type, content):
344 self._raw_write(_encode_packobj(type, content))
347 def breakpoint(self):
349 self.outbytes = self.count = 0
352 def write(self, type, content):
353 return self._write(calc_hash(type, content), type, content)
355 def exists(self, id):
356 if not self.objcache:
357 self._make_objcache()
358 return self.objcache.exists(id)
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)
367 def new_blob(self, blob):
368 return self.maybe_write('blob', blob)
370 def new_tree(self, shalist):
371 shalist = sorted(shalist, key = _shalist_sort_key)
373 for (mode,name,bin) in shalist:
375 assert(mode[0] != '0')
377 assert(len(bin) == 20)
378 l.append('%s %s\0%s' % (mode,name,bin))
379 return self.maybe_write('tree', ''.join(l))
381 def _new_commit(self, tree, parent, author, adate, committer, cdate, msg):
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)))
389 return self.maybe_write('commit', '\n'.join(l))
391 def new_commit(self, parent, tree, msg):
393 userline = '%s <%s@%s>' % (userfullname(), username(), hostname())
394 commit = self._new_commit(tree, parent,
395 userline, now, userline, now,
404 os.unlink(self.filename + '.pack')
408 if not f: return None
412 # update object count
414 cp = struct.pack('!i', self.count)
418 # calculate the pack sha1sum
425 f.write(sum.digest())
429 p = subprocess.Popen(['git', 'index-pack', '-v',
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)
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')
450 return time.strftime('%s %z', time.localtime(date))
454 os.environ['GIT_DIR'] = os.path.abspath(repo())
457 def list_refs(refname = None):
458 argv = ['git', 'show-ref', '--']
461 p = subprocess.Popen(argv, preexec_fn = _gitenv, stdout = subprocess.PIPE)
462 out = p.stdout.read().strip()
463 rv = p.wait() # not fatal
467 for d in out.split('\n'):
468 (sha, name) = d.split(' ', 1)
469 yield (name, sha.decode('hex'))
472 def read_ref(refname):
473 l = list(list_refs(refname))
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)
488 if s.startswith('commit '):
489 commit = s[7:].decode('hex')
493 rv = p.wait() # not fatal
495 raise GitError, 'git rev-list returned error %d' % rv
498 def update_ref(refname, newval, 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)
508 def guess_repo(path=None):
513 repodir = os.environ.get('BUP_DIR')
515 repodir = os.path.expanduser('~/.bup')
518 def init_repo(path=None):
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)
531 def check_repo_or_die(path=None):
533 if not os.path.isdir(repo('objects/pack/.')):
534 if repodir == home_repodir:
537 log('error: %r is not a bup/git repository\n' % repo())
543 while ofs < len(buf):
544 z = buf[ofs:].find('\0')
546 spl = buf[ofs:ofs+z].split(' ', 1)
547 assert(len(spl) == 2)
548 sha = buf[ofs+z+1:ofs+z+1+20]
550 yield (spl[0], spl[1], sha)
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)
563 raise GitError('git --version weird output: %r' % gvs)
564 _ver = tuple(m.group(1).split('.'))
565 needed = ('1','5', '3', '1')
567 raise GitError('git version %s or higher is required; you have %s'
568 % ('.'.join(needed), '.'.join(_ver)))
572 def _git_wait(cmd, p):
575 raise GitError('%s returned %d' % (cmd, rv))
578 def _git_capture(argv):
579 p = subprocess.Popen(argv, stdout=subprocess.PIPE, preexec_fn = _gitenv)
581 _git_wait(repr(argv), p)
589 wanted = ('1','5','6')
592 log('warning: git version < %s; bup will be slow.\n'
595 self.get = self._slow_get
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
603 def _fast_get(self, id):
604 assert(id.find('\n') < 0)
605 assert(id.find('\r') < 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)
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])))
620 except StopIteration:
623 assert(self.p.stdout.readline() == '\n')
625 def _slow_get(self, id):
626 assert(id.find('\n') < 0)
627 assert(id.find('\r') < 0)
629 type = _git_capture(['git', 'cat-file', '-t', id]).strip()
632 p = subprocess.Popen(['git', 'cat-file', type, id],
633 stdout=subprocess.PIPE,
634 preexec_fn = _gitenv)
635 for blob in chunkyreader(p.stdout):
637 _git_wait('git cat-file', p)
645 treefile = ''.join(it)
646 for (mode, name, sha) in _treeparse(treefile):
647 for blob in self.join(sha.encode('hex')):
649 elif type == 'commit':
650 treeline = ''.join(it).split('\n')[0]
651 assert(treeline.startswith('tree '))
652 for blob in self.join(treeline[5:]):
655 raise GitError('invalid object type %r: expected blob/tree/commit'
659 for d in self._join(self.get(id)):