def read_loose_ref(self, name): """Read a reference file and return its contents. If the reference file a symbolic reference, only read the first line of the file. Otherwise, only read the first 40 bytes. :param name: the refname to read, relative to refpath :return: The contents of the ref file, or None if the file does not exist. :raises IOError: if any other error occurs """ filename = self.refpath(name) try: f = GitFile(filename, 'rb') try: header = f.read(len(SYMREF)) if header == SYMREF: # Read only the first line return header + iter(f).next().rstrip("\r\n") else: # Read only the first 40 bytes return header + f.read(40-len(SYMREF)) finally: f.close() except IOError, e: if e.errno == errno.ENOENT: return None raise
def read_loose_ref(self, name): """Read a reference file and return its contents. If the reference file a symbolic reference, only read the first line of the file. Otherwise, only read the first 40 bytes. :param name: the refname to read, relative to refpath :return: The contents of the ref file, or None if the file does not exist. :raises IOError: if any other error occurs """ filename = self.refpath(name) try: f = GitFile(filename, 'rb') try: header = f.read(len(SYMREF)) if header == SYMREF: # Read only the first line return header + iter(f).next().rstrip("\r\n") else: # Read only the first 40 bytes return header + f.read(40 - len(SYMREF)) finally: f.close() except IOError as e: if e.errno == errno.ENOENT: return None raise
def test_readonly(self): f = GitFile(self.path("foo"), "rb") self.assertTrue(isinstance(f, io.IOBase)) self.assertEqual(b"foo contents", f.read()) self.assertEqual(b"", f.read()) f.seek(4) self.assertEqual(b"contents", f.read()) f.close()
def test_readonly(self): f = GitFile(self.path('foo'), 'rb') self.assertTrue(isinstance(f, io.IOBase)) self.assertEqual(b'foo contents', f.read()) self.assertEqual(b'', f.read()) f.seek(4) self.assertEqual(b'contents', f.read()) f.close()
def test_readonly(self): import _io f = GitFile(self.path('foo'), 'rb') self.assertTrue(isinstance(f, _io.BufferedReader)) self.assertEqual(b'foo contents', f.read()) self.assertEqual(b'', f.read()) f.seek(4) self.assertEqual(b'contents', f.read()) f.close()
def read(self): """Read current contents of index from disk.""" f = GitFile(self._filename, 'rb') try: f = SHA1Reader(f) for x in read_index(f): self[x[0]] = tuple(x[1:]) # FIXME: Additional data? f.read(os.path.getsize(self._filename)-f.tell()-20) f.check_sha() finally: f.close()
def read(self): """Read current contents of index from disk.""" if not os.path.exists(self._filename): return f = GitFile(self._filename, "rb") try: f = SHA1Reader(f) for x in read_index(f): self[x[0]] = IndexEntry(*x[1:]) # FIXME: Additional data? f.read(os.path.getsize(self._filename) - f.tell() - 20) f.check_sha() finally: f.close()
def read(self): """Read current contents of index from disk.""" if not os.path.exists(self._filename): return f = GitFile(self._filename, 'rb') try: f = SHA1Reader(f) for x in read_index(f): self[x[0]] = IndexEntry(*x[1:]) # FIXME: Additional data? f.read(os.path.getsize(self._filename)-f.tell()-20) f.check_sha() finally: f.close()
def read(self): """Read current contents of index from disk.""" if not os.path.exists(self._filename): return f = GitFile(self._filename, "rb") try: f = SHA1Reader(f) for name, entry in read_index(f): self[name] = entry # FIXME: Additional data? f.read(os.path.getsize(self._filename) - f.tell() - 20) f.check_sha() finally: f.close()
def _parse_file(self): f = GitFile(self._filename, 'rb') try: magic = f.read(2) if self._is_legacy_object(magic): self._parse_legacy_object(f) else: self._parse_object(f) finally: f.close()
def test_remove_packed_without_peeled(self): refs_file = os.path.join(self._repo.path, "packed-refs") f = GitFile(refs_file) refs_data = f.read() f.close() f = GitFile(refs_file, "wb") f.write("\n".join(l for l in refs_data.split("\n") if not l or l[0] not in "#^")) f.close() self._repo = Repo(self._repo.path) refs = self._repo.refs self.assertTrue(refs.remove_if_equals("refs/heads/packed", "42d06bd4b77fed026b154d16493e5deab78f02ec"))
def test_remove_packed_without_peeled(self): refs_file = os.path.join(self._repo.path, 'packed-refs') f = GitFile(refs_file) refs_data = f.read() f.close() f = GitFile(refs_file, 'wb') f.write(b'\n'.join(l for l in refs_data.split(b'\n') if not l or l[0] not in b'#^')) f.close() self._repo = Repo(self._repo.path) refs = self._repo.refs self.assertTrue(refs.remove_if_equals( b'refs/heads/packed', b'42d06bd4b77fed026b154d16493e5deab78f02ec'))
def test_remove_packed_without_peeled(self): refs_file = os.path.join(self._repo.path, "packed-refs") f = GitFile(refs_file) refs_data = f.read() f.close() f = GitFile(refs_file, "wb") f.write(b"\n".join(line for line in refs_data.split(b"\n") if not line or line[0] not in b"#^")) f.close() self._repo = Repo(self._repo.path) refs = self._repo.refs self.assertTrue( refs.remove_if_equals( b"refs/heads/packed", b"42d06bd4b77fed026b154d16493e5deab78f02ec", ))
def get_description(self): """Retrieve the description of this repository. :return: A string describing the repository or None. """ path = os.path.join(self._controldir, 'description') try: f = GitFile(path, 'rb') try: return f.read() finally: f.close() except (IOError, OSError) as e: if e.errno != errno.ENOENT: raise return None
def get_description(self): """Retrieve the description of this repository. :return: A string describing the repository or None. """ path = os.path.join(self._controldir, 'description') try: f = GitFile(path, 'rb') try: return f.read() finally: f.close() except (IOError, OSError), e: if e.errno != errno.ENOENT: raise return None
class PackData(object): """The data contained in a packfile. Pack files can be accessed both sequentially for exploding a pack, and directly with the help of an index to retrieve a specific object. The objects within are either complete or a delta aginst another. The header is variable length. If the MSB of each byte is set then it indicates that the subsequent byte is still part of the header. For the first byte the next MS bits are the type, which tells you the type of object, and whether it is a delta. The LS byte is the lowest bits of the size. For each subsequent byte the LS 7 bits are the next MS bits of the size, i.e. the last byte of the header contains the MS bits of the size. For the complete objects the data is stored as zlib deflated data. The size in the header is the uncompressed object size, so to uncompress you need to just keep feeding data to zlib until you get an object back, or it errors on bad data. This is done here by just giving the complete buffer from the start of the deflated object on. This is bad, but until I get mmap sorted out it will have to do. Currently there are no integrity checks done. Also no attempt is made to try and detect the delta case, or a request for an object at the wrong position. It will all just throw a zlib or KeyError. """ def __init__(self, filename, file=None, size=None): """Create a PackData object representing the pack in the given filename. The file must exist and stay readable until the object is disposed of. It must also stay the same size. It will be mapped whenever needed. Currently there is a restriction on the size of the pack as the python mmap implementation is flawed. """ self._filename = filename self._size = size self._header_size = 12 if file is None: self._file = GitFile(self._filename, 'rb') else: self._file = file (version, self._num_objects) = read_pack_header(self._file.read) self._offset_cache = LRUSizeCache(1024*1024*20, compute_size=_compute_object_size) self.pack = None @classmethod def from_file(cls, file, size): return cls(str(file), file=file, size=size) @classmethod def from_path(cls, path): return cls(filename=path) def close(self): self._file.close() def _get_size(self): if self._size is not None: return self._size self._size = os.path.getsize(self._filename) if self._size < self._header_size: errmsg = ("%s is too small for a packfile (%d < %d)" % (self._filename, self._size, self._header_size)) raise AssertionError(errmsg) return self._size def __len__(self): """Returns the number of objects in this pack.""" return self._num_objects def calculate_checksum(self): """Calculate the checksum for this pack. :return: 20-byte binary SHA1 digest """ s = make_sha() self._file.seek(0) todo = self._get_size() - 20 while todo > 0: x = self._file.read(min(todo, 1<<16)) s.update(x) todo -= len(x) return s.digest() def get_ref(self, sha): """Get the object for a ref SHA, only looking in this pack.""" # TODO: cache these results if self.pack is None: raise KeyError(sha) offset = self.pack.index.object_index(sha) if not offset: raise KeyError(sha) type, obj = self.get_object_at(offset) return offset, type, obj def resolve_object(self, offset, type, obj, get_ref=None): """Resolve an object, possibly resolving deltas when necessary. :return: Tuple with object type and contents. """ if type not in DELTA_TYPES: return type, obj if get_ref is None: get_ref = self.get_ref if type == OFS_DELTA: (delta_offset, delta) = obj # TODO: clean up asserts and replace with nicer error messages assert isinstance(offset, int) assert isinstance(delta_offset, int) base_offset = offset-delta_offset type, base_obj = self.get_object_at(base_offset) assert isinstance(type, int) elif type == REF_DELTA: (basename, delta) = obj assert isinstance(basename, str) and len(basename) == 20 base_offset, type, base_obj = get_ref(basename) assert isinstance(type, int) type, base_chunks = self.resolve_object(base_offset, type, base_obj) chunks = apply_delta(base_chunks, delta) # TODO(dborowitz): This can result in poor performance if large base # objects are separated from deltas in the pack. We should reorganize # so that we apply deltas to all objects in a chain one after the other # to optimize cache performance. if offset is not None: self._offset_cache[offset] = type, chunks return type, chunks def iterobjects(self, progress=None): return PackObjectIterator(self, progress) def iterentries(self, progress=None): """Yield entries summarizing the contents of this pack. :param progress: Progress function, called with current and total object count. :return: iterator of tuples with (sha, offset, crc32) """ for offset, type, obj, crc32 in self.iterobjects(progress=progress): assert isinstance(offset, int) assert isinstance(type, int) assert isinstance(obj, list) or isinstance(obj, tuple) type, obj = self.resolve_object(offset, type, obj) yield obj_sha(type, obj), offset, crc32 def sorted_entries(self, progress=None): """Return entries in this pack, sorted by SHA. :param progress: Progress function, called with current and total object count :return: List of tuples with (sha, offset, crc32) """ ret = list(self.iterentries(progress=progress)) ret.sort() return ret def create_index_v1(self, filename, progress=None): """Create a version 1 file for this data file. :param filename: Index filename. :param progress: Progress report function :return: Checksum of index file """ entries = self.sorted_entries(progress=progress) f = GitFile(filename, 'wb') try: return write_pack_index_v1(f, entries, self.calculate_checksum()) finally: f.close() def create_index_v2(self, filename, progress=None): """Create a version 2 index file for this data file. :param filename: Index filename. :param progress: Progress report function :return: Checksum of index file """ entries = self.sorted_entries(progress=progress) f = GitFile(filename, 'wb') try: return write_pack_index_v2(f, entries, self.calculate_checksum()) finally: f.close() def create_index(self, filename, progress=None, version=2): """Create an index file for this data file. :param filename: Index filename. :param progress: Progress report function :return: Checksum of index file """ if version == 1: return self.create_index_v1(filename, progress) elif version == 2: return self.create_index_v2(filename, progress) else: raise ValueError("unknown index format %d" % version) def get_stored_checksum(self): """Return the expected checksum stored in this pack.""" self._file.seek(self._get_size()-20) return self._file.read(20) def check(self): """Check the consistency of this pack.""" actual = self.calculate_checksum() stored = self.get_stored_checksum() if actual != stored: raise ChecksumMismatch(stored, actual) def get_object_at(self, offset): """Given an offset in to the packfile return the object that is there. Using the associated index the location of an object can be looked up, and then the packfile can be asked directly for that object using this function. """ if offset in self._offset_cache: return self._offset_cache[offset] assert isinstance(offset, long) or isinstance(offset, int),\ "offset was %r" % offset assert offset >= self._header_size self._file.seek(offset) return unpack_object(self._file.read)[:2]
def test_default_mode(self): f = GitFile(self.path("foo")) self.assertEqual(b"foo contents", f.read()) f.close()
def test_default_mode(self): f = GitFile(self.path('foo')) self.assertEqual(b'foo contents', f.read()) f.close()
class PackData(object): """The data contained in a packfile. Pack files can be accessed both sequentially for exploding a pack, and directly with the help of an index to retrieve a specific object. The objects within are either complete or a delta aginst another. The header is variable length. If the MSB of each byte is set then it indicates that the subsequent byte is still part of the header. For the first byte the next MS bits are the type, which tells you the type of object, and whether it is a delta. The LS byte is the lowest bits of the size. For each subsequent byte the LS 7 bits are the next MS bits of the size, i.e. the last byte of the header contains the MS bits of the size. For the complete objects the data is stored as zlib deflated data. The size in the header is the uncompressed object size, so to uncompress you need to just keep feeding data to zlib until you get an object back, or it errors on bad data. This is done here by just giving the complete buffer from the start of the deflated object on. This is bad, but until I get mmap sorted out it will have to do. Currently there are no integrity checks done. Also no attempt is made to try and detect the delta case, or a request for an object at the wrong position. It will all just throw a zlib or KeyError. """ def __init__(self, filename, file=None, size=None): """Create a PackData object that represents the pack in the given filename. The file must exist and stay readable until the object is disposed of. It must also stay the same size. It will be mapped whenever needed. Currently there is a restriction on the size of the pack as the python mmap implementation is flawed. """ self._filename = filename self._size = size self._header_size = 12 if file is None: self._file = GitFile(self._filename, 'rb') else: self._file = file (version, self._num_objects) = read_pack_header(self._file) self._offset_cache = LRUSizeCache(1024*1024*20, compute_size=_compute_object_size) @classmethod def from_file(cls, file, size): return cls(str(file), file=file, size=size) @classmethod def from_path(cls, path): return cls(filename=path) def close(self): self._file.close() def _get_size(self): if self._size is not None: return self._size self._size = os.path.getsize(self._filename) assert self._size >= self._header_size, "%s is too small for a packfile (%d < %d)" % (self._filename, self._size, self._header_size) return self._size def __len__(self): """Returns the number of objects in this pack.""" return self._num_objects def calculate_checksum(self): """Calculate the checksum for this pack. :return: 20-byte binary SHA1 digest """ s = make_sha() self._file.seek(0) todo = self._get_size() - 20 while todo > 0: x = self._file.read(min(todo, 1<<16)) s.update(x) todo -= len(x) return s.digest() def resolve_object(self, offset, type, obj, get_ref, get_offset=None): """Resolve an object, possibly resolving deltas when necessary. :return: Tuple with object type and contents. """ if type not in (6, 7): # Not a delta return type, obj if get_offset is None: get_offset = self.get_object_at if type == 6: # offset delta (delta_offset, delta) = obj assert isinstance(delta_offset, int) assert isinstance(delta, str) base_offset = offset-delta_offset type, base_obj = get_offset(base_offset) assert isinstance(type, int) elif type == 7: # ref delta (basename, delta) = obj assert isinstance(basename, str) and len(basename) == 20 assert isinstance(delta, str) type, base_obj = get_ref(basename) assert isinstance(type, int) # Can't be a ofs delta, as we wouldn't know the base offset assert type != 6 base_offset = None type, base_text = self.resolve_object(base_offset, type, base_obj, get_ref) if base_offset is not None: self._offset_cache[base_offset] = type, base_text ret = (type, apply_delta(base_text, delta)) return ret def iterobjects(self, progress=None): class ObjectIterator(object): def __init__(self, pack): self.i = 0 self.offset = pack._header_size self.num = len(pack) self.map = pack._file def __iter__(self): return self def __len__(self): return self.num def next(self): if self.i == self.num: raise StopIteration self.map.seek(self.offset) (type, obj, total_size, unused) = unpack_object(self.map.read) self.map.seek(self.offset) crc32 = zlib.crc32(self.map.read(total_size)) & 0xffffffff ret = (self.offset, type, obj, crc32) self.offset += total_size if progress: progress(self.i, self.num) self.i+=1 return ret return ObjectIterator(self) def iterentries(self, ext_resolve_ref=None, progress=None): """Yield entries summarizing the contents of this pack. :param ext_resolve_ref: Optional function to resolve base objects (in case this is a thin pack) :param progress: Progress function, called with current and total object count. This will yield tuples with (sha, offset, crc32) """ found = {} postponed = defaultdict(list) class Postpone(Exception): """Raised to postpone delta resolving.""" def get_ref_text(sha): assert len(sha) == 20 if sha in found: return self.get_object_at(found[sha]) if ext_resolve_ref: try: return ext_resolve_ref(sha) except KeyError: pass raise Postpone, (sha, ) extra = [] todo = chain(self.iterobjects(progress=progress), extra) for (offset, type, obj, crc32) in todo: assert isinstance(offset, int) assert isinstance(type, int) assert isinstance(obj, tuple) or isinstance(obj, str) try: type, obj = self.resolve_object(offset, type, obj, get_ref_text) except Postpone, (sha, ): postponed[sha].append((offset, type, obj)) else: shafile = ShaFile.from_raw_string(type, obj) sha = shafile.sha().digest() found[sha] = offset yield sha, offset, crc32 extra.extend(postponed.get(sha, [])) if postponed: raise KeyError([sha_to_hex(h) for h in postponed.keys()])
class PackIndex(object): """An index in to a packfile. Given a sha id of an object a pack index can tell you the location in the packfile of that object if it has it. To do the loop it opens the file, and indexes first 256 4 byte groups with the first byte of the sha id. The value in the four byte group indexed is the end of the group that shares the same starting byte. Subtract one from the starting byte and index again to find the start of the group. The values are sorted by sha id within the group, so do the math to find the start and end offset and then bisect in to find if the value is present. """ def __init__(self, filename, file=None, size=None): """Create a pack index object. Provide it with the name of the index file to consider, and it will map it whenever required. """ self._filename = filename # Take the size now, so it can be checked each time we map the file to # ensure that it hasn't changed. if file is None: self._file = GitFile(filename, 'rb') else: self._file = file fileno = getattr(self._file, 'fileno', None) if fileno is not None: fd = self._file.fileno() if size is None: self._size = os.fstat(fd).st_size else: self._size = size self._contents = mmap.mmap(fd, self._size, access=mmap.ACCESS_READ) else: self._file.seek(0) self._contents = self._file.read() self._size = len(self._contents) def __eq__(self, other): if not isinstance(other, PackIndex): return False if self._fan_out_table != other._fan_out_table: return False for (name1, _, _), (name2, _, _) in izip(self.iterentries(), other.iterentries()): if name1 != name2: return False return True def __ne__(self, other): return not self.__eq__(other) def close(self): self._file.close() def __len__(self): """Return the number of entries in this pack index.""" return self._fan_out_table[-1] def _unpack_entry(self, i): """Unpack the i-th entry in the index file. :return: Tuple with object name (SHA), offset in pack file and CRC32 checksum (if known).""" raise NotImplementedError(self._unpack_entry) def _unpack_name(self, i): """Unpack the i-th name from the index file.""" raise NotImplementedError(self._unpack_name) def _unpack_offset(self, i): """Unpack the i-th object offset from the index file.""" raise NotImplementedError(self._unpack_offset) def _unpack_crc32_checksum(self, i): """Unpack the crc32 checksum for the i-th object from the index file.""" raise NotImplementedError(self._unpack_crc32_checksum) def __iter__(self): """Iterate over the SHAs in this pack.""" return imap(sha_to_hex, self._itersha()) def _itersha(self): for i in range(len(self)): yield self._unpack_name(i) def objects_sha1(self): """Return the hex SHA1 over all the shas of all objects in this pack. :note: This is used for the filename of the pack. """ return iter_sha1(self._itersha()) def iterentries(self): """Iterate over the entries in this pack index. Will yield tuples with object name, offset in packfile and crc32 checksum. """ for i in range(len(self)): yield self._unpack_entry(i) def _read_fan_out_table(self, start_offset): ret = [] for i in range(0x100): ret.append(struct.unpack(">L", self._contents[start_offset+i*4:start_offset+(i+1)*4])[0]) return ret def check(self): """Check that the stored checksum matches the actual checksum.""" # TODO: Check pack contents, too return self.calculate_checksum() == self.get_stored_checksum() def calculate_checksum(self): """Calculate the SHA1 checksum over this pack index. :return: This is a 20-byte binary digest """ return make_sha(self._contents[:-20]).digest() def get_pack_checksum(self): """Return the SHA1 checksum stored for the corresponding packfile. :return: 20-byte binary digest """ return str(self._contents[-40:-20]) def get_stored_checksum(self): """Return the SHA1 checksum stored for this index. :return: 20-byte binary digest """ return str(self._contents[-20:]) def object_index(self, sha): """Return the index in to the corresponding packfile for the object. Given the name of an object it will return the offset that object lives at within the corresponding pack file. If the pack file doesn't have the object then None will be returned. """ if len(sha) == 40: sha = hex_to_sha(sha) return self._object_index(sha) def _object_index(self, sha): """See object_index. :param sha: A *binary* SHA string. (20 characters long)_ """ assert len(sha) == 20 idx = ord(sha[0]) if idx == 0: start = 0 else: start = self._fan_out_table[idx-1] end = self._fan_out_table[idx] i = bisect_find_sha(start, end, sha, self._unpack_name) if i is None: raise KeyError(sha) return self._unpack_offset(i)