1 import os, errno, zlib, time, sha, subprocess, struct, stat, re, tempfile
3 from bup.helpers import *
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))
205 def __init__(self, dir):
207 assert(_mpi_count == 0) # these things suck tons of VM; don't waste it
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):
245 (mxd, mxf) = os.path.split(mx.name)
247 for n in mx.idxnames:
248 if not os.path.exists(os.path.join(mxd, n)):
249 log(('warning: index %s missing\n' +
250 ' used by %s\n') % (n, mxf))
254 midxl.sort(lambda x,y: -cmp(len(x),len(y)))
257 for sub in ix.idxnames:
258 if not d.get(os.path.join(self.dir, sub)):
259 self.packs.append(ix)
261 for name in ix.idxnames:
262 d[os.path.join(self.dir, name)] = 1
266 log('midx: removing redundant: %s\n'
267 % os.path.basename(ix.name))
269 for f in os.listdir(self.dir):
270 full = os.path.join(self.dir, f)
271 if f.endswith('.idx') and not d.get(full):
272 self.packs.append(PackIdx(full))
274 log('PackIdxList: using %d index%s.\n'
275 % (len(self.packs), len(self.packs)!=1 and 'es' or ''))
284 def calc_hash(type, content):
285 header = '%s %d\0' % (type, len(content))
286 sum = sha.sha(header)
291 def _shalist_sort_key(ent):
292 (mode, name, id) = ent
293 if stat.S_ISDIR(int(mode, 8)):
299 def idxmerge(idxlist):
300 total = sum(len(i) for i in idxlist)
301 iters = (iter(i) for i in idxlist)
302 heap = [(next(it), it) for it in iters]
307 if (count % 10024) == 0:
308 progress('Reading indexes: %.2f%% (%d/%d)\r'
309 % (count*100.0/total, count, total))
317 heapq.heapreplace(heap, (e, it))
320 log('Reading indexes: %.2f%% (%d/%d), done.\n' % (100, total, total))
324 def __init__(self, objcache_maker=None):
329 self.objcache_maker = objcache_maker
335 def _make_objcache(self):
336 if not self.objcache:
337 if self.objcache_maker:
338 self.objcache = self.objcache_maker()
340 self.objcache = PackIdxList(repo('objects/pack'))
344 self._make_objcache()
345 (fd,name) = tempfile.mkstemp(suffix='.pack', dir=repo('objects'))
346 self.file = os.fdopen(fd, 'w+b')
347 assert(name.endswith('.pack'))
348 self.filename = name[:-5]
349 self.file.write('PACK\0\0\0\2\0\0\0\0')
351 def _raw_write(self, datalist):
354 # in case we get interrupted (eg. KeyboardInterrupt), it's best if
355 # the file never has a *partial* blob. So let's make sure it's
356 # all-or-nothing. (The blob shouldn't be very big anyway, thanks
357 # to our hashsplit algorithm.) f.write() does its own buffering,
358 # but that's okay because we'll flush it in _end().
359 oneblob = ''.join(datalist)
361 self.outbytes += len(oneblob)
364 def _write(self, bin, type, content):
367 self._raw_write(_encode_packobj(type, content))
370 def breakpoint(self):
372 self.outbytes = self.count = 0
375 def write(self, type, content):
376 return self._write(calc_hash(type, content), type, content)
378 def exists(self, id):
379 if not self.objcache:
380 self._make_objcache()
381 return self.objcache.exists(id)
383 def maybe_write(self, type, content):
384 bin = calc_hash(type, content)
385 if not self.exists(bin):
386 self._write(bin, type, content)
387 self.objcache.add(bin)
390 def new_blob(self, blob):
391 return self.maybe_write('blob', blob)
393 def new_tree(self, shalist):
394 shalist = sorted(shalist, key = _shalist_sort_key)
396 for (mode,name,bin) in shalist:
399 assert(mode[0] != '0')
401 assert(len(bin) == 20)
402 l.append('%s %s\0%s' % (mode,name,bin))
403 return self.maybe_write('tree', ''.join(l))
405 def _new_commit(self, tree, parent, author, adate, committer, cdate, msg):
407 if tree: l.append('tree %s' % tree.encode('hex'))
408 if parent: l.append('parent %s' % parent.encode('hex'))
409 if author: l.append('author %s %s' % (author, _git_date(adate)))
410 if committer: l.append('committer %s %s' % (committer, _git_date(cdate)))
413 return self.maybe_write('commit', '\n'.join(l))
415 def new_commit(self, parent, tree, msg):
417 userline = '%s <%s@%s>' % (userfullname(), username(), hostname())
418 commit = self._new_commit(tree, parent,
419 userline, now, userline, now,
428 os.unlink(self.filename + '.pack')
432 if not f: return None
436 # update object count
438 cp = struct.pack('!i', self.count)
442 # calculate the pack sha1sum
449 f.write(sum.digest())
453 p = subprocess.Popen(['git', 'index-pack', '-v',
455 self.filename + '.pack'],
456 preexec_fn = _gitenv,
457 stdout = subprocess.PIPE)
458 out = p.stdout.read().strip()
459 _git_wait('git index-pack', p)
461 raise GitError('git index-pack produced no output')
462 nameprefix = repo('objects/pack/%s' % out)
463 if os.path.exists(self.filename + '.map'):
464 os.unlink(self.filename + '.map')
465 os.rename(self.filename + '.pack', nameprefix + '.pack')
466 os.rename(self.filename + '.idx', nameprefix + '.idx')
474 return time.strftime('%s %z', time.localtime(date))
478 os.environ['GIT_DIR'] = os.path.abspath(repo())
481 def list_refs(refname = None):
482 argv = ['git', 'show-ref', '--']
485 p = subprocess.Popen(argv, preexec_fn = _gitenv, stdout = subprocess.PIPE)
486 out = p.stdout.read().strip()
487 rv = p.wait() # not fatal
491 for d in out.split('\n'):
492 (sha, name) = d.split(' ', 1)
493 yield (name, sha.decode('hex'))
496 def read_ref(refname):
497 l = list(list_refs(refname))
505 def rev_list(ref, count=None):
506 assert(not ref.startswith('-'))
509 opts += ['-n', str(atoi(count))]
510 argv = ['git', 'rev-list', '--pretty=format:%ct'] + opts + [ref, '--']
511 p = subprocess.Popen(argv, preexec_fn = _gitenv, stdout = subprocess.PIPE)
515 if s.startswith('commit '):
516 commit = s[7:].decode('hex')
520 rv = p.wait() # not fatal
522 raise GitError, 'git rev-list returned error %d' % rv
525 def rev_get_date(ref):
526 for (date, commit) in rev_list(ref, count=1):
528 raise GitError, 'no such commit %r' % ref
531 def update_ref(refname, newval, oldval):
534 assert(refname.startswith('refs/heads/'))
535 p = subprocess.Popen(['git', 'update-ref', refname,
536 newval.encode('hex'), oldval.encode('hex')],
537 preexec_fn = _gitenv)
538 _git_wait('git update-ref', p)
541 def guess_repo(path=None):
546 repodir = os.environ.get('BUP_DIR')
548 repodir = os.path.expanduser('~/.bup')
551 def init_repo(path=None):
554 if os.path.exists(d) and not os.path.isdir(os.path.join(d, '.')):
555 raise GitError('"%d" exists but is not a directory\n' % d)
556 p = subprocess.Popen(['git', '--bare', 'init'], stdout=sys.stderr,
557 preexec_fn = _gitenv)
558 _git_wait('git init', p)
559 p = subprocess.Popen(['git', 'config', 'pack.indexVersion', '2'],
560 stdout=sys.stderr, preexec_fn = _gitenv)
561 _git_wait('git config', p)
564 def check_repo_or_die(path=None):
566 if not os.path.isdir(repo('objects/pack/.')):
567 if repodir == home_repodir:
570 log('error: %r is not a bup/git repository\n' % repo())
576 while ofs < len(buf):
577 z = buf[ofs:].find('\0')
579 spl = buf[ofs:ofs+z].split(' ', 1)
580 assert(len(spl) == 2)
581 sha = buf[ofs+z+1:ofs+z+1+20]
583 yield (spl[0], spl[1], sha)
590 p = subprocess.Popen(['git', '--version'],
591 stdout=subprocess.PIPE)
592 gvs = p.stdout.read()
593 _git_wait('git --version', p)
594 m = re.match(r'git version (\S+.\S+)', gvs)
596 raise GitError('git --version weird output: %r' % gvs)
597 _ver = tuple(m.group(1).split('.'))
598 needed = ('1','5', '3', '1')
600 raise GitError('git version %s or higher is required; you have %s'
601 % ('.'.join(needed), '.'.join(_ver)))
605 def _git_wait(cmd, p):
608 raise GitError('%s returned %d' % (cmd, rv))
611 def _git_capture(argv):
612 p = subprocess.Popen(argv, stdout=subprocess.PIPE, preexec_fn = _gitenv)
614 _git_wait(repr(argv), p)
622 wanted = ('1','5','6')
625 log('warning: git version < %s; bup will be slow.\n'
628 self.get = self._slow_get
630 self.p = subprocess.Popen(['git', 'cat-file', '--batch'],
631 stdin=subprocess.PIPE,
632 stdout=subprocess.PIPE,
633 preexec_fn = _gitenv)
634 self.get = self._fast_get
635 self.inprogress = None
637 def _fast_get(self, id):
639 log('_fast_get: opening %r while %r is open'
640 % (id, self.inprogress))
641 assert(not self.inprogress)
642 assert(id.find('\n') < 0)
643 assert(id.find('\r') < 0)
646 self.p.stdin.write('%s\n' % id)
647 hdr = self.p.stdout.readline()
648 if hdr.endswith(' missing\n'):
649 raise KeyError('blob %r is missing' % id)
651 if len(spl) != 3 or len(spl[0]) != 40:
652 raise GitError('expected blob, got %r' % spl)
653 (hex, type, size) = spl
656 assert(self.p.stdout.readline() == '\n')
657 self.inprogress = None
659 it = AutoFlushIter(chunkyreader(self.p.stdout, int(spl[2])),
666 def _slow_get(self, id):
667 assert(id.find('\n') < 0)
668 assert(id.find('\r') < 0)
670 type = _git_capture(['git', 'cat-file', '-t', id]).strip()
673 p = subprocess.Popen(['git', 'cat-file', type, id],
674 stdout=subprocess.PIPE,
675 preexec_fn = _gitenv)
676 for blob in chunkyreader(p.stdout):
678 _git_wait('git cat-file', p)
686 treefile = ''.join(it)
687 for (mode, name, sha) in _treeparse(treefile):
688 for blob in self.join(sha.encode('hex')):
690 elif type == 'commit':
691 treeline = ''.join(it).split('\n')[0]
692 assert(treeline.startswith('tree '))
693 for blob in self.join(treeline[5:]):
696 raise GitError('invalid object type %r: expected blob/tree/commit'
701 for d in self._join(self.get(id)):
703 except StopIteration: