1 import os, errno, zlib, time, sha, subprocess, struct, stat, re
6 home_repodir = os.path.expanduser('~/.bup')
9 _typemap = { 'blob':3, 'tree':2, 'commit':1, 'tag':4 }
10 _typermap = { 3:'blob', 2:'tree', 1:'commit', 4:'tag' }
13 class GitError(Exception):
20 raise GitError('You should call check_repo_or_die()')
21 gd = os.path.join(repodir, '.git')
22 if os.path.exists(gd):
24 return os.path.join(repodir, sub)
27 def _encode_packobj(type, content):
30 szbits = (sz & 0x0f) | (_typemap[type]<<4)
39 z = zlib.compressobj(1)
41 yield z.compress(content)
45 def _encode_looseobj(type, content):
46 z = zlib.compressobj(1)
47 yield z.compress('%s %d\0' % (type, len(content)))
48 yield z.compress(content)
52 def _decode_looseobj(buf):
54 s = zlib.decompress(buf)
61 assert(type in _typemap)
62 assert(sz == len(content))
63 return (type, content)
66 def _decode_packobj(buf):
69 type = _typermap[(c & 0x70) >> 4]
76 sz |= (c & 0x7f) << shift
80 return (type, zlib.decompress(buf[i+1:]))
84 def __init__(self, filename):
86 self.map = mmap_read(open(filename))
87 assert(str(self.map[0:8]) == '\377tOc\0\0\0\2')
88 self.fanout = list(struct.unpack('!256I',
89 str(buffer(self.map, 8, 256*4))))
90 self.fanout.append(0) # entry "-1"
91 nsha = self.fanout[255]
92 self.ofstable = buffer(self.map,
93 8 + 256*4 + nsha*20 + nsha*4,
95 self.ofs64table = buffer(self.map,
96 8 + 256*4 + nsha*20 + nsha*4 + nsha*4)
98 def _ofs_from_idx(self, idx):
99 ofs = struct.unpack('!I', str(buffer(self.ofstable, idx*4, 4)))[0]
101 idx64 = ofs & 0x7fffffff
102 ofs = struct.unpack('!I',
103 str(buffer(self.ofs64table, idx64*8, 8)))[0]
106 def _idx_from_hash(self, hash):
107 assert(len(hash) == 20)
109 start = self.fanout[b1-1] # range -1..254
110 end = self.fanout[b1] # range 0..255
111 buf = buffer(self.map, 8 + 256*4, end*20)
114 mid = start + (end-start)/2
115 v = str(buf[mid*20:(mid+1)*20])
124 def find_offset(self, hash):
125 idx = self._idx_from_hash(hash)
127 return self._ofs_from_idx(idx)
130 def exists(self, hash):
131 return hash and (self._idx_from_hash(hash) != None) and True or None
134 for i in xrange(self.fanout[255]):
135 yield buffer(self.map, 8 + 256*4 + 20*i, 20)
138 return self.fanout[255]
141 def extract_bits(buf, bits):
143 v = struct.unpack('!Q', buf[0:8])[0]
144 v = (v >> (64-bits)) & mask
149 def __init__(self, filename):
151 assert(filename.endswith('.midx'))
152 self.map = mmap_read(open(filename))
153 assert(str(self.map[0:8]) == 'MIDX\0\0\0\1')
154 self.bits = struct.unpack('!I', self.map[8:12])[0]
155 self.entries = 2**self.bits
156 self.fanout = buffer(self.map, 12, self.entries*8)
157 shaofs = 12 + self.entries*8
158 nsha = self._fanget(self.entries-1)
159 self.shalist = buffer(self.map, shaofs, nsha*20)
160 self.idxnames = str(self.map[shaofs + 20*nsha:]).split('\0')
162 def _fanget(self, i):
164 s = self.fanout[start:start+8]
165 return struct.unpack('!Q', s)[0]
167 def exists(self, hash):
169 el = extract_bits(want, self.bits)
171 start = self._fanget(el-1)
174 end = self._fanget(el)
176 mid = start + (end-start)/2
177 v = str(self.shalist[mid*20:(mid+1)*20])
187 for i in xrange(self._fanget(self.entries-1)):
188 yield buffer(self.shalist, i*20, 20)
191 return self._fanget(self.entries-1)
195 class MultiPackIndex:
196 def __init__(self, dir):
198 assert(_mpi_count == 0)
208 assert(_mpi_count == 0)
210 def exists(self, hash):
211 if hash in self.also:
213 for i in range(len(self.packs)):
216 # reorder so most recently used packs are searched first
217 self.packs = [p] + self.packs[:i] + self.packs[i+1:]
223 d = dict([(p.name, 1) for p in self.packs])
224 if os.path.exists(self.dir):
227 for f in os.listdir(self.dir):
228 full = os.path.join(self.dir, f)
229 if f.endswith('.midx') and not d.get(full):
230 midxl.append(PackMidx(full))
231 midxl.sort(lambda x,y: -cmp(len(x),len(y)))
234 for sub in ix.idxnames:
235 if not d.get(os.path.join(self.dir, sub)):
236 self.packs.append(ix)
238 for name in ix.idxnames:
239 d[os.path.join(self.dir, name)] = 1
241 for f in os.listdir(self.dir):
242 full = os.path.join(self.dir, f)
243 if f.endswith('.idx') and not d.get(full):
244 self.packs.append(PackIndex(full))
246 #log('MultiPackIndex: using %d packs.\n' % len(self.packs))
255 def calc_hash(type, content):
256 header = '%s %d\0' % (type, len(content))
257 sum = sha.sha(header)
262 def _shalist_sort_key(ent):
263 (mode, name, id) = ent
264 if stat.S_ISDIR(int(mode, 8)):
271 def __init__(self, objcache_maker=None):
276 self.objcache_maker = objcache_maker
282 def _make_objcache(self):
283 if not self.objcache:
284 if self.objcache_maker:
285 self.objcache = self.objcache_maker()
287 self.objcache = MultiPackIndex(repo('objects/pack'))
291 self._make_objcache()
292 self.filename = repo('objects/bup%d' % os.getpid())
293 self.file = open(self.filename + '.pack', 'w+')
294 self.file.write('PACK\0\0\0\2\0\0\0\0')
296 def _raw_write(self, datalist):
301 self.outbytes += len(d)
304 def _write(self, bin, type, content):
307 self._raw_write(_encode_packobj(type, content))
310 def breakpoint(self):
312 self.outbytes = self.count = 0
315 def write(self, type, content):
316 return self._write(calc_hash(type, content), type, content)
318 def exists(self, id):
319 if not self.objcache:
320 self._make_objcache()
321 return self.objcache.exists(id)
323 def maybe_write(self, type, content):
324 bin = calc_hash(type, content)
325 if not self.exists(bin):
326 self._write(bin, type, content)
327 self.objcache.add(bin)
330 def new_blob(self, blob):
331 return self.maybe_write('blob', blob)
333 def new_tree(self, shalist):
334 shalist = sorted(shalist, key = _shalist_sort_key)
336 for (mode,name,bin) in shalist:
338 assert(mode[0] != '0')
340 assert(len(bin) == 20)
341 l.append('%s %s\0%s' % (mode,name,bin))
342 return self.maybe_write('tree', ''.join(l))
344 def _new_commit(self, tree, parent, author, adate, committer, cdate, msg):
346 if tree: l.append('tree %s' % tree.encode('hex'))
347 if parent: l.append('parent %s' % parent.encode('hex'))
348 if author: l.append('author %s %s' % (author, _git_date(adate)))
349 if committer: l.append('committer %s %s' % (committer, _git_date(cdate)))
352 return self.maybe_write('commit', '\n'.join(l))
354 def new_commit(self, parent, tree, msg):
356 userline = '%s <%s@%s>' % (userfullname(), username(), hostname())
357 commit = self._new_commit(tree, parent,
358 userline, now, userline, now,
367 os.unlink(self.filename + '.pack')
371 if not f: return None
375 # update object count
377 cp = struct.pack('!i', self.count)
381 # calculate the pack sha1sum
388 f.write(sum.digest())
392 p = subprocess.Popen(['git', 'index-pack', '-v',
394 self.filename + '.pack'],
395 preexec_fn = _gitenv,
396 stdout = subprocess.PIPE)
397 out = p.stdout.read().strip()
398 _git_wait('git index-pack', p)
400 raise GitError('git index-pack produced no output')
401 nameprefix = repo('objects/pack/%s' % out)
402 if os.path.exists(self.filename + '.map'):
403 os.unlink(self.filename + '.map')
404 os.rename(self.filename + '.pack', nameprefix + '.pack')
405 os.rename(self.filename + '.idx', nameprefix + '.idx')
413 return time.strftime('%s %z', time.localtime(date))
417 os.environ['GIT_DIR'] = os.path.abspath(repo())
420 def list_refs(refname = None):
421 argv = ['git', 'show-ref', '--']
424 p = subprocess.Popen(argv, preexec_fn = _gitenv, stdout = subprocess.PIPE)
425 out = p.stdout.read().strip()
426 rv = p.wait() # not fatal
430 for d in out.split('\n'):
431 (sha, name) = d.split(' ', 1)
432 yield (name, sha.decode('hex'))
435 def read_ref(refname):
436 l = list(list_refs(refname))
445 assert(not ref.startswith('-'))
446 argv = ['git', 'rev-list', '--pretty=format:%ct', ref, '--']
447 p = subprocess.Popen(argv, preexec_fn = _gitenv, stdout = subprocess.PIPE)
451 if s.startswith('commit '):
452 commit = s[7:].decode('hex')
456 rv = p.wait() # not fatal
458 raise GitError, 'git rev-list returned error %d' % rv
461 def update_ref(refname, newval, oldval):
464 assert(refname.startswith('refs/heads/'))
465 p = subprocess.Popen(['git', 'update-ref', refname,
466 newval.encode('hex'), oldval.encode('hex')],
467 preexec_fn = _gitenv)
468 _git_wait('git update-ref', p)
471 def guess_repo(path=None):
476 repodir = os.environ.get('BUP_DIR')
478 repodir = os.path.expanduser('~/.bup')
481 def init_repo(path=None):
484 if os.path.exists(d) and not os.path.isdir(os.path.join(d, '.')):
485 raise GitError('"%d" exists but is not a directory\n' % d)
486 p = subprocess.Popen(['git', '--bare', 'init'], stdout=sys.stderr,
487 preexec_fn = _gitenv)
488 _git_wait('git init', p)
489 p = subprocess.Popen(['git', 'config', 'pack.indexVersion', '2'],
490 stdout=sys.stderr, preexec_fn = _gitenv)
491 _git_wait('git config', p)
494 def check_repo_or_die(path=None):
496 if not os.path.isdir(repo('objects/pack/.')):
497 if repodir == home_repodir:
500 log('error: %r is not a bup/git repository\n' % repo())
506 while ofs < len(buf):
507 z = buf[ofs:].find('\0')
509 spl = buf[ofs:ofs+z].split(' ', 1)
510 assert(len(spl) == 2)
511 sha = buf[ofs+z+1:ofs+z+1+20]
513 yield (spl[0], spl[1], sha)
520 p = subprocess.Popen(['git', '--version'],
521 stdout=subprocess.PIPE)
522 gvs = p.stdout.read()
523 _git_wait('git --version', p)
524 m = re.match(r'git version (\S+.\S+)', gvs)
526 raise GitError('git --version weird output: %r' % gvs)
527 _ver = tuple(m.group(1).split('.'))
528 needed = ('1','5', '3', '1')
530 raise GitError('git version %s or higher is required; you have %s'
531 % ('.'.join(needed), '.'.join(_ver)))
535 def _git_wait(cmd, p):
538 raise GitError('%s returned %d' % (cmd, rv))
541 def _git_capture(argv):
542 p = subprocess.Popen(argv, stdout=subprocess.PIPE, preexec_fn = _gitenv)
544 _git_wait(repr(argv), p)
552 wanted = ('1','5','6')
555 log('warning: git version < %s; bup will be slow.\n'
558 self.get = self._slow_get
560 self.p = subprocess.Popen(['git', 'cat-file', '--batch'],
561 stdin=subprocess.PIPE,
562 stdout=subprocess.PIPE,
563 preexec_fn = _gitenv)
564 self.get = self._fast_get
566 def _fast_get(self, id):
567 assert(id.find('\n') < 0)
568 assert(id.find('\r') < 0)
570 self.p.stdin.write('%s\n' % id)
571 hdr = self.p.stdout.readline()
572 if hdr.endswith(' missing\n'):
573 raise KeyError('blob %r is missing' % id)
575 if len(spl) != 3 or len(spl[0]) != 40:
576 raise GitError('expected blob, got %r' % spl)
577 (hex, type, size) = spl
578 it = iter(chunkyreader(self.p.stdout, int(spl[2])))
587 except StopIteration:
589 assert(self.p.stdout.readline() == '\n')
591 def _slow_get(self, id):
592 assert(id.find('\n') < 0)
593 assert(id.find('\r') < 0)
595 type = _git_capture(['git', 'cat-file', '-t', id]).strip()
598 p = subprocess.Popen(['git', 'cat-file', type, id],
599 stdout=subprocess.PIPE,
600 preexec_fn = _gitenv)
601 for blob in chunkyreader(p.stdout):
603 _git_wait('git cat-file', p)
611 treefile = ''.join(it)
612 for (mode, name, sha) in _treeparse(treefile):
613 for blob in self.join(sha.encode('hex')):
615 elif type == 'commit':
616 treeline = ''.join(it).split('\n')[0]
617 assert(treeline.startswith('tree '))
618 for blob in self.join(treeline[5:]):
621 raise GitError('invalid object type %r: expected blob/tree/commit'
625 for d in self._join(self.get(id)):