Mercurial and Git clients can push and pull from this alias URL to interact with this repository. You can change to which repository an alias points by going to the Aliases link on the project page.
# pack.py -- For dealing with packed git objects.# Copyright (C) 2007 James Westby <jw+debian@jameswestby.net># Copyright (C) 2008-2009 Jelmer Vernooij <jelmer@samba.org>## This program is free software; you can redistribute it and/or# modify it under the terms of the GNU General Public License# as published by the Free Software Foundation; version 2# of the License or (at your option) a later version.## This program is distributed in the hope that it will be useful,# but WITHOUT ANY WARRANTY; without even the implied warranty of# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the# GNU General Public License for more details.## You should have received a copy of the GNU General Public License# along with this program; if not, write to the Free Software# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,# MA 02110-1301, USA."""Classes for dealing with packed git objects.A pack is a compact representation of a bunch of objects, storedusing deltas where possible.They have two parts, the pack file, which stores the data, and an indexthat tells you where the data is.To find an object you look in all of the index files 'til you find amatch for the object name. You then use the pointer got from this asa pointer in to the corresponding packfile."""try:fromcollectionsimportdefaultdictexceptImportError:fromdulwich._compatimportdefaultdictimportbinasciifromcStringIOimport(StringIO,)fromcollectionsimport(deque,)importdifflibfromitertoolsimport(chain,imap,izip,)try:importmmapexceptImportError:has_mmap=Falseelse:has_mmap=Trueimportosimportstructtry:fromstructimportunpack_fromexceptImportError:fromdulwich._compatimportunpack_fromimportsysimportwarningsimportzlibfromdulwich.errorsimport(ApplyDeltaError,ChecksumMismatch,)fromdulwich.fileimportGitFilefromdulwich.lru_cacheimport(LRUSizeCache,)fromdulwich._compatimport(make_sha,SEEK_CUR,SEEK_END,)fromdulwich.objectsimport(ShaFile,hex_to_sha,sha_to_hex,object_header,)supports_mmap_offset=(sys.version_info[0]>=3or(sys.version_info[0]==2andsys.version_info[1]>=6))OFS_DELTA=6REF_DELTA=7DELTA_TYPES=(OFS_DELTA,REF_DELTA)deftake_msb_bytes(read,crc32=None):"""Read bytes marked with most significant bit. :param read: Read function """ret=[]whilelen(ret)==0orret[-1]&0x80:b=read(1)ifcrc32isnotNone:crc32=binascii.crc32(b,crc32)ret.append(ord(b))returnret,crc32classUnpackedObject(object):"""Class encapsulating an object unpacked from a pack file. These objects should only be created from within unpack_object. Most members start out as empty and are filled in at various points by read_zlib_chunks, unpack_object, DeltaChainIterator, etc. End users of this object should take care that the function they're getting this object from is guaranteed to set the members they need. """__slots__=['offset',# Offset in its pack.'_sha',# Cached binary SHA.'obj_type_num',# Type of this object.'obj_chunks',# Decompressed and delta-resolved chunks.'pack_type_num',# Type of this object in the pack (may be a delta).'delta_base',# Delta base offset or SHA.'comp_chunks',# Compressed object chunks.'decomp_chunks',# Decompressed object chunks.'decomp_len',# Decompressed length of this object.'crc32',# CRC32.]# TODO(dborowitz): read_zlib_chunks and unpack_object could very well be# methods of this object.def__init__(self,pack_type_num,delta_base,decomp_len,crc32):self.offset=Noneself._sha=Noneself.pack_type_num=pack_type_numself.delta_base=delta_baseself.comp_chunks=Noneself.decomp_chunks=[]self.decomp_len=decomp_lenself.crc32=crc32ifpack_type_numinDELTA_TYPES:self.obj_type_num=Noneself.obj_chunks=Noneelse:self.obj_type_num=pack_type_numself.obj_chunks=self.decomp_chunksself.delta_base=delta_basedefsha(self):"""Return the binary SHA of this object."""ifself._shaisNone:self._sha=obj_sha(self.obj_type_num,self.obj_chunks)returnself._shadefsha_file(self):"""Return a ShaFile from this object."""returnShaFile.from_raw_chunks(self.obj_type_num,self.obj_chunks)# Only provided for backwards compatibility with code that expects either# chunks or a delta tuple.def_obj(self):"""Return the decompressed chunks, or (delta base, delta chunks)."""ifself.pack_type_numinDELTA_TYPES:return(self.delta_base,self.decomp_chunks)else:returnself.decomp_chunksdef__eq__(self,other):ifnotisinstance(other,UnpackedObject):returnFalseforslotinself.__slots__:ifgetattr(self,slot)!=getattr(other,slot):returnFalsereturnTruedef__ne__(self,other):returnnot(self==other)def__repr__(self):data=['%s=%r'%(s,getattr(self,s))forsinself.__slots__]return'%s(%s)'%(self.__class__.__name__,', '.join(data))_ZLIB_BUFSIZE=4096defread_zlib_chunks(read_some,unpacked,include_comp=False,buffer_size=_ZLIB_BUFSIZE):"""Read zlib data from a buffer. This function requires that the buffer have additional data following the compressed data, which is guaranteed to be the case for git pack files. :param read_some: Read function that returns at least one byte, but may return less than the requested size. :param unpacked: An UnpackedObject to write result data to. If its crc32 attr is not None, the CRC32 of the compressed bytes will be computed using this starting CRC32. After this function, will have the following attrs set: * comp_chunks (if include_comp is True) * decomp_chunks * decomp_len * crc32 :param include_comp: If True, include compressed data in the result. :param buffer_size: Size of the read buffer. :return: Leftover unused data from the decompression. :raise zlib.error: if a decompression error occurred. """ifunpacked.decomp_len<=-1:raiseValueError('non-negative zlib data stream size expected')decomp_obj=zlib.decompressobj()comp_chunks=[]decomp_chunks=unpacked.decomp_chunksdecomp_len=0crc32=unpacked.crc32whileTrue:add=read_some(buffer_size)ifnotadd:raisezlib.error('EOF before end of zlib stream')comp_chunks.append(add)decomp=decomp_obj.decompress(add)decomp_len+=len(decomp)decomp_chunks.append(decomp)unused=decomp_obj.unused_dataifunused:left=len(unused)ifcrc32isnotNone:crc32=binascii.crc32(add[:-left],crc32)ifinclude_comp:comp_chunks[-1]=add[:-left]breakelifcrc32isnotNone:crc32=binascii.crc32(add,crc32)ifcrc32isnotNone:crc32&=0xffffffffifdecomp_len!=unpacked.decomp_len:raisezlib.error('decompressed data does not match expected size')unpacked.crc32=crc32ifinclude_comp:unpacked.comp_chunks=comp_chunksreturnunuseddefiter_sha1(iter):"""Return the hexdigest of the SHA1 over a set of names. :param iter: Iterator over string objects :return: 40-byte hex sha1 digest """sha1=make_sha()fornameiniter:sha1.update(name)returnsha1.hexdigest()defload_pack_index(path):"""Load an index file by path. :param filename: Path to the index file :return: A PackIndex loaded from the given path """f=GitFile(path,'rb')try:returnload_pack_index_file(path,f)finally:f.close()def_load_file_contents(f,size=None):fileno=getattr(f,'fileno',None)# Attempt to use mmap if possibleiffilenoisnotNone:fd=f.fileno()ifsizeisNone:size=os.fstat(fd).st_sizeifhas_mmap:try:contents=mmap.mmap(fd,size,access=mmap.ACCESS_READ)exceptmmap.error:# Perhaps a socket?passelse:returncontents,sizecontents=f.read()size=len(contents)returncontents,sizedefload_pack_index_file(path,f):"""Load an index file from a file-like object. :param path: Path for the index file :param f: File-like object :return: A PackIndex loaded from the given file """contents,size=_load_file_contents(f)ifcontents[:4]=='\377tOc':version=struct.unpack('>L',contents[4:8])[0]ifversion==2:returnPackIndex2(path,file=f,contents=contents,size=size)else:raiseKeyError('Unknown pack index format %d'%version)else:returnPackIndex1(path,file=f,contents=contents,size=size)defbisect_find_sha(start,end,sha,unpack_name):"""Find a SHA in a data blob with sorted SHAs. :param start: Start index of range to search :param end: End index of range to search :param sha: Sha to find :param unpack_name: Callback to retrieve SHA by index :return: Index of the SHA, or None if it wasn't found """assertstart<=endwhilestart<=end:i=(start+end)/2file_sha=unpack_name(i)x=cmp(file_sha,sha)ifx<0:start=i+1elifx>0:end=i-1else:returnireturnNoneclassPackIndex(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. """def__eq__(self,other):ifnotisinstance(other,PackIndex):returnFalsefor(name1,_,_),(name2,_,_)inizip(self.iterentries(),other.iterentries()):ifname1!=name2:returnFalsereturnTruedef__ne__(self,other):returnnotself.__eq__(other)def__len__(self):"""Return the number of entries in this pack index."""raiseNotImplementedError(self.__len__)def__iter__(self):"""Iterate over the SHAs in this pack."""returnimap(sha_to_hex,self._itersha())defiterentries(self):"""Iterate over the entries in this pack index. :return: iterator over tuples with object name, offset in packfile and crc32 checksum. """raiseNotImplementedError(self.iterentries)defget_pack_checksum(self):"""Return the SHA1 checksum stored for the corresponding packfile. :return: 20-byte binary digest """raiseNotImplementedError(self.get_pack_checksum)defobject_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. """iflen(sha)==40:sha=hex_to_sha(sha)returnself._object_index(sha)def_object_index(self,sha):"""See object_index. :param sha: A *binary* SHA string. (20 characters long)_ """raiseNotImplementedError(self._object_index)defobjects_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. """returniter_sha1(self._itersha())def_itersha(self):"""Yield all the SHA1's of the objects in the index, sorted."""raiseNotImplementedError(self._itersha)classMemoryPackIndex(PackIndex):"""Pack index that is stored entirely in memory."""def__init__(self,entries,pack_checksum=None):"""Create a new MemoryPackIndex. :param entries: Sequence of name, idx, crc32 (sorted) :param pack_checksum: Optional pack checksum """self._by_sha={}forname,idx,crc32inentries:self._by_sha[name]=idxself._entries=entriesself._pack_checksum=pack_checksumdefget_pack_checksum(self):returnself._pack_checksumdef__len__(self):returnlen(self._entries)def_object_index(self,sha):returnself._by_sha[sha][0]def_itersha(self):returniter(self._by_sha)defiterentries(self):returniter(self._entries)classFilePackIndex(PackIndex):"""Pack index that is based on a file. 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,contents=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.iffileisNone:self._file=GitFile(filename,'rb')else:self._file=fileifcontentsisNone:self._contents,self._size=_load_file_contents(self._file,size)else:self._contents,self._size=(contents,size)def__eq__(self,other):# Quick optimization:if(isinstance(other,FilePackIndex)andself._fan_out_table!=other._fan_out_table):returnFalsereturnsuper(FilePackIndex,self).__eq__(other)defclose(self):self._file.close()ifgetattr(self._contents,"close",None)isnotNone:self._contents.close()def__len__(self):"""Return the number of entries in this pack index."""returnself._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). """raiseNotImplementedError(self._unpack_entry)def_unpack_name(self,i):"""Unpack the i-th name from the index file."""raiseNotImplementedError(self._unpack_name)def_unpack_offset(self,i):"""Unpack the i-th object offset from the index file."""raiseNotImplementedError(self._unpack_offset)def_unpack_crc32_checksum(self,i):"""Unpack the crc32 checksum for the i-th object from the index file."""raiseNotImplementedError(self._unpack_crc32_checksum)def_itersha(self):foriinrange(len(self)):yieldself._unpack_name(i)defiterentries(self):"""Iterate over the entries in this pack index. :return: iterator over tuples with object name, offset in packfile and crc32 checksum. """foriinrange(len(self)):yieldself._unpack_entry(i)def_read_fan_out_table(self,start_offset):ret=[]foriinrange(0x100):fanout_entry=self._contents[start_offset+i*4:start_offset+(i+1)*4]ret.append(struct.unpack('>L',fanout_entry)[0])returnretdefcheck(self):"""Check that the stored checksum matches the actual checksum."""actual=self.calculate_checksum()stored=self.get_stored_checksum()ifactual!=stored:raiseChecksumMismatch(stored,actual)defcalculate_checksum(self):"""Calculate the SHA1 checksum over this pack index. :return: This is a 20-byte binary digest """returnmake_sha(self._contents[:-20]).digest()defget_pack_checksum(self):"""Return the SHA1 checksum stored for the corresponding packfile. :return: 20-byte binary digest """returnstr(self._contents[-40:-20])defget_stored_checksum(self):"""Return the SHA1 checksum stored for this index. :return: 20-byte binary digest """returnstr(self._contents[-20:])def_object_index(self,sha):"""See object_index. :param sha: A *binary* SHA string. (20 characters long)_ """assertlen(sha)==20idx=ord(sha[0])ifidx==0:start=0else:start=self._fan_out_table[idx-1]end=self._fan_out_table[idx]i=bisect_find_sha(start,end,sha,self._unpack_name)ifiisNone:raiseKeyError(sha)returnself._unpack_offset(i)classPackIndex1(FilePackIndex):"""Version 1 Pack Index file."""def__init__(self,filename,file=None,contents=None,size=None):super(PackIndex1,self).__init__(filename,file,contents,size)self.version=1self._fan_out_table=self._read_fan_out_table(0)def_unpack_entry(self,i):(offset,name)=unpack_from('>L20s',self._contents,(0x100*4)+(i*24))return(name,offset,None)def_unpack_name(self,i):offset=(0x100*4)+(i*24)+4returnself._contents[offset:offset+20]def_unpack_offset(self,i):offset=(0x100*4)+(i*24)returnunpack_from('>L',self._contents,offset)[0]def_unpack_crc32_checksum(self,i):# Not stored in v1 index filesreturnNoneclassPackIndex2(FilePackIndex):"""Version 2 Pack Index file."""def__init__(self,filename,file=None,contents=None,size=None):super(PackIndex2,self).__init__(filename,file,contents,size)ifself._contents[:4]!='\377tOc':raiseAssertionError('Not a v2 pack index file')(self.version,)=unpack_from('>L',self._contents,4)ifself.version!=2:raiseAssertionError('Version was %d'%self.version)self._fan_out_table=self._read_fan_out_table(8)self._name_table_offset=8+0x100*4self._crc32_table_offset=self._name_table_offset+20*len(self)self._pack_offset_table_offset=(self._crc32_table_offset+4*len(self)) self._pack_offset_largetable_offset = (self._pack_offset_table_offset +
4 * len(self))
- def _unpack_entry(self, i):
return (self._unpack_name(i), self._unpack_offset(i),
self._unpack_crc32_checksum(i))
def_unpack_name(self,i):offset=self._name_table_offset+i*20returnself._contents[offset:offset+20]def_unpack_offset(self,i):offset=self._pack_offset_table_offset+i*4offset=unpack_from('>L',self._contents,offset)[0]if(offset&0x80000000):offset=self._pack_offset_largetable_offset+(offset&0x7fffffff)*8offset=unpack_from('>Q',self._contents,offset)[0]returnoffsetdef_unpack_crc32_checksum(self,i):returnunpack_from('>L',self._contents,self._crc32_table_offset+i*4)[0]defread_pack_header(read):"""Read the header of a pack file. :param read: Read function :return: Tuple of (pack version, number of objects). If no data is available to read, returns (None, None). """header=read(12)ifnotheader:returnNone,Noneifheader[:4]!='PACK':raiseAssertionError('Invalid pack header %r'%header)(version,)=unpack_from('>L',header,4)ifversionnotin(2,3):raiseAssertionError('Version was %d'%version)(num_objects,)=unpack_from('>L',header,8)return(version,num_objects)defchunks_length(chunks):returnsum(imap(len,chunks))defunpack_object(read_all,read_some=None,compute_crc32=False,include_comp=False,zlib_bufsize=_ZLIB_BUFSIZE):"""Unpack a Git object. :param read_all: Read function that blocks until the number of requested bytes are read. :param read_some: Read function that returns at least one byte, but may not return the number of bytes requested. :param compute_crc32: If True, compute the CRC32 of the compressed data. If False, the returned CRC32 will be None. :param include_comp: If True, include compressed data in the result. :param zlib_bufsize: An optional buffer size for zlib operations. :return: A tuple of (unpacked, unused), where unused is the unused data leftover from decompression, and unpacked in an UnpackedObject with the following attrs set: * obj_chunks (for non-delta types) * pack_type_num * delta_base (for delta types) * comp_chunks (if include_comp is True) * decomp_chunks * decomp_len * crc32 (if compute_crc32 is True) """ifread_someisNone:read_some=read_allifcompute_crc32:crc32=0else:crc32=Nonebytes,crc32=take_msb_bytes(read_all,crc32=crc32)type_num=(bytes[0]>>4)&0x07size=bytes[0]&0x0ffori,byteinenumerate(bytes[1:]):size+=(byte&0x7f)<<((i*7)+4)raw_base=len(bytes)iftype_num==OFS_DELTA:bytes,crc32=take_msb_bytes(read_all,crc32=crc32)raw_base+=len(bytes)ifbytes[-1]&0x80:raiseAssertionErrordelta_base_offset=bytes[0]&0x7fforbyteinbytes[1:]:delta_base_offset+=1delta_base_offset<<=7delta_base_offset+=(byte&0x7f)delta_base=delta_base_offseteliftype_num==REF_DELTA:delta_base=read_all(20)ifcompute_crc32:crc32=binascii.crc32(delta_base,crc32)raw_base+=20else:delta_base=Noneunpacked=UnpackedObject(type_num,delta_base,size,crc32)unused=read_zlib_chunks(read_some,unpacked,buffer_size=zlib_bufsize,include_comp=include_comp)returnunpacked,unuseddef_compute_object_size((num,obj)):"""Compute the size of a unresolved object for use with LRUSizeCache."""ifnuminDELTA_TYPES:returnchunks_length(obj[1])returnchunks_length(obj)classPackStreamReader(object):"""Class to read a pack stream. The pack is read from a ReceivableProtocol using read() or recv() as appropriate. """def__init__(self,read_all,read_some=None,zlib_bufsize=_ZLIB_BUFSIZE):self.read_all=read_allifread_someisNone:self.read_some=read_allelse:self.read_some=read_someself.sha=make_sha()self._offset=0self._rbuf=StringIO()# trailer is a deque to avoid memory allocation on small readsself._trailer=deque()self._zlib_bufsize=zlib_bufsizedef_read(self,read,size):"""Read up to size bytes using the given callback. As a side effect, update the verifier's hash (excluding the last 20 bytes read). :param read: The read callback to read from. :param size: The maximum number of bytes to read; the particular behavior is callback-specific. """data=read(size)# maintain a trailer of the last 20 bytes we've readn=len(data)self._offset+=ntn=len(self._trailer)ifn>=20:to_pop=tnto_add=20else:to_pop=max(n+tn-20,0)to_add=nfor_inxrange(to_pop):self.sha.update(self._trailer.popleft())self._trailer.extend(data[-to_add:])# hash everything but the trailerself.sha.update(data[:-to_add])returndatadef_buf_len(self):buf=self._rbufstart=buf.tell()buf.seek(0,SEEK_END)end=buf.tell()buf.seek(start)returnend-start@propertydefoffset(self):returnself._offset-self._buf_len()defread(self,size):"""Read, blocking until size bytes are read."""buf_len=self._buf_len()ifbuf_len>=size:returnself._rbuf.read(size)buf_data=self._rbuf.read()self._rbuf=StringIO()returnbuf_data+self._read(self.read_all,size-buf_len)defrecv(self,size):"""Read up to size bytes, blocking until one byte is read."""buf_len=self._buf_len()ifbuf_len:data=self._rbuf.read(size)ifsize>=buf_len:self._rbuf=StringIO()returndatareturnself._read(self.read_some,size)def__len__(self):returnself._num_objectsdefread_objects(self,compute_crc32=False):"""Read the objects in this pack file. :param compute_crc32: If True, compute the CRC32 of the compressed data. If False, the returned CRC32 will be None. :return: Iterator over UnpackedObjects with the following members set: offset obj_type_num obj_chunks (for non-delta types) delta_base (for delta types) decomp_chunks decomp_len crc32 (if compute_crc32 is True) :raise ChecksumMismatch: if the checksum of the pack contents does not match the checksum in the pack trailer. :raise zlib.error: if an error occurred during zlib decompression. :raise IOError: if an error occurred writing to the output file. """pack_version,self._num_objects=read_pack_header(self.read)ifpack_versionisNone:returnforiinxrange(self._num_objects):offset=self.offsetunpacked,unused=unpack_object(self.read,read_some=self.recv,compute_crc32=compute_crc32,zlib_bufsize=self._zlib_bufsize)unpacked.offset=offset# prepend any unused data to current read bufferbuf=StringIO()buf.write(unused)buf.write(self._rbuf.read())buf.seek(0)self._rbuf=bufyieldunpackedifself._buf_len()<20:# If the read buffer is full, then the last read() got the whole# trailer off the wire. If not, it means there is still some of the# trailer to read. We need to read() all 20 bytes; N come from the# read buffer and (20 - N) come from the wire.self.read(20)pack_sha=''.join(self._trailer)ifpack_sha!=self.sha.digest():raiseChecksumMismatch(sha_to_hex(pack_sha),self.sha.hexdigest())classPackStreamCopier(PackStreamReader):"""Class to verify a pack stream as it is being read. The pack is read from a ReceivableProtocol using read() or recv() as appropriate and written out to the given file-like object. """def__init__(self,read_all,read_some,outfile,delta_iter=None):"""Initialize the copier. :param read_all: Read function that blocks until the number of requested bytes are read. :param read_some: Read function that returns at least one byte, but may not return the number of bytes requested. :param outfile: File-like object to write output through. :param delta_iter: Optional DeltaChainIterator to record deltas as we read them. """super(PackStreamCopier,self).__init__(read_all,read_some=read_some)self.outfile=outfileself._delta_iter=delta_iterdef_read(self,read,size):"""Read data from the read callback and write it to the file."""data=super(PackStreamCopier,self)._read(read,size)self.outfile.write(data)returndatadefverify(self):"""Verify a pack stream and write it to the output file. See PackStreamReader.iterobjects for a list of exceptions this may throw. """ifself._delta_iter:forunpackedinself.read_objects():self._delta_iter.record(unpacked)else:for_inself.read_objects():passdefobj_sha(type,chunks):"""Compute the SHA for a numeric type and object chunks."""sha=make_sha()sha.update(object_header(type,chunks_length(chunks)))forchunkinchunks:sha.update(chunk)returnsha.digest()defcompute_file_sha(f,start_ofs=0,end_ofs=0,buffer_size=1<<16):"""Hash a portion of a file into a new SHA. :param f: A file-like object to read from that supports seek(). :param start_ofs: The offset in the file to start reading at. :param end_ofs: The offset in the file to end reading at, relative to the end of the file. :param buffer_size: A buffer size for reading. :return: A new SHA object updated with data read from the file. """sha=make_sha()f.seek(0,SEEK_END)todo=f.tell()+end_ofs-start_ofsf.seek(start_ofs)whiletodo:data=f.read(min(todo,buffer_size))sha.update(data)todo-=len(data)returnshaclassPackData(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=filenameself._size=sizeself._header_size=12iffileisNone: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@classmethoddeffrom_file(cls,file,size):returncls(str(file),file=file,size=size)@classmethoddeffrom_path(cls,path):returncls(filename=path)defclose(self):self._file.close()def_get_size(self):ifself._sizeisnotNone:returnself._sizeself._size=os.path.getsize(self._filename)ifself._size<self._header_size:errmsg=('%s is too small for a packfile (%d < %d)'%(self._filename,self._size,self._header_size))raiseAssertionError(errmsg)returnself._sizedef__len__(self):"""Returns the number of objects in this pack."""returnself._num_objectsdefcalculate_checksum(self):"""Calculate the checksum for this pack. :return: 20-byte binary SHA1 digest """returncompute_file_sha(self._file,end_ofs=-20).digest()defget_ref(self,sha):"""Get the object for a ref SHA, only looking in this pack."""# TODO: cache these resultsifself.packisNone:raiseKeyError(sha)offset=self.pack.index.object_index(sha)ifnotoffset:raiseKeyError(sha)type,obj=self.get_object_at(offset)returnoffset,type,objdefresolve_object(self,offset,type,obj,get_ref=None):"""Resolve an object, possibly resolving deltas when necessary. :return: Tuple with object type and contents. """iftypenotinDELTA_TYPES:returntype,objifget_refisNone:get_ref=self.get_refiftype==OFS_DELTA:(delta_offset,delta)=obj# TODO: clean up asserts and replace with nicer error messagesassertisinstance(offset,int)orisinstance(offset,long)assertisinstance(delta_offset,int)orisinstance(offset,long)base_offset=offset-delta_offsettype,base_obj=self.get_object_at(base_offset)assertisinstance(type,int)eliftype==REF_DELTA:(basename,delta)=objassertisinstance(basename,str)andlen(basename)==20base_offset,type,base_obj=get_ref(basename)assertisinstance(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.ifoffsetisnotNone:self._offset_cache[offset]=type,chunksreturntype,chunksdefiterobjects(self,progress=None,compute_crc32=True):self._file.seek(self._header_size)foriinxrange(1,self._num_objects+1):offset=self._file.tell()unpacked,unused=unpack_object(self._file.read,compute_crc32=compute_crc32)ifprogressisnotNone:progress(i,self._num_objects)yield(offset,unpacked.pack_type_num,unpacked._obj(),unpacked.crc32)self._file.seek(-len(unused),SEEK_CUR)# Back up over unused data.def_iter_unpacked(self):# TODO(dborowitz): Merge this with iterobjects, if we can change its# return type.self._file.seek(self._header_size)for_inxrange(self._num_objects):offset=self._file.tell()unpacked,unused=unpack_object(self._file.read,compute_crc32=False)unpacked.offset=offsetyieldunpackedself._file.seek(-len(unused),SEEK_CUR)# Back up over unused data.defiterentries(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) """num_objects=self._num_objectsfori,resultinenumerate(PackIndexer.for_pack_data(self)):ifprogressisnotNone:progress(i,num_objects)yieldresultdefsorted_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()returnretdefcreate_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:returnwrite_pack_index_v1(f,entries,self.calculate_checksum())finally:f.close()defcreate_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:returnwrite_pack_index_v2(f,entries,self.calculate_checksum())finally:f.close()defcreate_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 """ifversion==1:returnself.create_index_v1(filename,progress)elifversion==2:returnself.create_index_v2(filename,progress)else:raiseValueError('unknown index format %d'%version)defget_stored_checksum(self):"""Return the expected checksum stored in this pack."""self._file.seek(-20,SEEK_END)returnself._file.read(20)defcheck(self):"""Check the consistency of this pack."""actual=self.calculate_checksum()stored=self.get_stored_checksum()ifactual!=stored:raiseChecksumMismatch(stored,actual)defget_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. """ifoffsetinself._offset_cache:returnself._offset_cache[offset]assertisinstance(offset,long)orisinstance(offset,int),\
'offset was %r'%offsetassertoffset>=self._header_sizeself._file.seek(offset)unpacked,_=unpack_object(self._file.read)return(unpacked.pack_type_num,unpacked._obj())classDeltaChainIterator(object):"""Abstract iterator over pack data based on delta chains. Each object in the pack is guaranteed to be inflated exactly once, regardless of how many objects reference it as a delta base. As a result, memory usage is proportional to the length of the longest delta chain. Subclasses can override _result to define the result type of the iterator. By default, results are UnpackedObjects with the following members set: * offset * obj_type_num * obj_chunks * pack_type_num * delta_base (for delta types) * comp_chunks (if _include_comp is True) * decomp_chunks * decomp_len * crc32 (if _compute_crc32 is True) """_compute_crc32=False_include_comp=Falsedef__init__(self,file_obj,resolve_ext_ref=None):self._file=file_objself._resolve_ext_ref=resolve_ext_refself._pending_ofs=defaultdict(list)self._pending_ref=defaultdict(list)self._full_ofs=[]self._shas={}self._ext_refs=[]@classmethoddeffor_pack_data(cls,pack_data,resolve_ext_ref=None):walker=cls(None,resolve_ext_ref=resolve_ext_ref)walker.set_pack_data(pack_data)forunpackedinpack_data._iter_unpacked():walker.record(unpacked)returnwalkerdefrecord(self,unpacked):type_num=unpacked.pack_type_numoffset=unpacked.offsetiftype_num==OFS_DELTA:base_offset=offset-unpacked.delta_baseself._pending_ofs[base_offset].append(offset)eliftype_num==REF_DELTA:self._pending_ref[unpacked.delta_base].append(offset)else:self._full_ofs.append((offset,type_num))defset_pack_data(self,pack_data):self._file=pack_data._filedef_walk_all_chains(self):foroffset,type_numinself._full_ofs:forresultinself._follow_chain(offset,type_num,None):yieldresultforresultinself._walk_ref_chains():yieldresultassertnotself._pending_ofsdef_ensure_no_pending(self):ifself._pending_ref:raiseKeyError([sha_to_hex(s)forsinself._pending_ref])def_walk_ref_chains(self):ifnotself._resolve_ext_ref:self._ensure_no_pending()returnforbase_sha,pendinginsorted(self._pending_ref.iteritems()):try:type_num,chunks=self._resolve_ext_ref(base_sha)exceptKeyError:# Not an external ref, but may depend on one. Either it will get# popped via a _follow_chain call, or we will raise an error# below.continueself._ext_refs.append(base_sha)self._pending_ref.pop(base_sha)fornew_offsetinpending:forresultinself._follow_chain(new_offset,type_num,chunks):yieldresultself._ensure_no_pending()def_result(self,unpacked):returnunpackeddef_resolve_object(self,offset,obj_type_num,base_chunks):self._file.seek(offset)unpacked,_=unpack_object(self._file.read,include_comp=self._include_comp,compute_crc32=self._compute_crc32)unpacked.offset=offsetifbase_chunksisNone:assertunpacked.pack_type_num==obj_type_numelse:assertunpacked.pack_type_numinDELTA_TYPESunpacked.obj_type_num=obj_type_numunpacked.obj_chunks=apply_delta(base_chunks,unpacked.decomp_chunks)returnunpackeddef_follow_chain(self,offset,obj_type_num,base_chunks):# Unlike PackData.get_object_at, there is no need to cache offsets as# this approach by design inflates each object exactly once.unpacked=self._resolve_object(offset,obj_type_num,base_chunks)yieldself._result(unpacked)pending=chain(self._pending_ofs.pop(unpacked.offset,[]),self._pending_ref.pop(unpacked.sha(),[]))fornew_offsetinpending:fornew_resultinself._follow_chain(new_offset,unpacked.obj_type_num,unpacked.obj_chunks):yieldnew_resultdef__iter__(self):returnself._walk_all_chains()defext_refs(self):returnself._ext_refsclassPackIndexer(DeltaChainIterator):"""Delta chain iterator that yields index entries."""_compute_crc32=Truedef_result(self,unpacked):returnunpacked.sha(),unpacked.offset,unpacked.crc32classPackInflater(DeltaChainIterator):"""Delta chain iterator that yields ShaFile objects."""def_result(self,unpacked):returnunpacked.sha_file()classSHA1Reader(object):"""Wrapper around a file-like object that remembers the SHA1 of its data."""def__init__(self,f):self.f=fself.sha1=make_sha('')defread(self,num=None):data=self.f.read(num)self.sha1.update(data)returndatadefcheck_sha(self):stored=self.f.read(20)ifstored!=self.sha1.digest():raiseChecksumMismatch(self.sha1.hexdigest(),sha_to_hex(stored))defclose(self):returnself.f.close()deftell(self):returnself.f.tell()classSHA1Writer(object):"""Wrapper around a file-like object that remembers the SHA1 of its data."""def__init__(self,f):self.f=fself.length=0self.sha1=make_sha('')defwrite(self,data):self.sha1.update(data)self.f.write(data)self.length+=len(data)defwrite_sha(self):sha=self.sha1.digest()assertlen(sha)==20self.f.write(sha)self.length+=len(sha)returnshadefclose(self):sha=self.write_sha()self.f.close()returnshadefoffset(self):returnself.lengthdeftell(self):returnself.f.tell()defpack_object_header(type_num,delta_base,size):"""Create a pack object header for the given object info. :param type_num: Numeric type of the object. :param delta_base: Delta base offset or ref, or None for whole objects. :param size: Uncompressed object size. :return: A header for a packed object. """header=''c=(type_num<<4)|(size&15)size>>=4whilesize:header+=(chr(c|0x80))c=size&0x7fsize>>=7header+=chr(c)iftype_num==OFS_DELTA:ret=[delta_base&0x7f]delta_base>>=7whiledelta_base:delta_base-=1ret.insert(0,0x80|(delta_base&0x7f))delta_base>>=7header+=''.join([chr(x)forxinret])eliftype_num==REF_DELTA:assertlen(delta_base)==20header+=delta_basereturnheaderdefwrite_pack_object(f,type,object,sha=None):"""Write pack object to a file. :param f: File to write to :param type: Numeric type of the object :param object: Object to write :return: Tuple with offset at which the object was written, and crc32 """iftypeinDELTA_TYPES:delta_base,object=objectelse:delta_base=Noneheader=pack_object_header(type,delta_base,len(object))comp_data=zlib.compress(object)crc32=0fordatain(header,comp_data):f.write(data)ifshaisnotNone:sha.update(data)crc32=binascii.crc32(data,crc32)returncrc32&0xffffffffdefwrite_pack(filename,objects,num_objects=None):"""Write a new pack data file. :param filename: Path to the new pack file (without .pack extension) :param objects: Iterable of (object, path) tuples to write. Should provide __len__ :return: Tuple with checksum of pack file and index file """ifnum_objectsisnotNone:warnings.warn('num_objects argument to write_pack is deprecated',DeprecationWarning)f=GitFile(filename+'.pack','wb')try:entries,data_sum=write_pack_objects(f,objects,num_objects=num_objects)finally:f.close()entries=[(k,v[0],v[1])for(k,v)inentries.iteritems()]entries.sort()f=GitFile(filename+'.idx','wb')try:returndata_sum,write_pack_index_v2(f,entries,data_sum)finally:f.close()defwrite_pack_header(f,num_objects):"""Write a pack header for the given number of objects."""f.write('PACK')# Pack headerf.write(struct.pack('>L',2))# Pack versionf.write(struct.pack('>L',num_objects))# Number of objects in packdefdeltify_pack_objects(objects,window=10):"""Generate deltas for pack objects. :param objects: Objects to deltify :param window: Window size :return: Iterator over type_num, object id, delta_base, content delta_base is None for full text entries """# Build a list of objects ordered by the magic Linus heuristic# This helps us find good objects to diff against usmagic=[]forobj,pathinobjects:magic.append((obj.type_num,path,-obj.raw_length(),obj))magic.sort()possible_bases=deque()fortype_num,path,neg_length,oinmagic:raw=o.as_raw_string()winner=rawwinner_base=Noneforbaseinpossible_bases:ifbase.type_num!=type_num:continuedelta=create_delta(base.as_raw_string(),raw)iflen(delta)<len(winner):winner_base=base.sha().digest()winner=deltayieldtype_num,o.sha().digest(),winner_base,winnerpossible_bases.appendleft(o)whilelen(possible_bases)>window:possible_bases.pop()defwrite_pack_objects(f,objects,window=10,num_objects=None):"""Write a new pack data file. :param f: File to write to :param objects: Iterable of (object, path) tuples to write. Should provide __len__ :param window: Sliding window size for searching for deltas; currently unimplemented :param num_objects: Number of objects (do not use, deprecated) :return: Dict mapping id -> (offset, crc32 checksum), pack checksum """ifnum_objectsisNone:num_objects=len(objects)# FIXME: pack_contents = deltify_pack_objects(objects, window)pack_contents=((o.type_num,o.sha().digest(),None,o.as_raw_string())for(o,path)inobjects)returnwrite_pack_data(f,num_objects,pack_contents)defwrite_pack_data(f,num_records,records):"""Write a new pack data file. :param f: File to write to :param num_records: Number of records :param records: Iterator over type_num, object_id, delta_base, raw :return: Dict mapping id -> (offset, crc32 checksum), pack checksum """# Write the packentries={}f=SHA1Writer(f)write_pack_header(f,num_records)fortype_num,object_id,delta_base,rawinrecords:ifdelta_baseisnotNone:try:base_offset,base_crc32=entries[delta_base]exceptKeyError:type_num=REF_DELTAraw=(delta_base,raw)else:type_num=OFS_DELTAraw=(base_offset,raw)offset=f.offset()crc32=write_pack_object(f,type_num,raw)entries[object_id]=(offset,crc32)returnentries,f.write_sha()defwrite_pack_index_v1(f,entries,pack_checksum):"""Write a new pack index file. :param f: A file-like object to write to :param entries: List of tuples with object name (sha), offset_in_pack, and crc32_checksum. :param pack_checksum: Checksum of the pack file. :return: The SHA of the written index file """f=SHA1Writer(f)fan_out_table=defaultdict(lambda:0)for(name,offset,entry_checksum)inentries:fan_out_table[ord(name[0])]+=1# Fan-out tableforiinrange(0x100): f.write(struct.pack('>L', fan_out_table[i]))
fan_out_table[i+1] += fan_out_table[i]
for (name, offset, entry_checksum) in entries:
+ assert offset <= 0xffffffff f.write(struct.pack('>L20s', offset, name))
assert len(pack_checksum) == 20
f.write(pack_checksum)
returnf.write_sha()defcreate_delta(base_buf,target_buf):"""Use python difflib to work out how to transform base_buf to target_buf. :param base_buf: Base buffer :param target_buf: Target buffer """assertisinstance(base_buf,str)assertisinstance(target_buf,str)out_buf=''# write delta headerdefencode_size(size):ret=''c=size&0x7fsize>>=7whilesize:ret+=chr(c|0x80)c=size&0x7fsize>>=7ret+=chr(c)returnretout_buf+=encode_size(len(base_buf))out_buf+=encode_size(len(target_buf))# write out delta opcodesseq=difflib.SequenceMatcher(a=base_buf,b=target_buf)foropcode,i1,i2,j1,j2inseq.get_opcodes():# Git patch opcodes don't care about deletes!#if opcode == 'replace' or opcode == 'delete':# passifopcode=='equal':# If they are equal, unpacker will use data from base_buf# Write out an opcode that says what range to usescratch=''op=0x80o=i1foriinrange(4):ifo&0xff<<i*8:scratch+=chr((o>>i*8)&0xff)op|=1<<is=i2-i1foriinrange(2):ifs&0xff<<i*8:scratch+=chr((s>>i*8)&0xff)op|=1<<(4+i)out_buf+=chr(op)out_buf+=scratchifopcode=='replace'oropcode=='insert':# If we are replacing a range or adding one, then we just# output it to the stream (prefixed by its size)s=j2-j1o=j1whiles>127:out_buf+=chr(127)out_buf+=target_buf[o:o+127]s-=127o+=127out_buf+=chr(s)out_buf+=target_buf[o:o+s]returnout_bufdefapply_delta(src_buf,delta):"""Based on the similar function in git's patch-delta.c. :param src_buf: Source buffer :param delta: Delta instructions """iftype(src_buf)!=str:src_buf=''.join(src_buf)iftype(delta)!=str:delta=''.join(delta)out=[]index=0delta_length=len(delta)defget_delta_header_size(delta,index):size=0i=0whiledelta:cmd=ord(delta[index])index+=1size|=(cmd&~0x80)<<ii+=7ifnotcmd&0x80:breakreturnsize,indexsrc_size,index=get_delta_header_size(delta,index)dest_size,index=get_delta_header_size(delta,index)assertsrc_size==len(src_buf),'%d vs %d'%(src_size,len(src_buf))whileindex<delta_length:cmd=ord(delta[index])index+=1ifcmd&0x80:cp_off=0foriinrange(4):ifcmd&(1<<i):x=ord(delta[index])index+=1cp_off|=x<<(i*8)cp_size=0foriinrange(3):ifcmd&(1<<(4+i)):x=ord(delta[index])index+=1cp_size|=x<<(i*8)ifcp_size==0:cp_size=0x10000if(cp_off+cp_size<cp_sizeorcp_off+cp_size>src_sizeorcp_size>dest_size):breakout.append(src_buf[cp_off:cp_off+cp_size])elifcmd!=0:out.append(delta[index:index+cmd])index+=cmdelse:raiseApplyDeltaError('Invalid opcode 0')ifindex!=delta_length:raiseApplyDeltaError('delta not empty: %r'%delta[index:])ifdest_size!=chunks_length(out):raiseApplyDeltaError('dest size incorrect')returnoutdefwrite_pack_index_v2(f,entries,pack_checksum):"""Write a new pack index file. :param f: File-like object to write to :param entries: List of tuples with object name (sha), offset_in_pack, and crc32_checksum. :param pack_checksum: Checksum of the pack file. :return: The SHA of the index file written """f=SHA1Writer(f)f.write('\377tOc')# Magic!f.write(struct.pack('>L',2))fan_out_table=defaultdict(lambda:0) for (name, offset, entry_checksum) in entries:
fan_out_table[ord(name[0])] += 1
# Fan-out table
+ largetable = [] for i in range(0x100):
f.write(struct.pack('>L', fan_out_table[i]))
fan_out_table[i+1] += fan_out_table[i]
for(name,offset,entry_checksum)inentries:f.write(name) for (name, offset, entry_checksum) in entries:
f.write(struct.pack('>L', entry_checksum))
for (name, offset, entry_checksum) in entries:
-# FIXME: handle if MSBitissetinoffset- f.write(struct.pack('>L', offset))
-#FIXME: handletable for pack files > 8 Gb+ if offset<0x80000000:+ f.write(struct.pack('>L', offset))
+ else:
+ f.write(struct.pack('>L', 0x80000000 + len(largetable)))+ largetable.append(offset)+ for offset in largetable:+ f.write(struct.pack('>Q',offset)) assert len(pack_checksum) == 20
f.write(pack_checksum)
return f.write_sha()
classPack(object):"""A Git pack object."""def__init__(self,basename):self._basename=basenameself._data=Noneself._idx=Noneself._idx_path=self._basename+'.idx'self._data_path=self._basename+'.pack'self._data_load=lambda:PackData(self._data_path)self._idx_load=lambda:load_pack_index(self._idx_path)@classmethoddeffrom_lazy_objects(self,data_fn,idx_fn):"""Create a new pack object from callables to load pack data and index objects."""ret=Pack('')ret._data_load=data_fnret._idx_load=idx_fnreturnret@classmethoddeffrom_objects(self,data,idx):"""Create a new pack object from pack data and index objects."""ret=Pack('')ret._data_load=lambda:dataret._idx_load=lambda:idxreturnretdefname(self):"""The SHA over the SHAs of the objects in this pack."""returnself.index.objects_sha1()@propertydefdata(self):"""The pack data object being used."""ifself._dataisNone:self._data=self._data_load()self._data.pack=selfself.check_length_and_checksum()returnself._data@propertydefindex(self):"""The index being used. :note: This may be an in-memory index """ifself._idxisNone:self._idx=self._idx_load()returnself._idxdefclose(self):ifself._dataisnotNone:self._data.close()self.index.close()def__eq__(self,other):returntype(self)==type(other)andself.index==other.indexdef__len__(self):"""Number of entries in this pack."""returnlen(self.index)def__repr__(self):return'%s(%r)'%(self.__class__.__name__,self._basename)def__iter__(self):"""Iterate over all the sha1s of the objects in this pack."""returniter(self.index)defcheck_length_and_checksum(self):"""Sanity check the length and checksum of the pack index and data."""assertlen(self.index)==len(self.data)idx_stored_checksum=self.index.get_pack_checksum()data_stored_checksum=self.data.get_stored_checksum()ifidx_stored_checksum!=data_stored_checksum:raiseChecksumMismatch(sha_to_hex(idx_stored_checksum),sha_to_hex(data_stored_checksum))defcheck(self):"""Check the integrity of this pack. :raise ChecksumMismatch: if a checksum for the index or data is wrong """self.index.check()self.data.check()forobjinself.iterobjects():obj.check()# TODO: object connectivity checksdefget_stored_checksum(self):returnself.data.get_stored_checksum()def__contains__(self,sha1):"""Check whether this pack contains a particular SHA1."""try:self.index.object_index(sha1)returnTrueexceptKeyError:returnFalsedefget_raw(self,sha1):offset=self.index.object_index(sha1)obj_type,obj=self.data.get_object_at(offset)type_num,chunks=self.data.resolve_object(offset,obj_type,obj)returntype_num,''.join(chunks)def__getitem__(self,sha1):"""Retrieve the specified SHA1."""type,uncomp=self.get_raw(sha1)returnShaFile.from_raw_string(type,uncomp)defiterobjects(self):"""Iterate over the objects in this pack."""returniter(PackInflater.for_pack_data(self.data))defpack_tuples(self):"""Provide an iterable for use with write_pack_objects. :return: Object that can iterate over (object, path) tuples and provides __len__ """classPackTupleIterable(object):def__init__(self,pack):self.pack=packdef__len__(self):returnlen(self.pack)def__iter__(self):return((o,None)foroinself.pack.iterobjects())returnPackTupleIterable(self)defkeep(self,msg=None):"""Add a .keep file for the pack, preventing git from garbage collecting it. :param msg: A message written inside the .keep file; can be used later to determine whether or not a .keep file is obsolete. :return: The path of the .keep file, as a string. """keepfile_name='%s.keep'%self._basenamekeepfile=GitFile(keepfile_name,'wb')try:ifmsg:keepfile.write(msg)keepfile.write('\n')finally:keepfile.close()returnkeepfile_nametry:fromdulwich._packimportapply_delta,bisect_find_shaexceptImportError:pass
Attach a Trello Card
Add a tag
Your session has expired
You are no longer logged in. Please log in and try your request again.
Filter RSS Feed
This RSS feed URL allows you to see the contents of your current filter using any feed reader.
This link includes a special authentication token. If you share the URL with anyone else, they can see this RSS feed's activity. You can disable these tokens when needed.
Your current filter is unsaved; changing it won't affect this RSS feed.