diff --git a/dulwich/index.py b/dulwich/index.py index b938e410..1b2289f6 100644 --- a/dulwich/index.py +++ b/dulwich/index.py @@ -1,818 +1,841 @@ # index.py -- File parser/writer for the git index file # Copyright (C) 2008-2013 Jelmer Vernooij # # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Parser for the git index file format.""" import collections import errno import os import stat import struct import sys from dulwich.file import GitFile from dulwich.objects import ( Blob, S_IFGITLINK, S_ISGITLINK, Tree, hex_to_sha, sha_to_hex, ) from dulwich.pack import ( SHA1Reader, SHA1Writer, ) IndexEntry = collections.namedtuple( 'IndexEntry', [ 'ctime', 'mtime', 'dev', 'ino', 'mode', 'uid', 'gid', 'size', 'sha', 'flags']) FLAG_STAGEMASK = 0x3000 FLAG_VALID = 0x8000 FLAG_EXTENDED = 0x4000 def pathsplit(path): """Split a /-delimited path into a directory part and a basename. Args: path: The path to split. Returns: Tuple with directory name and basename """ try: (dirname, basename) = path.rsplit(b"/", 1) except ValueError: return (b"", path) else: return (dirname, basename) def pathjoin(*args): """Join a /-delimited path. """ return b"/".join([p for p in args if p]) def read_cache_time(f): """Read a cache time. Args: f: File-like object to read from Returns: Tuple with seconds and nanoseconds """ return struct.unpack(">LL", f.read(8)) def write_cache_time(f, t): """Write a cache time. Args: f: File-like object to write to t: Time to write (as int, float or tuple with secs and nsecs) """ if isinstance(t, int): t = (t, 0) elif isinstance(t, float): (secs, nsecs) = divmod(t, 1.0) t = (int(secs), int(nsecs * 1000000000)) elif not isinstance(t, tuple): raise TypeError(t) f.write(struct.pack(">LL", *t)) def read_cache_entry(f): """Read an entry from a cache file. Args: f: File-like object to read from Returns: tuple with: device, inode, mode, uid, gid, size, sha, flags """ beginoffset = f.tell() ctime = read_cache_time(f) mtime = read_cache_time(f) (dev, ino, mode, uid, gid, size, sha, flags, ) = \ struct.unpack(">LLLLLL20sH", f.read(20 + 4 * 6 + 2)) name = f.read((flags & 0x0fff)) # Padding: real_size = ((f.tell() - beginoffset + 8) & ~7) f.read((beginoffset + real_size) - f.tell()) return (name, ctime, mtime, dev, ino, mode, uid, gid, size, sha_to_hex(sha), flags & ~0x0fff) def write_cache_entry(f, entry): """Write an index entry to a file. Args: f: File object entry: Entry to write, tuple with: (name, ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) """ beginoffset = f.tell() (name, ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = entry write_cache_time(f, ctime) write_cache_time(f, mtime) flags = len(name) | (flags & ~0x0fff) f.write(struct.pack( b'>LLLLLL20sH', dev & 0xFFFFFFFF, ino & 0xFFFFFFFF, mode, uid, gid, size, hex_to_sha(sha), flags)) f.write(name) real_size = ((f.tell() - beginoffset + 8) & ~7) f.write(b'\0' * ((beginoffset + real_size) - f.tell())) def read_index(f): """Read an index file, yielding the individual entries.""" header = f.read(4) if header != b'DIRC': raise AssertionError("Invalid index file header: %r" % header) (version, num_entries) = struct.unpack(b'>LL', f.read(4 * 2)) assert version in (1, 2) for i in range(num_entries): yield read_cache_entry(f) def read_index_dict(f): """Read an index file and return it as a dictionary. Args: f: File object to read from """ ret = {} for x in read_index(f): ret[x[0]] = IndexEntry(*x[1:]) return ret def write_index(f, entries): """Write an index file. - :param f: File-like object to write to - :param entries: Iterable over the entries to write + Args: + f: File-like object to write to + entries: Iterable over the entries to write """ f.write(b'DIRC') f.write(struct.pack(b'>LL', 2, len(entries))) for x in entries: write_cache_entry(f, x) def write_index_dict(f, entries): """Write an index file based on the contents of a dictionary. """ entries_list = [] for name in sorted(entries): entries_list.append((name,) + tuple(entries[name])) write_index(f, entries_list) def cleanup_mode(mode): """Cleanup a mode value. This will return a mode that can be stored in a tree object. - :param mode: Mode to clean up. + Args: + mode: Mode to clean up. """ if stat.S_ISLNK(mode): return stat.S_IFLNK elif stat.S_ISDIR(mode): return stat.S_IFDIR elif S_ISGITLINK(mode): return S_IFGITLINK ret = stat.S_IFREG | 0o644 ret |= (mode & 0o111) return ret class Index(object): """A Git Index file.""" def __init__(self, filename): """Open an index file. - :param filename: Path to the index file + Args: + filename: Path to the index file """ self._filename = filename self.clear() self.read() @property def path(self): return self._filename def __repr__(self): return "%s(%r)" % (self.__class__.__name__, self._filename) def write(self): """Write current contents of index to disk.""" f = GitFile(self._filename, 'wb') try: f = SHA1Writer(f) write_index_dict(f, self._byname) 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 __len__(self): """Number of entries in this index file.""" return len(self._byname) def __getitem__(self, name): """Retrieve entry by relative path. - :return: tuple with (ctime, mtime, dev, ino, mode, uid, gid, size, sha, + Returns: tuple with (ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) """ return self._byname[name] def __iter__(self): """Iterate over the paths in this index.""" return iter(self._byname) def get_sha1(self, path): """Return the (git object) SHA1 for the object at a path.""" return self[path].sha def get_mode(self, path): """Return the POSIX file mode for the object at a path.""" return self[path].mode def iterobjects(self): """Iterate over path, sha, mode tuples for use with commit_tree.""" for path in self: entry = self[path] yield path, entry.sha, cleanup_mode(entry.mode) def iterblobs(self): import warnings warnings.warn('Use iterobjects() instead.', PendingDeprecationWarning) return self.iterobjects() def clear(self): """Remove all contents from this index.""" self._byname = {} def __setitem__(self, name, x): assert isinstance(name, bytes) assert len(x) == 10 # Remove the old entry if any self._byname[name] = IndexEntry(*x) def __delitem__(self, name): assert isinstance(name, bytes) del self._byname[name] def iteritems(self): return self._byname.items() def items(self): return self._byname.items() def update(self, entries): for name, value in entries.items(): self[name] = value def changes_from_tree(self, object_store, tree, want_unchanged=False): """Find the differences between the contents of this index and a tree. - :param object_store: Object store to use for retrieving tree contents - :param tree: SHA1 of the root tree - :param want_unchanged: Whether unchanged files should be reported - :return: Iterator over tuples with (oldpath, newpath), (oldmode, + Args: + object_store: Object store to use for retrieving tree contents + tree: SHA1 of the root tree + want_unchanged: Whether unchanged files should be reported + Returns: Iterator over tuples with (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) """ def lookup_entry(path): entry = self[path] return entry.sha, entry.mode for (name, mode, sha) in changes_from_tree( self._byname.keys(), lookup_entry, object_store, tree, want_unchanged=want_unchanged): yield (name, mode, sha) def commit(self, object_store): """Create a new tree from an index. - :param object_store: Object store to save the tree in - :return: Root tree SHA + Args: + object_store: Object store to save the tree in + Returns: + Root tree SHA """ return commit_tree(object_store, self.iterobjects()) def commit_tree(object_store, blobs): """Commit a new tree. - :param object_store: Object store to add trees to - :param blobs: Iterable over blob path, sha, mode entries - :return: SHA1 of the created tree. + Args: + object_store: Object store to add trees to + blobs: Iterable over blob path, sha, mode entries + Returns: + SHA1 of the created tree. """ trees = {b'': {}} def add_tree(path): if path in trees: return trees[path] dirname, basename = pathsplit(path) t = add_tree(dirname) assert isinstance(basename, bytes) newtree = {} t[basename] = newtree trees[path] = newtree return newtree for path, sha, mode in blobs: tree_path, basename = pathsplit(path) tree = add_tree(tree_path) tree[basename] = (mode, sha) def build_tree(path): tree = Tree() for basename, entry in trees[path].items(): if isinstance(entry, dict): mode = stat.S_IFDIR sha = build_tree(pathjoin(path, basename)) else: (mode, sha) = entry tree.add(basename, mode, sha) object_store.add_object(tree) return tree.id return build_tree(b'') def commit_index(object_store, index): """Create a new tree from an index. - :param object_store: Object store to save the tree in - :param index: Index file - :note: This function is deprecated, use index.commit() instead. - :return: Root tree sha. + Args: + object_store: Object store to save the tree in + index: Index file + Note: This function is deprecated, use index.commit() instead. + Returns: Root tree sha. """ return commit_tree(object_store, index.iterobjects()) def changes_from_tree(names, lookup_entry, object_store, tree, want_unchanged=False): """Find the differences between the contents of a tree and a working copy. - :param names: Iterable of names in the working copy - :param lookup_entry: Function to lookup an entry in the working copy - :param object_store: Object store to use for retrieving tree contents - :param tree: SHA1 of the root tree, or None for an empty tree - :param want_unchanged: Whether unchanged files should be reported - :return: Iterator over tuples with (oldpath, newpath), (oldmode, newmode), + Args: + names: Iterable of names in the working copy + lookup_entry: Function to lookup an entry in the working copy + object_store: Object store to use for retrieving tree contents + tree: SHA1 of the root tree, or None for an empty tree + want_unchanged: Whether unchanged files should be reported + Returns: Iterator over tuples with (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) """ # TODO(jelmer): Support a include_trees option other_names = set(names) if tree is not None: for (name, mode, sha) in object_store.iter_tree_contents(tree): try: (other_sha, other_mode) = lookup_entry(name) except KeyError: # Was removed yield ((name, None), (mode, None), (sha, None)) else: other_names.remove(name) if (want_unchanged or other_sha != sha or other_mode != mode): yield ((name, name), (mode, other_mode), (sha, other_sha)) # Mention added files for name in other_names: try: (other_sha, other_mode) = lookup_entry(name) except KeyError: pass else: yield ((None, name), (None, other_mode), (None, other_sha)) def index_entry_from_stat(stat_val, hex_sha, flags, mode=None): """Create a new index entry from a stat value. - :param stat_val: POSIX stat_result instance - :param hex_sha: Hex sha of the object - :param flags: Index flags + Args: + stat_val: POSIX stat_result instance + hex_sha: Hex sha of the object + flags: Index flags """ if mode is None: mode = cleanup_mode(stat_val.st_mode) return IndexEntry( stat_val.st_ctime, stat_val.st_mtime, stat_val.st_dev, stat_val.st_ino, mode, stat_val.st_uid, stat_val.st_gid, stat_val.st_size, hex_sha, flags) def build_file_from_blob(blob, mode, target_path, honor_filemode=True): """Build a file or symlink on disk based on a Git object. - :param obj: The git object - :param mode: File mode - :param target_path: Path to write to - :param honor_filemode: An optional flag to honor core.filemode setting in + Args: + obj: The git object + mode: File mode + target_path: Path to write to + honor_filemode: An optional flag to honor core.filemode setting in config file, default is core.filemode=True, change executable bit - :return: stat object for the file + Returns: stat object for the file """ try: oldstat = os.lstat(target_path) except OSError as e: if e.errno == errno.ENOENT: oldstat = None else: raise contents = blob.as_raw_string() if stat.S_ISLNK(mode): # FIXME: This will fail on Windows. What should we do instead? if oldstat: os.unlink(target_path) if sys.platform == 'win32' and sys.version_info[0] == 3: # os.readlink on Python3 on Windows requires a unicode string. # TODO(jelmer): Don't assume tree_encoding == fs_encoding tree_encoding = sys.getfilesystemencoding() contents = contents.decode(tree_encoding) target_path = target_path.decode(tree_encoding) os.symlink(contents, target_path) else: if oldstat is not None and oldstat.st_size == len(contents): with open(target_path, 'rb') as f: if f.read() == contents: return oldstat with open(target_path, 'wb') as f: # Write out file f.write(contents) if honor_filemode: os.chmod(target_path, mode) return os.lstat(target_path) INVALID_DOTNAMES = (b".git", b".", b"..", b"") def validate_path_element_default(element): return element.lower() not in INVALID_DOTNAMES def validate_path_element_ntfs(element): stripped = element.rstrip(b". ").lower() if stripped in INVALID_DOTNAMES: return False if stripped == b"git~1": return False return True def validate_path(path, element_validator=validate_path_element_default): """Default path validator that just checks for .git/.""" parts = path.split(b"/") for p in parts: if not element_validator(p): return False else: return True def build_index_from_tree(root_path, index_path, object_store, tree_id, honor_filemode=True, validate_path_element=validate_path_element_default): """Generate and materialize index from a tree - :param tree_id: Tree to materialize - :param root_path: Target dir for materialized index files - :param index_path: Target path for generated index - :param object_store: Non-empty object store holding tree contents - :param honor_filemode: An optional flag to honor core.filemode setting in + Args: + tree_id: Tree to materialize + root_path: Target dir for materialized index files + index_path: Target path for generated index + object_store: Non-empty object store holding tree contents + honor_filemode: An optional flag to honor core.filemode setting in config file, default is core.filemode=True, change executable bit - :param validate_path_element: Function to validate path elements to check + validate_path_element: Function to validate path elements to check out; default just refuses .git and .. directories. - :note:: existing index is wiped and contents are not merged + Note: existing index is wiped and contents are not merged in a working dir. Suitable only for fresh clones. """ index = Index(index_path) if not isinstance(root_path, bytes): root_path = root_path.encode(sys.getfilesystemencoding()) for entry in object_store.iter_tree_contents(tree_id): if not validate_path(entry.path, validate_path_element): continue full_path = _tree_to_fs_path(root_path, entry.path) if not os.path.exists(os.path.dirname(full_path)): os.makedirs(os.path.dirname(full_path)) # TODO(jelmer): Merge new index into working tree if S_ISGITLINK(entry.mode): if not os.path.isdir(full_path): os.mkdir(full_path) st = os.lstat(full_path) # TODO(jelmer): record and return submodule paths else: obj = object_store[entry.sha] st = build_file_from_blob( obj, entry.mode, full_path, honor_filemode=honor_filemode) # Add file to index if not honor_filemode or S_ISGITLINK(entry.mode): # we can not use tuple slicing to build a new tuple, # because on windows that will convert the times to # longs, which causes errors further along st_tuple = (entry.mode, st.st_ino, st.st_dev, st.st_nlink, st.st_uid, st.st_gid, st.st_size, st.st_atime, st.st_mtime, st.st_ctime) st = st.__class__(st_tuple) index[entry.path] = index_entry_from_stat(st, entry.sha, 0) index.write() def blob_from_path_and_stat(fs_path, st): """Create a blob from a path and a stat object. - :param fs_path: Full file system path to file - :param st: A stat object - :return: A `Blob` object + Args: + fs_path: Full file system path to file + st: A stat object + Returns: A `Blob` object """ assert isinstance(fs_path, bytes) blob = Blob() if not stat.S_ISLNK(st.st_mode): with open(fs_path, 'rb') as f: blob.data = f.read() else: if sys.platform == 'win32' and sys.version_info[0] == 3: # os.readlink on Python3 on Windows requires a unicode string. # TODO(jelmer): Don't assume tree_encoding == fs_encoding tree_encoding = sys.getfilesystemencoding() fs_path = fs_path.decode(tree_encoding) blob.data = os.readlink(fs_path).encode(tree_encoding) else: blob.data = os.readlink(fs_path) return blob def read_submodule_head(path): """Read the head commit of a submodule. - :param path: path to the submodule - :return: HEAD sha, None if not a valid head/repository + Args: + path: path to the submodule + Returns: HEAD sha, None if not a valid head/repository """ from dulwich.errors import NotGitRepository from dulwich.repo import Repo # Repo currently expects a "str", so decode if necessary. # TODO(jelmer): Perhaps move this into Repo() ? if not isinstance(path, str): path = path.decode(sys.getfilesystemencoding()) try: repo = Repo(path) except NotGitRepository: return None try: return repo.head() except KeyError: return None def _has_directory_changed(tree_path, entry): """Check if a directory has changed after getting an error. When handling an error trying to create a blob from a path, call this function. It will check if the path is a directory. If it's a directory and a submodule, check the submodule head to see if it's has changed. If not, consider the file as changed as Git tracked a file and not a directory. Return true if the given path should be considered as changed and False otherwise or if the path is not a directory. """ # This is actually a directory if os.path.exists(os.path.join(tree_path, b'.git')): # Submodule head = read_submodule_head(tree_path) if entry.sha != head: return True else: # The file was changed to a directory, so consider it removed. return True return False def get_unstaged_changes(index, root_path, filter_blob_callback=None): """Walk through an index and check for differences against working tree. - :param index: index to check - :param root_path: path in which to find files - :return: iterator over paths with unstaged changes + Args: + index: index to check + root_path: path in which to find files + Returns: iterator over paths with unstaged changes """ # For each entry in the index check the sha1 & ensure not staged if not isinstance(root_path, bytes): root_path = root_path.encode(sys.getfilesystemencoding()) for tree_path, entry in index.iteritems(): full_path = _tree_to_fs_path(root_path, tree_path) try: st = os.lstat(full_path) if stat.S_ISDIR(st.st_mode): if _has_directory_changed(tree_path, entry): yield tree_path continue blob = blob_from_path_and_stat(full_path, st) if filter_blob_callback is not None: blob = filter_blob_callback(blob, tree_path) except EnvironmentError as e: if e.errno == errno.ENOENT: # The file was removed, so we assume that counts as # different from whatever file used to exist. yield tree_path else: raise else: if blob.id != entry.sha: yield tree_path os_sep_bytes = os.sep.encode('ascii') def _tree_to_fs_path(root_path, tree_path): """Convert a git tree path to a file system path. - :param root_path: Root filesystem path - :param tree_path: Git tree path as bytes + Args: + root_path: Root filesystem path + tree_path: Git tree path as bytes - :return: File system path. + Returns: File system path. """ assert isinstance(tree_path, bytes) if os_sep_bytes != b'/': sep_corrected_path = tree_path.replace(b'/', os_sep_bytes) else: sep_corrected_path = tree_path return os.path.join(root_path, sep_corrected_path) def _fs_to_tree_path(fs_path, fs_encoding=None): """Convert a file system path to a git tree path. - :param fs_path: File system path. - :param fs_encoding: File system encoding + Args: + fs_path: File system path. + fs_encoding: File system encoding - :return: Git tree path as bytes + Returns: Git tree path as bytes """ if fs_encoding is None: fs_encoding = sys.getfilesystemencoding() if not isinstance(fs_path, bytes): fs_path_bytes = fs_path.encode(fs_encoding) else: fs_path_bytes = fs_path if os_sep_bytes != b'/': tree_path = fs_path_bytes.replace(os_sep_bytes, b'/') else: tree_path = fs_path_bytes return tree_path def index_entry_from_path(path, object_store=None): """Create an index from a filesystem path. This returns an index value for files, symlinks and tree references. for directories and non-existant files it returns None - :param path: Path to create an index entry for - :param object_store: Optional object store to + Args: + path: Path to create an index entry for + object_store: Optional object store to save new blobs in - :return: An index entry; None for directories + Returns: An index entry; None for directories """ assert isinstance(path, bytes) st = os.lstat(path) if stat.S_ISDIR(st.st_mode): if os.path.exists(os.path.join(path, b'.git')): head = read_submodule_head(path) if head is None: return None return index_entry_from_stat( st, head, 0, mode=S_IFGITLINK) return None blob = blob_from_path_and_stat(path, st) if object_store is not None: object_store.add_object(blob) return index_entry_from_stat(st, blob.id, 0) def iter_fresh_entries(paths, root_path, object_store=None): """Iterate over current versions of index entries on disk. - :param paths: Paths to iterate over - :param root_path: Root path to access from - :param store: Optional store to save new blobs in - :return: Iterator over path, index_entry + Args: + paths: Paths to iterate over + root_path: Root path to access from + store: Optional store to save new blobs in + Returns: Iterator over path, index_entry """ for path in paths: p = _tree_to_fs_path(root_path, path) try: entry = index_entry_from_path(p, object_store=object_store) except EnvironmentError as e: if e.errno in (errno.ENOENT, errno.EISDIR): entry = None else: raise yield path, entry def iter_fresh_blobs(index, root_path): """Iterate over versions of blobs on disk referenced by index. Don't use this function; it removes missing entries from index. - :param index: Index file - :param root_path: Root path to access from - :param include_deleted: Include deleted entries with sha and + Args: + index: Index file + root_path: Root path to access from + include_deleted: Include deleted entries with sha and mode set to None - :return: Iterator over path, sha, mode + Returns: Iterator over path, sha, mode """ import warnings warnings.warn(PendingDeprecationWarning, "Use iter_fresh_objects instead.") for entry in iter_fresh_objects( index, root_path, include_deleted=True): if entry[1] is None: del index[entry[0]] else: yield entry def iter_fresh_objects(paths, root_path, include_deleted=False, object_store=None): """Iterate over versions of objecs on disk referenced by index. - :param index: Index file - :param root_path: Root path to access from - :param include_deleted: Include deleted entries with sha and + Args: + index: Index file + root_path: Root path to access from + include_deleted: Include deleted entries with sha and mode set to None - :param object_store: Optional object store to report new items to - :return: Iterator over path, sha, mode + object_store: Optional object store to report new items to + Returns: Iterator over path, sha, mode """ for path, entry in iter_fresh_entries(paths, root_path, object_store=object_store): if entry is None: if include_deleted: yield path, None, None else: entry = IndexEntry(*entry) yield path, entry.sha, cleanup_mode(entry.mode) def refresh_index(index, root_path): """Refresh the contents of an index. This is the equivalent to running 'git commit -a'. - :param index: Index to update - :param root_path: Root filesystem path + Args: + index: Index to update + root_path: Root filesystem path """ for path, entry in iter_fresh_entries(index, root_path): index[path] = path diff --git a/dulwich/line_ending.py b/dulwich/line_ending.py index 14f94ae0..b17d9315 100644 --- a/dulwich/line_ending.py +++ b/dulwich/line_ending.py @@ -1,274 +1,278 @@ # line_ending.py -- Line ending conversion functions # Copyright (C) 2018-2018 Boris Feld # # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """ All line-ending related functions, from conversions to config processing Line-ending normalization is a complex beast. Here is some notes and details about how it seems to work. The normalization is a two-fold process that happens at two moments: - When reading a file from the index and to the working directory. For example when doing a `git clone` or `git checkout` call. We call this process the read filter in this module. - When writing a file to the index from the working directory. For example when doing a `git add` call. We call this process the write filter in this module. One thing to know is that Git does line-ending normalization only on text files. How does Git know that a file is text? We can either mark a file as a text file, a binary file or ask Git to automatically decides. Git has an heuristic to detect if a file is a text file or a binary file. It seems based on the percentage of non-printable characters in files. The code for this heuristic is here: https://git.kernel.org/pub/scm/git/git.git/tree/convert.c#n46 Dulwich have an implementation with a slightly different heuristic, the `is_binary` function in `dulwich.patch`. The binary detection heuristic implementation is close to the one in JGit: https://github.com/eclipse/jgit/blob/f6873ffe522bbc3536969a3a3546bf9a819b92bf/org.eclipse.jgit/src/org/eclipse/jgit/diff/RawText.java#L300 There is multiple variables that impact the normalization. First, a repository can contains a `.gitattributes` file (or more than one...) that can further customize the operation on some file patterns, for example: *.txt text Force all `.txt` files to be treated as text files and to have their lines endings normalized. *.jpg -text Force all `.jpg` files to be treated as binary files and to not have their lines endings converted. *.vcproj text eol=crlf Force all `.vcproj` files to be treated as text files and to have their lines endings converted into `CRLF` in working directory no matter the native EOL of the platform. *.sh text eol=lf Force all `.sh` files to be treated as text files and to have their lines endings converted into `LF` in working directory no matter the native EOL of the platform. If the `eol` attribute is not defined, Git uses the `core.eol` configuration value described later. * text=auto Force all files to be scanned by the text file heuristic detection and to have their line endings normalized in case they are detected as text files. Git also have a obsolete attribute named `crlf` that can be translated to the corresponding text attribute value. Then there are some configuration option (that can be defined at the repository or user level): - core.autocrlf - core.eol `core.autocrlf` is taken into account for all files that doesn't have a `text` attribute defined in `.gitattributes`; it takes three possible values: - `true`: This forces all files on the working directory to have CRLF line-endings in the working directory and convert line-endings to LF when writing to the index. When autocrlf is set to true, eol value is ignored. - `input`: Quite similar to the `true` value but only force the write filter, ie line-ending of new files added to the index will get their line-endings converted to LF. - `false` (default): No normalization is done. `core.eol` is the top-level configuration to define the line-ending to use when applying the read_filer. It takes three possible values: - `lf`: When normalization is done, force line-endings to be `LF` in the working directory. - `crlf`: When normalization is done, force line-endings to be `CRLF` in the working directory. - `native` (default): When normalization is done, force line-endings to be the platform's native line ending. One thing to remember is when line-ending normalization is done on a file, Git always normalize line-ending to `LF` when writing to the index. There are sources that seems to indicate that Git won't do line-ending normalization when a file contains mixed line-endings. I think this logic might be in text / binary detection heuristic but couldn't find it yet. Sources: - https://git-scm.com/docs/git-config#git-config-coreeol - https://git-scm.com/docs/git-config#git-config-coreautocrlf - https://git-scm.com/docs/gitattributes#_checking_out_and_checking_in - https://adaptivepatchwork.com/2012/03/01/mind-the-end-of-your-line/ """ from dulwich.objects import Blob from dulwich.patch import is_binary CRLF = b"\r\n" LF = b"\n" def convert_crlf_to_lf(text_hunk): """Convert CRLF in text hunk into LF - :param text_hunk: A bytes string representing a text hunk - :return: The text hunk with the same type, with CRLF replaced into LF + Args: + text_hunk: A bytes string representing a text hunk + Returns: The text hunk with the same type, with CRLF replaced into LF """ return text_hunk.replace(CRLF, LF) def convert_lf_to_crlf(text_hunk): """Convert LF in text hunk into CRLF - :param text_hunk: A bytes string representing a text hunk - :return: The text hunk with the same type, with LF replaced into CRLF + Args: + text_hunk: A bytes string representing a text hunk + Returns: The text hunk with the same type, with LF replaced into CRLF """ # TODO find a more efficient way of doing it intermediary = text_hunk.replace(CRLF, LF) return intermediary.replace(LF, CRLF) def get_checkout_filter(core_eol, core_autocrlf, git_attributes): """ Returns the correct checkout filter based on the passed arguments """ # TODO this function should process the git_attributes for the path and if # the text attribute is not defined, fallback on the # get_checkout_filter_autocrlf function with the autocrlf value return get_checkout_filter_autocrlf(core_autocrlf) def get_checkin_filter(core_eol, core_autocrlf, git_attributes): """ Returns the correct checkin filter based on the passed arguments """ # TODO this function should process the git_attributes for the path and if # the text attribute is not defined, fallback on the # get_checkin_filter_autocrlf function with the autocrlf value return get_checkin_filter_autocrlf(core_autocrlf) def get_checkout_filter_autocrlf(core_autocrlf): """ Returns the correct checkout filter base on autocrlf value - :param core_autocrlf: The bytes configuration value of core.autocrlf. + Args: + core_autocrlf: The bytes configuration value of core.autocrlf. Valid values are: b'true', b'false' or b'input'. - :return: Either None if no filter has to be applied or a function + Returns: Either None if no filter has to be applied or a function accepting a single argument, a binary text hunk """ if core_autocrlf == b"true": return convert_lf_to_crlf return None def get_checkin_filter_autocrlf(core_autocrlf): """ Returns the correct checkin filter base on autocrlf value - :param core_autocrlf: The bytes configuration value of core.autocrlf. + Args: + core_autocrlf: The bytes configuration value of core.autocrlf. Valid values are: b'true', b'false' or b'input'. - :return: Either None if no filter has to be applied or a function + Returns: Either None if no filter has to be applied or a function accepting a single argument, a binary text hunk """ if core_autocrlf == b"true" or core_autocrlf == b"input": return convert_crlf_to_lf # Checking filter should never be `convert_lf_to_crlf` return None class BlobNormalizer(object): """ An object to store computation result of which filter to apply based on configuration, gitattributes, path and operation (checkin or checkout) """ def __init__(self, config_stack, gitattributes): self.config_stack = config_stack self.gitattributes = gitattributes # Compute which filters we needs based on parameters try: core_eol = config_stack.get("core", "eol") except KeyError: core_eol = "native" try: core_autocrlf = config_stack.get("core", "autocrlf").lower() except KeyError: core_autocrlf = False self.fallback_read_filter = get_checkout_filter( core_eol, core_autocrlf, self.gitattributes ) self.fallback_write_filter = get_checkin_filter( core_eol, core_autocrlf, self.gitattributes ) def checkin_normalize(self, blob, tree_path): """ Normalize a blob during a checkin operation """ if self.fallback_write_filter is not None: return normalize_blob( blob, self.fallback_write_filter, binary_detection=True ) return blob def checkout_normalize(self, blob, tree_path): """ Normalize a blob during a checkout operation """ if self.fallback_read_filter is not None: return normalize_blob( blob, self.fallback_read_filter, binary_detection=True ) return blob def normalize_blob(blob, conversion, binary_detection): """ Takes a blob as input returns either the original blob if binary_detection is True and the blob content looks like binary, else return a new blob with converted data """ # Read the original blob data = blob.data # If we need to detect if a file is binary and the file is detected as # binary, do not apply the conversion function and return the original # chunked text if binary_detection is True: if is_binary(data): return blob # Now apply the conversion converted_data = conversion(data) new_blob = Blob() new_blob.data = converted_data return new_blob diff --git a/dulwich/lru_cache.py b/dulwich/lru_cache.py index 821da5b8..913ab865 100644 --- a/dulwich/lru_cache.py +++ b/dulwich/lru_cache.py @@ -1,371 +1,374 @@ # lru_cache.py -- Simple LRU cache for dulwich # Copyright (C) 2006, 2008 Canonical Ltd # # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """A simple least-recently-used (LRU) cache.""" _null_key = object() class _LRUNode(object): """This maintains the linked-list which is the lru internals.""" __slots__ = ('prev', 'next_key', 'key', 'value', 'cleanup', 'size') def __init__(self, key, value, cleanup=None): self.prev = None self.next_key = _null_key self.key = key self.value = value self.cleanup = cleanup # TODO: We could compute this 'on-the-fly' like we used to, and remove # one pointer from this object, we just need to decide if it # actually costs us much of anything in normal usage self.size = None def __repr__(self): if self.prev is None: prev_key = None else: prev_key = self.prev.key return '%s(%r n:%r p:%r)' % (self.__class__.__name__, self.key, self.next_key, prev_key) def run_cleanup(self): if self.cleanup is not None: self.cleanup(self.key, self.value) self.cleanup = None # Just make sure to break any refcycles, etc self.value = None class LRUCache(object): """A class which manages a cache of entries, removing unused ones.""" def __init__(self, max_cache=100, after_cleanup_count=None): self._cache = {} # The "HEAD" of the lru linked list self._most_recently_used = None # The "TAIL" of the lru linked list self._least_recently_used = None self._update_max_cache(max_cache, after_cleanup_count) def __contains__(self, key): return key in self._cache def __getitem__(self, key): cache = self._cache node = cache[key] # Inlined from _record_access to decrease the overhead of __getitem__ # We also have more knowledge about structure if __getitem__ is # succeeding, then we know that self._most_recently_used must not be # None, etc. mru = self._most_recently_used if node is mru: # Nothing to do, this node is already at the head of the queue return node.value # Remove this node from the old location node_prev = node.prev next_key = node.next_key # benchmarking shows that the lookup of _null_key in globals is faster # than the attribute lookup for (node is self._least_recently_used) if next_key is _null_key: # 'node' is the _least_recently_used, because it doesn't have a # 'next' item. So move the current lru to the previous node. self._least_recently_used = node_prev else: node_next = cache[next_key] node_next.prev = node_prev node_prev.next_key = next_key # Insert this node at the front of the list node.next_key = mru.key mru.prev = node self._most_recently_used = node node.prev = None return node.value def __len__(self): return len(self._cache) def _walk_lru(self): """Walk the LRU list, only meant to be used in tests.""" node = self._most_recently_used if node is not None: if node.prev is not None: raise AssertionError('the _most_recently_used entry is not' ' supposed to have a previous entry' ' %s' % (node,)) while node is not None: if node.next_key is _null_key: if node is not self._least_recently_used: raise AssertionError('only the last node should have' ' no next value: %s' % (node,)) node_next = None else: node_next = self._cache[node.next_key] if node_next.prev is not node: raise AssertionError('inconsistency found, node.next.prev' ' != node: %s' % (node,)) if node.prev is None: if node is not self._most_recently_used: raise AssertionError('only the _most_recently_used should' ' not have a previous node: %s' % (node,)) else: if node.prev.next_key != node.key: raise AssertionError('inconsistency found, node.prev.next' ' != node: %s' % (node,)) yield node node = node_next def add(self, key, value, cleanup=None): """Add a new value to the cache. Also, if the entry is ever removed from the cache, call cleanup(key, value). - :param key: The key to store it under - :param value: The object to store - :param cleanup: None or a function taking (key, value) to indicate + Args: + key: The key to store it under + value: The object to store + cleanup: None or a function taking (key, value) to indicate 'value' should be cleaned up. """ if key is _null_key: raise ValueError('cannot use _null_key as a key') if key in self._cache: node = self._cache[key] node.run_cleanup() node.value = value node.cleanup = cleanup else: node = _LRUNode(key, value, cleanup=cleanup) self._cache[key] = node self._record_access(node) if len(self._cache) > self._max_cache: # Trigger the cleanup self.cleanup() def cache_size(self): """Get the number of entries we will cache.""" return self._max_cache def get(self, key, default=None): node = self._cache.get(key, None) if node is None: return default self._record_access(node) return node.value def keys(self): """Get the list of keys currently cached. Note that values returned here may not be available by the time you request them later. This is simply meant as a peak into the current state. - :return: An unordered list of keys that are currently cached. + Returns: An unordered list of keys that are currently cached. """ return self._cache.keys() def items(self): """Get the key:value pairs as a dict.""" return dict((k, n.value) for k, n in self._cache.items()) def cleanup(self): """Clear the cache until it shrinks to the requested size. This does not completely wipe the cache, just makes sure it is under the after_cleanup_count. """ # Make sure the cache is shrunk to the correct size while len(self._cache) > self._after_cleanup_count: self._remove_lru() def __setitem__(self, key, value): """Add a value to the cache, there will be no cleanup function.""" self.add(key, value, cleanup=None) def _record_access(self, node): """Record that key was accessed.""" # Move 'node' to the front of the queue if self._most_recently_used is None: self._most_recently_used = node self._least_recently_used = node return elif node is self._most_recently_used: # Nothing to do, this node is already at the head of the queue return # We've taken care of the tail pointer, remove the node, and insert it # at the front # REMOVE if node is self._least_recently_used: self._least_recently_used = node.prev if node.prev is not None: node.prev.next_key = node.next_key if node.next_key is not _null_key: node_next = self._cache[node.next_key] node_next.prev = node.prev # INSERT node.next_key = self._most_recently_used.key self._most_recently_used.prev = node self._most_recently_used = node node.prev = None def _remove_node(self, node): if node is self._least_recently_used: self._least_recently_used = node.prev self._cache.pop(node.key) # If we have removed all entries, remove the head pointer as well if self._least_recently_used is None: self._most_recently_used = None node.run_cleanup() # Now remove this node from the linked list if node.prev is not None: node.prev.next_key = node.next_key if node.next_key is not _null_key: node_next = self._cache[node.next_key] node_next.prev = node.prev # And remove this node's pointers node.prev = None node.next_key = _null_key def _remove_lru(self): """Remove one entry from the lru, and handle consequences. If there are no more references to the lru, then this entry should be removed from the cache. """ self._remove_node(self._least_recently_used) def clear(self): """Clear out all of the cache.""" # Clean up in LRU order while self._cache: self._remove_lru() def resize(self, max_cache, after_cleanup_count=None): """Change the number of entries that will be cached.""" self._update_max_cache(max_cache, after_cleanup_count=after_cleanup_count) def _update_max_cache(self, max_cache, after_cleanup_count=None): self._max_cache = max_cache if after_cleanup_count is None: self._after_cleanup_count = self._max_cache * 8 / 10 else: self._after_cleanup_count = min(after_cleanup_count, self._max_cache) self.cleanup() class LRUSizeCache(LRUCache): """An LRUCache that removes things based on the size of the values. This differs in that it doesn't care how many actual items there are, it just restricts the cache to be cleaned up after so much data is stored. The size of items added will be computed using compute_size(value), which defaults to len() if not supplied. """ def __init__(self, max_size=1024*1024, after_cleanup_size=None, compute_size=None): """Create a new LRUSizeCache. - :param max_size: The max number of bytes to store before we start + Args: + max_size: The max number of bytes to store before we start clearing out entries. - :param after_cleanup_size: After cleaning up, shrink everything to this + after_cleanup_size: After cleaning up, shrink everything to this size. - :param compute_size: A function to compute the size of the values. We + compute_size: A function to compute the size of the values. We use a function here, so that you can pass 'len' if you are just using simple strings, or a more complex function if you are using something like a list of strings, or even a custom object. The function should take the form "compute_size(value) => integer". If not supplied, it defaults to 'len()' """ self._value_size = 0 self._compute_size = compute_size if compute_size is None: self._compute_size = len self._update_max_size(max_size, after_cleanup_size=after_cleanup_size) LRUCache.__init__(self, max_cache=max(int(max_size/512), 1)) def add(self, key, value, cleanup=None): """Add a new value to the cache. Also, if the entry is ever removed from the cache, call cleanup(key, value). - :param key: The key to store it under - :param value: The object to store - :param cleanup: None or a function taking (key, value) to indicate + Args: + key: The key to store it under + value: The object to store + cleanup: None or a function taking (key, value) to indicate 'value' should be cleaned up. """ if key is _null_key: raise ValueError('cannot use _null_key as a key') node = self._cache.get(key, None) value_len = self._compute_size(value) if value_len >= self._after_cleanup_size: # The new value is 'too big to fit', as it would fill up/overflow # the cache all by itself if node is not None: # We won't be replacing the old node, so just remove it self._remove_node(node) if cleanup is not None: cleanup(key, value) return if node is None: node = _LRUNode(key, value, cleanup=cleanup) self._cache[key] = node else: self._value_size -= node.size node.size = value_len self._value_size += value_len self._record_access(node) if self._value_size > self._max_size: # Time to cleanup self.cleanup() def cleanup(self): """Clear the cache until it shrinks to the requested size. This does not completely wipe the cache, just makes sure it is under the after_cleanup_size. """ # Make sure the cache is shrunk to the correct size while self._value_size > self._after_cleanup_size: self._remove_lru() def _remove_node(self, node): self._value_size -= node.size LRUCache._remove_node(self, node) def resize(self, max_size, after_cleanup_size=None): """Change the number of bytes that will be cached.""" self._update_max_size(max_size, after_cleanup_size=after_cleanup_size) max_cache = max(int(max_size/512), 1) self._update_max_cache(max_cache) def _update_max_size(self, max_size, after_cleanup_size=None): self._max_size = max_size if after_cleanup_size is None: self._after_cleanup_size = self._max_size * 8 // 10 else: self._after_cleanup_size = min(after_cleanup_size, self._max_size) diff --git a/dulwich/mailmap.py b/dulwich/mailmap.py index be4737bf..12d6445b 100644 --- a/dulwich/mailmap.py +++ b/dulwich/mailmap.py @@ -1,111 +1,113 @@ # mailmap.py -- Mailmap reader # Copyright (C) 2018 Jelmer Vernooij # # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Mailmap file reader.""" def parse_identity(text): # TODO(jelmer): Integrate this with dulwich.fastexport.split_email and # dulwich.repo.check_user_identity (name, email) = text.rsplit(b"<", 1) name = name.strip() email = email.rstrip(b">").strip() if not name: name = None if not email: email = None return (name, email) def read_mailmap(f): """Read a mailmap. - :param f: File-like object to read from - :return: Iterator over + Args: + f: File-like object to read from + Returns: Iterator over ((canonical_name, canonical_email), (from_name, from_email)) tuples """ for line in f: # Remove comments line = line.split(b'#')[0] line = line.strip() if not line: continue (canonical_identity, from_identity) = line.split(b'>', 1) canonical_identity += b">" if from_identity.strip(): parsed_from_identity = parse_identity(from_identity) else: parsed_from_identity = None parsed_canonical_identity = parse_identity(canonical_identity) yield parsed_canonical_identity, parsed_from_identity class Mailmap(object): """Class for accessing a mailmap file.""" def __init__(self, map=None): self._table = {} if map: for (canonical_identity, from_identity) in map: self.add_entry(canonical_identity, from_identity) def add_entry(self, canonical_identity, from_identity=None): """Add an entry to the mail mail. Any of the fields can be None, but at least one of them needs to be set. - :param canonical_identity: The canonical identity (tuple) - :param from_identity: The from identity (tuple) + Args: + canonical_identity: The canonical identity (tuple) + from_identity: The from identity (tuple) """ if from_identity is None: from_name, from_email = None, None else: (from_name, from_email) = from_identity (canonical_name, canonical_email) = canonical_identity if from_name is None and from_email is None: self._table[canonical_name, None] = canonical_identity self._table[None, canonical_email] = canonical_identity else: self._table[from_name, from_email] = canonical_identity def lookup(self, identity): """Lookup an identity in this mailmail.""" if not isinstance(identity, tuple): was_tuple = False identity = parse_identity(identity) else: was_tuple = True for query in [identity, (None, identity[1]), (identity[0], None)]: canonical_identity = self._table.get(query) if canonical_identity is not None: identity = ( canonical_identity[0] or identity[0], canonical_identity[1] or identity[1]) break if was_tuple: return identity else: return identity[0] + b" <" + identity[1] + b">" @classmethod def from_path(cls, path): with open(path, 'rb') as f: return cls(read_mailmap(f)) diff --git a/dulwich/object_store.py b/dulwich/object_store.py index ab0e245f..3a073823 100644 --- a/dulwich/object_store.py +++ b/dulwich/object_store.py @@ -1,1352 +1,1383 @@ # object_store.py -- Object store for git objects # Copyright (C) 2008-2013 Jelmer Vernooij # and others # # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Git object store interfaces and implementation.""" from io import BytesIO import errno import os import stat import sys import tempfile from dulwich.diff_tree import ( tree_changes, walk_trees, ) from dulwich.errors import ( NotTreeError, ) from dulwich.file import GitFile from dulwich.objects import ( Commit, ShaFile, Tag, Tree, ZERO_SHA, hex_to_sha, sha_to_hex, hex_to_filename, S_ISGITLINK, object_class, ) from dulwich.pack import ( Pack, PackData, PackInflater, PackFileDisappeared, iter_sha1, pack_objects_to_data, write_pack_header, write_pack_index_v2, write_pack_data, write_pack_object, compute_file_sha, PackIndexer, PackStreamCopier, ) from dulwich.refs import ANNOTATED_TAG_SUFFIX INFODIR = 'info' PACKDIR = 'pack' class BaseObjectStore(object): """Object store interface.""" def determine_wants_all(self, refs): return [sha for (ref, sha) in refs.items() if sha not in self and not ref.endswith(ANNOTATED_TAG_SUFFIX) and not sha == ZERO_SHA] def iter_shas(self, shas): """Iterate over the objects for the specified shas. - :param shas: Iterable object with SHAs - :return: Object iterator + Args: + shas: Iterable object with SHAs + Returns: Object iterator """ return ObjectStoreIterator(self, shas) def contains_loose(self, sha): """Check if a particular object is present by SHA1 and is loose.""" raise NotImplementedError(self.contains_loose) def contains_packed(self, sha): """Check if a particular object is present by SHA1 and is packed.""" raise NotImplementedError(self.contains_packed) def __contains__(self, sha): """Check if a particular object is present by SHA1. This method makes no distinction between loose and packed objects. """ return self.contains_packed(sha) or self.contains_loose(sha) @property def packs(self): """Iterable of pack objects.""" raise NotImplementedError def get_raw(self, name): """Obtain the raw text for an object. - :param name: sha for the object. - :return: tuple with numeric type and object contents. + Args: + name: sha for the object. + Returns: tuple with numeric type and object contents. """ raise NotImplementedError(self.get_raw) def __getitem__(self, sha): """Obtain an object by SHA1.""" type_num, uncomp = self.get_raw(sha) return ShaFile.from_raw_string(type_num, uncomp, sha=sha) def __iter__(self): """Iterate over the SHAs that are present in this store.""" raise NotImplementedError(self.__iter__) def add_object(self, obj): """Add a single object to this object store. """ raise NotImplementedError(self.add_object) def add_objects(self, objects, progress=None): """Add a set of objects to this object store. - :param objects: Iterable over a list of (object, path) tuples + Args: + objects: Iterable over a list of (object, path) tuples """ raise NotImplementedError(self.add_objects) def add_pack_data(self, count, pack_data, progress=None): """Add pack data to this object store. - :param num_items: Number of items to add - :param pack_data: Iterator over pack data tuples + Args: + num_items: Number of items to add + pack_data: Iterator over pack data tuples """ if count == 0: # Don't bother writing an empty pack file return f, commit, abort = self.add_pack() try: write_pack_data(f, count, pack_data, progress) except BaseException: abort() raise else: return commit() def tree_changes(self, source, target, want_unchanged=False, include_trees=False, change_type_same=False): """Find the differences between the contents of two trees - :param source: SHA1 of the source tree - :param target: SHA1 of the target tree - :param want_unchanged: Whether unchanged files should be reported - :param include_trees: Whether to include trees - :param change_type_same: Whether to report files changing + Args: + source: SHA1 of the source tree + target: SHA1 of the target tree + want_unchanged: Whether unchanged files should be reported + include_trees: Whether to include trees + change_type_same: Whether to report files changing type in the same entry. - :return: Iterator over tuples with + Returns: Iterator over tuples with (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) """ for change in tree_changes(self, source, target, want_unchanged=want_unchanged, include_trees=include_trees, change_type_same=change_type_same): yield ((change.old.path, change.new.path), (change.old.mode, change.new.mode), (change.old.sha, change.new.sha)) def iter_tree_contents(self, tree_id, include_trees=False): """Iterate the contents of a tree and all subtrees. Iteration is depth-first pre-order, as in e.g. os.walk. - :param tree_id: SHA1 of the tree. - :param include_trees: If True, include tree objects in the iteration. - :return: Iterator over TreeEntry namedtuples for all the objects in a + Args: + tree_id: SHA1 of the tree. + include_trees: If True, include tree objects in the iteration. + Returns: Iterator over TreeEntry namedtuples for all the objects in a tree. """ for entry, _ in walk_trees(self, tree_id, None): if ((entry.mode is not None and not stat.S_ISDIR(entry.mode)) or include_trees): yield entry def find_missing_objects(self, haves, wants, progress=None, get_tagged=None, get_parents=lambda commit: commit.parents, depth=None): """Find the missing objects required for a set of revisions. - :param haves: Iterable over SHAs already in common. - :param wants: Iterable over SHAs of objects to fetch. - :param progress: Simple progress function that will be called with + Args: + haves: Iterable over SHAs already in common. + wants: Iterable over SHAs of objects to fetch. + progress: Simple progress function that will be called with updated progress strings. - :param get_tagged: Function that returns a dict of pointed-to sha -> + get_tagged: Function that returns a dict of pointed-to sha -> tag sha for including tags. - :param get_parents: Optional function for getting the parents of a + get_parents: Optional function for getting the parents of a commit. - :return: Iterator over (sha, path) pairs. + Returns: Iterator over (sha, path) pairs. """ finder = MissingObjectFinder(self, haves, wants, progress, get_tagged, get_parents=get_parents) return iter(finder.next, None) def find_common_revisions(self, graphwalker): """Find which revisions this store has in common using graphwalker. - :param graphwalker: A graphwalker object. - :return: List of SHAs that are in common + Args: + graphwalker: A graphwalker object. + Returns: List of SHAs that are in common """ haves = [] sha = next(graphwalker) while sha: if sha in self: haves.append(sha) graphwalker.ack(sha) sha = next(graphwalker) return haves def generate_pack_contents(self, have, want, progress=None): """Iterate over the contents of a pack file. - :param have: List of SHA1s of objects that should not be sent - :param want: List of SHA1s of objects that should be sent - :param progress: Optional progress reporting method + Args: + have: List of SHA1s of objects that should not be sent + want: List of SHA1s of objects that should be sent + progress: Optional progress reporting method """ return self.iter_shas(self.find_missing_objects(have, want, progress)) def generate_pack_data(self, have, want, progress=None, ofs_delta=True): """Generate pack data objects for a set of wants/haves. - :param have: List of SHA1s of objects that should not be sent - :param want: List of SHA1s of objects that should be sent - :param ofs_delta: Whether OFS deltas can be included - :param progress: Optional progress reporting method + Args: + have: List of SHA1s of objects that should not be sent + want: List of SHA1s of objects that should be sent + ofs_delta: Whether OFS deltas can be included + progress: Optional progress reporting method """ # TODO(jelmer): More efficient implementation return pack_objects_to_data( self.generate_pack_contents(have, want, progress)) def peel_sha(self, sha): """Peel all tags from a SHA. - :param sha: The object SHA to peel. - :return: The fully-peeled SHA1 of a tag object, after peeling all + Args: + sha: The object SHA to peel. + Returns: The fully-peeled SHA1 of a tag object, after peeling all intermediate tags; if the original ref does not point to a tag, this will equal the original SHA1. """ obj = self[sha] obj_class = object_class(obj.type_name) while obj_class is Tag: obj_class, sha = obj.object obj = self[sha] return obj def _collect_ancestors(self, heads, common=set(), get_parents=lambda commit: commit.parents): """Collect all ancestors of heads up to (excluding) those in common. - :param heads: commits to start from - :param common: commits to end at, or empty set to walk repository + Args: + heads: commits to start from + common: commits to end at, or empty set to walk repository completely - :param get_parents: Optional function for getting the parents of a + get_parents: Optional function for getting the parents of a commit. - :return: a tuple (A, B) where A - all commits reachable + Returns: a tuple (A, B) where A - all commits reachable from heads but not present in common, B - common (shared) elements that are directly reachable from heads """ bases = set() commits = set() queue = [] queue.extend(heads) while queue: e = queue.pop(0) if e in common: bases.add(e) elif e not in commits: commits.add(e) cmt = self[e] queue.extend(get_parents(cmt)) return (commits, bases) def close(self): """Close any files opened by this object store.""" # Default implementation is a NO-OP class PackBasedObjectStore(BaseObjectStore): def __init__(self): self._pack_cache = {} @property def alternates(self): return [] def contains_packed(self, sha): """Check if a particular object is present by SHA1 and is packed. This does not check alternates. """ for pack in self.packs: try: if sha in pack: return True except PackFileDisappeared: pass return False def __contains__(self, sha): """Check if a particular object is present by SHA1. This method makes no distinction between loose and packed objects. """ if self.contains_packed(sha) or self.contains_loose(sha): return True for alternate in self.alternates: if sha in alternate: return True return False def _add_cached_pack(self, base_name, pack): """Add a newly appeared pack to the cache by path. """ prev_pack = self._pack_cache.get(base_name) if prev_pack is not pack: self._pack_cache[base_name] = pack if prev_pack: prev_pack.close() def _clear_cached_packs(self): pack_cache = self._pack_cache self._pack_cache = {} while pack_cache: (name, pack) = pack_cache.popitem() pack.close() def _iter_cached_packs(self): return self._pack_cache.values() def _update_pack_cache(self): raise NotImplementedError(self._update_pack_cache) def close(self): self._clear_cached_packs() @property def packs(self): """List with pack objects.""" return ( list(self._iter_cached_packs()) + list(self._update_pack_cache())) def _iter_alternate_objects(self): """Iterate over the SHAs of all the objects in alternate stores.""" for alternate in self.alternates: for alternate_object in alternate: yield alternate_object def _iter_loose_objects(self): """Iterate over the SHAs of all loose objects.""" raise NotImplementedError(self._iter_loose_objects) def _get_loose_object(self, sha): raise NotImplementedError(self._get_loose_object) def _remove_loose_object(self, sha): raise NotImplementedError(self._remove_loose_object) def _remove_pack(self, name): raise NotImplementedError(self._remove_pack) def pack_loose_objects(self): """Pack loose objects. - :return: Number of objects packed + Returns: Number of objects packed """ objects = set() for sha in self._iter_loose_objects(): objects.add((self._get_loose_object(sha), None)) self.add_objects(list(objects)) for obj, path in objects: self._remove_loose_object(obj.id) return len(objects) def repack(self): """Repack the packs in this repository. Note that this implementation is fairly naive and currently keeps all objects in memory while it repacks. """ loose_objects = set() for sha in self._iter_loose_objects(): loose_objects.add(self._get_loose_object(sha)) objects = {(obj, None) for obj in loose_objects} old_packs = {p.name(): p for p in self.packs} for name, pack in old_packs.items(): objects.update((obj, None) for obj in pack.iterobjects()) # The name of the consolidated pack might match the name of a # pre-existing pack. Take care not to remove the newly created # consolidated pack. consolidated = self.add_objects(objects) old_packs.pop(consolidated.name(), None) for obj in loose_objects: self._remove_loose_object(obj.id) for name, pack in old_packs.items(): self._remove_pack(pack) self._update_pack_cache() return len(objects) def __iter__(self): """Iterate over the SHAs that are present in this store.""" self._update_pack_cache() for pack in self._iter_cached_packs(): try: for sha in pack: yield sha except PackFileDisappeared: pass for sha in self._iter_loose_objects(): yield sha for sha in self._iter_alternate_objects(): yield sha def contains_loose(self, sha): """Check if a particular object is present by SHA1 and is loose. This does not check alternates. """ return self._get_loose_object(sha) is not None def get_raw(self, name): """Obtain the raw fulltext for an object. - :param name: sha for the object. - :return: tuple with numeric type and object contents. + Args: + name: sha for the object. + Returns: tuple with numeric type and object contents. """ if name == ZERO_SHA: raise KeyError(name) if len(name) == 40: sha = hex_to_sha(name) hexsha = name elif len(name) == 20: sha = name hexsha = None else: raise AssertionError("Invalid object name %r" % (name, )) for pack in self._iter_cached_packs(): try: return pack.get_raw(sha) except (KeyError, PackFileDisappeared): pass if hexsha is None: hexsha = sha_to_hex(name) ret = self._get_loose_object(hexsha) if ret is not None: return ret.type_num, ret.as_raw_string() # Maybe something else has added a pack with the object # in the mean time? for pack in self._update_pack_cache(): try: return pack.get_raw(sha) except KeyError: pass for alternate in self.alternates: try: return alternate.get_raw(hexsha) except KeyError: pass raise KeyError(hexsha) def add_objects(self, objects, progress=None): """Add a set of objects to this object store. - :param objects: Iterable over (object, path) tuples, should support + Args: + objects: Iterable over (object, path) tuples, should support __len__. - :return: Pack object of the objects written. + Returns: Pack object of the objects written. """ return self.add_pack_data( *pack_objects_to_data(objects), progress=progress) class DiskObjectStore(PackBasedObjectStore): """Git-style object store that exists on disk.""" def __init__(self, path): """Open an object store. - :param path: Path of the object store. + Args: + path: Path of the object store. """ super(DiskObjectStore, self).__init__() self.path = path self.pack_dir = os.path.join(self.path, PACKDIR) self._alternates = None def __repr__(self): return "<%s(%r)>" % (self.__class__.__name__, self.path) @property def alternates(self): if self._alternates is not None: return self._alternates self._alternates = [] for path in self._read_alternate_paths(): self._alternates.append(DiskObjectStore(path)) return self._alternates def _read_alternate_paths(self): try: f = GitFile(os.path.join(self.path, INFODIR, "alternates"), 'rb') except (OSError, IOError) as e: if e.errno == errno.ENOENT: return raise with f: for line in f.readlines(): line = line.rstrip(b"\n") if line[0] == b"#": continue if os.path.isabs(line): yield line.decode(sys.getfilesystemencoding()) else: yield os.path.join(self.path, line).decode( sys.getfilesystemencoding()) def add_alternate_path(self, path): """Add an alternate path to this object store. """ try: os.mkdir(os.path.join(self.path, INFODIR)) except OSError as e: if e.errno != errno.EEXIST: raise alternates_path = os.path.join(self.path, INFODIR, "alternates") with GitFile(alternates_path, 'wb') as f: try: orig_f = open(alternates_path, 'rb') except (OSError, IOError) as e: if e.errno != errno.ENOENT: raise else: with orig_f: f.write(orig_f.read()) f.write(path.encode(sys.getfilesystemencoding()) + b"\n") if not os.path.isabs(path): path = os.path.join(self.path, path) self.alternates.append(DiskObjectStore(path)) def _update_pack_cache(self): """Read and iterate over new pack files and cache them.""" try: pack_dir_contents = os.listdir(self.pack_dir) except OSError as e: if e.errno == errno.ENOENT: self.close() return [] raise pack_files = set() for name in pack_dir_contents: if name.startswith("pack-") and name.endswith(".pack"): # verify that idx exists first (otherwise the pack was not yet # fully written) idx_name = os.path.splitext(name)[0] + ".idx" if idx_name in pack_dir_contents: pack_name = name[:-len(".pack")] pack_files.add(pack_name) # Open newly appeared pack files new_packs = [] for f in pack_files: if f not in self._pack_cache: pack = Pack(os.path.join(self.pack_dir, f)) new_packs.append(pack) self._pack_cache[f] = pack # Remove disappeared pack files for f in set(self._pack_cache) - pack_files: self._pack_cache.pop(f).close() return new_packs def _get_shafile_path(self, sha): # Check from object dir return hex_to_filename(self.path, sha) def _iter_loose_objects(self): for base in os.listdir(self.path): if len(base) != 2: continue for rest in os.listdir(os.path.join(self.path, base)): yield (base+rest).encode(sys.getfilesystemencoding()) def _get_loose_object(self, sha): path = self._get_shafile_path(sha) try: return ShaFile.from_path(path) except (OSError, IOError) as e: if e.errno == errno.ENOENT: return None raise def _remove_loose_object(self, sha): os.remove(self._get_shafile_path(sha)) def _remove_pack(self, pack): try: del self._pack_cache[os.path.basename(pack._basename)] except KeyError: pass pack.close() os.remove(pack.data.path) os.remove(pack.index.path) def _get_pack_basepath(self, entries): suffix = iter_sha1(entry[0] for entry in entries) # TODO: Handle self.pack_dir being bytes suffix = suffix.decode('ascii') return os.path.join(self.pack_dir, "pack-" + suffix) def _complete_thin_pack(self, f, path, copier, indexer): """Move a specific file containing a pack into the pack directory. - :note: The file should be on the same file system as the + Note: The file should be on the same file system as the packs directory. - :param f: Open file object for the pack. - :param path: Path to the pack file. - :param copier: A PackStreamCopier to use for writing pack data. - :param indexer: A PackIndexer for indexing the pack. + Args: + f: Open file object for the pack. + path: Path to the pack file. + copier: A PackStreamCopier to use for writing pack data. + indexer: A PackIndexer for indexing the pack. """ entries = list(indexer) # Update the header with the new number of objects. f.seek(0) write_pack_header(f, len(entries) + len(indexer.ext_refs())) # Must flush before reading (http://bugs.python.org/issue3207) f.flush() # Rescan the rest of the pack, computing the SHA with the new header. new_sha = compute_file_sha(f, end_ofs=-20) # Must reposition before writing (http://bugs.python.org/issue3207) f.seek(0, os.SEEK_CUR) # Complete the pack. for ext_sha in indexer.ext_refs(): assert len(ext_sha) == 20 type_num, data = self.get_raw(ext_sha) offset = f.tell() crc32 = write_pack_object(f, type_num, data, sha=new_sha) entries.append((ext_sha, offset, crc32)) pack_sha = new_sha.digest() f.write(pack_sha) f.close() # Move the pack in. entries.sort() pack_base_name = self._get_pack_basepath(entries) target_pack = pack_base_name + '.pack' if sys.platform == 'win32': # Windows might have the target pack file lingering. Attempt # removal, silently passing if the target does not exist. try: os.remove(target_pack) except (IOError, OSError) as e: if e.errno != errno.ENOENT: raise os.rename(path, target_pack) # Write the index. index_file = GitFile(pack_base_name + '.idx', 'wb') try: write_pack_index_v2(index_file, entries, pack_sha) index_file.close() finally: index_file.abort() # Add the pack to the store and return it. final_pack = Pack(pack_base_name) final_pack.check_length_and_checksum() self._add_cached_pack(pack_base_name, final_pack) return final_pack def add_thin_pack(self, read_all, read_some): """Add a new thin pack to this object store. Thin packs are packs that contain deltas with parents that exist outside the pack. They should never be placed in the object store directly, and always indexed and completed as they are copied. - :param read_all: Read function that blocks until the number of + Args: + 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 + read_some: Read function that returns at least one byte, but may not return the number of bytes requested. - :return: A Pack object pointing at the now-completed thin pack in the + Returns: A Pack object pointing at the now-completed thin pack in the objects/pack directory. """ fd, path = tempfile.mkstemp(dir=self.path, prefix='tmp_pack_') with os.fdopen(fd, 'w+b') as f: indexer = PackIndexer(f, resolve_ext_ref=self.get_raw) copier = PackStreamCopier(read_all, read_some, f, delta_iter=indexer) copier.verify() return self._complete_thin_pack(f, path, copier, indexer) def move_in_pack(self, path): """Move a specific file containing a pack into the pack directory. - :note: The file should be on the same file system as the + Note: The file should be on the same file system as the packs directory. - :param path: Path to the pack file. + Args: + path: Path to the pack file. """ with PackData(path) as p: entries = p.sorted_entries() basename = self._get_pack_basepath(entries) index_name = basename + ".idx" if not os.path.exists(index_name): with GitFile(index_name, "wb") as f: write_pack_index_v2(f, entries, p.get_stored_checksum()) for pack in self.packs: if pack._basename == basename: return pack target_pack = basename + '.pack' if sys.platform == 'win32': # Windows might have the target pack file lingering. Attempt # removal, silently passing if the target does not exist. try: os.remove(target_pack) except (IOError, OSError) as e: if e.errno != errno.ENOENT: raise os.rename(path, target_pack) final_pack = Pack(basename) self._add_cached_pack(basename, final_pack) return final_pack def add_pack(self): """Add a new pack to this object store. - :return: Fileobject to write to, a commit function to + Returns: Fileobject to write to, a commit function to call when the pack is finished and an abort function. """ fd, path = tempfile.mkstemp(dir=self.pack_dir, suffix=".pack") f = os.fdopen(fd, 'wb') def commit(): f.flush() os.fsync(fd) f.close() if os.path.getsize(path) > 0: return self.move_in_pack(path) else: os.remove(path) return None def abort(): f.close() os.remove(path) return f, commit, abort def add_object(self, obj): """Add a single object to this object store. - :param obj: Object to add + Args: + obj: Object to add """ path = self._get_shafile_path(obj.id) dir = os.path.dirname(path) try: os.mkdir(dir) except OSError as e: if e.errno != errno.EEXIST: raise if os.path.exists(path): return # Already there, no need to write again with GitFile(path, 'wb') as f: f.write(obj.as_legacy_object()) @classmethod def init(cls, path): try: os.mkdir(path) except OSError as e: if e.errno != errno.EEXIST: raise os.mkdir(os.path.join(path, "info")) os.mkdir(os.path.join(path, PACKDIR)) return cls(path) class MemoryObjectStore(BaseObjectStore): """Object store that keeps all objects in memory.""" def __init__(self): super(MemoryObjectStore, self).__init__() self._data = {} def _to_hexsha(self, sha): if len(sha) == 40: return sha elif len(sha) == 20: return sha_to_hex(sha) else: raise ValueError("Invalid sha %r" % (sha,)) def contains_loose(self, sha): """Check if a particular object is present by SHA1 and is loose.""" return self._to_hexsha(sha) in self._data def contains_packed(self, sha): """Check if a particular object is present by SHA1 and is packed.""" return False def __iter__(self): """Iterate over the SHAs that are present in this store.""" return iter(self._data.keys()) @property def packs(self): """List with pack objects.""" return [] def get_raw(self, name): """Obtain the raw text for an object. - :param name: sha for the object. - :return: tuple with numeric type and object contents. + Args: + name: sha for the object. + Returns: tuple with numeric type and object contents. """ obj = self[self._to_hexsha(name)] return obj.type_num, obj.as_raw_string() def __getitem__(self, name): return self._data[self._to_hexsha(name)].copy() def __delitem__(self, name): """Delete an object from this store, for testing only.""" del self._data[self._to_hexsha(name)] def add_object(self, obj): """Add a single object to this object store. """ self._data[obj.id] = obj.copy() def add_objects(self, objects, progress=None): """Add a set of objects to this object store. - :param objects: Iterable over a list of (object, path) tuples + Args: + objects: Iterable over a list of (object, path) tuples """ for obj, path in objects: self.add_object(obj) def add_pack(self): """Add a new pack to this object store. Because this object store doesn't support packs, we extract and add the individual objects. - :return: Fileobject to write to and a commit function to + Returns: Fileobject to write to and a commit function to call when the pack is finished. """ f = BytesIO() def commit(): p = PackData.from_file(BytesIO(f.getvalue()), f.tell()) f.close() for obj in PackInflater.for_pack_data(p, self.get_raw): self.add_object(obj) def abort(): pass return f, commit, abort def _complete_thin_pack(self, f, indexer): """Complete a thin pack by adding external references. - :param f: Open file object for the pack. - :param indexer: A PackIndexer for indexing the pack. + Args: + f: Open file object for the pack. + indexer: A PackIndexer for indexing the pack. """ entries = list(indexer) # Update the header with the new number of objects. f.seek(0) write_pack_header(f, len(entries) + len(indexer.ext_refs())) # Rescan the rest of the pack, computing the SHA with the new header. new_sha = compute_file_sha(f, end_ofs=-20) # Complete the pack. for ext_sha in indexer.ext_refs(): assert len(ext_sha) == 20 type_num, data = self.get_raw(ext_sha) write_pack_object(f, type_num, data, sha=new_sha) pack_sha = new_sha.digest() f.write(pack_sha) def add_thin_pack(self, read_all, read_some): """Add a new thin pack to this object store. Thin packs are packs that contain deltas with parents that exist outside the pack. Because this object store doesn't support packs, we extract and add the individual objects. - :param read_all: Read function that blocks until the number of + Args: + 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 + read_some: Read function that returns at least one byte, but may not return the number of bytes requested. """ f, commit, abort = self.add_pack() try: indexer = PackIndexer(f, resolve_ext_ref=self.get_raw) copier = PackStreamCopier(read_all, read_some, f, delta_iter=indexer) copier.verify() self._complete_thin_pack(f, indexer) except BaseException: abort() raise else: commit() class ObjectIterator(object): """Interface for iterating over objects.""" def iterobjects(self): raise NotImplementedError(self.iterobjects) class ObjectStoreIterator(ObjectIterator): """ObjectIterator that works on top of an ObjectStore.""" def __init__(self, store, sha_iter): """Create a new ObjectIterator. - :param store: Object store to retrieve from - :param sha_iter: Iterator over (sha, path) tuples + Args: + store: Object store to retrieve from + sha_iter: Iterator over (sha, path) tuples """ self.store = store self.sha_iter = sha_iter self._shas = [] def __iter__(self): """Yield tuple with next object and path.""" for sha, path in self.itershas(): yield self.store[sha], path def iterobjects(self): """Iterate over just the objects.""" for o, path in self: yield o def itershas(self): """Iterate over the SHAs.""" for sha in self._shas: yield sha for sha in self.sha_iter: self._shas.append(sha) yield sha def __contains__(self, needle): """Check if an object is present. - :note: This checks if the object is present in + Note: This checks if the object is present in the underlying object store, not if it would be yielded by the iterator. - :param needle: SHA1 of the object to check for + Args: + needle: SHA1 of the object to check for """ if needle == ZERO_SHA: return False return needle in self.store def __getitem__(self, key): """Find an object by SHA1. - :note: This retrieves the object from the underlying + Note: This retrieves the object from the underlying object store. It will also succeed if the object would not be returned by the iterator. """ return self.store[key] def __len__(self): """Return the number of objects.""" return len(list(self.itershas())) def empty(self): import warnings warnings.warn('Use bool() instead.', DeprecationWarning) return self._empty() def _empty(self): it = self.itershas() try: next(it) except StopIteration: return True else: return False def __bool__(self): """Indicate whether this object has contents.""" return not self._empty() def tree_lookup_path(lookup_obj, root_sha, path): """Look up an object in a Git tree. - :param lookup_obj: Callback for retrieving object by SHA1 - :param root_sha: SHA1 of the root tree - :param path: Path to lookup - :return: A tuple of (mode, SHA) of the resulting path. + Args: + lookup_obj: Callback for retrieving object by SHA1 + root_sha: SHA1 of the root tree + path: Path to lookup + Returns: A tuple of (mode, SHA) of the resulting path. """ tree = lookup_obj(root_sha) if not isinstance(tree, Tree): raise NotTreeError(root_sha) return tree.lookup_path(lookup_obj, path) def _collect_filetree_revs(obj_store, tree_sha, kset): """Collect SHA1s of files and directories for specified tree. - :param obj_store: Object store to get objects by SHA from - :param tree_sha: tree reference to walk - :param kset: set to fill with references to files and directories + Args: + obj_store: Object store to get objects by SHA from + tree_sha: tree reference to walk + kset: set to fill with references to files and directories """ filetree = obj_store[tree_sha] for name, mode, sha in filetree.iteritems(): if not S_ISGITLINK(mode) and sha not in kset: kset.add(sha) if stat.S_ISDIR(mode): _collect_filetree_revs(obj_store, sha, kset) def _split_commits_and_tags(obj_store, lst, ignore_unknown=False): """Split object id list into three lists with commit, tag, and other SHAs. Commits referenced by tags are included into commits list as well. Only SHA1s known in this repository will get through, and unless ignore_unknown argument is True, KeyError is thrown for SHA1 missing in the repository - :param obj_store: Object store to get objects by SHA1 from - :param lst: Collection of commit and tag SHAs - :param ignore_unknown: True to skip SHA1 missing in the repository + Args: + obj_store: Object store to get objects by SHA1 from + lst: Collection of commit and tag SHAs + ignore_unknown: True to skip SHA1 missing in the repository silently. - :return: A tuple of (commits, tags, others) SHA1s + Returns: A tuple of (commits, tags, others) SHA1s """ commits = set() tags = set() others = set() for e in lst: try: o = obj_store[e] except KeyError: if not ignore_unknown: raise else: if isinstance(o, Commit): commits.add(e) elif isinstance(o, Tag): tags.add(e) tagged = o.object[1] c, t, o = _split_commits_and_tags( obj_store, [tagged], ignore_unknown=ignore_unknown) commits |= c tags |= t others |= o else: others.add(e) return (commits, tags, others) class MissingObjectFinder(object): """Find the objects missing from another object store. - :param object_store: Object store containing at least all objects to be + Args: + object_store: Object store containing at least all objects to be sent - :param haves: SHA1s of commits not to send (already present in target) - :param wants: SHA1s of commits to send - :param progress: Optional function to report progress to. - :param get_tagged: Function that returns a dict of pointed-to sha -> tag + haves: SHA1s of commits not to send (already present in target) + wants: SHA1s of commits to send + progress: Optional function to report progress to. + get_tagged: Function that returns a dict of pointed-to sha -> tag sha for including tags. - :param get_parents: Optional function for getting the parents of a commit. - :param tagged: dict of pointed-to sha -> tag sha for including tags + get_parents: Optional function for getting the parents of a commit. + tagged: dict of pointed-to sha -> tag sha for including tags """ def __init__(self, object_store, haves, wants, progress=None, get_tagged=None, get_parents=lambda commit: commit.parents): self.object_store = object_store self._get_parents = get_parents # process Commits and Tags differently # Note, while haves may list commits/tags not available locally, # and such SHAs would get filtered out by _split_commits_and_tags, # wants shall list only known SHAs, and otherwise # _split_commits_and_tags fails with KeyError have_commits, have_tags, have_others = ( _split_commits_and_tags(object_store, haves, True)) want_commits, want_tags, want_others = ( _split_commits_and_tags(object_store, wants, False)) # all_ancestors is a set of commits that shall not be sent # (complete repository up to 'haves') all_ancestors = object_store._collect_ancestors( have_commits, get_parents=self._get_parents)[0] # all_missing - complete set of commits between haves and wants # common - commits from all_ancestors we hit into while # traversing parent hierarchy of wants missing_commits, common_commits = object_store._collect_ancestors( want_commits, all_ancestors, get_parents=self._get_parents) self.sha_done = set() # Now, fill sha_done with commits and revisions of # files and directories known to be both locally # and on target. Thus these commits and files # won't get selected for fetch for h in common_commits: self.sha_done.add(h) cmt = object_store[h] _collect_filetree_revs(object_store, cmt.tree, self.sha_done) # record tags we have as visited, too for t in have_tags: self.sha_done.add(t) missing_tags = want_tags.difference(have_tags) missing_others = want_others.difference(have_others) # in fact, what we 'want' is commits, tags, and others # we've found missing wants = missing_commits.union(missing_tags) wants = wants.union(missing_others) self.objects_to_send = set([(w, None, False) for w in wants]) if progress is None: self.progress = lambda x: None else: self.progress = progress self._tagged = get_tagged and get_tagged() or {} def add_todo(self, entries): self.objects_to_send.update([e for e in entries if not e[0] in self.sha_done]) def next(self): while True: if not self.objects_to_send: return None (sha, name, leaf) = self.objects_to_send.pop() if sha not in self.sha_done: break if not leaf: o = self.object_store[sha] if isinstance(o, Commit): self.add_todo([(o.tree, "", False)]) elif isinstance(o, Tree): self.add_todo([(s, n, not stat.S_ISDIR(m)) for n, m, s in o.iteritems() if not S_ISGITLINK(m)]) elif isinstance(o, Tag): self.add_todo([(o.object[1], None, False)]) if sha in self._tagged: self.add_todo([(self._tagged[sha], None, True)]) self.sha_done.add(sha) self.progress(("counting objects: %d\r" % len(self.sha_done)).encode('ascii')) return (sha, name) __next__ = next class ObjectStoreGraphWalker(object): """Graph walker that finds what commits are missing from an object store. :ivar heads: Revisions without descendants in the local repo :ivar get_parents: Function to retrieve parents in the local repo """ def __init__(self, local_heads, get_parents, shallow=None): """Create a new instance. - :param local_heads: Heads to start search with - :param get_parents: Function for finding the parents of a SHA1. + Args: + local_heads: Heads to start search with + get_parents: Function for finding the parents of a SHA1. """ self.heads = set(local_heads) self.get_parents = get_parents self.parents = {} if shallow is None: shallow = set() self.shallow = shallow def ack(self, sha): """Ack that a revision and its ancestors are present in the source.""" if len(sha) != 40: raise ValueError("unexpected sha %r received" % sha) ancestors = set([sha]) # stop if we run out of heads to remove while self.heads: for a in ancestors: if a in self.heads: self.heads.remove(a) # collect all ancestors new_ancestors = set() for a in ancestors: ps = self.parents.get(a) if ps is not None: new_ancestors.update(ps) self.parents[a] = None # no more ancestors; stop if not new_ancestors: break ancestors = new_ancestors def next(self): """Iterate over ancestors of heads in the target.""" if self.heads: ret = self.heads.pop() ps = self.get_parents(ret) self.parents[ret] = ps self.heads.update( [p for p in ps if p not in self.parents]) return ret return None __next__ = next def commit_tree_changes(object_store, tree, changes): """Commit a specified set of changes to a tree structure. This will apply a set of changes on top of an existing tree, storing new objects in object_store. changes are a list of tuples with (path, mode, object_sha). Paths can be both blobs and trees. See the mode and object sha to None deletes the path. This method works especially well if there are only a small number of changes to a big tree. For a large number of changes to a large tree, use e.g. commit_tree. - :param object_store: Object store to store new objects in + Args: + object_store: Object store to store new objects in and retrieve old ones from. - :param tree: Original tree root - :param changes: changes to apply - :return: New tree root object + tree: Original tree root + changes: changes to apply + Returns: New tree root object """ # TODO(jelmer): Save up the objects and add them using .add_objects # rather than with individual calls to .add_object. nested_changes = {} for (path, new_mode, new_sha) in changes: try: (dirname, subpath) = path.split(b'/', 1) except ValueError: if new_sha is None: del tree[path] else: tree[path] = (new_mode, new_sha) else: nested_changes.setdefault(dirname, []).append( (subpath, new_mode, new_sha)) for name, subchanges in nested_changes.items(): try: orig_subtree = object_store[tree[name][1]] except KeyError: orig_subtree = Tree() subtree = commit_tree_changes(object_store, orig_subtree, subchanges) if len(subtree) == 0: del tree[name] else: tree[name] = (stat.S_IFDIR, subtree.id) object_store.add_object(tree) return tree class OverlayObjectStore(BaseObjectStore): """Object store that can overlay multiple object stores.""" def __init__(self, bases, add_store=None): self.bases = bases self.add_store = add_store def add_object(self, object): if self.add_store is None: raise NotImplementedError(self.add_object) return self.add_store.add_object(object) def add_objects(self, objects, progress=None): if self.add_store is None: raise NotImplementedError(self.add_object) return self.add_store.add_objects(objects, progress) @property def packs(self): ret = [] for b in self.bases: ret.extend(b.packs) return ret def __iter__(self): done = set() for b in self.bases: for o_id in b: if o_id not in done: yield o_id done.add(o_id) def get_raw(self, sha_id): for b in self.bases: try: return b.get_raw(sha_id) except KeyError: pass raise KeyError(sha_id) def contains_packed(self, sha): for b in self.bases: if b.contains_packed(sha): return True return False def contains_loose(self, sha): for b in self.bases: if b.contains_loose(sha): return True return False def read_packs_file(f): """Yield the packs listed in a packs file.""" for line in f.read().splitlines(): if not line: continue (kind, name) = line.split(b" ", 1) if kind != b"P": continue yield name.decode(sys.getfilesystemencoding()) diff --git a/dulwich/objects.py b/dulwich/objects.py index 3a41732d..8976d4fd 100644 --- a/dulwich/objects.py +++ b/dulwich/objects.py @@ -1,1403 +1,1434 @@ # objects.py -- Access to base git objects # Copyright (C) 2007 James Westby # Copyright (C) 2008-2013 Jelmer Vernooij # # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Access to base git objects.""" import binascii from io import BytesIO from collections import namedtuple import os import posixpath import stat import sys import warnings import zlib from hashlib import sha1 from dulwich.errors import ( ChecksumMismatch, NotBlobError, NotCommitError, NotTagError, NotTreeError, ObjectFormatException, EmptyFileException, ) from dulwich.file import GitFile ZERO_SHA = b'0' * 40 # Header fields for commits _TREE_HEADER = b'tree' _PARENT_HEADER = b'parent' _AUTHOR_HEADER = b'author' _COMMITTER_HEADER = b'committer' _ENCODING_HEADER = b'encoding' _MERGETAG_HEADER = b'mergetag' _GPGSIG_HEADER = b'gpgsig' # Header fields for objects _OBJECT_HEADER = b'object' _TYPE_HEADER = b'type' _TAG_HEADER = b'tag' _TAGGER_HEADER = b'tagger' S_IFGITLINK = 0o160000 MAX_TIME = 9223372036854775807 # (2**63) - 1 - signed long int max BEGIN_PGP_SIGNATURE = b"-----BEGIN PGP SIGNATURE-----" def S_ISGITLINK(m): """Check if a mode indicates a submodule. - :param m: Mode to check - :return: a ``boolean`` + Args: + m: Mode to check + Returns: a ``boolean`` """ return (stat.S_IFMT(m) == S_IFGITLINK) def _decompress(string): dcomp = zlib.decompressobj() dcomped = dcomp.decompress(string) dcomped += dcomp.flush() return dcomped def sha_to_hex(sha): """Takes a string and returns the hex of the sha within""" hexsha = binascii.hexlify(sha) assert len(hexsha) == 40, "Incorrect length of sha1 string: %d" % hexsha return hexsha def hex_to_sha(hex): """Takes a hex sha and returns a binary sha""" assert len(hex) == 40, "Incorrect length of hexsha: %s" % hex try: return binascii.unhexlify(hex) except TypeError as exc: if not isinstance(hex, bytes): raise raise ValueError(exc.args[0]) def valid_hexsha(hex): if len(hex) != 40: return False try: binascii.unhexlify(hex) except (TypeError, binascii.Error): return False else: return True def hex_to_filename(path, hex): """Takes a hex sha and returns its filename relative to the given path.""" # os.path.join accepts bytes or unicode, but all args must be of the same # type. Make sure that hex which is expected to be bytes, is the same type # as path. if getattr(path, 'encode', None) is not None: hex = hex.decode('ascii') dir = hex[:2] file = hex[2:] # Check from object dir return os.path.join(path, dir, file) def filename_to_hex(filename): """Takes an object filename and returns its corresponding hex sha.""" # grab the last (up to) two path components names = filename.rsplit(os.path.sep, 2)[-2:] errmsg = "Invalid object filename: %s" % filename assert len(names) == 2, errmsg base, rest = names assert len(base) == 2 and len(rest) == 38, errmsg hex = (base + rest).encode('ascii') hex_to_sha(hex) return hex def object_header(num_type, length): """Return an object header for the given numeric type and text length.""" return (object_class(num_type).type_name + b' ' + str(length).encode('ascii') + b'\0') def serializable_property(name, docstring=None): """A property that helps tracking whether serialization is necessary. """ def set(obj, value): setattr(obj, "_"+name, value) obj._needs_serialization = True def get(obj): return getattr(obj, "_"+name) return property(get, set, doc=docstring) def object_class(type): """Get the object class corresponding to the given type. - :param type: Either a type name string or a numeric type. - :return: The ShaFile subclass corresponding to the given type, or None if + Args: + type: Either a type name string or a numeric type. + Returns: The ShaFile subclass corresponding to the given type, or None if type is not a valid type name/number. """ return _TYPE_MAP.get(type, None) def check_hexsha(hex, error_msg): """Check if a string is a valid hex sha string. - :param hex: Hex string to check - :param error_msg: Error message to use in exception - :raise ObjectFormatException: Raised when the string is not valid + Args: + hex: Hex string to check + error_msg: Error message to use in exception + Raises: + ObjectFormatException: Raised when the string is not valid """ if not valid_hexsha(hex): raise ObjectFormatException("%s %s" % (error_msg, hex)) def check_identity(identity, error_msg): """Check if the specified identity is valid. This will raise an exception if the identity is not valid. - :param identity: Identity string - :param error_msg: Error message to use in exception + Args: + identity: Identity string + error_msg: Error message to use in exception """ email_start = identity.find(b'<') email_end = identity.find(b'>') if (email_start < 0 or email_end < 0 or email_end <= email_start or identity.find(b'<', email_start + 1) >= 0 or identity.find(b'>', email_end + 1) >= 0 or not identity.endswith(b'>')): raise ObjectFormatException(error_msg) def check_time(time_seconds): """Check if the specified time is not prone to overflow error. This will raise an exception if the time is not valid. - :param time_info: author/committer/tagger info + Args: + time_info: author/committer/tagger info """ # Prevent overflow error if time_seconds > MAX_TIME: raise ObjectFormatException( 'Date field should not exceed %s' % MAX_TIME) def git_line(*items): """Formats items into a space separated line.""" return b' '.join(items) + b'\n' class FixedSha(object): """SHA object that behaves like hashlib's but is given a fixed value.""" __slots__ = ('_hexsha', '_sha') def __init__(self, hexsha): if getattr(hexsha, 'encode', None) is not None: hexsha = hexsha.encode('ascii') if not isinstance(hexsha, bytes): raise TypeError('Expected bytes for hexsha, got %r' % hexsha) self._hexsha = hexsha self._sha = hex_to_sha(hexsha) def digest(self): """Return the raw SHA digest.""" return self._sha def hexdigest(self): """Return the hex SHA digest.""" return self._hexsha.decode('ascii') class ShaFile(object): """A git SHA file.""" __slots__ = ('_chunked_text', '_sha', '_needs_serialization') @staticmethod def _parse_legacy_object_header(magic, f): """Parse a legacy object, creating it but not reading the file.""" bufsize = 1024 decomp = zlib.decompressobj() header = decomp.decompress(magic) start = 0 end = -1 while end < 0: extra = f.read(bufsize) header += decomp.decompress(extra) magic += extra end = header.find(b'\0', start) start = len(header) header = header[:end] type_name, size = header.split(b' ', 1) try: int(size) # sanity check except ValueError as e: raise ObjectFormatException("Object size not an integer: %s" % e) obj_class = object_class(type_name) if not obj_class: raise ObjectFormatException("Not a known type: %s" % type_name) return obj_class() def _parse_legacy_object(self, map): """Parse a legacy object, setting the raw string.""" text = _decompress(map) header_end = text.find(b'\0') if header_end < 0: raise ObjectFormatException("Invalid object header, no \\0") self.set_raw_string(text[header_end+1:]) def as_legacy_object_chunks(self): """Return chunks representing the object in the experimental format. - :return: List of strings + Returns: List of strings """ compobj = zlib.compressobj() yield compobj.compress(self._header()) for chunk in self.as_raw_chunks(): yield compobj.compress(chunk) yield compobj.flush() def as_legacy_object(self): """Return string representing the object in the experimental format. """ return b''.join(self.as_legacy_object_chunks()) def as_raw_chunks(self): """Return chunks with serialization of the object. - :return: List of strings, not necessarily one per line + Returns: List of strings, not necessarily one per line """ if self._needs_serialization: self._sha = None self._chunked_text = self._serialize() self._needs_serialization = False return self._chunked_text def as_raw_string(self): """Return raw string with serialization of the object. - :return: String object + Returns: String object """ return b''.join(self.as_raw_chunks()) if sys.version_info[0] >= 3: def __bytes__(self): """Return raw string serialization of this object.""" return self.as_raw_string() else: def __str__(self): """Return raw string serialization of this object.""" return self.as_raw_string() def __hash__(self): """Return unique hash for this object.""" return hash(self.id) def as_pretty_string(self): """Return a string representing this object, fit for display.""" return self.as_raw_string() def set_raw_string(self, text, sha=None): """Set the contents of this object from a serialized string.""" if not isinstance(text, bytes): raise TypeError('Expected bytes for text, got %r' % text) self.set_raw_chunks([text], sha) def set_raw_chunks(self, chunks, sha=None): """Set the contents of this object from a list of chunks.""" self._chunked_text = chunks self._deserialize(chunks) if sha is None: self._sha = None else: self._sha = FixedSha(sha) self._needs_serialization = False @staticmethod def _parse_object_header(magic, f): """Parse a new style object, creating it but not reading the file.""" num_type = (ord(magic[0:1]) >> 4) & 7 obj_class = object_class(num_type) if not obj_class: raise ObjectFormatException("Not a known type %d" % num_type) return obj_class() def _parse_object(self, map): """Parse a new style object, setting self._text.""" # skip type and size; type must have already been determined, and # we trust zlib to fail if it's otherwise corrupted byte = ord(map[0:1]) used = 1 while (byte & 0x80) != 0: byte = ord(map[used:used+1]) used += 1 raw = map[used:] self.set_raw_string(_decompress(raw)) @classmethod def _is_legacy_object(cls, magic): b0 = ord(magic[0:1]) b1 = ord(magic[1:2]) word = (b0 << 8) + b1 return (b0 & 0x8F) == 0x08 and (word % 31) == 0 @classmethod def _parse_file(cls, f): map = f.read() if not map: raise EmptyFileException('Corrupted empty file detected') if cls._is_legacy_object(map): obj = cls._parse_legacy_object_header(map, f) obj._parse_legacy_object(map) else: obj = cls._parse_object_header(map, f) obj._parse_object(map) return obj def __init__(self): """Don't call this directly""" self._sha = None self._chunked_text = [] self._needs_serialization = True def _deserialize(self, chunks): raise NotImplementedError(self._deserialize) def _serialize(self): raise NotImplementedError(self._serialize) @classmethod def from_path(cls, path): """Open a SHA file from disk.""" with GitFile(path, 'rb') as f: return cls.from_file(f) @classmethod def from_file(cls, f): """Get the contents of a SHA file on disk.""" try: obj = cls._parse_file(f) obj._sha = None return obj except (IndexError, ValueError): raise ObjectFormatException("invalid object header") @staticmethod def from_raw_string(type_num, string, sha=None): """Creates an object of the indicated type from the raw string given. - :param type_num: The numeric type of the object. - :param string: The raw uncompressed contents. - :param sha: Optional known sha for the object + Args: + type_num: The numeric type of the object. + string: The raw uncompressed contents. + sha: Optional known sha for the object """ obj = object_class(type_num)() obj.set_raw_string(string, sha) return obj @staticmethod def from_raw_chunks(type_num, chunks, sha=None): """Creates an object of the indicated type from the raw chunks given. - :param type_num: The numeric type of the object. - :param chunks: An iterable of the raw uncompressed contents. - :param sha: Optional known sha for the object + Args: + type_num: The numeric type of the object. + chunks: An iterable of the raw uncompressed contents. + sha: Optional known sha for the object """ obj = object_class(type_num)() obj.set_raw_chunks(chunks, sha) return obj @classmethod def from_string(cls, string): """Create a ShaFile from a string.""" obj = cls() obj.set_raw_string(string) return obj def _check_has_member(self, member, error_msg): """Check that the object has a given member variable. - :param member: the member variable to check for - :param error_msg: the message for an error if the member is missing - :raise ObjectFormatException: with the given error_msg if member is + Args: + member: the member variable to check for + error_msg: the message for an error if the member is missing + Raises: + ObjectFormatException: with the given error_msg if member is missing or is None """ if getattr(self, member, None) is None: raise ObjectFormatException(error_msg) def check(self): """Check this object for internal consistency. - :raise ObjectFormatException: if the object is malformed in some way - :raise ChecksumMismatch: if the object was created with a SHA that does + Raises: + ObjectFormatException: if the object is malformed in some way + ChecksumMismatch: if the object was created with a SHA that does not match its contents """ # TODO: if we find that error-checking during object parsing is a # performance bottleneck, those checks should be moved to the class's # check() method during optimization so we can still check the object # when necessary. old_sha = self.id try: self._deserialize(self.as_raw_chunks()) self._sha = None new_sha = self.id except Exception as e: raise ObjectFormatException(e) if old_sha != new_sha: raise ChecksumMismatch(new_sha, old_sha) def _header(self): return object_header(self.type, self.raw_length()) def raw_length(self): """Returns the length of the raw string of this object.""" ret = 0 for chunk in self.as_raw_chunks(): ret += len(chunk) return ret def sha(self): """The SHA1 object that is the name of this object.""" if self._sha is None or self._needs_serialization: # this is a local because as_raw_chunks() overwrites self._sha new_sha = sha1() new_sha.update(self._header()) for chunk in self.as_raw_chunks(): new_sha.update(chunk) self._sha = new_sha return self._sha def copy(self): """Create a new copy of this SHA1 object from its raw string""" obj_class = object_class(self.get_type()) return obj_class.from_raw_string( self.get_type(), self.as_raw_string(), self.id) @property def id(self): """The hex SHA of this object.""" return self.sha().hexdigest().encode('ascii') def get_type(self): """Return the type number for this object class.""" return self.type_num def set_type(self, type): """Set the type number for this object class.""" self.type_num = type # DEPRECATED: use type_num or type_name as needed. type = property(get_type, set_type) def __repr__(self): return "<%s %s>" % (self.__class__.__name__, self.id) def __ne__(self, other): """Check whether this object does not match the other.""" return not isinstance(other, ShaFile) or self.id != other.id def __eq__(self, other): """Return True if the SHAs of the two objects match. """ return isinstance(other, ShaFile) and self.id == other.id def __lt__(self, other): """Return whether SHA of this object is less than the other. """ if not isinstance(other, ShaFile): raise TypeError return self.id < other.id def __le__(self, other): """Check whether SHA of this object is less than or equal to the other. """ if not isinstance(other, ShaFile): raise TypeError return self.id <= other.id def __cmp__(self, other): """Compare the SHA of this object with that of the other object. """ if not isinstance(other, ShaFile): raise TypeError return cmp(self.id, other.id) # noqa: F821 class Blob(ShaFile): """A Git Blob object.""" __slots__ = () type_name = b'blob' type_num = 3 def __init__(self): super(Blob, self).__init__() self._chunked_text = [] self._needs_serialization = False def _get_data(self): return self.as_raw_string() def _set_data(self, data): self.set_raw_string(data) data = property(_get_data, _set_data, "The text contained within the blob object.") def _get_chunked(self): return self._chunked_text def _set_chunked(self, chunks): self._chunked_text = chunks def _serialize(self): return self._chunked_text def _deserialize(self, chunks): self._chunked_text = chunks chunked = property( _get_chunked, _set_chunked, "The text within the blob object, as chunks (not necessarily lines).") @classmethod def from_path(cls, path): blob = ShaFile.from_path(path) if not isinstance(blob, cls): raise NotBlobError(path) return blob def check(self): """Check this object for internal consistency. - :raise ObjectFormatException: if the object is malformed in some way + Raises: + ObjectFormatException: if the object is malformed in some way """ super(Blob, self).check() def splitlines(self): """Return list of lines in this blob. This preserves the original line endings. """ chunks = self.chunked if not chunks: return [] if len(chunks) == 1: return chunks[0].splitlines(True) remaining = None ret = [] for chunk in chunks: lines = chunk.splitlines(True) if len(lines) > 1: ret.append((remaining or b"") + lines[0]) ret.extend(lines[1:-1]) remaining = lines[-1] elif len(lines) == 1: if remaining is None: remaining = lines.pop() else: remaining += lines.pop() if remaining is not None: ret.append(remaining) return ret def _parse_message(chunks): """Parse a message with a list of fields and a body. - :param chunks: the raw chunks of the tag or commit object. - :return: iterator of tuples of (field, value), one per header line, in the + Args: + chunks: the raw chunks of the tag or commit object. + Returns: iterator of tuples of (field, value), one per header line, in the order read from the text, possibly including duplicates. Includes a field named None for the freeform tag/commit text. """ f = BytesIO(b''.join(chunks)) k = None v = "" eof = False def _strip_last_newline(value): """Strip the last newline from value""" if value and value.endswith(b'\n'): return value[:-1] return value # Parse the headers # # Headers can contain newlines. The next line is indented with a space. # We store the latest key as 'k', and the accumulated value as 'v'. for line in f: if line.startswith(b' '): # Indented continuation of the previous line v += line[1:] else: if k is not None: # We parsed a new header, return its value yield (k, _strip_last_newline(v)) if line == b'\n': # Empty line indicates end of headers break (k, v) = line.split(b' ', 1) else: # We reached end of file before the headers ended. We still need to # return the previous header, then we need to return a None field for # the text. eof = True if k is not None: yield (k, _strip_last_newline(v)) yield (None, None) if not eof: # We didn't reach the end of file while parsing headers. We can return # the rest of the file as a message. yield (None, f.read()) f.close() class Tag(ShaFile): """A Git Tag object.""" type_name = b'tag' type_num = 4 __slots__ = ('_tag_timezone_neg_utc', '_name', '_object_sha', '_object_class', '_tag_time', '_tag_timezone', '_tagger', '_message', '_signature') def __init__(self): super(Tag, self).__init__() self._tagger = None self._tag_time = None self._tag_timezone = None self._tag_timezone_neg_utc = False self._signature = None @classmethod def from_path(cls, filename): tag = ShaFile.from_path(filename) if not isinstance(tag, cls): raise NotTagError(filename) return tag def check(self): """Check this object for internal consistency. - :raise ObjectFormatException: if the object is malformed in some way + Raises: + ObjectFormatException: if the object is malformed in some way """ super(Tag, self).check() self._check_has_member("_object_sha", "missing object sha") self._check_has_member("_object_class", "missing object type") self._check_has_member("_name", "missing tag name") if not self._name: raise ObjectFormatException("empty tag name") check_hexsha(self._object_sha, "invalid object sha") if getattr(self, "_tagger", None): check_identity(self._tagger, "invalid tagger") self._check_has_member("_tag_time", "missing tag time") check_time(self._tag_time) last = None for field, _ in _parse_message(self._chunked_text): if field == _OBJECT_HEADER and last is not None: raise ObjectFormatException("unexpected object") elif field == _TYPE_HEADER and last != _OBJECT_HEADER: raise ObjectFormatException("unexpected type") elif field == _TAG_HEADER and last != _TYPE_HEADER: raise ObjectFormatException("unexpected tag name") elif field == _TAGGER_HEADER and last != _TAG_HEADER: raise ObjectFormatException("unexpected tagger") last = field def _serialize(self): chunks = [] chunks.append(git_line(_OBJECT_HEADER, self._object_sha)) chunks.append(git_line(_TYPE_HEADER, self._object_class.type_name)) chunks.append(git_line(_TAG_HEADER, self._name)) if self._tagger: if self._tag_time is None: chunks.append(git_line(_TAGGER_HEADER, self._tagger)) else: chunks.append(git_line( _TAGGER_HEADER, self._tagger, str(self._tag_time).encode('ascii'), format_timezone( self._tag_timezone, self._tag_timezone_neg_utc))) if self._message is not None: chunks.append(b'\n') # To close headers chunks.append(self._message) if self._signature is not None: chunks.append(self._signature) return chunks def _deserialize(self, chunks): """Grab the metadata attached to the tag""" self._tagger = None self._tag_time = None self._tag_timezone = None self._tag_timezone_neg_utc = False for field, value in _parse_message(chunks): if field == _OBJECT_HEADER: self._object_sha = value elif field == _TYPE_HEADER: obj_class = object_class(value) if not obj_class: raise ObjectFormatException("Not a known type: %s" % value) self._object_class = obj_class elif field == _TAG_HEADER: self._name = value elif field == _TAGGER_HEADER: (self._tagger, self._tag_time, (self._tag_timezone, self._tag_timezone_neg_utc)) = parse_time_entry(value) elif field is None: if value is None: self._message = None self._signature = None else: try: sig_idx = value.index(BEGIN_PGP_SIGNATURE) except ValueError: self._message = value self._signature = None else: self._message = value[:sig_idx] self._signature = value[sig_idx:] else: raise ObjectFormatException("Unknown field %s" % field) def _get_object(self): """Get the object pointed to by this tag. - :return: tuple of (object class, sha). + Returns: tuple of (object class, sha). """ return (self._object_class, self._object_sha) def _set_object(self, value): (self._object_class, self._object_sha) = value self._needs_serialization = True object = property(_get_object, _set_object) name = serializable_property("name", "The name of this tag") tagger = serializable_property( "tagger", "Returns the name of the person who created this tag") tag_time = serializable_property( "tag_time", "The creation timestamp of the tag. As the number of seconds " "since the epoch") tag_timezone = serializable_property( "tag_timezone", "The timezone that tag_time is in.") message = serializable_property( "message", "the message attached to this tag") signature = serializable_property( "signature", "Optional detached GPG signature") class TreeEntry(namedtuple('TreeEntry', ['path', 'mode', 'sha'])): """Named tuple encapsulating a single tree entry.""" def in_path(self, path): """Return a copy of this entry with the given path prepended.""" if not isinstance(self.path, bytes): raise TypeError('Expected bytes for path, got %r' % path) return TreeEntry(posixpath.join(path, self.path), self.mode, self.sha) def parse_tree(text, strict=False): """Parse a tree text. - :param text: Serialized text to parse - :return: iterator of tuples of (name, mode, sha) - :raise ObjectFormatException: if the object was malformed in some way + Args: + text: Serialized text to parse + Returns: iterator of tuples of (name, mode, sha) + Raises: + ObjectFormatException: if the object was malformed in some way """ count = 0 length = len(text) while count < length: mode_end = text.index(b' ', count) mode_text = text[count:mode_end] if strict and mode_text.startswith(b'0'): raise ObjectFormatException("Invalid mode '%s'" % mode_text) try: mode = int(mode_text, 8) except ValueError: raise ObjectFormatException("Invalid mode '%s'" % mode_text) name_end = text.index(b'\0', mode_end) name = text[mode_end+1:name_end] count = name_end+21 sha = text[name_end+1:count] if len(sha) != 20: raise ObjectFormatException("Sha has invalid length") hexsha = sha_to_hex(sha) yield (name, mode, hexsha) def serialize_tree(items): """Serialize the items in a tree to a text. - :param items: Sorted iterable over (name, mode, sha) tuples - :return: Serialized tree text as chunks + Args: + items: Sorted iterable over (name, mode, sha) tuples + Returns: Serialized tree text as chunks """ for name, mode, hexsha in items: yield (("%04o" % mode).encode('ascii') + b' ' + name + b'\0' + hex_to_sha(hexsha)) def sorted_tree_items(entries, name_order): """Iterate over a tree entries dictionary. - :param name_order: If True, iterate entries in order of their name. If + Args: + name_order: If True, iterate entries in order of their name. If False, iterate entries in tree order, that is, treat subtree entries as having '/' appended. - :param entries: Dictionary mapping names to (mode, sha) tuples - :return: Iterator over (name, mode, hexsha) + entries: Dictionary mapping names to (mode, sha) tuples + Returns: Iterator over (name, mode, hexsha) """ key_func = name_order and key_entry_name_order or key_entry for name, entry in sorted(entries.items(), key=key_func): mode, hexsha = entry # Stricter type checks than normal to mirror checks in the C version. mode = int(mode) if not isinstance(hexsha, bytes): raise TypeError('Expected bytes for SHA, got %r' % hexsha) yield TreeEntry(name, mode, hexsha) def key_entry(entry): """Sort key for tree entry. - :param entry: (name, value) tuplee + Args: + entry: (name, value) tuplee """ (name, value) = entry if stat.S_ISDIR(value[0]): name += b'/' return name def key_entry_name_order(entry): """Sort key for tree entry in name order.""" return entry[0] def pretty_format_tree_entry(name, mode, hexsha, encoding="utf-8"): """Pretty format tree entry. - :param name: Name of the directory entry - :param mode: Mode of entry - :param hexsha: Hexsha of the referenced object - :return: string describing the tree entry + Args: + name: Name of the directory entry + mode: Mode of entry + hexsha: Hexsha of the referenced object + Returns: string describing the tree entry """ if mode & stat.S_IFDIR: kind = "tree" else: kind = "blob" return "%04o %s %s\t%s\n" % ( mode, kind, hexsha.decode('ascii'), name.decode(encoding, 'replace')) class Tree(ShaFile): """A Git tree object""" type_name = b'tree' type_num = 2 __slots__ = ('_entries') def __init__(self): super(Tree, self).__init__() self._entries = {} @classmethod def from_path(cls, filename): tree = ShaFile.from_path(filename) if not isinstance(tree, cls): raise NotTreeError(filename) return tree def __contains__(self, name): return name in self._entries def __getitem__(self, name): return self._entries[name] def __setitem__(self, name, value): """Set a tree entry by name. - :param name: The name of the entry, as a string. - :param value: A tuple of (mode, hexsha), where mode is the mode of the + Args: + name: The name of the entry, as a string. + value: A tuple of (mode, hexsha), where mode is the mode of the entry as an integral type and hexsha is the hex SHA of the entry as a string. """ mode, hexsha = value self._entries[name] = (mode, hexsha) self._needs_serialization = True def __delitem__(self, name): del self._entries[name] self._needs_serialization = True def __len__(self): return len(self._entries) def __iter__(self): return iter(self._entries) def add(self, name, mode, hexsha): """Add an entry to the tree. - :param mode: The mode of the entry as an integral type. Not all + Args: + mode: The mode of the entry as an integral type. Not all possible modes are supported by git; see check() for details. - :param name: The name of the entry, as a string. - :param hexsha: The hex SHA of the entry as a string. + name: The name of the entry, as a string. + hexsha: The hex SHA of the entry as a string. """ if isinstance(name, int) and isinstance(mode, bytes): (name, mode) = (mode, name) warnings.warn( "Please use Tree.add(name, mode, hexsha)", category=DeprecationWarning, stacklevel=2) self._entries[name] = mode, hexsha self._needs_serialization = True def iteritems(self, name_order=False): """Iterate over entries. - :param name_order: If True, iterate in name order instead of tree + Args: + name_order: If True, iterate in name order instead of tree order. - :return: Iterator over (name, mode, sha) tuples + Returns: Iterator over (name, mode, sha) tuples """ return sorted_tree_items(self._entries, name_order) def items(self): """Return the sorted entries in this tree. - :return: List with (name, mode, sha) tuples + Returns: List with (name, mode, sha) tuples """ return list(self.iteritems()) def _deserialize(self, chunks): """Grab the entries in the tree""" try: parsed_entries = parse_tree(b''.join(chunks)) except ValueError as e: raise ObjectFormatException(e) # TODO: list comprehension is for efficiency in the common (small) # case; if memory efficiency in the large case is a concern, use a # genexp. self._entries = dict([(n, (m, s)) for n, m, s in parsed_entries]) def check(self): """Check this object for internal consistency. - :raise ObjectFormatException: if the object is malformed in some way + Raises: + ObjectFormatException: if the object is malformed in some way """ super(Tree, self).check() last = None allowed_modes = (stat.S_IFREG | 0o755, stat.S_IFREG | 0o644, stat.S_IFLNK, stat.S_IFDIR, S_IFGITLINK, # TODO: optionally exclude as in git fsck --strict stat.S_IFREG | 0o664) for name, mode, sha in parse_tree(b''.join(self._chunked_text), True): check_hexsha(sha, 'invalid sha %s' % sha) if b'/' in name or name in (b'', b'.', b'..', b'.git'): raise ObjectFormatException( 'invalid name %s' % name.decode('utf-8', 'replace')) if mode not in allowed_modes: raise ObjectFormatException('invalid mode %06o' % mode) entry = (name, (mode, sha)) if last: if key_entry(last) > key_entry(entry): raise ObjectFormatException('entries not sorted') if name == last[0]: raise ObjectFormatException('duplicate entry %s' % name) last = entry def _serialize(self): return list(serialize_tree(self.iteritems())) def as_pretty_string(self): text = [] for name, mode, hexsha in self.iteritems(): text.append(pretty_format_tree_entry(name, mode, hexsha)) return "".join(text) def lookup_path(self, lookup_obj, path): """Look up an object in a Git tree. - :param lookup_obj: Callback for retrieving object by SHA1 - :param path: Path to lookup - :return: A tuple of (mode, SHA) of the resulting path. + Args: + lookup_obj: Callback for retrieving object by SHA1 + path: Path to lookup + Returns: A tuple of (mode, SHA) of the resulting path. """ parts = path.split(b'/') sha = self.id mode = None for p in parts: if not p: continue obj = lookup_obj(sha) if not isinstance(obj, Tree): raise NotTreeError(sha) mode, sha = obj[p] return mode, sha def parse_timezone(text): """Parse a timezone text fragment (e.g. '+0100'). - :param text: Text to parse. - :return: Tuple with timezone as seconds difference to UTC + Args: + text: Text to parse. + Returns: Tuple with timezone as seconds difference to UTC and a boolean indicating whether this was a UTC timezone prefixed with a negative sign (-0000). """ # cgit parses the first character as the sign, and the rest # as an integer (using strtol), which could also be negative. # We do the same for compatibility. See #697828. if not text[0] in b'+-': raise ValueError("Timezone must start with + or - (%(text)s)" % vars()) sign = text[:1] offset = int(text[1:]) if sign == b'-': offset = -offset unnecessary_negative_timezone = (offset >= 0 and sign == b'-') signum = (offset < 0) and -1 or 1 offset = abs(offset) hours = int(offset / 100) minutes = (offset % 100) return (signum * (hours * 3600 + minutes * 60), unnecessary_negative_timezone) def format_timezone(offset, unnecessary_negative_timezone=False): """Format a timezone for Git serialization. - :param offset: Timezone offset as seconds difference to UTC - :param unnecessary_negative_timezone: Whether to use a minus sign for + Args: + offset: Timezone offset as seconds difference to UTC + unnecessary_negative_timezone: Whether to use a minus sign for UTC or positive timezones (-0000 and --700 rather than +0000 / +0700). """ if offset % 60 != 0: raise ValueError("Unable to handle non-minute offset.") if offset < 0 or unnecessary_negative_timezone: sign = '-' offset = -offset else: sign = '+' return ('%c%02d%02d' % (sign, offset / 3600, (offset / 60) % 60)).encode('ascii') def parse_time_entry(value): """Parse time entry behavior - :param value: Bytes representing a git commit/tag line - :raise: ObjectFormatException in case of parsing error (malformed - field date) - :return: Tuple of (author, time, (timezone, timezone_neg_utc)) + Args: + value: Bytes representing a git commit/tag line + Raises: + ObjectFormatException in case of parsing error (malformed + field date) + Returns: Tuple of (author, time, (timezone, timezone_neg_utc)) """ try: sep = value.rindex(b'> ') except ValueError: return (value, None, (None, False)) try: person = value[0:sep+1] rest = value[sep+2:] timetext, timezonetext = rest.rsplit(b' ', 1) time = int(timetext) timezone, timezone_neg_utc = parse_timezone(timezonetext) except ValueError as e: raise ObjectFormatException(e) return person, time, (timezone, timezone_neg_utc) def parse_commit(chunks): """Parse a commit object from chunks. - :param chunks: Chunks to parse - :return: Tuple of (tree, parents, author_info, commit_info, + Args: + chunks: Chunks to parse + Returns: Tuple of (tree, parents, author_info, commit_info, encoding, mergetag, gpgsig, message, extra) """ parents = [] extra = [] tree = None author_info = (None, None, (None, None)) commit_info = (None, None, (None, None)) encoding = None mergetag = [] message = None gpgsig = None for field, value in _parse_message(chunks): # TODO(jelmer): Enforce ordering if field == _TREE_HEADER: tree = value elif field == _PARENT_HEADER: parents.append(value) elif field == _AUTHOR_HEADER: author_info = parse_time_entry(value) elif field == _COMMITTER_HEADER: commit_info = parse_time_entry(value) elif field == _ENCODING_HEADER: encoding = value elif field == _MERGETAG_HEADER: mergetag.append(Tag.from_string(value + b'\n')) elif field == _GPGSIG_HEADER: gpgsig = value elif field is None: message = value else: extra.append((field, value)) return (tree, parents, author_info, commit_info, encoding, mergetag, gpgsig, message, extra) class Commit(ShaFile): """A git commit object""" type_name = b'commit' type_num = 1 __slots__ = ('_parents', '_encoding', '_extra', '_author_timezone_neg_utc', '_commit_timezone_neg_utc', '_commit_time', '_author_time', '_author_timezone', '_commit_timezone', '_author', '_committer', '_tree', '_message', '_mergetag', '_gpgsig') def __init__(self): super(Commit, self).__init__() self._parents = [] self._encoding = None self._mergetag = [] self._gpgsig = None self._extra = [] self._author_timezone_neg_utc = False self._commit_timezone_neg_utc = False @classmethod def from_path(cls, path): commit = ShaFile.from_path(path) if not isinstance(commit, cls): raise NotCommitError(path) return commit def _deserialize(self, chunks): (self._tree, self._parents, author_info, commit_info, self._encoding, self._mergetag, self._gpgsig, self._message, self._extra) = ( parse_commit(chunks)) (self._author, self._author_time, (self._author_timezone, self._author_timezone_neg_utc)) = author_info (self._committer, self._commit_time, (self._commit_timezone, self._commit_timezone_neg_utc)) = commit_info def check(self): """Check this object for internal consistency. - :raise ObjectFormatException: if the object is malformed in some way + Raises: + ObjectFormatException: if the object is malformed in some way """ super(Commit, self).check() self._check_has_member("_tree", "missing tree") self._check_has_member("_author", "missing author") self._check_has_member("_committer", "missing committer") self._check_has_member("_author_time", "missing author time") self._check_has_member("_commit_time", "missing commit time") for parent in self._parents: check_hexsha(parent, "invalid parent sha") check_hexsha(self._tree, "invalid tree sha") check_identity(self._author, "invalid author") check_identity(self._committer, "invalid committer") check_time(self._author_time) check_time(self._commit_time) last = None for field, _ in _parse_message(self._chunked_text): if field == _TREE_HEADER and last is not None: raise ObjectFormatException("unexpected tree") elif field == _PARENT_HEADER and last not in (_PARENT_HEADER, _TREE_HEADER): raise ObjectFormatException("unexpected parent") elif field == _AUTHOR_HEADER and last not in (_TREE_HEADER, _PARENT_HEADER): raise ObjectFormatException("unexpected author") elif field == _COMMITTER_HEADER and last != _AUTHOR_HEADER: raise ObjectFormatException("unexpected committer") elif field == _ENCODING_HEADER and last != _COMMITTER_HEADER: raise ObjectFormatException("unexpected encoding") last = field # TODO: optionally check for duplicate parents def _serialize(self): chunks = [] tree_bytes = ( self._tree.id if isinstance(self._tree, Tree) else self._tree) chunks.append(git_line(_TREE_HEADER, tree_bytes)) for p in self._parents: chunks.append(git_line(_PARENT_HEADER, p)) chunks.append(git_line( _AUTHOR_HEADER, self._author, str(self._author_time).encode('ascii'), format_timezone( self._author_timezone, self._author_timezone_neg_utc))) chunks.append(git_line( _COMMITTER_HEADER, self._committer, str(self._commit_time).encode('ascii'), format_timezone(self._commit_timezone, self._commit_timezone_neg_utc))) if self.encoding: chunks.append(git_line(_ENCODING_HEADER, self.encoding)) for mergetag in self.mergetag: mergetag_chunks = mergetag.as_raw_string().split(b'\n') chunks.append(git_line(_MERGETAG_HEADER, mergetag_chunks[0])) # Embedded extra header needs leading space for chunk in mergetag_chunks[1:]: chunks.append(b' ' + chunk + b'\n') # No trailing empty line if chunks[-1].endswith(b' \n'): chunks[-1] = chunks[-1][:-2] for k, v in self.extra: if b'\n' in k or b'\n' in v: raise AssertionError( "newline in extra data: %r -> %r" % (k, v)) chunks.append(git_line(k, v)) if self.gpgsig: sig_chunks = self.gpgsig.split(b'\n') chunks.append(git_line(_GPGSIG_HEADER, sig_chunks[0])) for chunk in sig_chunks[1:]: chunks.append(git_line(b'', chunk)) chunks.append(b'\n') # There must be a new line after the headers chunks.append(self._message) return chunks tree = serializable_property( "tree", "Tree that is the state of this commit") def _get_parents(self): """Return a list of parents of this commit.""" return self._parents def _set_parents(self, value): """Set a list of parents of this commit.""" self._needs_serialization = True self._parents = value parents = property(_get_parents, _set_parents, doc="Parents of this commit, by their SHA1.") def _get_extra(self): """Return extra settings of this commit.""" return self._extra extra = property( _get_extra, doc="Extra header fields not understood (presumably added in a " "newer version of git). Kept verbatim so the object can " "be correctly reserialized. For private commit metadata, use " "pseudo-headers in Commit.message, rather than this field.") author = serializable_property( "author", "The name of the author of the commit") committer = serializable_property( "committer", "The name of the committer of the commit") message = serializable_property( "message", "The commit message") commit_time = serializable_property( "commit_time", "The timestamp of the commit. As the number of seconds since the " "epoch.") commit_timezone = serializable_property( "commit_timezone", "The zone the commit time is in") author_time = serializable_property( "author_time", "The timestamp the commit was written. As the number of " "seconds since the epoch.") author_timezone = serializable_property( "author_timezone", "Returns the zone the author time is in.") encoding = serializable_property( "encoding", "Encoding of the commit message.") mergetag = serializable_property( "mergetag", "Associated signed tag.") gpgsig = serializable_property( "gpgsig", "GPG Signature.") OBJECT_CLASSES = ( Commit, Tree, Blob, Tag, ) _TYPE_MAP = {} for cls in OBJECT_CLASSES: _TYPE_MAP[cls.type_name] = cls _TYPE_MAP[cls.type_num] = cls # Hold on to the pure-python implementations for testing _parse_tree_py = parse_tree _sorted_tree_items_py = sorted_tree_items try: # Try to import C versions from dulwich._objects import parse_tree, sorted_tree_items except ImportError: pass diff --git a/dulwich/objectspec.py b/dulwich/objectspec.py index 48c0116d..f588d313 100644 --- a/dulwich/objectspec.py +++ b/dulwich/objectspec.py @@ -1,218 +1,234 @@ # objectspec.py -- Object specification # Copyright (C) 2014 Jelmer Vernooij # # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Object specification.""" def to_bytes(text): if getattr(text, "encode", None) is not None: text = text.encode('ascii') return text def parse_object(repo, objectish): """Parse a string referring to an object. - :param repo: A `Repo` object - :param objectish: A string referring to an object - :return: A git object - :raise KeyError: If the object can not be found + Args: + repo: A `Repo` object + objectish: A string referring to an object + Returns: A git object + Raises: + KeyError: If the object can not be found """ objectish = to_bytes(objectish) return repo[objectish] def parse_tree(repo, treeish): """Parse a string referring to a tree. - :param repo: A `Repo` object - :param treeish: A string referring to a tree - :return: A git object - :raise KeyError: If the object can not be found + Args: + repo: A `Repo` object + treeish: A string referring to a tree + Returns: A git object + Raises: + KeyError: If the object can not be found """ treeish = to_bytes(treeish) o = repo[treeish] if o.type_name == b"commit": return repo[o.tree] return o def parse_ref(container, refspec): """Parse a string referring to a reference. - :param container: A RefsContainer object - :param refspec: A string referring to a ref - :return: A ref - :raise KeyError: If the ref can not be found + Args: + container: A RefsContainer object + refspec: A string referring to a ref + Returns: A ref + Raises: + KeyError: If the ref can not be found """ refspec = to_bytes(refspec) possible_refs = [ refspec, b"refs/" + refspec, b"refs/tags/" + refspec, b"refs/heads/" + refspec, b"refs/remotes/" + refspec, b"refs/remotes/" + refspec + b"/HEAD" ] for ref in possible_refs: if ref in container: return ref raise KeyError(refspec) def parse_reftuple(lh_container, rh_container, refspec): """Parse a reftuple spec. - :param lh_container: A RefsContainer object - :param hh_container: A RefsContainer object - :param refspec: A string - :return: A tuple with left and right ref - :raise KeyError: If one of the refs can not be found + Args: + lh_container: A RefsContainer object + hh_container: A RefsContainer object + refspec: A string + Returns: A tuple with left and right ref + Raises: + KeyError: If one of the refs can not be found """ refspec = to_bytes(refspec) if refspec.startswith(b"+"): force = True refspec = refspec[1:] else: force = False if b":" in refspec: (lh, rh) = refspec.split(b":") else: lh = rh = refspec if lh == b"": lh = None else: lh = parse_ref(lh_container, lh) if rh == b"": rh = None else: try: rh = parse_ref(rh_container, rh) except KeyError: # TODO: check force? if b"/" not in rh: rh = b"refs/heads/" + rh return (lh, rh, force) def parse_reftuples(lh_container, rh_container, refspecs): """Parse a list of reftuple specs to a list of reftuples. - :param lh_container: A RefsContainer object - :param hh_container: A RefsContainer object - :param refspecs: A list of refspecs or a string - :return: A list of refs - :raise KeyError: If one of the refs can not be found + Args: + lh_container: A RefsContainer object + hh_container: A RefsContainer object + refspecs: A list of refspecs or a string + Returns: A list of refs + Raises: + KeyError: If one of the refs can not be found """ if not isinstance(refspecs, list): refspecs = [refspecs] ret = [] # TODO: Support * in refspecs for refspec in refspecs: ret.append(parse_reftuple(lh_container, rh_container, refspec)) return ret def parse_refs(container, refspecs): """Parse a list of refspecs to a list of refs. - :param container: A RefsContainer object - :param refspecs: A list of refspecs or a string - :return: A list of refs - :raise KeyError: If one of the refs can not be found + Args: + container: A RefsContainer object + refspecs: A list of refspecs or a string + Returns: A list of refs + Raises: + KeyError: If one of the refs can not be found """ # TODO: Support * in refspecs if not isinstance(refspecs, list): refspecs = [refspecs] ret = [] for refspec in refspecs: ret.append(parse_ref(container, refspec)) return ret def parse_commit_range(repo, committishs): """Parse a string referring to a range of commits. - :param repo: A `Repo` object - :param committishs: A string referring to a range of commits. - :return: An iterator over `Commit` objects - :raise KeyError: When the reference commits can not be found - :raise ValueError: If the range can not be parsed + Args: + repo: A `Repo` object + committishs: A string referring to a range of commits. + Returns: An iterator over `Commit` objects + Raises: + KeyError: When the reference commits can not be found + ValueError: If the range can not be parsed """ committishs = to_bytes(committishs) # TODO(jelmer): Support more than a single commit.. return iter([parse_commit(repo, committishs)]) class AmbiguousShortId(Exception): """The short id is ambiguous.""" def __init__(self, prefix, options): self.prefix = prefix self.options = options def scan_for_short_id(object_store, prefix): """Scan an object store for a short id.""" # TODO(jelmer): This could short-circuit looking for objects # starting with a certain prefix. ret = [] for object_id in object_store: if object_id.startswith(prefix): ret.append(object_store[object_id]) if not ret: raise KeyError(prefix) if len(ret) == 1: return ret[0] raise AmbiguousShortId(prefix, ret) def parse_commit(repo, committish): """Parse a string referring to a single commit. - :param repo: A` Repo` object - :param commitish: A string referring to a single commit. - :return: A Commit object - :raise KeyError: When the reference commits can not be found - :raise ValueError: If the range can not be parsed + Args: + repo: A` Repo` object + commitish: A string referring to a single commit. + Returns: A Commit object + Raises: + KeyError: When the reference commits can not be found + ValueError: If the range can not be parsed """ committish = to_bytes(committish) try: return repo[committish] except KeyError: pass try: return repo[parse_ref(repo, committish)] except KeyError: pass if len(committish) >= 4 and len(committish) < 40: try: int(committish, 16) except ValueError: pass else: try: return scan_for_short_id(repo.object_store, committish) except KeyError: pass raise KeyError(committish) # TODO: parse_path_in_tree(), which handles e.g. v1.0:Documentation diff --git a/dulwich/pack.py b/dulwich/pack.py index e7da3cc8..7b276c36 100644 --- a/dulwich/pack.py +++ b/dulwich/pack.py @@ -1,2052 +1,2088 @@ # pack.py -- For dealing with packed git objects. # Copyright (C) 2007 James Westby # Copyright (C) 2008-2013 Jelmer Vernooij # # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Classes for dealing with packed git objects. A pack is a compact representation of a bunch of objects, stored using deltas where possible. They have two parts, the pack file, which stores the data, and an index that tells you where the data is. To find an object you look in all of the index files 'til you find a match for the object name. You then use the pointer got from this as a pointer in to the corresponding packfile. """ from collections import defaultdict import binascii from io import BytesIO, UnsupportedOperation from collections import ( deque, ) import difflib import struct from itertools import chain try: from itertools import imap, izip except ImportError: # Python3 imap = map izip = zip import os import sys from hashlib import sha1 from os import ( SEEK_CUR, SEEK_END, ) from struct import unpack_from import zlib try: import mmap except ImportError: has_mmap = False else: has_mmap = True # For some reason the above try, except fails to set has_mmap = False for plan9 if sys.platform == 'Plan9': has_mmap = False from dulwich.errors import ( # noqa: E402 ApplyDeltaError, ChecksumMismatch, ) from dulwich.file import GitFile # noqa: E402 from dulwich.lru_cache import ( # noqa: E402 LRUSizeCache, ) from dulwich.objects import ( # noqa: E402 ShaFile, hex_to_sha, sha_to_hex, object_header, ) OFS_DELTA = 6 REF_DELTA = 7 DELTA_TYPES = (OFS_DELTA, REF_DELTA) DEFAULT_PACK_DELTA_WINDOW_SIZE = 10 def take_msb_bytes(read, crc32=None): """Read bytes marked with most significant bit. - :param read: Read function + Args: + read: Read function """ ret = [] while len(ret) == 0 or ret[-1] & 0x80: b = read(1) if crc32 is not None: crc32 = binascii.crc32(b, crc32) ret.append(ord(b[:1])) return ret, crc32 class PackFileDisappeared(Exception): def __init__(self, obj): self.obj = obj class UnpackedObject(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 = None self._sha = None self.pack_type_num = pack_type_num self.delta_base = delta_base self.comp_chunks = None self.decomp_chunks = [] self.decomp_len = decomp_len self.crc32 = crc32 if pack_type_num in DELTA_TYPES: self.obj_type_num = None self.obj_chunks = None else: self.obj_type_num = pack_type_num self.obj_chunks = self.decomp_chunks self.delta_base = delta_base def sha(self): """Return the binary SHA of this object.""" if self._sha is None: self._sha = obj_sha(self.obj_type_num, self.obj_chunks) return self._sha def sha_file(self): """Return a ShaFile from this object.""" return ShaFile.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).""" if self.pack_type_num in DELTA_TYPES: return (self.delta_base, self.decomp_chunks) else: return self.decomp_chunks def __eq__(self, other): if not isinstance(other, UnpackedObject): return False for slot in self.__slots__: if getattr(self, slot) != getattr(other, slot): return False return True def __ne__(self, other): return not (self == other) def __repr__(self): data = ['%s=%r' % (s, getattr(self, s)) for s in self.__slots__] return '%s(%s)' % (self.__class__.__name__, ', '.join(data)) _ZLIB_BUFSIZE = 4096 def read_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 + Args: + 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 + 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. + include_comp: If True, include compressed data in the result. + buffer_size: Size of the read buffer. + Returns: Leftover unused data from the decompression. + Raises: + zlib.error: if a decompression error occurred. """ if unpacked.decomp_len <= -1: raise ValueError('non-negative zlib data stream size expected') decomp_obj = zlib.decompressobj() comp_chunks = [] decomp_chunks = unpacked.decomp_chunks decomp_len = 0 crc32 = unpacked.crc32 while True: add = read_some(buffer_size) if not add: raise zlib.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_data if unused: left = len(unused) if crc32 is not None: crc32 = binascii.crc32(add[:-left], crc32) if include_comp: comp_chunks[-1] = add[:-left] break elif crc32 is not None: crc32 = binascii.crc32(add, crc32) if crc32 is not None: crc32 &= 0xffffffff if decomp_len != unpacked.decomp_len: raise zlib.error('decompressed data does not match expected size') unpacked.crc32 = crc32 if include_comp: unpacked.comp_chunks = comp_chunks return unused def iter_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 + Args: + iter: Iterator over string objects + Returns: 40-byte hex sha1 digest """ sha = sha1() for name in iter: sha.update(name) return sha.hexdigest().encode('ascii') def load_pack_index(path): """Load an index file by path. - :param filename: Path to the index file - :return: A PackIndex loaded from the given path + Args: + filename: Path to the index file + Returns: A PackIndex loaded from the given path """ with GitFile(path, 'rb') as f: return load_pack_index_file(path, f) def _load_file_contents(f, size=None): try: fd = f.fileno() except (UnsupportedOperation, AttributeError): fd = None # Attempt to use mmap if possible if fd is not None: if size is None: size = os.fstat(fd).st_size if has_mmap: try: contents = mmap.mmap(fd, size, access=mmap.ACCESS_READ) except mmap.error: # Perhaps a socket? pass else: return contents, size contents = f.read() size = len(contents) return contents, size def load_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 + Args: + path: Path for the index file + f: File-like object + Returns: A PackIndex loaded from the given file """ contents, size = _load_file_contents(f) if contents[:4] == b'\377tOc': version = struct.unpack(b'>L', contents[4:8])[0] if version == 2: return PackIndex2( path, file=f, contents=contents, size=size) else: raise KeyError('Unknown pack index format %d' % version) else: return PackIndex1(path, file=f, contents=contents, size=size) def bisect_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 + Args: + start: Start index of range to search + end: End index of range to search + sha: Sha to find + unpack_name: Callback to retrieve SHA by index + Returns: Index of the SHA, or None if it wasn't found """ assert start <= end while start <= end: i = (start + end) // 2 file_sha = unpack_name(i) if file_sha < sha: start = i + 1 elif file_sha > sha: end = i - 1 else: return i return None 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. """ def __eq__(self, other): if not isinstance(other, PackIndex): 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 __len__(self): """Return the number of entries in this pack index.""" raise NotImplementedError(self.__len__) def __iter__(self): """Iterate over the SHAs in this pack.""" return imap(sha_to_hex, self._itersha()) def iterentries(self): """Iterate over the entries in this pack index. - :return: iterator over tuples with object name, offset in packfile and + Returns: iterator over tuples with object name, offset in packfile and crc32 checksum. """ raise NotImplementedError(self.iterentries) def get_pack_checksum(self): """Return the SHA1 checksum stored for the corresponding packfile. - :return: 20-byte binary digest + Returns: 20-byte binary digest """ raise NotImplementedError(self.get_pack_checksum) 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) try: return self._object_index(sha) except ValueError: closed = getattr(self._contents, 'closed', None) if closed in (None, True): raise PackFileDisappeared(self) raise def object_sha1(self, index): """Return the SHA1 corresponding to the index in the pack file. """ # PERFORMANCE/TODO(jelmer): Avoid scanning entire index for (name, offset, crc32) in self.iterentries(): if offset == index: return name else: raise KeyError(index) def _object_index(self, sha): """See object_index. - :param sha: A *binary* SHA string. (20 characters long)_ + Args: + sha: A *binary* SHA string. (20 characters long)_ """ raise NotImplementedError(self._object_index) 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. + Note: This is used for the filename of the pack. """ return iter_sha1(self._itersha()) def _itersha(self): """Yield all the SHA1's of the objects in the index, sorted.""" raise NotImplementedError(self._itersha) class MemoryPackIndex(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 + Args: + entries: Sequence of name, idx, crc32 (sorted) + pack_checksum: Optional pack checksum """ self._by_sha = {} self._by_index = {} for name, idx, crc32 in entries: self._by_sha[name] = idx self._by_index[idx] = name self._entries = entries self._pack_checksum = pack_checksum def get_pack_checksum(self): return self._pack_checksum def __len__(self): return len(self._entries) def _object_index(self, sha): return self._by_sha[sha][0] def object_sha1(self, index): return self._by_index[index] def _itersha(self): return iter(self._by_sha) def iterentries(self): return iter(self._entries) class FilePackIndex(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. if file is None: self._file = GitFile(filename, 'rb') else: self._file = file if contents is None: self._contents, self._size = _load_file_contents(self._file, size) else: self._contents, self._size = (contents, size) @property def path(self): return self._filename def __eq__(self, other): # Quick optimization: if (isinstance(other, FilePackIndex) and self._fan_out_table != other._fan_out_table): return False return super(FilePackIndex, self).__eq__(other) def close(self): self._file.close() if getattr(self._contents, "close", None) is not None: self._contents.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 + Returns: 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 ith object from the index file. """ raise NotImplementedError(self._unpack_crc32_checksum) def _itersha(self): for i in range(len(self)): yield self._unpack_name(i) def iterentries(self): """Iterate over the entries in this pack index. - :return: iterator over tuples with object name, offset in packfile and + Returns: iterator over 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): fanout_entry = self._contents[ start_offset+i*4:start_offset+(i+1)*4] ret.append(struct.unpack('>L', fanout_entry)[0]) return ret def check(self): """Check that the stored checksum matches the actual checksum.""" actual = self.calculate_checksum() stored = self.get_stored_checksum() if actual != stored: raise ChecksumMismatch(stored, actual) def calculate_checksum(self): """Calculate the SHA1 checksum over this pack index. - :return: This is a 20-byte binary digest + Returns: This is a 20-byte binary digest """ return sha1(self._contents[:-20]).digest() def get_pack_checksum(self): """Return the SHA1 checksum stored for the corresponding packfile. - :return: 20-byte binary digest + Returns: 20-byte binary digest """ return bytes(self._contents[-40:-20]) def get_stored_checksum(self): """Return the SHA1 checksum stored for this index. - :return: 20-byte binary digest + Returns: 20-byte binary digest """ return bytes(self._contents[-20:]) def _object_index(self, sha): """See object_index. - :param sha: A *binary* SHA string. (20 characters long)_ + Args: + sha: A *binary* SHA string. (20 characters long)_ """ assert len(sha) == 20 idx = ord(sha[:1]) 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) class PackIndex1(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 = 1 self._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) + 4 return self._contents[offset:offset+20] def _unpack_offset(self, i): offset = (0x100 * 4) + (i * 24) return unpack_from('>L', self._contents, offset)[0] def _unpack_crc32_checksum(self, i): # Not stored in v1 index files return None class PackIndex2(FilePackIndex): """Version 2 Pack Index file.""" def __init__(self, filename, file=None, contents=None, size=None): super(PackIndex2, self).__init__(filename, file, contents, size) if self._contents[:4] != b'\377tOc': raise AssertionError('Not a v2 pack index file') (self.version, ) = unpack_from(b'>L', self._contents, 4) if self.version != 2: raise AssertionError('Version was %d' % self.version) self._fan_out_table = self._read_fan_out_table(8) self._name_table_offset = 8 + 0x100 * 4 self._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 * 20 return self._contents[offset:offset+20] def _unpack_offset(self, i): offset = self._pack_offset_table_offset + i * 4 offset = unpack_from('>L', self._contents, offset)[0] if offset & (2**31): offset = ( self._pack_offset_largetable_offset + (offset & (2 ** 31 - 1)) * 8) offset = unpack_from('>Q', self._contents, offset)[0] return offset def _unpack_crc32_checksum(self, i): return unpack_from('>L', self._contents, self._crc32_table_offset + i * 4)[0] def read_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 + Args: + read: Read function + Returns: Tuple of (pack version, number of objects). If no data is available to read, returns (None, None). """ header = read(12) if not header: return None, None if header[:4] != b'PACK': raise AssertionError('Invalid pack header %r' % header) (version,) = unpack_from(b'>L', header, 4) if version not in (2, 3): raise AssertionError('Version was %d' % version) (num_objects,) = unpack_from(b'>L', header, 8) return (version, num_objects) def chunks_length(chunks): if isinstance(chunks, bytes): return len(chunks) else: return sum(imap(len, chunks)) def unpack_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 + Args: + 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 + 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 + 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 + include_comp: If True, include compressed data in the result. + zlib_bufsize: An optional buffer size for zlib operations. + Returns: 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) """ if read_some is None: read_some = read_all if compute_crc32: crc32 = 0 else: crc32 = None bytes, crc32 = take_msb_bytes(read_all, crc32=crc32) type_num = (bytes[0] >> 4) & 0x07 size = bytes[0] & 0x0f for i, byte in enumerate(bytes[1:]): size += (byte & 0x7f) << ((i * 7) + 4) raw_base = len(bytes) if type_num == OFS_DELTA: bytes, crc32 = take_msb_bytes(read_all, crc32=crc32) raw_base += len(bytes) if bytes[-1] & 0x80: raise AssertionError delta_base_offset = bytes[0] & 0x7f for byte in bytes[1:]: delta_base_offset += 1 delta_base_offset <<= 7 delta_base_offset += (byte & 0x7f) delta_base = delta_base_offset elif type_num == REF_DELTA: delta_base = read_all(20) if compute_crc32: crc32 = binascii.crc32(delta_base, crc32) raw_base += 20 else: delta_base = None unpacked = UnpackedObject(type_num, delta_base, size, crc32) unused = read_zlib_chunks(read_some, unpacked, buffer_size=zlib_bufsize, include_comp=include_comp) return unpacked, unused def _compute_object_size(value): """Compute the size of a unresolved object for use with LRUSizeCache.""" (num, obj) = value if num in DELTA_TYPES: return chunks_length(obj[1]) return chunks_length(obj) class PackStreamReader(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_all if read_some is None: self.read_some = read_all else: self.read_some = read_some self.sha = sha1() self._offset = 0 self._rbuf = BytesIO() # trailer is a deque to avoid memory allocation on small reads self._trailer = deque() self._zlib_bufsize = zlib_bufsize def _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 + Args: + read: The read callback to read from. + 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 read n = len(data) self._offset += n tn = len(self._trailer) if n >= 20: to_pop = tn to_add = 20 else: to_pop = max(n + tn - 20, 0) to_add = n self.sha.update( bytes(bytearray([self._trailer.popleft() for _ in range(to_pop)]))) self._trailer.extend(data[-to_add:]) # hash everything but the trailer self.sha.update(data[:-to_add]) return data def _buf_len(self): buf = self._rbuf start = buf.tell() buf.seek(0, SEEK_END) end = buf.tell() buf.seek(start) return end - start @property def offset(self): return self._offset - self._buf_len() def read(self, size): """Read, blocking until size bytes are read.""" buf_len = self._buf_len() if buf_len >= size: return self._rbuf.read(size) buf_data = self._rbuf.read() self._rbuf = BytesIO() return buf_data + self._read(self.read_all, size - buf_len) def recv(self, size): """Read up to size bytes, blocking until one byte is read.""" buf_len = self._buf_len() if buf_len: data = self._rbuf.read(size) if size >= buf_len: self._rbuf = BytesIO() return data return self._read(self.read_some, size) def __len__(self): return self._num_objects def read_objects(self, compute_crc32=False): """Read the objects in this pack file. - :param compute_crc32: If True, compute the CRC32 of the compressed + Args: + 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: + Returns: 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 + Raises: + 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. + zlib.error: if an error occurred during zlib decompression. + IOError: if an error occurred writing to the output file. """ pack_version, self._num_objects = read_pack_header(self.read) if pack_version is None: return for i in range(self._num_objects): offset = self.offset unpacked, 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 buffer buf = BytesIO() buf.write(unused) buf.write(self._rbuf.read()) buf.seek(0) self._rbuf = buf yield unpacked if self._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 = bytearray(self._trailer) if pack_sha != self.sha.digest(): raise ChecksumMismatch(sha_to_hex(pack_sha), self.sha.hexdigest()) class PackStreamCopier(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 + Args: + 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 + 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 + outfile: File-like object to write output through. + delta_iter: Optional DeltaChainIterator to record deltas as we read them. """ super(PackStreamCopier, self).__init__(read_all, read_some=read_some) self.outfile = outfile self._delta_iter = delta_iter def _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) return data def verify(self): """Verify a pack stream and write it to the output file. See PackStreamReader.iterobjects for a list of exceptions this may throw. """ if self._delta_iter: for unpacked in self.read_objects(): self._delta_iter.record(unpacked) else: for _ in self.read_objects(): pass def obj_sha(type, chunks): """Compute the SHA for a numeric type and object chunks.""" sha = sha1() sha.update(object_header(type, chunks_length(chunks))) if isinstance(chunks, bytes): sha.update(chunks) else: for chunk in chunks: sha.update(chunk) return sha.digest() def compute_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 + Args: + f: A file-like object to read from that supports seek(). + start_ofs: The offset in the file to start reading at. + 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. + buffer_size: A buffer size for reading. + Returns: A new SHA object updated with data read from the file. """ sha = sha1() f.seek(0, SEEK_END) length = f.tell() if (end_ofs < 0 and length + end_ofs < start_ofs) or end_ofs > length: raise AssertionError( "Attempt to read beyond file length. " "start_ofs: %d, end_ofs: %d, file length: %d" % ( start_ofs, end_ofs, length)) todo = length + end_ofs - start_ofs f.seek(start_ofs) while todo: data = f.read(min(todo, buffer_size)) sha.update(data) todo -= len(data) return sha 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 against 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 @property def filename(self): return os.path.basename(self._filename) @property def path(self): return self._filename @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 __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.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 + Returns: 20-byte binary SHA1 digest """ return compute_file_sha(self._file, end_ofs=-20).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) try: offset = self.pack.index.object_index(sha) except KeyError: offset = None if offset: type, obj = self.get_object_at(offset) elif self.pack is not None and self.pack.resolve_ext_ref: type, obj = self.pack.resolve_ext_ref(sha) else: raise KeyError(sha) 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. + Returns: Tuple with object type and contents. """ # Walk down the delta chain, building a stack of deltas to reach # the requested object. base_offset = offset base_type = type base_obj = obj delta_stack = [] while base_type in DELTA_TYPES: prev_offset = base_offset if get_ref is None: get_ref = self.get_ref if base_type == OFS_DELTA: (delta_offset, delta) = base_obj # TODO: clean up asserts and replace with nicer error messages base_offset = base_offset - delta_offset base_type, base_obj = self.get_object_at(base_offset) assert isinstance(base_type, int) elif base_type == REF_DELTA: (basename, delta) = base_obj assert isinstance(basename, bytes) and len(basename) == 20 base_offset, base_type, base_obj = get_ref(basename) assert isinstance(base_type, int) delta_stack.append((prev_offset, base_type, delta)) # Now grab the base object (mustn't be a delta) and apply the # deltas all the way up the stack. chunks = base_obj for prev_offset, delta_type, delta in reversed(delta_stack): chunks = apply_delta(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 prev_offset is not None: self._offset_cache[prev_offset] = base_type, chunks return base_type, chunks def iterobjects(self, progress=None, compute_crc32=True): self._file.seek(self._header_size) for i in range(1, self._num_objects + 1): offset = self._file.tell() unpacked, unused = unpack_object( self._file.read, compute_crc32=compute_crc32) if progress is not None: progress(i, self._num_objects) yield (offset, unpacked.pack_type_num, unpacked._obj(), unpacked.crc32) # Back up over unused data. self._file.seek(-len(unused), SEEK_CUR) def _iter_unpacked(self): # TODO(dborowitz): Merge this with iterobjects, if we can change its # return type. self._file.seek(self._header_size) if self._num_objects is None: return for _ in range(self._num_objects): offset = self._file.tell() unpacked, unused = unpack_object( self._file.read, compute_crc32=False) unpacked.offset = offset yield unpacked # Back up over unused data. self._file.seek(-len(unused), SEEK_CUR) def iterentries(self, progress=None): """Yield entries summarizing the contents of this pack. - :param progress: Progress function, called with current and total + Args: + progress: Progress function, called with current and total object count. - :return: iterator of tuples with (sha, offset, crc32) + Returns: iterator of tuples with (sha, offset, crc32) """ num_objects = self._num_objects resolve_ext_ref = ( self.pack.resolve_ext_ref if self.pack is not None else None) indexer = PackIndexer.for_pack_data( self, resolve_ext_ref=resolve_ext_ref) for i, result in enumerate(indexer): if progress is not None: progress(i, num_objects) yield result def sorted_entries(self, progress=None): """Return entries in this pack, sorted by SHA. - :param progress: Progress function, called with current and total + Args: + progress: Progress function, called with current and total object count - :return: List of tuples with (sha, offset, crc32) + Returns: List of tuples with (sha, offset, crc32) """ ret = sorted(self.iterentries(progress=progress)) 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 + Args: + filename: Index filename. + progress: Progress report function + Returns: Checksum of index file """ entries = self.sorted_entries(progress=progress) with GitFile(filename, 'wb') as f: return write_pack_index_v1(f, entries, self.calculate_checksum()) 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 + Args: + filename: Index filename. + progress: Progress report function + Returns: Checksum of index file """ entries = self.sorted_entries(progress=progress) with GitFile(filename, 'wb') as f: return write_pack_index_v2(f, entries, self.calculate_checksum()) 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 + Args: + filename: Index filename. + progress: Progress report function + Returns: 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(-20, SEEK_END) 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_compressed_data_at(self, offset): """Given offset in the packfile return compressed data 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. """ assert offset >= self._header_size self._file.seek(offset) unpacked, _ = unpack_object(self._file.read, include_comp=True) return (unpacked.pack_type_num, unpacked.delta_base, unpacked.comp_chunks) 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. """ try: return self._offset_cache[offset] except KeyError: pass assert offset >= self._header_size self._file.seek(offset) unpacked, _ = unpack_object(self._file.read) return (unpacked.pack_type_num, unpacked._obj()) class DeltaChainIterator(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 = False def __init__(self, file_obj, resolve_ext_ref=None): self._file = file_obj self._resolve_ext_ref = resolve_ext_ref self._pending_ofs = defaultdict(list) self._pending_ref = defaultdict(list) self._full_ofs = [] self._shas = {} self._ext_refs = [] @classmethod def for_pack_data(cls, pack_data, resolve_ext_ref=None): walker = cls(None, resolve_ext_ref=resolve_ext_ref) walker.set_pack_data(pack_data) for unpacked in pack_data._iter_unpacked(): walker.record(unpacked) return walker def record(self, unpacked): type_num = unpacked.pack_type_num offset = unpacked.offset if type_num == OFS_DELTA: base_offset = offset - unpacked.delta_base self._pending_ofs[base_offset].append(offset) elif type_num == REF_DELTA: self._pending_ref[unpacked.delta_base].append(offset) else: self._full_ofs.append((offset, type_num)) def set_pack_data(self, pack_data): self._file = pack_data._file def _walk_all_chains(self): for offset, type_num in self._full_ofs: for result in self._follow_chain(offset, type_num, None): yield result for result in self._walk_ref_chains(): yield result assert not self._pending_ofs def _ensure_no_pending(self): if self._pending_ref: raise KeyError([sha_to_hex(s) for s in self._pending_ref]) def _walk_ref_chains(self): if not self._resolve_ext_ref: self._ensure_no_pending() return for base_sha, pending in sorted(self._pending_ref.items()): if base_sha not in self._pending_ref: continue try: type_num, chunks = self._resolve_ext_ref(base_sha) except KeyError: # 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. continue self._ext_refs.append(base_sha) self._pending_ref.pop(base_sha) for new_offset in pending: for result in self._follow_chain(new_offset, type_num, chunks): yield result self._ensure_no_pending() def _result(self, unpacked): return unpacked def _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 = offset if base_chunks is None: assert unpacked.pack_type_num == obj_type_num else: assert unpacked.pack_type_num in DELTA_TYPES unpacked.obj_type_num = obj_type_num unpacked.obj_chunks = apply_delta(base_chunks, unpacked.decomp_chunks) return unpacked def _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. todo = [(offset, obj_type_num, base_chunks)] for offset, obj_type_num, base_chunks in todo: unpacked = self._resolve_object(offset, obj_type_num, base_chunks) yield self._result(unpacked) unblocked = chain(self._pending_ofs.pop(unpacked.offset, []), self._pending_ref.pop(unpacked.sha(), [])) todo.extend( (new_offset, unpacked.obj_type_num, unpacked.obj_chunks) for new_offset in unblocked) def __iter__(self): return self._walk_all_chains() def ext_refs(self): return self._ext_refs class PackIndexer(DeltaChainIterator): """Delta chain iterator that yields index entries.""" _compute_crc32 = True def _result(self, unpacked): return unpacked.sha(), unpacked.offset, unpacked.crc32 class PackInflater(DeltaChainIterator): """Delta chain iterator that yields ShaFile objects.""" def _result(self, unpacked): return unpacked.sha_file() class SHA1Reader(object): """Wrapper for file-like object that remembers the SHA1 of its data.""" def __init__(self, f): self.f = f self.sha1 = sha1(b'') def read(self, num=None): data = self.f.read(num) self.sha1.update(data) return data def check_sha(self): stored = self.f.read(20) if stored != self.sha1.digest(): raise ChecksumMismatch(self.sha1.hexdigest(), sha_to_hex(stored)) def close(self): return self.f.close() def tell(self): return self.f.tell() class SHA1Writer(object): """Wrapper for file-like object that remembers the SHA1 of its data.""" def __init__(self, f): self.f = f self.length = 0 self.sha1 = sha1(b'') def write(self, data): self.sha1.update(data) self.f.write(data) self.length += len(data) def write_sha(self): sha = self.sha1.digest() assert len(sha) == 20 self.f.write(sha) self.length += len(sha) return sha def close(self): sha = self.write_sha() self.f.close() return sha def offset(self): return self.length def tell(self): return self.f.tell() def pack_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. + Args: + type_num: Numeric type of the object. + delta_base: Delta base offset or ref, or None for whole objects. + size: Uncompressed object size. + Returns: A header for a packed object. """ header = [] c = (type_num << 4) | (size & 15) size >>= 4 while size: header.append(c | 0x80) c = size & 0x7f size >>= 7 header.append(c) if type_num == OFS_DELTA: ret = [delta_base & 0x7f] delta_base >>= 7 while delta_base: delta_base -= 1 ret.insert(0, 0x80 | (delta_base & 0x7f)) delta_base >>= 7 header.extend(ret) elif type_num == REF_DELTA: assert len(delta_base) == 20 header += delta_base return bytearray(header) def write_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 + Args: + f: File to write to + type: Numeric type of the object + object: Object to write + Returns: Tuple with offset at which the object was written, and crc32 """ if type in DELTA_TYPES: delta_base, object = object else: delta_base = None header = bytes(pack_object_header(type, delta_base, len(object))) comp_data = zlib.compress(object) crc32 = 0 for data in (header, comp_data): f.write(data) if sha is not None: sha.update(data) crc32 = binascii.crc32(data, crc32) return crc32 & 0xffffffff def write_pack(filename, objects, deltify=None, delta_window_size=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. + Args: + filename: Path to the new pack file (without .pack extension) + objects: Iterable of (object, path) tuples to write. Should provide __len__ - :param window_size: Delta window size - :param deltify: Whether to deltify pack objects - :return: Tuple with checksum of pack file and index file + window_size: Delta window size + deltify: Whether to deltify pack objects + Returns: Tuple with checksum of pack file and index file """ with GitFile(filename + '.pack', 'wb') as f: entries, data_sum = write_pack_objects( f, objects, delta_window_size=delta_window_size, deltify=deltify) entries = sorted([(k, v[0], v[1]) for (k, v) in entries.items()]) with GitFile(filename + '.idx', 'wb') as f: return data_sum, write_pack_index_v2(f, entries, data_sum) def write_pack_header(f, num_objects): """Write a pack header for the given number of objects.""" f.write(b'PACK') # Pack header f.write(struct.pack(b'>L', 2)) # Pack version f.write(struct.pack(b'>L', num_objects)) # Number of objects in pack def deltify_pack_objects(objects, window_size=None): """Generate deltas for pack objects. - :param objects: An iterable of (object, path) tuples to deltify. - :param window_size: Window size; None for default - :return: Iterator over type_num, object id, delta_base, content + Args: + objects: An iterable of (object, path) tuples to deltify. + window_size: Window size; None for default + Returns: Iterator over type_num, object id, delta_base, content delta_base is None for full text entries """ # TODO(jelmer): Use threads if window_size is None: window_size = DEFAULT_PACK_DELTA_WINDOW_SIZE # Build a list of objects ordered by the magic Linus heuristic # This helps us find good objects to diff against us magic = [] for obj, path in objects: magic.append((obj.type_num, path, -obj.raw_length(), obj)) magic.sort() possible_bases = deque() for type_num, path, neg_length, o in magic: raw = o.as_raw_string() winner = raw winner_base = None for base in possible_bases: if base.type_num != type_num: continue delta = create_delta(base.as_raw_string(), raw) if len(delta) < len(winner): winner_base = base.sha().digest() winner = delta yield type_num, o.sha().digest(), winner_base, winner possible_bases.appendleft(o) while len(possible_bases) > window_size: possible_bases.pop() def pack_objects_to_data(objects): """Create pack data from objects - :param objects: Pack objects - :return: Tuples with (type_num, hexdigest, delta base, object chunks) + Args: + objects: Pack objects + Returns: Tuples with (type_num, hexdigest, delta base, object chunks) """ count = len(objects) return (count, ((o.type_num, o.sha().digest(), None, o.as_raw_string()) for (o, path) in objects)) def write_pack_objects(f, objects, delta_window_size=None, deltify=None): """Write a new pack data file. - :param f: File to write to - :param objects: Iterable of (object, path) tuples to write. + Args: + f: File to write to + objects: Iterable of (object, path) tuples to write. Should provide __len__ - :param window_size: Sliding window size for searching for deltas; + window_size: Sliding window size for searching for deltas; Set to None for default window size. - :param deltify: Whether to deltify objects - :return: Dict mapping id -> (offset, crc32 checksum), pack checksum + deltify: Whether to deltify objects + Returns: Dict mapping id -> (offset, crc32 checksum), pack checksum """ if deltify is None: # PERFORMANCE/TODO(jelmer): This should be enabled but is *much* too # slow at the moment. deltify = False if deltify: pack_contents = deltify_pack_objects(objects, delta_window_size) pack_contents_count = len(objects) else: pack_contents_count, pack_contents = pack_objects_to_data(objects) return write_pack_data(f, pack_contents_count, pack_contents) def write_pack_data(f, num_records, records, progress=None): """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 - :param progress: Function to report progress to - :return: Dict mapping id -> (offset, crc32 checksum), pack checksum + Args: + f: File to write to + num_records: Number of records + records: Iterator over type_num, object_id, delta_base, raw + progress: Function to report progress to + Returns: Dict mapping id -> (offset, crc32 checksum), pack checksum """ # Write the pack entries = {} f = SHA1Writer(f) write_pack_header(f, num_records) for i, (type_num, object_id, delta_base, raw) in enumerate(records): if progress is not None: progress(( 'writing pack data: %d/%d\r' % (i, num_records)).encode('ascii')) offset = f.offset() if delta_base is not None: try: base_offset, base_crc32 = entries[delta_base] except KeyError: type_num = REF_DELTA raw = (delta_base, raw) else: type_num = OFS_DELTA raw = (offset - base_offset, raw) crc32 = write_pack_object(f, type_num, raw) entries[object_id] = (offset, crc32) return entries, f.write_sha() def write_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, + Args: + f: A file-like object to write to + 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 + pack_checksum: Checksum of the pack file. + Returns: The SHA of the written index file """ f = SHA1Writer(f) fan_out_table = defaultdict(lambda: 0) for (name, offset, entry_checksum) in entries: fan_out_table[ord(name[:1])] += 1 # Fan-out table 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) in entries: if not (offset <= 0xffffffff): raise TypeError("pack format 1 only supports offsets < 2Gb") f.write(struct.pack('>L20s', offset, name)) assert len(pack_checksum) == 20 f.write(pack_checksum) return f.write_sha() def _delta_encode_size(size): ret = bytearray() c = size & 0x7f size >>= 7 while size: ret.append(c | 0x80) c = size & 0x7f size >>= 7 ret.append(c) return ret # The length of delta compression copy operations in version 2 packs is limited # to 64K. To copy more, we use several copy operations. Version 3 packs allow # 24-bit lengths in copy operations, but we always make version 2 packs. _MAX_COPY_LEN = 0xffff def _encode_copy_operation(start, length): scratch = [] op = 0x80 for i in range(4): if start & 0xff << i*8: scratch.append((start >> i*8) & 0xff) op |= 1 << i for i in range(2): if length & 0xff << i*8: scratch.append((length >> i*8) & 0xff) op |= 1 << (4+i) return bytearray([op] + scratch) def create_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 + Args: + base_buf: Base buffer + target_buf: Target buffer """ assert isinstance(base_buf, bytes) assert isinstance(target_buf, bytes) out_buf = bytearray() # write delta header out_buf += _delta_encode_size(len(base_buf)) out_buf += _delta_encode_size(len(target_buf)) # write out delta opcodes seq = difflib.SequenceMatcher(a=base_buf, b=target_buf) for opcode, i1, i2, j1, j2 in seq.get_opcodes(): # Git patch opcodes don't care about deletes! # if opcode == 'replace' or opcode == 'delete': # pass if opcode == 'equal': # If they are equal, unpacker will use data from base_buf # Write out an opcode that says what range to use copy_start = i1 copy_len = i2 - i1 while copy_len > 0: to_copy = min(copy_len, _MAX_COPY_LEN) out_buf += _encode_copy_operation(copy_start, to_copy) copy_start += to_copy copy_len -= to_copy if opcode == 'replace' or opcode == 'insert': # If we are replacing a range or adding one, then we just # output it to the stream (prefixed by its size) s = j2 - j1 o = j1 while s > 127: out_buf.append(127) out_buf += bytearray(target_buf[o:o+127]) s -= 127 o += 127 out_buf.append(s) out_buf += bytearray(target_buf[o:o+s]) return bytes(out_buf) def apply_delta(src_buf, delta): """Based on the similar function in git's patch-delta.c. - :param src_buf: Source buffer - :param delta: Delta instructions + Args: + src_buf: Source buffer + delta: Delta instructions """ if not isinstance(src_buf, bytes): src_buf = b''.join(src_buf) if not isinstance(delta, bytes): delta = b''.join(delta) out = [] index = 0 delta_length = len(delta) def get_delta_header_size(delta, index): size = 0 i = 0 while delta: cmd = ord(delta[index:index+1]) index += 1 size |= (cmd & ~0x80) << i i += 7 if not cmd & 0x80: break return size, index src_size, index = get_delta_header_size(delta, index) dest_size, index = get_delta_header_size(delta, index) assert src_size == len(src_buf), '%d vs %d' % (src_size, len(src_buf)) while index < delta_length: cmd = ord(delta[index:index+1]) index += 1 if cmd & 0x80: cp_off = 0 for i in range(4): if cmd & (1 << i): x = ord(delta[index:index+1]) index += 1 cp_off |= x << (i * 8) cp_size = 0 # Version 3 packs can contain copy sizes larger than 64K. for i in range(3): if cmd & (1 << (4+i)): x = ord(delta[index:index+1]) index += 1 cp_size |= x << (i * 8) if cp_size == 0: cp_size = 0x10000 if (cp_off + cp_size < cp_size or cp_off + cp_size > src_size or cp_size > dest_size): break out.append(src_buf[cp_off:cp_off+cp_size]) elif cmd != 0: out.append(delta[index:index+cmd]) index += cmd else: raise ApplyDeltaError('Invalid opcode 0') if index != delta_length: raise ApplyDeltaError('delta not empty: %r' % delta[index:]) if dest_size != chunks_length(out): raise ApplyDeltaError('dest size incorrect') return out def write_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 + Args: + f: File-like object to write to + 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 + pack_checksum: Checksum of the pack file. + Returns: The SHA of the index file written """ f = SHA1Writer(f) f.write(b'\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[:1])] += 1 # Fan-out table largetable = [] for i in range(0x100): f.write(struct.pack(b'>L', fan_out_table[i])) fan_out_table[i+1] += fan_out_table[i] for (name, offset, entry_checksum) in entries: f.write(name) for (name, offset, entry_checksum) in entries: f.write(struct.pack(b'>L', entry_checksum)) for (name, offset, entry_checksum) in entries: if offset < 2**31: f.write(struct.pack(b'>L', offset)) else: f.write(struct.pack(b'>L', 2**31 + len(largetable))) largetable.append(offset) for offset in largetable: f.write(struct.pack(b'>Q', offset)) assert len(pack_checksum) == 20 f.write(pack_checksum) return f.write_sha() write_pack_index = write_pack_index_v2 class Pack(object): """A Git pack object.""" def __init__(self, basename, resolve_ext_ref=None): self._basename = basename self._data = None self._idx = None self._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) self.resolve_ext_ref = resolve_ext_ref @classmethod def from_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_fn ret._idx_load = idx_fn return ret @classmethod def from_objects(self, data, idx): """Create a new pack object from pack data and index objects.""" ret = Pack('') ret._data_load = lambda: data ret._idx_load = lambda: idx return ret def name(self): """The SHA over the SHAs of the objects in this pack.""" return self.index.objects_sha1() @property def data(self): """The pack data object being used.""" if self._data is None: self._data = self._data_load() self._data.pack = self self.check_length_and_checksum() return self._data @property def index(self): """The index being used. - :note: This may be an in-memory index + Note: This may be an in-memory index """ if self._idx is None: self._idx = self._idx_load() return self._idx def close(self): if self._data is not None: self._data.close() if self._idx is not None: self._idx.close() def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() def __eq__(self, other): return isinstance(self, type(other)) and self.index == other.index def __len__(self): """Number of entries in this pack.""" return len(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.""" return iter(self.index) def check_length_and_checksum(self): """Sanity check the length and checksum of the pack index and data.""" assert len(self.index) == len(self.data) idx_stored_checksum = self.index.get_pack_checksum() data_stored_checksum = self.data.get_stored_checksum() if idx_stored_checksum != data_stored_checksum: raise ChecksumMismatch(sha_to_hex(idx_stored_checksum), sha_to_hex(data_stored_checksum)) def check(self): """Check the integrity of this pack. - :raise ChecksumMismatch: if a checksum for the index or data is wrong + Raises: + ChecksumMismatch: if a checksum for the index or data is wrong """ self.index.check() self.data.check() for obj in self.iterobjects(): obj.check() # TODO: object connectivity checks def get_stored_checksum(self): return self.data.get_stored_checksum() def __contains__(self, sha1): """Check whether this pack contains a particular SHA1.""" try: self.index.object_index(sha1) return True except KeyError: return False def get_raw_unresolved(self, sha1): """Get raw unresolved data for a SHA. - :param sha1: SHA to return data for - :return: Tuple with pack object type, delta base (if applicable), + Args: + sha1: SHA to return data for + Returns: Tuple with pack object type, delta base (if applicable), list of data chunks """ offset = self.index.object_index(sha1) (obj_type, delta_base, chunks) = self.data.get_compressed_data_at( offset) if obj_type == OFS_DELTA: delta_base = sha_to_hex( self.index.object_sha1(offset - delta_base)) obj_type = REF_DELTA return (obj_type, delta_base, chunks) def get_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) return type_num, b''.join(chunks) def __getitem__(self, sha1): """Retrieve the specified SHA1.""" type, uncomp = self.get_raw(sha1) return ShaFile.from_raw_string(type, uncomp, sha=sha1) def iterobjects(self): """Iterate over the objects in this pack.""" return iter(PackInflater.for_pack_data( self.data, resolve_ext_ref=self.resolve_ext_ref)) def pack_tuples(self): """Provide an iterable for use with write_pack_objects. - :return: Object that can iterate over (object, path) tuples + Returns: Object that can iterate over (object, path) tuples and provides __len__ """ class PackTupleIterable(object): def __init__(self, pack): self.pack = pack def __len__(self): return len(self.pack) def __iter__(self): return ((o, None) for o in self.pack.iterobjects()) return PackTupleIterable(self) def keep(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 + Args: + 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. + Returns: The path of the .keep file, as a string. """ keepfile_name = '%s.keep' % self._basename with GitFile(keepfile_name, 'wb') as keepfile: if msg: keepfile.write(msg) keepfile.write(b'\n') return keepfile_name try: from dulwich._pack import apply_delta, bisect_find_sha # noqa: F811 except ImportError: pass