1 import os, errno, zlib, time, sha, subprocess, struct, mmap, stat
5 repodir = os.environ.get('BUP_DIR', '.git')
9 gd = os.path.join(repodir, '.git')
10 if os.path.exists(gd):
12 return os.path.join(repodir, sub)
16 def __init__(self, filename):
19 self.map = mmap.mmap(f.fileno(), 0,
20 mmap.MAP_SHARED, mmap.PROT_READ)
21 f.close() # map will persist beyond file close
22 assert(str(self.map[0:8]) == '\377tOc\0\0\0\2')
23 self.fanout = list(struct.unpack('!256I', buffer(self.map, 8, 256*4)))
24 self.fanout.append(0) # entry "-1"
25 nsha = self.fanout[255]
26 self.ofstable = buffer(self.map,
27 8 + 256*4 + nsha*20 + nsha*4,
29 self.ofs64table = buffer(self.map,
30 8 + 256*4 + nsha*20 + nsha*4 + nsha*4)
32 def _ofs_from_idx(self, idx):
33 ofs = struct.unpack('!I', buffer(self.ofstable, idx*4, 4))[0]
35 idx64 = ofs & 0x7fffffff
36 ofs = struct.unpack('!I', buffer(self.ofs64table, idx64*8, 8))[0]
39 def _idx_from_hash(self, hash):
40 assert(len(hash) == 20)
42 start = self.fanout[b1-1] # range -1..254
43 end = self.fanout[b1] # range 0..255
44 buf = buffer(self.map, 8 + 256*4, end*20)
47 mid = start + (end-start)/2
48 v = buffer(buf, mid*20, 20)
57 def find_offset(self, hash):
58 idx = self._idx_from_hash(hash)
60 return self._ofs_from_idx(idx)
63 def exists(self, hash):
64 return (self._idx_from_hash(hash) != None) and True or None
68 def __init__(self, dir):
71 for f in os.listdir(dir):
72 if f.endswith('.idx'):
73 self.packs.append(PackIndex(os.path.join(dir, f)))
75 def exists(self, hash):
78 for i in range(len(self.packs)):
81 # reorder so most recently used packs are searched first
82 self.packs = [p] + self.packs[:i] + self.packs[i+1:]
93 def calc_hash(type, content):
94 header = '%s %d\0' % (type, len(content))
100 def _shalist_sort_key(ent):
101 (mode, name, id) = ent
102 if stat.S_ISDIR(int(mode, 8)):
108 _typemap = dict(blob=3, tree=2, commit=1, tag=8)
110 def __init__(self, objcache=None):
114 self.objcache = objcache or MultiPackIndex(repo('objects/pack'))
120 assert(not self.file)
121 self.objcache.zap_also()
122 self.filename = repo('objects/bup%d' % os.getpid())
123 self.file = open(self.filename + '.pack', 'w+')
124 self.file.write('PACK\0\0\0\2\0\0\0\0')
126 def _raw_write(self, datalist):
134 def _write(self, bin, type, content):
141 szbits = (sz & 0x0f) | (_typemap[type]<<4)
144 if sz: szbits |= 0x80
145 out.append(chr(szbits))
151 z = zlib.compressobj(1)
152 out.append(z.compress(content))
153 out.append(z.flush())
158 def write(self, type, content):
159 return self._write(calc_hash(type, content), type, content)
161 def maybe_write(self, type, content):
162 bin = calc_hash(type, content)
163 if not self.objcache.exists(bin):
164 self._write(bin, type, content)
165 self.objcache.add(bin)
168 def new_blob(self, blob):
169 return self.maybe_write('blob', blob)
171 def new_tree(self, shalist):
172 shalist = sorted(shalist, key = _shalist_sort_key)
173 l = ['%s %s\0%s' % (mode,name,bin)
174 for (mode,name,bin) in shalist]
175 return self.maybe_write('tree', ''.join(l))
177 def _new_commit(self, tree, parent, author, adate, committer, cdate, msg):
179 if tree: l.append('tree %s' % tree.encode('hex'))
180 if parent: l.append('parent %s' % parent)
181 if author: l.append('author %s %s' % (author, _git_date(adate)))
182 if committer: l.append('committer %s %s' % (committer, _git_date(cdate)))
185 return self.maybe_write('commit', '\n'.join(l))
187 def new_commit(self, ref, tree, msg):
189 userline = '%s <%s@%s>' % (userfullname(), username(), hostname())
190 oldref = ref and _read_ref(ref) or None
191 commit = self._new_commit(tree, oldref,
192 userline, now, userline, now,
195 self.close() # UGLY: needed so _update_ref can see the new objects
196 _update_ref(ref, commit.encode('hex'), oldref)
204 os.unlink(self.filename + '.pack')
208 if not f: return None
211 # update object count
213 cp = struct.pack('!i', self.count)
217 # calculate the pack sha1sum
224 f.write(sum.digest())
228 p = subprocess.Popen(['git', 'index-pack', '-v',
229 self.filename + '.pack'],
230 preexec_fn = _gitenv,
231 stdout = subprocess.PIPE)
232 out = p.stdout.read().strip()
233 if p.wait() or not out:
234 raise Exception('git index-pack returned an error')
235 nameprefix = repo('objects/pack/%s' % out)
236 os.rename(self.filename + '.pack', nameprefix + '.pack')
237 os.rename(self.filename + '.idx', nameprefix + '.idx')
241 class PackWriter_Remote(PackWriter):
242 def __init__(self, conn, objcache=None):
243 PackWriter.__init__(self, objcache)
245 self.filename = 'remote socket'
248 assert(not "can't reopen a PackWriter_Remote")
252 self.file.write('\0\0\0\0')
255 def _raw_write(self, datalist):
257 data = ''.join(datalist)
259 self.file.write(struct.pack('!I', len(data)) + data)
263 return time.strftime('%s %z', time.localtime(date))
267 os.environ['GIT_DIR'] = os.path.abspath(repo())
270 def _read_ref(refname):
271 p = subprocess.Popen(['git', 'show-ref', '--', refname],
272 preexec_fn = _gitenv,
273 stdout = subprocess.PIPE)
274 out = p.stdout.read().strip()
277 return out.split()[0]
282 def _update_ref(refname, newval, oldval):
285 p = subprocess.Popen(['git', 'update-ref', '--', refname, newval, oldval],
286 preexec_fn = _gitenv)
293 if os.path.exists(d) and not os.path.isdir(os.path.join(d, '.')):
294 raise Exception('"%d" exists but is not a directory\n' % d)
295 p = subprocess.Popen(['git', 'init', '--bare'],
296 preexec_fn = _gitenv)
300 def check_repo_or_die():
301 if not os.path.isdir(repo('objects/pack/.')):
302 log('error: %r is not a bup/git repository\n' % repo())