diff --git a/NEWS b/NEWS index 90cab28c..e1dff052 100644 --- a/NEWS +++ b/NEWS @@ -1,1983 +1,1996 @@ +0.19.15 2020-01-26 + + * Properly handle files that are just executable for the + current user. (Jelmer Vernooij, #734) + + * Fix handling of stored encoding in + ``dulwich.porcelain.get_object_by_path`` on Python 3. + (Jelmer Vernooij) + + * Support the include_trees and rename_detector arguments + at the same time when diffing trees. + (Jelmer Vernooij) + 0.19.14 2019-11-30 * Strip superfluous <> around email. (monnerat) * Stop checking for ref validity client-side. Users can still call check_wants manually. (Jelmer Vernooij) * Switch over to Google-style docstrings. (Jelmer Vernooij) * Add a ``dulwich.porcelain.active_branch`` function. (Jelmer Vernooij) * Cleanup new directory if clone fails. (Jelmer Vernooij, #733) * Expand "~" in global exclude path. (Jelmer Vernooij) 0.19.13 2019-08-19 BUG FIXES * Avoid ``PermissionError``, since it is Python3-specific. (Jelmer Vernooij) * Fix regression that added a dependency on C git for the test suite. (Jelmer Vernooij, #720) * Fix compatibility with Python 3.8 - mostly deprecation warnings. (Jelmer Vernooij) 0.19.12 2019-08-13 BUG FIXES * Update directory detection for `get_unstaged_changes` for Python 3. (Boris Feld, #684) * Add a basic ``porcelain.clean``. (Lane Barlow, #398) * Fix output format of ``porcelain.diff`` to match that of C Git. (Boris Feld) * Return a 404 not found error when repository is not found. * Mark ``.git`` directories as hidden on Windows. (Martin Packman, #585) * Implement ``RefsContainer.__iter__`` (Jelmer Vernooij, #717) * Don't trust modes if they can't be modified after a file has been created. (Jelmer Vernooij, #719) 0.19.11 2019-02-07 IMPROVEMENTS * Use fullname from gecos field, if available. (Jelmer Vernooij) * Support ``GIT_AUTHOR_NAME`` / ``GIT_AUTHOR_EMAIL``. (Jelmer Vernooij) * Add support for short ids in parse_commit. (Jelmer Vernooij) * Add support for ``prune`` and ``prune_tags`` arguments to ``porcelain.fetch``. (Jelmer Vernooij, #681) BUG FIXES * Fix handling of race conditions when new packs appear. (Jelmer Vernooij) 0.19.10 2018-01-15 IMPROVEMENTS * Add `dulwich.porcelain.write_tree`. (Jelmer Vernooij) * Support reading ``MERGE_HEADS`` in ``Repo.do_commit``. (Jelmer Vernooij) * Import from ``collections.abc`` rather than ``collections`` where applicable. Required for 3.8 compatibility. (Jelmer Vernooij) * Support plain strings as refspec arguments to ``dulwich.porcelain.push``. (Jelmer Vernooij) * Add support for creating signed tags. (Jelmer Vernooij, #542) BUG FIXES * Handle invalid ref that pretends to be a sub-folder under a valid ref. (KS Chan) 0.19.9 2018-11-17 BUG FIXES * Avoid fetching ghosts in ``Repo.fetch``. (Jelmer Vernooij) * Preserve port and username in parsed HTTP URLs. (Jelmer Vernooij) * Add basic server side implementation of ``git-upload-archive``. (Jelmer Vernooij) 0.19.8 2018-11-06 * Fix encoding when reading README file in setup.py. (egor , #668) 0.19.7 2018-11-05 CHANGES * Drop support for Python 3 < 3.4. This is because pkg_resources (which get used by setuptools and mock) no longer supports 3.3 and earlier. (Jelmer Vernooij) IMPROVEMENTS * Support ``depth`` argument to ``GitClient.fetch_pack`` and support fetching and updating shallow metadata. (Jelmer Vernooij, #240) BUG FIXES * Don't write to stdout and stderr when they are not available (such as is the case for pythonw). (Sylvia van Os, #652) * Fix compatibility with newer versions of git, which expect CONTENT_LENGTH to be set to 0 for empty body requests. (Jelmer Vernooij, #657) * Raise an exception client-side when a caller tries to request SHAs that are not directly referenced the servers' refs. (Jelmer Vernooij) * Raise more informative errors when unable to connect to repository over SSH or subprocess. (Jelmer Vernooij) * Handle commit identity fields with multiple ">" characters. (Nicolas Dandrimont) IMPROVEMENTS * ``dulwich.porcelain.get_object_by_path`` method for easily accessing a path in another tree. (Jelmer Vernooij) * Support the ``i18n.commitEncoding`` setting in config. (Jelmer Vernooij) 0.19.6 2018-08-11 BUG FIXES * Fix support for custom transport arguments in ``dulwich.porcelain.clone``. (Semyon Slepov) * Fix compatibility with Python 3.8 (Jelmer Vernooij, Daniel M. Capella) * Fix some corner cases in ``path_to_tree_path``. (Romain Keramitas) * Support paths as bytestrings in various places in ``dulwich.index`` (Jelmer Vernooij) * Avoid setup.cfg for now, since it seems to break pypi metadata. (Jelmer Vernooij, #658) 0.19.5 2018-07-08 IMPROVEMENTS * Add ``porcelain.describe``. (Sylvia van Os) BUG FIXES * Fix regression in ``dulwich.porcelain.clone`` that prevented cloning of remote repositories. (Jelmer Vernooij, #639) * Don't leave around empty parent directories for removed refs. (Damien Tournoud, #640) 0.19.4 2018-06-24 IMPROVEMENTS * Add ``porcelain.ls_files``. (Jelmer Vernooij) * Add ``Index.items``. (Jelmer Vernooij) BUG FIXES * Avoid unicode characters (e.g. the digraph ij in my surname) in setup.cfg, since setuptools doesn't deal well with them. See https://github.com/pypa/setuptools/issues/1062. (Jelmer Vernooij, #637) 0.19.3 2018-06-17 IMPROVEMENTS * Add really basic `dulwich.porcelain.fsck` implementation. (Jelmer Vernooij) * When the `DULWICH_PDB` environment variable is set, make SIGQUIT open pdb in the 'dulwich' command. * Add `checkout` argument to `Repo.clone`. (Jelmer Vernooij, #503) * Add `Repo.get_shallow` method. (Jelmer Vernooij) * Add basic `dulwich.stash` module. (Jelmer Vernooij) * Support a `prefix` argument to `dulwich.archive.tar_stream`. (Jelmer Vernooij) BUG FIXES * Fix handling of encoding for tags. (Jelmer Vernooij, #608) * Fix tutorial tests on Python 3. (Jelmer Vernooij, #573) * Fix remote refs created by `porcelain.fetch`. (Daniel Andersson, #623) * More robust pack creation on Windows. (Daniel Andersson) * Fix recursive option for `porcelain.ls_tree`. (Romain Keramitas) TESTS * Some improvements to paramiko tests. (Filipp Frizzy) 0.19.2 2018-04-07 BUG FIXES * Fix deprecated Index.iterblobs method. (Jelmer Vernooij) 0.19.1 2018-04-05 IMPROVEMENTS * Add 'dulwich.mailmap' file for reading mailmap files. (Jelmer Vernooij) * Dulwich no longer depends on urllib3[secure]. Instead, "dulwich[https]" can be used to pull in the necessary dependencies for HTTPS support. (Jelmer Vernooij, #616) * Support the `http.sslVerify` and `http.sslCAInfo` configuration options. (Jelmer Vernooij) * Factor out `dulwich.client.parse_rsync_url` function. (Jelmer Vernooij) * Fix repeat HTTP requests using the same smart HTTP client. (Jelmer Vernooij) * New 'client.PLinkSSHVendor' for creating connections using PuTTY's plink.exe. (Adam Bradley, Filipp Frizzy) * Only pass in `key_filename` and `password` to SSHVendor implementations if those parameters are set. (This helps with older SSHVendor implementations) (Jelmer Vernooij) API CHANGES * Index.iterblobs has been renamed to Index.iterobjects. (Jelmer Vernooij) 0.19.0 2018-03-10 BUG FIXES * Make `dulwich.archive` set the gzip header file modification time so that archives created from the same Git tree are always identical. (#577, Jonas Haag) * Allow comment characters (#, ;) within configuration file strings (Daniel Andersson, #579) * Raise exception when passing in invalid author/committer values to Repo.do_commit(). (Jelmer Vernooij, #602) IMPROVEMENTS * Add a fastimport ``extra``. (Jelmer Vernooij) * Start writing reflog entries. (Jelmer Vernooij) * Add ability to use password and keyfile ssh options with SSHVendor. (Filipp Kucheryavy) * Add ``change_type_same`` flag to ``tree_changes``. (Jelmer Vernooij) API CHANGES * ``GitClient.send_pack`` now accepts a ``generate_pack_data`` rather than a ``generate_pack_contents`` function for performance reasons. (Jelmer Vernooij) * Dulwich now uses urllib3 internally for HTTP requests. The `opener` argument to `dulwich.client.HttpGitClient` that took a `urllib2` opener instance has been replaced by a `pool_manager` argument that takes a `urllib3` pool manager instance. (Daniel Andersson) 0.18.6 2017-11-11 BUG FIXES * Fix handling of empty repositories in ``porcelain.clone``. (#570, Jelmer Vernooij) * Raise an error when attempting to add paths that are not under the repository. (Jelmer Vernooij) * Fix error message for missing trailing ]. (Daniel Andersson) * Raise EmptyFileException when corruption (in the form of an empty file) is detected. (Antoine R. Dumont, #582) IMPROVEMENTS * Enforce date field parsing consistency. This also add checks on those date fields for potential overflow. (Antoine R. Dumont, #567) 0.18.5 2017-10-29 BUG FIXES * Fix cwd for hooks. (Fabian Grünbichler) * Fix setting of origin in config when non-standard origin is passed into ``Repo.clone``. (Kenneth Lareau, #565) * Prevent setting SSH arguments from SSH URLs when using SSH through a subprocess. Note that Dulwich doesn't support cloning submodules. (CVE-2017-16228) (Jelmer Vernooij) IMPROVEMENTS * Silently ignored directories in ``Repo.stage``. (Jelmer Vernooij, #564) API CHANGES * GitFile now raises ``FileLocked`` when encountering a lock rather than OSError(EEXIST). (Jelmer Vernooij) 0.18.4 2017-10-01 BUG FIXES * Make default User-Agent start with "git/" because GitHub won't response to HTTP smart server requests otherwise (and reply with a 404). (Jelmer vernooij, #562) 0.18.3 2017-09-03 BUG FIXES * Read config during porcelain operations that involve remotes. (Jelmer Vernooij, #545) * Fix headers of empty chunks in unified diffs. (Taras Postument, #543) * Properly follow redirects over HTTP. (Jelmer Vernooij, #117) IMPROVEMENTS * Add ``dulwich.porcelain.update_head``. (Jelmer Vernooij, #439) * ``GitClient.fetch_pack`` now returns symrefs. (Jelmer Vernooij, #485) * The server now supports providing symrefs. (Jelmer Vernooij, #485) * Add ``dulwich.object_store.commit_tree_changes`` to incrementally commit changes to a tree structure. (Jelmer Vernooij) * Add basic ``PackBasedObjectStore.repack`` method. (Jelmer Vernooij, Earl Chew, #296, #549, #552) 0.18.2 2017-08-01 TEST FIXES * Use constant timestamp so tests pass in all timezones, not just BST. (Jelmer Vernooij) 0.18.1 2017-07-31 BUG FIXES * Fix syntax error in dulwich.contrib.test_swift_smoke. (Jelmer Vernooij) 0.18.0 2017-07-31 BUG FIXES * Fix remaining tests on Windows. (Jelmer Vernooij, #493) * Fix build of C extensions with Python 3 on Windows. (Jelmer Vernooij) * Pass 'mkdir' argument onto Repo.init_bare in Repo.clone. (Jelmer Vernooij, #504) * In ``dulwich.porcelain.add``, if no files are specified, add from current working directory rather than repository root. (Jelmer Vernooij, #521) * Properly deal with submodules in 'porcelain.status'. (Jelmer Vernooij, #517) * ``dulwich.porcelain.remove`` now actually removes files from disk, not just from the index. (Jelmer Vernooij, #488) * Fix handling of "reset" command with markers and without "from". (Antoine Pietri) * Fix handling of "merge" command with markers. (Antoine Pietri) * Support treeish argument to porcelain.reset(), rather than requiring a ref/commit id. (Jelmer Vernooij) * Handle race condition when mtime doesn't change between writes/reads. (Jelmer Vernooij, #541) * Fix ``dulwich.porcelain.show`` on commits with Python 3. (Jelmer Vernooij, #532) IMPROVEMENTS * Add basic support for reading ignore files in ``dulwich.ignore``. ``dulwich.porcelain.add`` and ``dulwich.porcelain.status`` now honor ignores. (Jelmer Vernooij, Segev Finer, #524, #526) * New ``dulwich.porcelain.check_ignore`` command. (Jelmer Vernooij) * ``dulwich.porcelain.status`` now supports a ``ignored`` argument. (Jelmer Vernooij) DOCUMENTATION * Clarified docstrings for Client.{send_pack,fetch_pack} implementations. (Jelmer Vernooij, #523) 0.17.3 2017-03-20 PLATFORM SUPPORT * List Python 3.3 as supported. (Jelmer Vernooij, #513) BUG FIXES * Fix compatibility with pypy 3. (Jelmer Vernooij) 0.17.2 2017-03-19 BUG FIXES * Add workaround for https://bitbucket.org/pypy/pypy/issues/2499/cpyext-pystring_asstring-doesnt-work, fixing Dulwich when used with C extensions on pypy < 5.6. (Victor Stinner) * Properly quote config values with a '#' character in them. (Jelmer Vernooij, #511) 0.17.1 2017-03-01 IMPROVEMENTS * Add basic 'dulwich pull' command. (Jelmer Vernooij) BUG FIXES * Cope with existing submodules during pull. (Jelmer Vernooij, #505) 0.17.0 2017-03-01 TEST FIXES * Skip test that requires sync to synchronize filesystems if os.sync is not available. (Koen Martens) IMPROVEMENTS * Implement MemoryRepo.{set_description,get_description}. (Jelmer Vernooij) * Raise exception in Repo.stage() when absolute paths are passed in. Allow passing in relative paths to porcelain.add().(Jelmer Vernooij) BUG FIXES * Handle multi-line quoted values in config files. (Jelmer Vernooij, #495) * Allow porcelain.clone of repository without HEAD. (Jelmer Vernooij, #501) * Support passing tag ids to Walker()'s include argument. (Jelmer Vernooij) * Don't strip trailing newlines from extra headers. (Nicolas Dandrimont) * Set bufsize=0 for subprocess interaction with SSH client. Fixes hangs on Python 3. (René Stern, #434) * Don't drop first slash for SSH paths, except for those starting with "~". (Jelmer Vernooij, René Stern, #463) * Properly log off after retrieving just refs. (Jelmer Vernooij) 0.16.3 2016-01-14 TEST FIXES * Remove racy check that relies on clock time changing between writes. (Jelmer Vernooij) IMPROVEMENTS * Add porcelain.remote_add. (Jelmer Vernooij) 0.16.2 2016-01-14 IMPROVEMENTS * Fixed failing test-cases on windows. (Koen Martens) API CHANGES * Repo is now a context manager, so that it can be easily closed using a ``with`` statement. (Søren Løvborg) TEST FIXES * Only run worktree list compat tests against git 2.7.0, when 'git worktree list' was introduced. (Jelmer Vernooij) BUG FIXES * Ignore filemode when building index when core.filemode is false. (Koen Martens) * Initialize core.filemode configuration setting by probing the filesystem for trustable permissions. (Koen Martens) * Fix ``porcelain.reset`` to respect the comittish argument. (Koen Martens) * Fix dulwich.porcelain.ls_remote() on Python 3. (#471, Jelmer Vernooij) * Allow both unicode and byte strings for host paths in dulwich.client. (#435, Jelmer Vernooij) * Add remote from porcelain.clone. (#466, Jelmer Vernooij) * Fix unquoting of credentials before passing to urllib2. (#475, Volodymyr Holovko) * Cope with submodules in `build_index_from_tree`. (#477, Jelmer Vernooij) * Handle deleted files in `get_unstaged_changes`. (#483, Doug Hellmann) * Don't overwrite files when they haven't changed in `build_file_from_blob`. (#479, Benoît HERVIER) * Check for existence of index file before opening pack. Fixes a race when new packs are being added. (#482, wme) 0.16.1 2016-12-25 BUG FIXES * Fix python3 compatibility for dulwich.contrib.release_robot. (Jelmer Vernooij) 0.16.0 2016-12-24 IMPROVEMENTS * Add support for worktrees. See `git-worktree(1)` and `gitrepository-layout(5)`. (Laurent Rineau) * Add support for `commondir` file in Git control directories. (Laurent Rineau) * Add support for passwords in HTTP URLs. (Jon Bain, Mika Mäenpää) * Add `release_robot` script to contrib, allowing easy finding of current version based on Git tags. (Mark Mikofski) * Add ``Blob.splitlines`` method. (Jelmer Vernooij) BUG FIXES * Fix handling of ``Commit.tree`` being set to an actual tree object rather than a tree id. (Jelmer Vernooij) * Return remote refs from LocalGitClient.fetch_pack(), consistent with the documentation for that method. (#461, Jelmer Vernooij) * Fix handling of unknown URL schemes in get_transport_and_path. (#465, Jelmer Vernooij) 0.15.0 2016-10-09 BUG FIXES * Allow missing trailing LF when reading service name from HTTP servers. (Jelmer Vernooij, Andrew Shadura, #442) * Fix dulwich.porcelain.pull() on Python3. (Jelmer Vernooij, #451) * Properly pull in tags during dulwich.porcelain.clone. (Jelmer Vernooij, #408) CHANGES * Changed license from "GNU General Public License, version 2.0 or later" to "Apache License, version 2.0 or later or GNU General Public License, version 2.0 or later". (#153) IMPROVEMENTS * Add ``dulwich.porcelain.ls_tree`` implementation. (Jelmer Vernooij) 0.14.1 2016-07-05 BUG FIXES * Fix regression removing untouched refs when pushing over SSH. (Jelmer Vernooij #441) * Skip Python3 tests for SWIFT contrib module, as it has not yet been ported. 0.14.0 2016-07-03 BUG FIXES * Fix ShaFile.id after modification of a copied ShaFile. (Félix Mattrat, Jelmer Vernooij) * Support removing refs from porcelain.push. (Jelmer Vernooij, #437) * Stop magic protocol ref `capabilities^{}` from leaking out to clients. (Jelmer Vernooij, #254) IMPROVEMENTS * Add `dulwich.config.parse_submodules` function. * Add `RefsContainer.follow` method. (#438) 0.13.0 2016-04-24 IMPROVEMENTS * Support `ssh://` URLs in get_transport_and_path_from_url(). (Jelmer Vernooij, #402) * Support missing empty line after headers in Git commits and tags. (Nicolas Dandrimont, #413) * Fix `dulwich.porcelain.status` when used in empty trees. (Jelmer Vernooij, #415) * Return copies of objects in MemoryObjectStore rather than references, making the behaviour more consistent with that of DiskObjectStore. (Félix Mattrat, Jelmer Vernooij) * Fix ``dulwich.web`` on Python3. (#295, Jonas Haag) CHANGES * Drop support for Python 2.6. * Fix python3 client web support. (Jelmer Vernooij) BUG FIXES * Fix hang on Gzip decompression. (Jonas Haag) * Don't rely on working tell() and seek() methods on wsgi.input. (Jonas Haag) * Support fastexport/fastimport functionality on python3 with newer versions of fastimport (>= 0.9.5). (Jelmer Vernooij, Félix Mattrat) 0.12.0 2015-12-13 IMPROVEMENTS * Add a `dulwich.archive` module that can create tarballs. Based on code from Jonas Haag in klaus. * Add a `dulwich.reflog` module for reading and writing reflogs. (Jelmer Vernooij) * Fix handling of ambiguous refs in `parse_ref` to make it match the behaviour described in https://git-scm.com/docs/gitrevisions. (Chris Bunney) * Support Python3 in C modules. (Lele Gaifax) BUG FIXES * Simplify handling of SSH command invocation. Fixes quoting of paths. Thanks, Thomas Liebetraut. (#384) * Fix inconsistent handling of trailing slashes for DictRefsContainer. (#383) * Add hack to support thin packs duing fetch(), albeit while requiring the entire pack file to be loaded into memory. (jsbain) CHANGES * This will be the last release to support Python 2.6. 0.11.2 2015-09-18 IMPROVEMENTS * Add support for agent= capability. (Jelmer Vernooij, #298) * Add support for quiet capability. (Jelmer Vernooij) CHANGES * The ParamikoSSHVendor class has been moved to * dulwich.contrib.paramiko_vendor, as it's currently untested. (Jelmer Vernooij, #364) 0.11.1 2015-09-13 Fix-up release to exclude broken blame.py file. 0.11.0 2015-09-13 IMPROVEMENTS * Extended Python3 support to most of the codebase. (Gary van der Merwe, Jelmer Vernooij) * The `Repo` object has a new `close` method that can be called to close any open resources. (Gary van der Merwe) * Support 'git.bat' in SubprocessGitClient on Windows. (Stefan Zimmermann) * Advertise 'ofs-delta' capability in receive-pack server side capabilities. (Jelmer Vernooij) * Switched `default_local_git_client_cls` to `LocalGitClient`. (Gary van der Merwe) * Add `porcelain.ls_remote` and `GitClient.get_refs`. (Michael Edgar) * Add `Repo.discover` method. (B. M. Corser) * Add `dulwich.objectspec.parse_refspec`. (Jelmer Vernooij) * Add `porcelain.pack_objects` and `porcelain.repack`. (Jelmer Vernooij) BUG FIXES * Fix handling of 'done' in graph walker and implement the 'no-done' capability. (Tommy Yu, #88) * Avoid recursion limit issues resolving deltas. (William Grant, #81) * Allow arguments in local client binary path overrides. (Jelmer Vernooij) * Fix handling of commands with arguments in paramiko SSH client. (Andreas Klöckner, Jelmer Vernooij, #363) * Fix parsing of quoted strings in configs. (Jelmer Vernooij, #305) 0.10.1 2015-03-25 BUG FIXES * Return `ApplyDeltaError` when encountering delta errors in both C extensions and native delta application code. (Jelmer Vernooij, #259) 0.10.0 2015-03-22 BUG FIXES * In dulwich.index.build_index_from_tree, by default refuse to create entries that start with .git/. * Fix running of testsuite when installed. (Jelmer Vernooij, #223) * Use a block cache in _find_content_rename_candidates(), improving performance. (Mike Williams) * Add support for ``core.protectNTFS`` setting. (Jelmer Vernooij) * Fix TypeError when fetching empty updates. (Hwee Miin Koh) * Resolve delta refs when pulling into a MemoryRepo. (Max Shawabkeh, #256) * Fix handling of tags of non-commits in missing object finder. (Augie Fackler, #211) * Explicitly disable mmap on plan9 where it doesn't work. (Jeff Sickel) IMPROVEMENTS * New public method `Repo.reset_index`. (Jelmer Vernooij) * Prevent duplicate parsing of loose files in objects directory when reading. Thanks to David Keijser for the report. (Jelmer Vernooij, #231) 0.9.9 2015-03-20 SECURITY BUG FIXES * Fix buffer overflow in C implementation of pack apply_delta(). (CVE-2015-0838) Thanks to Ivan Fratric of the Google Security Team for reporting this issue. (Jelmer Vernooij) 0.9.8 2014-11-30 BUG FIXES * Various fixes to improve test suite running on Windows. (Gary van der Merwe) * Limit delta copy length to 64K in v2 pack files. (Robert Brown) * Strip newline from final ACKed SHA while fetching packs. (Michael Edgar) * Remove assignment to PyList_SIZE() that was causing segfaults on pypy. (Jelmer Vernooij, #196) IMPROVEMENTS * Add porcelain 'receive-pack' and 'upload-pack'. (Jelmer Vernooij) * Handle SIGINT signals in bin/dulwich. (Jelmer Vernooij) * Add 'status' support to bin/dulwich. (Jelmer Vernooij) * Add 'branch_create', 'branch_list', 'branch_delete' porcelain. (Jelmer Vernooij) * Add 'fetch' porcelain. (Jelmer Vernooij) * Add 'tag_delete' porcelain. (Jelmer Vernooij) * Add support for serializing/deserializing 'gpgsig' attributes in Commit. (Jelmer Vernooij) CHANGES * dul-web is now available as 'dulwich web-daemon'. (Jelmer Vernooij) * dulwich.porcelain.tag has been renamed to tag_create. dulwich.porcelain.list_tags has been renamed to tag_list. (Jelmer Vernooij) API CHANGES * Restore support for Python 2.6. (Jelmer Vernooij, Gary van der Merwe) 0.9.7 2014-06-08 BUG FIXES * Fix tests dependent on hash ordering. (Michael Edgar) * Support staging symbolic links in Repo.stage. (Robert Brown) * Ensure that all files object are closed when running the test suite. (Gary van der Merwe) * When writing OFS_DELTA pack entries, write correct offset. (Augie Fackler) * Fix handler of larger copy operations in packs. (Augie Fackler) * Various fixes to improve test suite running on Windows. (Gary van der Merwe) * Fix logic for extra adds of identical files in rename detector. (Robert Brown) IMPROVEMENTS * Add porcelain 'status'. (Ryan Faulkner) * Add porcelain 'daemon'. (Jelmer Vernooij) * Add `dulwich.greenthreads` module which provides support for concurrency of some object store operations. (Fabien Boucher) * Various changes to improve compatibility with Python 3. (Gary van der Merwe, Hannu Valtonen, michael-k) * Add OpenStack Swift backed repository implementation in dulwich.contrib. See README.swift for details. (Fabien Boucher) API CHANGES * An optional close function can be passed to the Protocol class. This will be called by its close method. (Gary van der Merwe) * All classes with close methods are now context managers, so that they can be easily closed using a `with` statement. (Gary van der Merwe) * Remove deprecated `num_objects` argument to `write_pack` methods. (Jelmer Vernooij) OTHER CHANGES * The 'dul-daemon' script has been removed. The same functionality is now available as 'dulwich daemon'. (Jelmer Vernooij) 0.9.6 2014-04-23 IMPROVEMENTS * Add support for recursive add in 'git add'. (Ryan Faulkner, Jelmer Vernooij) * Add porcelain 'list_tags'. (Ryan Faulkner) * Add porcelain 'push'. (Ryan Faulkner) * Add porcelain 'pull'. (Ryan Faulkner) * Support 'http.proxy' in HttpGitClient. (Jelmer Vernooij, #1096030) * Support 'http.useragent' in HttpGitClient. (Jelmer Vernooij) * In server, wait for clients to send empty list of wants when talking to empty repository. (Damien Tournoud) * Various changes to improve compatibility with Python 3. (Gary van der Merwe) BUG FIXES * Support unseekable 'wsgi.input' streams. (Jonas Haag) * Raise TypeError when passing unicode() object to Repo.__getitem__. (Jonas Haag) * Fix handling of `reset` command in dulwich.fastexport. (Jelmer Vernooij, #1249029) * In client, don't wait for server to close connection first. Fixes hang when used against GitHub server implementation. (Siddharth Agarwal) * DeltaChainIterator: fix a corner case where an object is inflated as an object already in the repository. (Damien Tournoud, #135) * Stop leaking file handles during pack reload. (Damien Tournoud) * Avoid reopening packs during pack cache reload. (Jelmer Vernooij) API CHANGES * Drop support for Python 2.6. (Jelmer Vernooij) 0.9.5 2014-02-23 IMPROVEMENTS * Add porcelain 'tag'. (Ryan Faulkner) * New module `dulwich.objectspec` for parsing strings referencing objects and commit ranges. (Jelmer Vernooij) * Add shallow branch support. (milki) * Allow passing urllib2 `opener` into HttpGitClient. (Dov Feldstern, #909037) CHANGES * Drop support for Python 2.4 and 2.5. (Jelmer Vernooij) API CHANGES * Remove long deprecated ``Repo.commit``, ``Repo.get_blob``, ``Repo.tree`` and ``Repo.tag``. (Jelmer Vernooij) * Remove long deprecated ``Repo.revision_history`` and ``Repo.ref``. (Jelmer Vernooij) * Remove long deprecated ``Tree.entries``. (Jelmer Vernooij) BUG FIXES * Raise KeyError rather than TypeError when passing in unicode object of length 20 or 40 to Repo.__getitem__. (Jelmer Vernooij) * Use 'rm' rather than 'unlink' in tests, since the latter does not exist on OpenBSD and other platforms. (Dmitrij D. Czarkoff) 0.9.4 2013-11-30 IMPROVEMENTS * Add ssh_kwargs attribute to ParamikoSSHVendor. (milki) * Add Repo.set_description(). (Víðir Valberg Guðmundsson) * Add a basic `dulwich.porcelain` module. (Jelmer Vernooij, Marcin Kuzminski) * Various performance improvements for object access. (Jelmer Vernooij) * New function `get_transport_and_path_from_url`, similar to `get_transport_and_path` but only supports URLs. (Jelmer Vernooij) * Add support for file:// URLs in `get_transport_and_path_from_url`. (Jelmer Vernooij) * Add LocalGitClient implementation. (Jelmer Vernooij) BUG FIXES * Support filesystems with 64bit inode and device numbers. (André Roth) CHANGES * Ref handling has been moved to dulwich.refs. (Jelmer Vernooij) API CHANGES * Remove long deprecated RefsContainer.set_ref(). (Jelmer Vernooij) * Repo.ref() is now deprecated in favour of Repo.refs[]. (Jelmer Vernooij) FEATURES * Add support for graftpoints. (milki) 0.9.3 2013-09-27 BUG FIXES * Fix path for stdint.h in MANIFEST.in. (Jelmer Vernooij) 0.9.2 2013-09-26 BUG FIXES * Include stdint.h in MANIFEST.in (Mark Mikofski) 0.9.1 2013-09-22 BUG FIXES * Support lookups of 40-character refs in BaseRepo.__getitem__. (Chow Loong Jin, Jelmer Vernooij) * Fix fetching packs with side-band-64k capability disabled. (David Keijser, Jelmer Vernooij) * Several fixes in send-pack protocol behaviour - handling of empty pack files and deletes. (milki, #1063087) * Fix capability negotiation when fetching packs over HTTP. (#1072461, William Grant) * Enforce determine_wants returning an empty list rather than None. (Fabien Boucher, Jelmer Vernooij) * In the server, support pushes just removing refs. (Fabien Boucher, Jelmer Vernooij) IMPROVEMENTS * Support passing a single revision to BaseRepo.get_walker() rather than a list of revisions. (Alberto Ruiz) * Add `Repo.get_description` method. (Jelmer Vernooij) * Support thin packs in Pack.iterobjects() and Pack.get_raw(). (William Grant) * Add `MemoryObjectStore.add_pack` and `MemoryObjectStore.add_thin_pack` methods. (David Bennett) * Add paramiko-based SSH vendor. (Aaron O'Mullan) * Support running 'dulwich.server' and 'dulwich.web' using 'python -m'. (Jelmer Vernooij) * Add ObjectStore.close(). (Jelmer Vernooij) * Raise appropriate NotImplementedError when encountering dumb HTTP servers. (Jelmer Vernooij) API CHANGES * SSHVendor.connect_ssh has been renamed to SSHVendor.run_command. (Jelmer Vernooij) * ObjectStore.add_pack() now returns a 3-tuple. The last element will be an abort() method that can be used to cancel the pack operation. (Jelmer Vernooij) 0.9.0 2013-05-31 BUG FIXES * Push efficiency - report missing objects only. (#562676, Artem Tikhomirov) * Use indentation consistent with C Git in config files. (#1031356, Curt Moore, Jelmer Vernooij) * Recognize and skip binary files in diff function. (Takeshi Kanemoto) * Fix handling of relative paths in dulwich.client.get_transport_and_path. (Brian Visel, #1169368) * Preserve ordering of entries in configuration. (Benjamin Pollack) * Support ~ expansion in SSH client paths. (milki, #1083439) * Support relative paths in alternate paths. (milki, Michel Lespinasse, #1175007) * Log all error messages from wsgiref server to the logging module. This makes the test suit quiet again. (Gary van der Merwe) * Support passing None for empty tree in changes_from_tree. (Kevin Watters) * Support fetching empty repository in client. (milki, #1060462) IMPROVEMENTS: * Add optional honor_filemode flag to build_index_from_tree. (Mark Mikofski) * Support core/filemode setting when building trees. (Jelmer Vernooij) * Add chapter on tags in tutorial. (Ryan Faulkner) FEATURES * Add support for mergetags. (milki, #963525) * Add support for posix shell hooks. (milki) 0.8.7 2012-11-27 BUG FIXES * Fix use of alternates in ``DiskObjectStore``.{__contains__,__iter__}. (Dmitriy) * Fix compatibility with Python 2.4. (David Carr) 0.8.6 2012-11-09 API CHANGES * dulwich.__init__ no longer imports client, protocol, repo and server modules. (Jelmer Vernooij) FEATURES * ConfigDict now behaves more like a dictionary. (Adam 'Cezar' Jenkins, issue #58) * HTTPGitApplication now takes an optional `fallback_app` argument. (Jonas Haag, issue #67) * Support for large pack index files. (Jameson Nash) TESTING * Make index entry tests a little bit less strict, to cope with slightly different behaviour on various platforms. (Jelmer Vernooij) * ``setup.py test`` (available when setuptools is installed) now runs all tests, not just the basic unit tests. (Jelmer Vernooij) BUG FIXES * Commit._deserialize now actually deserializes the current state rather than the previous one. (Yifan Zhang, issue #59) * Handle None elements in lists of TreeChange objects. (Alex Holmes) * Support cloning repositories without HEAD set. (D-Key, Jelmer Vernooij, issue #69) * Support ``MemoryRepo.get_config``. (Jelmer Vernooij) * In ``get_transport_and_path``, pass extra keyword arguments on to HttpGitClient. (Jelmer Vernooij) 0.8.5 2012-03-29 BUG FIXES * Avoid use of 'with' in dulwich.index. (Jelmer Vernooij) * Be a little bit strict about OS behaviour in index tests. Should fix the tests on Debian GNU/kFreeBSD. (Jelmer Vernooij) 0.8.4 2012-03-28 BUG FIXES * Options on the same line as sections in config files are now supported. (Jelmer Vernooij, #920553) * Only negotiate capabilities that are also supported by the server. (Rod Cloutier, Risto Kankkunen) * Fix parsing of invalid timezone offsets with two minus signs. (Jason R. Coombs, #697828) * Reset environment variables during tests, to avoid test isolation leaks reading ~/.gitconfig. (Risto Kankkunen) TESTS * $HOME is now explicitly specified for tests that use it to read ``~/.gitconfig``, to prevent test isolation issues. (Jelmer Vernooij, #920330) FEATURES * Additional arguments to get_transport_and_path are now passed on to the constructor of the transport. (Sam Vilain) * The WSGI server now transparently handles when a git client submits data using Content-Encoding: gzip. (David Blewett, Jelmer Vernooij) * Add dulwich.index.build_index_from_tree(). (milki) 0.8.3 2012-01-21 FEATURES * The config parser now supports the git-config file format as described in git-config(1) and can write git config files. (Jelmer Vernooij, #531092, #768687) * ``Repo.do_commit`` will now use the user identity from .git/config or ~/.gitconfig if none was explicitly specified. (Jelmer Vernooij) BUG FIXES * Allow ``determine_wants`` methods to include the zero sha in their return value. (Jelmer Vernooij) 0.8.2 2011-12-18 BUG FIXES * Cope with different zlib buffer sizes in sha1 file parser. (Jelmer Vernooij) * Fix get_transport_and_path for HTTP/HTTPS URLs. (Bruno Renié) * Avoid calling free_objects() on NULL in error cases. (Chris Eberle) * Fix use --bare argument to 'dulwich init'. (Chris Eberle) * Properly abort connections when the determine_wants function raises an exception. (Jelmer Vernooij, #856769) * Tweak xcodebuild hack to deal with more error output. (Jelmer Vernooij, #903840) FEATURES * Add support for retrieving tarballs from remote servers. (Jelmer Vernooij, #379087) * New method ``update_server_info`` which generates data for dumb server access. (Jelmer Vernooij, #731235) 0.8.1 2011-10-31 FEATURES * Repo.do_commit has a new argument 'ref'. * Repo.do_commit has a new argument 'merge_heads'. (Jelmer Vernooij) * New ``Repo.get_walker`` method. (Jelmer Vernooij) * New ``Repo.clone`` method. (Jelmer Vernooij, #725369) * ``GitClient.send_pack`` now supports the 'side-band-64k' capability. (Jelmer Vernooij) * ``HttpGitClient`` which supports the smart server protocol over HTTP. "dumb" access is not yet supported. (Jelmer Vernooij, #373688) * Add basic support for alternates. (Jelmer Vernooij, #810429) CHANGES * unittest2 or python >= 2.7 is now required for the testsuite. testtools is no longer supported. (Jelmer Vernooij, #830713) BUG FIXES * Fix compilation with older versions of MSVC. (Martin gz) * Special case 'refs/stash' as a valid ref. (Jelmer Vernooij, #695577) * Smart protocol clients can now change refs even if they are not uploading new data. (Jelmer Vernooij, #855993) * Don't compile C extensions when running in pypy. (Ronny Pfannschmidt, #881546) * Use different name for strnlen replacement function to avoid clashing with system strnlen. (Jelmer Vernooij, #880362) API CHANGES * ``Repo.revision_history`` is now deprecated in favor of ``Repo.get_walker``. (Jelmer Vernooij) 0.8.0 2011-08-07 FEATURES * New DeltaChainIterator abstract class for quickly iterating all objects in a pack, with implementations for pack indexing and inflation. (Dave Borowitz) * New walk module with a Walker class for customizable commit walking. (Dave Borowitz) * New tree_changes_for_merge function in diff_tree. (Dave Borowitz) * Easy rename detection in RenameDetector even without find_copies_harder. (Dave Borowitz) BUG FIXES * Avoid storing all objects in memory when writing pack. (Jelmer Vernooij, #813268) * Support IPv6 for git:// connections. (Jelmer Vernooij, #801543) * Improve performance of Repo.revision_history(). (Timo Schmid, #535118) * Fix use of SubprocessWrapper on Windows. (Paulo Madeira, #670035) * Fix compilation on newer versions of Mac OS X (Lion and up). (Ryan McKern, #794543) * Prevent raising ValueError for correct refs in RefContainer.__delitem__. * Correctly return a tuple from MemoryObjectStore.get_raw. (Dave Borowitz) * Fix a bug in reading the pack checksum when there are fewer than 20 bytes left in the buffer. (Dave Borowitz) * Support ~ in git:// URL paths. (Jelmer Vernooij, #813555) * Make ShaFile.__eq__ work when other is not a ShaFile. (Dave Borowitz) * ObjectStore.get_graph_walker() now no longer yields the same revision more than once. This has a significant improvement for performance when wide revision graphs are involved. (Jelmer Vernooij, #818168) * Teach ReceivePackHandler how to read empty packs. (Dave Borowitz) * Don't send a pack with duplicates of the same object. (Dave Borowitz) * Teach the server how to serve a clone of an empty repo. (Dave Borowitz) * Correctly advertise capabilities during receive-pack. (Dave Borowitz) * Fix add/add and add/rename conflicts in tree_changes_for_merge. (Dave Borowitz) * Use correct MIME types in web server. (Dave Borowitz) API CHANGES * write_pack no longer takes the num_objects argument and requires an object to be passed in that is iterable (rather than an iterator) and that provides __len__. (Jelmer Vernooij) * write_pack_data has been renamed to write_pack_objects and no longer takes a num_objects argument. (Jelmer Vernooij) * take_msb_bytes, read_zlib_chunks, unpack_objects, and PackStreamReader.read_objects now take an additional argument indicating a crc32 to compute. (Dave Borowitz) * PackObjectIterator was removed; its functionality is still exposed by PackData.iterobjects. (Dave Borowitz) * Add a sha arg to write_pack_object to incrementally compute a SHA. (Dave Borowitz) * Include offset in PackStreamReader results. (Dave Borowitz) * Move PackStreamReader from server to pack. (Dave Borowitz) * Extract a check_length_and_checksum, compute_file_sha, and pack_object_header pack helper functions. (Dave Borowitz) * Extract a compute_file_sha function. (Dave Borowitz) * Remove move_in_thin_pack as a separate method; add_thin_pack now completes the thin pack and moves it in in one step. Remove ThinPackData as well. (Dave Borowitz) * Custom buffer size in read_zlib_chunks. (Dave Borowitz) * New UnpackedObject data class that replaces ad-hoc tuples in the return value of unpack_object and various DeltaChainIterator methods. (Dave Borowitz) * Add a lookup_path convenience method to Tree. (Dave Borowitz) * Optionally create RenameDetectors without passing in tree SHAs. (Dave Borowitz) * Optionally include unchanged entries in RenameDetectors. (Dave Borowitz) * Optionally pass a RenameDetector to tree_changes. (Dave Borowitz) * Optionally pass a request object through to server handlers. (Dave Borowitz) TEST CHANGES * If setuptools is installed, "python setup.py test" will now run the testsuite. (Jelmer Vernooij) * Add a new build_pack test utility for building packs from a simple spec. (Dave Borowitz) * Add a new build_commit_graph test utility for building commits from a simple spec. (Dave Borowitz) 0.7.1 2011-04-12 BUG FIXES * Fix double decref in _diff_tree.c. (Ted Horst, #715528) * Fix the build on Windows. (Pascal Quantin) * Fix get_transport_and_path compatibility with pre-2.6.5 versions of Python. (Max Bowsher, #707438) * BaseObjectStore.determine_wants_all no longer breaks on zero SHAs. (Jelmer Vernooij) * write_tree_diff() now supports submodules. (Jelmer Vernooij) * Fix compilation for XCode 4 and older versions of distutils.sysconfig. (Daniele Sluijters) IMPROVEMENTS * Sphinxified documentation. (Lukasz Balcerzak) * Add Pack.keep.(Marc Brinkmann) API CHANGES * The order of the parameters to Tree.add(name, mode, sha) has changed, and is now consistent with the rest of Dulwich. Existing code will still work but print a DeprecationWarning. (Jelmer Vernooij, #663550) * Tree.entries() is now deprecated in favour of Tree.items() and Tree.iteritems(). (Jelmer Vernooij) 0.7.0 2011-01-21 FEATURES * New `dulwich.diff_tree` module for simple content-based rename detection. (Dave Borowitz) * Add Tree.items(). (Jelmer Vernooij) * Add eof() and unread_pkt_line() methods to Protocol. (Dave Borowitz) * Add write_tree_diff(). (Jelmer Vernooij) * Add `serve_command` function for git server commands as executables. (Jelmer Vernooij) * dulwich.client.get_transport_and_path now supports rsync-style repository URLs. (Dave Borowitz, #568493) BUG FIXES * Correct short-circuiting operation for no-op fetches in the server. (Dave Borowitz) * Support parsing git mbox patches without a version tail, as generated by Mercurial. (Jelmer Vernooij) * Fix dul-receive-pack and dul-upload-pack. (Jelmer Vernooij) * Zero-padded file modes in Tree objects no longer trigger an exception but the check code warns about them. (Augie Fackler, #581064) * Repo.init() now honors the mkdir flag. (#671159) * The ref format is now checked when setting a ref rather than when reading it back. (Dave Borowitz, #653527) * Make sure pack files are closed correctly. (Tay Ray Chuan) DOCUMENTATION * Run the tutorial inside the test suite. (Jelmer Vernooij) * Reorganized and updated the tutorial. (Jelmer Vernooij, Dave Borowitz, #610550, #610540) 0.6.2 2010-10-16 BUG FIXES * HTTP server correctly handles empty CONTENT_LENGTH. (Dave Borowitz) * Don't error when creating GitFiles with the default mode. (Dave Borowitz) * ThinPackData.from_file now works with resolve_ext_ref callback. (Dave Borowitz) * Provide strnlen() on mingw32 which doesn't have it. (Hans Kolek) * Set bare=true in the configuratin for bare repositories. (Dirk Neumann) FEATURES * Use slots for core objects to save up on memory. (Jelmer Vernooij) * Web server supports streaming progress/pack output. (Dave Borowitz) * New public function dulwich.pack.write_pack_header. (Dave Borowitz) * Distinguish between missing files and read errors in HTTP server. (Dave Borowitz) * Initial work on support for fastimport using python-fastimport. (Jelmer Vernooij) * New dulwich.pack.MemoryPackIndex class. (Jelmer Vernooij) * Delegate SHA peeling to the object store. (Dave Borowitz) TESTS * Use GitFile when modifying packed-refs in tests. (Dave Borowitz) * New tests in test_web with better coverage and fewer ad-hoc mocks. (Dave Borowitz) * Standardize quote delimiters in test_protocol. (Dave Borowitz) * Fix use when testtools is installed. (Jelmer Vernooij) * Add trivial test for write_pack_header. (Jelmer Vernooij) * Refactor some of dulwich.tests.compat.server_utils. (Dave Borowitz) * Allow overwriting id property of objects in test utils. (Dave Borowitz) * Use real in-memory objects rather than stubs for server tests. (Dave Borowitz) * Clean up MissingObjectFinder. (Dave Borowitz) API CHANGES * ObjectStore.iter_tree_contents now walks contents in depth-first, sorted order. (Dave Borowitz) * ObjectStore.iter_tree_contents can optionally yield tree objects as well. (Dave Borowitz). * Add side-band-64k support to ReceivePackHandler. (Dave Borowitz) * Change server capabilities methods to classmethods. (Dave Borowitz) * Tweak server handler injection. (Dave Borowitz) * PackIndex1 and PackIndex2 now subclass FilePackIndex, which is itself a subclass of PackIndex. (Jelmer Vernooij) DOCUMENTATION * Add docstrings for various functions in dulwich.objects. (Jelmer Vernooij) * Clean up docstrings in dulwich.protocol. (Dave Borowitz) * Explicitly specify allowed protocol commands to ProtocolGraphWalker.read_proto_line. (Dave Borowitz) * Add utility functions to DictRefsContainer. (Dave Borowitz) 0.6.1 2010-07-22 BUG FIXES * Fix memory leak in C implementation of sorted_tree_items. (Dave Borowitz) * Use correct path separators for named repo files. (Dave Borowitz) * python > 2.7 and testtools-based test runners will now also pick up skipped tests correctly. (Jelmer Vernooij) FEATURES * Move named file initilization to BaseRepo. (Dave Borowitz) * Add logging utilities and git/HTTP server logging. (Dave Borowitz) * The GitClient interface has been cleaned up and instances are now reusable. (Augie Fackler) * Allow overriding paths to executables in GitSSHClient. (Ross Light, Jelmer Vernooij, #585204) * Add PackBasedObjectStore.pack_loose_objects(). (Jelmer Vernooij) TESTS * Add tests for sorted_tree_items and C implementation. (Dave Borowitz) * Add a MemoryRepo that stores everything in memory. (Dave Borowitz) * Quiet logging output from web tests. (Dave Borowitz) * More flexible version checking for compat tests. (Dave Borowitz) * Compat tests for servers with and without side-band-64k. (Dave Borowitz) CLEANUP * Clean up file headers. (Dave Borowitz) TESTS * Use GitFile when modifying packed-refs in tests. (Dave Borowitz) API CHANGES * dulwich.pack.write_pack_index_v{1,2} now take a file-like object rather than a filename. (Jelmer Vernooij) * Make dul-daemon/dul-web trivial wrappers around server functionality. (Dave Borowitz) * Move reference WSGI handler to web.py. (Dave Borowitz) * Factor out _report_status in ReceivePackHandler. (Dave Borowitz) * Factor out a function to convert a line to a pkt-line. (Dave Borowitz) 0.6.0 2010-05-22 note: This list is most likely incomplete for 0.6.0. BUG FIXES * Fix ReceivePackHandler to disallow removing refs without delete-refs. (Dave Borowitz) * Deal with capabilities required by the client, even if they can not be disabled in the server. (Dave Borowitz) * Fix trailing newlines in generated patch files. (Jelmer Vernooij) * Implement RefsContainer.__contains__. (Jelmer Vernooij) * Cope with \r in ref files on Windows. ( http://github.com/jelmer/dulwich/issues/#issue/13, Jelmer Vernooij) * Fix GitFile breakage on Windows. (Anatoly Techtonik, #557585) * Support packed ref deletion with no peeled refs. (Augie Fackler) * Fix send pack when there is nothing to fetch. (Augie Fackler) * Fix fetch if no progress function is specified. (Augie Fackler) * Allow double-staging of files that are deleted in the index. (Dave Borowitz) * Fix RefsContainer.add_if_new to support dangling symrefs. (Dave Borowitz) * Non-existant index files in non-bare repositories are now treated as empty. (Dave Borowitz) * Always update ShaFile.id when the contents of the object get changed. (Jelmer Vernooij) * Various Python2.4-compatibility fixes. (Dave Borowitz) * Fix thin pack handling. (Dave Borowitz) FEATURES * Add include-tag capability to server. (Dave Borowitz) * New dulwich.fastexport module that can generate fastexport streams. (Jelmer Vernooij) * Implemented BaseRepo.__contains__. (Jelmer Vernooij) * Add __setitem__ to DictRefsContainer. (Dave Borowitz) * Overall improvements checking Git objects. (Dave Borowitz) * Packs are now verified while they are received. (Dave Borowitz) TESTS * Add framework for testing compatibility with C Git. (Dave Borowitz) * Add various tests for the use of non-bare repositories. (Dave Borowitz) * Cope with diffstat not being available on all platforms. (Tay Ray Chuan, Jelmer Vernooij) * Add make_object and make_commit convenience functions to test utils. (Dave Borowitz) API BREAKAGES * The 'committer' and 'message' arguments to Repo.do_commit() have been swapped. 'committer' is now optional. (Jelmer Vernooij) * Repo.get_blob, Repo.commit, Repo.tag and Repo.tree are now deprecated. (Jelmer Vernooij) * RefsContainer.set_ref() was renamed to RefsContainer.set_symbolic_ref(), for clarity. (Jelmer Vernooij) API CHANGES * The primary serialization APIs in dulwich.objects now work with chunks of strings rather than with full-text strings. (Jelmer Vernooij) 0.5.02010-03-03 BUG FIXES * Support custom fields in commits (readonly). (Jelmer Vernooij) * Improved ref handling. (Dave Borowitz) * Rework server protocol to be smarter and interoperate with cgit client. (Dave Borowitz) * Add a GitFile class that uses the same locking protocol for writes as cgit. (Dave Borowitz) * Cope with forward slashes correctly in the index on Windows. (Jelmer Vernooij, #526793) FEATURES * --pure option to setup.py to allow building/installing without the C extensions. (Hal Wine, Anatoly Techtonik, Jelmer Vernooij, #434326) * Implement Repo.get_config(). (Jelmer Vernooij, Augie Fackler) * HTTP dumb and smart server. (Dave Borowitz) * Add abstract baseclass for Repo that does not require file system operations. (Dave Borowitz) 0.4.1 2010-01-03 FEATURES * Add ObjectStore.iter_tree_contents(). (Jelmer Vernooij) * Add Index.changes_from_tree(). (Jelmer Vernooij) * Add ObjectStore.tree_changes(). (Jelmer Vernooij) * Add functionality for writing patches in dulwich.patch. (Jelmer Vernooij) 0.4.0 2009-10-07 DOCUMENTATION * Added tutorial. API CHANGES * dulwich.object_store.tree_lookup_path will now return the mode and sha of the object found rather than the object itself. BUG FIXES * Use binascii.hexlify / binascii.unhexlify for better performance. * Cope with extra unknown data in index files by ignoring it (for now). * Add proper error message when server unexpectedly hangs up. (#415843) * Correctly write opcode for equal in create_delta. 0.3.3 2009-07-23 FEATURES * Implement ShaFile.__hash__(). * Implement Tree.__len__() BUG FIXES * Check for 'objects' and 'refs' directories when looking for a Git repository. (#380818) 0.3.2 2009-05-20 BUG FIXES * Support the encoding field in Commits. * Some Windows compatibility fixes. * Fixed several issues in commit support. FEATURES * Basic support for handling submodules. 0.3.1 2009-05-13 FEATURES * Implemented Repo.__getitem__, Repo.__setitem__ and Repo.__delitem__ to access content. API CHANGES * Removed Repo.set_ref, Repo.remove_ref, Repo.tags, Repo.get_refs and Repo.heads in favor of Repo.refs, a dictionary-like object for accessing refs. BUG FIXES * Removed import of 'sha' module in objects.py, which was causing deprecation warnings on Python 2.6. 0.3.0 2009-05-10 FEATURES * A new function 'commit_tree' has been added that can commit a tree based on an index. BUG FIXES * The memory usage when generating indexes has been significantly reduced. * A memory leak in the C implementation of parse_tree has been fixed. * The send-pack smart server command now works. (Thanks Scott Chacon) * The handling of short timestamps (less than 10 digits) has been fixed. * The handling of timezones has been fixed. 0.2.1 2009-04-30 BUG FIXES * Fix compatibility with Python2.4. 0.2.0 2009-04-30 FEATURES * Support for activity reporting in smart protocol client. * Optional C extensions for better performance in a couple of places that are performance-critical. 0.1.1 2009-03-13 BUG FIXES * Fixed regression in Repo.find_missing_objects() * Don't fetch ^{} objects from remote hosts, as requesting them causes a hangup. * Always write pack to disk completely before calculating checksum. FEATURES * Allow disabling thin packs when talking to remote hosts. 0.1.0 2009-01-24 * Initial release. diff --git a/PKG-INFO b/PKG-INFO index 2d25463b..029a76f5 100644 --- a/PKG-INFO +++ b/PKG-INFO @@ -1,125 +1,125 @@ Metadata-Version: 2.1 Name: dulwich -Version: 0.19.14 +Version: 0.19.15 Summary: Python Git Library Home-page: https://www.dulwich.io/ Author: Jelmer Vernooij Author-email: jelmer@jelmer.uk License: Apachev2 or later or GPLv2 Project-URL: Bug Tracker, https://github.com/dulwich/dulwich/issues Project-URL: GitHub, https://github.com/dulwich/dulwich Project-URL: Repository, https://www.dulwich.io/code/ Description: .. image:: https://travis-ci.org/dulwich/dulwich.png?branch=master :alt: Build Status :target: https://travis-ci.org/dulwich/dulwich .. image:: https://ci.appveyor.com/api/projects/status/mob7g4vnrfvvoweb?svg=true :alt: Windows Build Status :target: https://ci.appveyor.com/project/jelmer/dulwich/branch/master This is the Dulwich project. It aims to provide an interface to git repos (both local and remote) that doesn't call out to git directly but instead uses pure Python. **Main website**: **License**: Apache License, version 2 or GNU General Public License, version 2 or later. The project is named after the part of London that Mr. and Mrs. Git live in in the particular Monty Python sketch. Installation ------------ By default, Dulwich' setup.py will attempt to build and install the optional C extensions. The reason for this is that they significantly improve the performance since some low-level operations that are executed often are much slower in CPython. If you don't want to install the C bindings, specify the --pure argument to setup.py:: $ python setup.py --pure install or if you are installing from pip:: $ pip install dulwich --global-option="--pure" Note that you can also specify --global-option in a `requirements.txt `_ file, e.g. like this:: dulwich --global-option=--pure Getting started --------------- Dulwich comes with both a lower-level API and higher-level plumbing ("porcelain"). For example, to use the lower level API to access the commit message of the last commit:: >>> from dulwich.repo import Repo >>> r = Repo('.') >>> r.head() '57fbe010446356833a6ad1600059d80b1e731e15' >>> c = r[r.head()] >>> c >>> c.message 'Add note about encoding.\n' And to print it using porcelain:: >>> from dulwich import porcelain >>> porcelain.log('.', max_entries=1) -------------------------------------------------- commit: 57fbe010446356833a6ad1600059d80b1e731e15 Author: Jelmer Vernooij Date: Sat Apr 29 2017 23:57:34 +0000 Add note about encoding. Further documentation --------------------- The dulwich documentation can be found in docs/ and built by running ``make doc``. It can also be found `on the web `_. Help ---- There is a *#dulwich* IRC channel on the `Freenode `_, and `dulwich-announce `_ and `dulwich-discuss `_ mailing lists. Contributing ------------ For a full list of contributors, see the git logs or `AUTHORS `_. If you'd like to contribute to Dulwich, see the `CONTRIBUTING `_ file and `list of open issues `_. Supported versions of Python ---------------------------- At the moment, Dulwich supports (and is tested on) CPython 2.7, 3.4, 3.5, 3.6, 3.7 and Pypy. Keywords: git vcs Platform: UNKNOWN Classifier: Development Status :: 4 - Beta Classifier: License :: OSI Approved :: Apache Software License Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Programming Language :: Python :: Implementation :: PyPy Classifier: Operating System :: POSIX Classifier: Operating System :: Microsoft :: Windows Classifier: Topic :: Software Development :: Version Control Provides-Extra: fastimport Provides-Extra: https Provides-Extra: pgp diff --git a/docs/api/dulwich.archive.txt b/docs/api/dulwich.archive.txt deleted file mode 100644 index 1029a717..00000000 --- a/docs/api/dulwich.archive.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.archive module -====================== - -.. automodule:: dulwich.archive - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.client.txt b/docs/api/dulwich.client.txt deleted file mode 100644 index 4ad3532d..00000000 --- a/docs/api/dulwich.client.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.client module -===================== - -.. automodule:: dulwich.client - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.config.txt b/docs/api/dulwich.config.txt deleted file mode 100644 index 10ebef48..00000000 --- a/docs/api/dulwich.config.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.config module -===================== - -.. automodule:: dulwich.config - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.contrib.paramiko_vendor.txt b/docs/api/dulwich.contrib.paramiko_vendor.txt deleted file mode 100644 index cef82545..00000000 --- a/docs/api/dulwich.contrib.paramiko_vendor.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.contrib.paramiko\_vendor module -======================================= - -.. automodule:: dulwich.contrib.paramiko_vendor - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.contrib.release_robot.txt b/docs/api/dulwich.contrib.release_robot.txt deleted file mode 100644 index 690d5124..00000000 --- a/docs/api/dulwich.contrib.release_robot.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.contrib.release\_robot module -===================================== - -.. automodule:: dulwich.contrib.release_robot - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.contrib.swift.txt b/docs/api/dulwich.contrib.swift.txt deleted file mode 100644 index 152b9b16..00000000 --- a/docs/api/dulwich.contrib.swift.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.contrib.swift module -============================ - -.. automodule:: dulwich.contrib.swift - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.contrib.test_release_robot.txt b/docs/api/dulwich.contrib.test_release_robot.txt deleted file mode 100644 index 9fd50579..00000000 --- a/docs/api/dulwich.contrib.test_release_robot.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.contrib.test\_release\_robot module -=========================================== - -.. automodule:: dulwich.contrib.test_release_robot - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.contrib.test_swift.txt b/docs/api/dulwich.contrib.test_swift.txt deleted file mode 100644 index d5054338..00000000 --- a/docs/api/dulwich.contrib.test_swift.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.contrib.test\_swift module -================================== - -.. automodule:: dulwich.contrib.test_swift - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.contrib.test_swift_smoke.txt b/docs/api/dulwich.contrib.test_swift_smoke.txt deleted file mode 100644 index eed7d9b1..00000000 --- a/docs/api/dulwich.contrib.test_swift_smoke.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.contrib.test\_swift\_smoke module -========================================= - -.. automodule:: dulwich.contrib.test_swift_smoke - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.contrib.txt b/docs/api/dulwich.contrib.txt deleted file mode 100644 index 5178261f..00000000 --- a/docs/api/dulwich.contrib.txt +++ /dev/null @@ -1,19 +0,0 @@ -dulwich.contrib package -======================= - -.. automodule:: dulwich.contrib - :members: - :undoc-members: - :show-inheritance: - -Submodules ----------- - -.. toctree:: - - dulwich.contrib.paramiko_vendor - dulwich.contrib.release_robot - dulwich.contrib.swift - dulwich.contrib.test_release_robot - dulwich.contrib.test_swift - dulwich.contrib.test_swift_smoke diff --git a/docs/api/dulwich.diff_tree.txt b/docs/api/dulwich.diff_tree.txt deleted file mode 100644 index b2d52665..00000000 --- a/docs/api/dulwich.diff_tree.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.diff\_tree module -========================= - -.. automodule:: dulwich.diff_tree - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.errors.txt b/docs/api/dulwich.errors.txt deleted file mode 100644 index e17f8ee7..00000000 --- a/docs/api/dulwich.errors.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.errors module -===================== - -.. automodule:: dulwich.errors - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.fastexport.txt b/docs/api/dulwich.fastexport.txt deleted file mode 100644 index 4a0be6d7..00000000 --- a/docs/api/dulwich.fastexport.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.fastexport module -========================= - -.. automodule:: dulwich.fastexport - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.file.txt b/docs/api/dulwich.file.txt deleted file mode 100644 index f76b46ee..00000000 --- a/docs/api/dulwich.file.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.file module -=================== - -.. automodule:: dulwich.file - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.greenthreads.txt b/docs/api/dulwich.greenthreads.txt deleted file mode 100644 index ed3a4e8e..00000000 --- a/docs/api/dulwich.greenthreads.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.greenthreads module -=========================== - -.. automodule:: dulwich.greenthreads - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.hooks.txt b/docs/api/dulwich.hooks.txt deleted file mode 100644 index eaa54b45..00000000 --- a/docs/api/dulwich.hooks.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.hooks module -==================== - -.. automodule:: dulwich.hooks - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.ignore.txt b/docs/api/dulwich.ignore.txt deleted file mode 100644 index f465cd8d..00000000 --- a/docs/api/dulwich.ignore.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.ignore module -===================== - -.. automodule:: dulwich.ignore - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.index.txt b/docs/api/dulwich.index.txt deleted file mode 100644 index 1f624266..00000000 --- a/docs/api/dulwich.index.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.index module -==================== - -.. automodule:: dulwich.index - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.line_ending.txt b/docs/api/dulwich.line_ending.txt deleted file mode 100644 index 13a7b502..00000000 --- a/docs/api/dulwich.line_ending.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.line\_ending module -=========================== - -.. automodule:: dulwich.line_ending - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.log_utils.txt b/docs/api/dulwich.log_utils.txt deleted file mode 100644 index 10b42f94..00000000 --- a/docs/api/dulwich.log_utils.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.log\_utils module -========================= - -.. automodule:: dulwich.log_utils - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.lru_cache.txt b/docs/api/dulwich.lru_cache.txt deleted file mode 100644 index 48e2ff6e..00000000 --- a/docs/api/dulwich.lru_cache.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.lru\_cache module -========================= - -.. automodule:: dulwich.lru_cache - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.mailmap.txt b/docs/api/dulwich.mailmap.txt deleted file mode 100644 index 792723af..00000000 --- a/docs/api/dulwich.mailmap.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.mailmap module -====================== - -.. automodule:: dulwich.mailmap - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.object_store.txt b/docs/api/dulwich.object_store.txt deleted file mode 100644 index a460df52..00000000 --- a/docs/api/dulwich.object_store.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.object\_store module -============================ - -.. automodule:: dulwich.object_store - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.objects.txt b/docs/api/dulwich.objects.txt deleted file mode 100644 index bc5b14d4..00000000 --- a/docs/api/dulwich.objects.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.objects module -====================== - -.. automodule:: dulwich.objects - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.objectspec.txt b/docs/api/dulwich.objectspec.txt deleted file mode 100644 index 55f5ff6f..00000000 --- a/docs/api/dulwich.objectspec.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.objectspec module -========================= - -.. automodule:: dulwich.objectspec - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.pack.txt b/docs/api/dulwich.pack.txt deleted file mode 100644 index 1bc81c82..00000000 --- a/docs/api/dulwich.pack.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.pack module -=================== - -.. automodule:: dulwich.pack - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.patch.txt b/docs/api/dulwich.patch.txt deleted file mode 100644 index d4b2cd20..00000000 --- a/docs/api/dulwich.patch.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.patch module -==================== - -.. automodule:: dulwich.patch - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.porcelain.txt b/docs/api/dulwich.porcelain.txt deleted file mode 100644 index 2dd1014b..00000000 --- a/docs/api/dulwich.porcelain.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.porcelain module -======================== - -.. automodule:: dulwich.porcelain - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.protocol.txt b/docs/api/dulwich.protocol.txt deleted file mode 100644 index f28128c7..00000000 --- a/docs/api/dulwich.protocol.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.protocol module -======================= - -.. automodule:: dulwich.protocol - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.reflog.txt b/docs/api/dulwich.reflog.txt deleted file mode 100644 index 9eb7ecbd..00000000 --- a/docs/api/dulwich.reflog.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.reflog module -===================== - -.. automodule:: dulwich.reflog - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.refs.txt b/docs/api/dulwich.refs.txt deleted file mode 100644 index d495594a..00000000 --- a/docs/api/dulwich.refs.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.refs module -=================== - -.. automodule:: dulwich.refs - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.repo.txt b/docs/api/dulwich.repo.txt deleted file mode 100644 index d141835f..00000000 --- a/docs/api/dulwich.repo.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.repo module -=================== - -.. automodule:: dulwich.repo - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.server.txt b/docs/api/dulwich.server.txt deleted file mode 100644 index 36b4f03f..00000000 --- a/docs/api/dulwich.server.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.server module -===================== - -.. automodule:: dulwich.server - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.stash.txt b/docs/api/dulwich.stash.txt deleted file mode 100644 index 79ed2840..00000000 --- a/docs/api/dulwich.stash.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.stash module -==================== - -.. automodule:: dulwich.stash - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.tests.compat.server_utils.txt b/docs/api/dulwich.tests.compat.server_utils.txt deleted file mode 100644 index a0531b72..00000000 --- a/docs/api/dulwich.tests.compat.server_utils.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.compat.server\_utils module -========================================= - -.. automodule:: dulwich.tests.compat.server_utils - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.tests.compat.test_client.txt b/docs/api/dulwich.tests.compat.test_client.txt deleted file mode 100644 index ef361099..00000000 --- a/docs/api/dulwich.tests.compat.test_client.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.compat.test\_client module -======================================== - -.. automodule:: dulwich.tests.compat.test_client - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.tests.compat.test_pack.txt b/docs/api/dulwich.tests.compat.test_pack.txt deleted file mode 100644 index 329ec105..00000000 --- a/docs/api/dulwich.tests.compat.test_pack.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.compat.test\_pack module -====================================== - -.. automodule:: dulwich.tests.compat.test_pack - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.tests.compat.test_patch.txt b/docs/api/dulwich.tests.compat.test_patch.txt deleted file mode 100644 index f1615c01..00000000 --- a/docs/api/dulwich.tests.compat.test_patch.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.compat.test\_patch module -======================================= - -.. automodule:: dulwich.tests.compat.test_patch - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.tests.compat.test_repository.txt b/docs/api/dulwich.tests.compat.test_repository.txt deleted file mode 100644 index 45e5117e..00000000 --- a/docs/api/dulwich.tests.compat.test_repository.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.compat.test\_repository module -============================================ - -.. automodule:: dulwich.tests.compat.test_repository - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.tests.compat.test_server.txt b/docs/api/dulwich.tests.compat.test_server.txt deleted file mode 100644 index 74484145..00000000 --- a/docs/api/dulwich.tests.compat.test_server.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.compat.test\_server module -======================================== - -.. automodule:: dulwich.tests.compat.test_server - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.tests.compat.test_utils.txt b/docs/api/dulwich.tests.compat.test_utils.txt deleted file mode 100644 index a7e65f6d..00000000 --- a/docs/api/dulwich.tests.compat.test_utils.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.compat.test\_utils module -======================================= - -.. automodule:: dulwich.tests.compat.test_utils - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.tests.compat.test_web.txt b/docs/api/dulwich.tests.compat.test_web.txt deleted file mode 100644 index 9bf8f8b1..00000000 --- a/docs/api/dulwich.tests.compat.test_web.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.compat.test\_web module -===================================== - -.. automodule:: dulwich.tests.compat.test_web - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.tests.compat.txt b/docs/api/dulwich.tests.compat.txt deleted file mode 100644 index 2fecac20..00000000 --- a/docs/api/dulwich.tests.compat.txt +++ /dev/null @@ -1,22 +0,0 @@ -dulwich.tests.compat package -============================ - -.. automodule:: dulwich.tests.compat - :members: - :undoc-members: - :show-inheritance: - -Submodules ----------- - -.. toctree:: - - dulwich.tests.compat.server_utils - dulwich.tests.compat.test_client - dulwich.tests.compat.test_pack - dulwich.tests.compat.test_patch - dulwich.tests.compat.test_repository - dulwich.tests.compat.test_server - dulwich.tests.compat.test_utils - dulwich.tests.compat.test_web - dulwich.tests.compat.utils diff --git a/docs/api/dulwich.tests.compat.utils.txt b/docs/api/dulwich.tests.compat.utils.txt deleted file mode 100644 index 2d6252e0..00000000 --- a/docs/api/dulwich.tests.compat.utils.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.compat.utils module -================================= - -.. automodule:: dulwich.tests.compat.utils - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.tests.test_archive.txt b/docs/api/dulwich.tests.test_archive.txt deleted file mode 100644 index 1a826433..00000000 --- a/docs/api/dulwich.tests.test_archive.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_archive module -================================== - -.. automodule:: dulwich.tests.test_archive - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.tests.test_blackbox.txt b/docs/api/dulwich.tests.test_blackbox.txt deleted file mode 100644 index 82ba287a..00000000 --- a/docs/api/dulwich.tests.test_blackbox.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_blackbox module -=================================== - -.. automodule:: dulwich.tests.test_blackbox - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.tests.test_client.txt b/docs/api/dulwich.tests.test_client.txt deleted file mode 100644 index a461ee8d..00000000 --- a/docs/api/dulwich.tests.test_client.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_client module -================================= - -.. automodule:: dulwich.tests.test_client - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.tests.test_config.txt b/docs/api/dulwich.tests.test_config.txt deleted file mode 100644 index c0c2c4be..00000000 --- a/docs/api/dulwich.tests.test_config.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_config module -================================= - -.. automodule:: dulwich.tests.test_config - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.tests.test_diff_tree.txt b/docs/api/dulwich.tests.test_diff_tree.txt deleted file mode 100644 index 941f4898..00000000 --- a/docs/api/dulwich.tests.test_diff_tree.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_diff\_tree module -===================================== - -.. automodule:: dulwich.tests.test_diff_tree - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.tests.test_fastexport.txt b/docs/api/dulwich.tests.test_fastexport.txt deleted file mode 100644 index bda391e0..00000000 --- a/docs/api/dulwich.tests.test_fastexport.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_fastexport module -===================================== - -.. automodule:: dulwich.tests.test_fastexport - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.tests.test_file.txt b/docs/api/dulwich.tests.test_file.txt deleted file mode 100644 index cc853354..00000000 --- a/docs/api/dulwich.tests.test_file.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_file module -=============================== - -.. automodule:: dulwich.tests.test_file - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.tests.test_grafts.txt b/docs/api/dulwich.tests.test_grafts.txt deleted file mode 100644 index f4d492c8..00000000 --- a/docs/api/dulwich.tests.test_grafts.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_grafts module -================================= - -.. automodule:: dulwich.tests.test_grafts - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.tests.test_greenthreads.txt b/docs/api/dulwich.tests.test_greenthreads.txt deleted file mode 100644 index 5db075d1..00000000 --- a/docs/api/dulwich.tests.test_greenthreads.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_greenthreads module -======================================= - -.. automodule:: dulwich.tests.test_greenthreads - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.tests.test_hooks.txt b/docs/api/dulwich.tests.test_hooks.txt deleted file mode 100644 index 9b2dc02f..00000000 --- a/docs/api/dulwich.tests.test_hooks.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_hooks module -================================ - -.. automodule:: dulwich.tests.test_hooks - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.tests.test_ignore.txt b/docs/api/dulwich.tests.test_ignore.txt deleted file mode 100644 index 94a16a3c..00000000 --- a/docs/api/dulwich.tests.test_ignore.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_ignore module -================================= - -.. automodule:: dulwich.tests.test_ignore - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.tests.test_index.txt b/docs/api/dulwich.tests.test_index.txt deleted file mode 100644 index 883cc48e..00000000 --- a/docs/api/dulwich.tests.test_index.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_index module -================================ - -.. automodule:: dulwich.tests.test_index - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.tests.test_line_ending.txt b/docs/api/dulwich.tests.test_line_ending.txt deleted file mode 100644 index 3ee4b97b..00000000 --- a/docs/api/dulwich.tests.test_line_ending.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_line\_ending module -======================================= - -.. automodule:: dulwich.tests.test_line_ending - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.tests.test_lru_cache.txt b/docs/api/dulwich.tests.test_lru_cache.txt deleted file mode 100644 index 2e51a2f8..00000000 --- a/docs/api/dulwich.tests.test_lru_cache.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_lru\_cache module -===================================== - -.. automodule:: dulwich.tests.test_lru_cache - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.tests.test_mailmap.txt b/docs/api/dulwich.tests.test_mailmap.txt deleted file mode 100644 index e5faf0d9..00000000 --- a/docs/api/dulwich.tests.test_mailmap.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_mailmap module -================================== - -.. automodule:: dulwich.tests.test_mailmap - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.tests.test_missing_obj_finder.txt b/docs/api/dulwich.tests.test_missing_obj_finder.txt deleted file mode 100644 index 89d3574b..00000000 --- a/docs/api/dulwich.tests.test_missing_obj_finder.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_missing\_obj\_finder module -=============================================== - -.. automodule:: dulwich.tests.test_missing_obj_finder - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.tests.test_object_store.txt b/docs/api/dulwich.tests.test_object_store.txt deleted file mode 100644 index 3d2bf813..00000000 --- a/docs/api/dulwich.tests.test_object_store.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_object\_store module -======================================== - -.. automodule:: dulwich.tests.test_object_store - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.tests.test_objects.txt b/docs/api/dulwich.tests.test_objects.txt deleted file mode 100644 index faef329d..00000000 --- a/docs/api/dulwich.tests.test_objects.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_objects module -================================== - -.. automodule:: dulwich.tests.test_objects - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.tests.test_objectspec.txt b/docs/api/dulwich.tests.test_objectspec.txt deleted file mode 100644 index 475a2ab1..00000000 --- a/docs/api/dulwich.tests.test_objectspec.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_objectspec module -===================================== - -.. automodule:: dulwich.tests.test_objectspec - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.tests.test_pack.txt b/docs/api/dulwich.tests.test_pack.txt deleted file mode 100644 index 586a192c..00000000 --- a/docs/api/dulwich.tests.test_pack.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_pack module -=============================== - -.. automodule:: dulwich.tests.test_pack - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.tests.test_patch.txt b/docs/api/dulwich.tests.test_patch.txt deleted file mode 100644 index 0b270508..00000000 --- a/docs/api/dulwich.tests.test_patch.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_patch module -================================ - -.. automodule:: dulwich.tests.test_patch - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.tests.test_porcelain.txt b/docs/api/dulwich.tests.test_porcelain.txt deleted file mode 100644 index f1257f40..00000000 --- a/docs/api/dulwich.tests.test_porcelain.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_porcelain module -==================================== - -.. automodule:: dulwich.tests.test_porcelain - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.tests.test_protocol.txt b/docs/api/dulwich.tests.test_protocol.txt deleted file mode 100644 index f92179c1..00000000 --- a/docs/api/dulwich.tests.test_protocol.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_protocol module -=================================== - -.. automodule:: dulwich.tests.test_protocol - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.tests.test_reflog.txt b/docs/api/dulwich.tests.test_reflog.txt deleted file mode 100644 index 11862681..00000000 --- a/docs/api/dulwich.tests.test_reflog.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_reflog module -================================= - -.. automodule:: dulwich.tests.test_reflog - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.tests.test_refs.txt b/docs/api/dulwich.tests.test_refs.txt deleted file mode 100644 index d9a70e3f..00000000 --- a/docs/api/dulwich.tests.test_refs.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_refs module -=============================== - -.. automodule:: dulwich.tests.test_refs - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.tests.test_repository.txt b/docs/api/dulwich.tests.test_repository.txt deleted file mode 100644 index 7fa472db..00000000 --- a/docs/api/dulwich.tests.test_repository.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_repository module -===================================== - -.. automodule:: dulwich.tests.test_repository - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.tests.test_server.txt b/docs/api/dulwich.tests.test_server.txt deleted file mode 100644 index 9795a0f6..00000000 --- a/docs/api/dulwich.tests.test_server.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_server module -================================= - -.. automodule:: dulwich.tests.test_server - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.tests.test_stash.txt b/docs/api/dulwich.tests.test_stash.txt deleted file mode 100644 index 3e345342..00000000 --- a/docs/api/dulwich.tests.test_stash.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_stash module -================================ - -.. automodule:: dulwich.tests.test_stash - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.tests.test_utils.txt b/docs/api/dulwich.tests.test_utils.txt deleted file mode 100644 index f9477117..00000000 --- a/docs/api/dulwich.tests.test_utils.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_utils module -================================ - -.. automodule:: dulwich.tests.test_utils - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.tests.test_walk.txt b/docs/api/dulwich.tests.test_walk.txt deleted file mode 100644 index 3eb49fcb..00000000 --- a/docs/api/dulwich.tests.test_walk.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_walk module -=============================== - -.. automodule:: dulwich.tests.test_walk - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.tests.test_web.txt b/docs/api/dulwich.tests.test_web.txt deleted file mode 100644 index 3df6df26..00000000 --- a/docs/api/dulwich.tests.test_web.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_web module -============================== - -.. automodule:: dulwich.tests.test_web - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.tests.txt b/docs/api/dulwich.tests.txt deleted file mode 100644 index 80ae3af6..00000000 --- a/docs/api/dulwich.tests.txt +++ /dev/null @@ -1,52 +0,0 @@ -dulwich.tests package -===================== - -.. automodule:: dulwich.tests - :members: - :undoc-members: - :show-inheritance: - -Subpackages ------------ - -.. toctree:: - - dulwich.tests.compat - -Submodules ----------- - -.. toctree:: - - dulwich.tests.test_archive - dulwich.tests.test_blackbox - dulwich.tests.test_client - dulwich.tests.test_config - dulwich.tests.test_diff_tree - dulwich.tests.test_fastexport - dulwich.tests.test_file - dulwich.tests.test_grafts - dulwich.tests.test_greenthreads - dulwich.tests.test_hooks - dulwich.tests.test_ignore - dulwich.tests.test_index - dulwich.tests.test_line_ending - dulwich.tests.test_lru_cache - dulwich.tests.test_mailmap - dulwich.tests.test_missing_obj_finder - dulwich.tests.test_object_store - dulwich.tests.test_objects - dulwich.tests.test_objectspec - dulwich.tests.test_pack - dulwich.tests.test_patch - dulwich.tests.test_porcelain - dulwich.tests.test_protocol - dulwich.tests.test_reflog - dulwich.tests.test_refs - dulwich.tests.test_repository - dulwich.tests.test_server - dulwich.tests.test_stash - dulwich.tests.test_utils - dulwich.tests.test_walk - dulwich.tests.test_web - dulwich.tests.utils diff --git a/docs/api/dulwich.tests.utils.txt b/docs/api/dulwich.tests.utils.txt deleted file mode 100644 index 3cb92327..00000000 --- a/docs/api/dulwich.tests.utils.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.utils module -========================== - -.. automodule:: dulwich.tests.utils - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.txt b/docs/api/dulwich.txt deleted file mode 100644 index 39bef9e0..00000000 --- a/docs/api/dulwich.txt +++ /dev/null @@ -1,50 +0,0 @@ -dulwich package -=============== - -.. automodule:: dulwich - :members: - :undoc-members: - :show-inheritance: - -Subpackages ------------ - -.. toctree:: - - dulwich.contrib - dulwich.tests - -Submodules ----------- - -.. toctree:: - - dulwich.archive - dulwich.client - dulwich.config - dulwich.diff_tree - dulwich.errors - dulwich.fastexport - dulwich.file - dulwich.greenthreads - dulwich.hooks - dulwich.ignore - dulwich.index - dulwich.line_ending - dulwich.log_utils - dulwich.lru_cache - dulwich.mailmap - dulwich.object_store - dulwich.objects - dulwich.objectspec - dulwich.pack - dulwich.patch - dulwich.porcelain - dulwich.protocol - dulwich.reflog - dulwich.refs - dulwich.repo - dulwich.server - dulwich.stash - dulwich.walk - dulwich.web diff --git a/docs/api/dulwich.walk.txt b/docs/api/dulwich.walk.txt deleted file mode 100644 index 62b7b74c..00000000 --- a/docs/api/dulwich.walk.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.walk module -=================== - -.. automodule:: dulwich.walk - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/dulwich.web.txt b/docs/api/dulwich.web.txt deleted file mode 100644 index c49acd82..00000000 --- a/docs/api/dulwich.web.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.web module -================== - -.. automodule:: dulwich.web - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/api/modules.txt b/docs/api/modules.txt deleted file mode 100644 index ca2f0c3b..00000000 --- a/docs/api/modules.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich -======= - -.. toctree:: - :maxdepth: 4 - - dulwich diff --git a/docs/build/html/_sources/api/dulwich.archive.txt b/docs/build/html/_sources/api/dulwich.archive.txt deleted file mode 100644 index 1029a717..00000000 --- a/docs/build/html/_sources/api/dulwich.archive.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.archive module -====================== - -.. automodule:: dulwich.archive - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.client.txt b/docs/build/html/_sources/api/dulwich.client.txt deleted file mode 100644 index 4ad3532d..00000000 --- a/docs/build/html/_sources/api/dulwich.client.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.client module -===================== - -.. automodule:: dulwich.client - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.config.txt b/docs/build/html/_sources/api/dulwich.config.txt deleted file mode 100644 index 10ebef48..00000000 --- a/docs/build/html/_sources/api/dulwich.config.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.config module -===================== - -.. automodule:: dulwich.config - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.contrib.paramiko_vendor.txt b/docs/build/html/_sources/api/dulwich.contrib.paramiko_vendor.txt deleted file mode 100644 index cef82545..00000000 --- a/docs/build/html/_sources/api/dulwich.contrib.paramiko_vendor.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.contrib.paramiko\_vendor module -======================================= - -.. automodule:: dulwich.contrib.paramiko_vendor - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.contrib.release_robot.txt b/docs/build/html/_sources/api/dulwich.contrib.release_robot.txt deleted file mode 100644 index 690d5124..00000000 --- a/docs/build/html/_sources/api/dulwich.contrib.release_robot.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.contrib.release\_robot module -===================================== - -.. automodule:: dulwich.contrib.release_robot - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.contrib.swift.txt b/docs/build/html/_sources/api/dulwich.contrib.swift.txt deleted file mode 100644 index 152b9b16..00000000 --- a/docs/build/html/_sources/api/dulwich.contrib.swift.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.contrib.swift module -============================ - -.. automodule:: dulwich.contrib.swift - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.contrib.test_release_robot.txt b/docs/build/html/_sources/api/dulwich.contrib.test_release_robot.txt deleted file mode 100644 index 9fd50579..00000000 --- a/docs/build/html/_sources/api/dulwich.contrib.test_release_robot.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.contrib.test\_release\_robot module -=========================================== - -.. automodule:: dulwich.contrib.test_release_robot - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.contrib.test_swift.txt b/docs/build/html/_sources/api/dulwich.contrib.test_swift.txt deleted file mode 100644 index d5054338..00000000 --- a/docs/build/html/_sources/api/dulwich.contrib.test_swift.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.contrib.test\_swift module -================================== - -.. automodule:: dulwich.contrib.test_swift - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.contrib.test_swift_smoke.txt b/docs/build/html/_sources/api/dulwich.contrib.test_swift_smoke.txt deleted file mode 100644 index eed7d9b1..00000000 --- a/docs/build/html/_sources/api/dulwich.contrib.test_swift_smoke.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.contrib.test\_swift\_smoke module -========================================= - -.. automodule:: dulwich.contrib.test_swift_smoke - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.contrib.txt b/docs/build/html/_sources/api/dulwich.contrib.txt deleted file mode 100644 index 5178261f..00000000 --- a/docs/build/html/_sources/api/dulwich.contrib.txt +++ /dev/null @@ -1,19 +0,0 @@ -dulwich.contrib package -======================= - -.. automodule:: dulwich.contrib - :members: - :undoc-members: - :show-inheritance: - -Submodules ----------- - -.. toctree:: - - dulwich.contrib.paramiko_vendor - dulwich.contrib.release_robot - dulwich.contrib.swift - dulwich.contrib.test_release_robot - dulwich.contrib.test_swift - dulwich.contrib.test_swift_smoke diff --git a/docs/build/html/_sources/api/dulwich.diff_tree.txt b/docs/build/html/_sources/api/dulwich.diff_tree.txt deleted file mode 100644 index b2d52665..00000000 --- a/docs/build/html/_sources/api/dulwich.diff_tree.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.diff\_tree module -========================= - -.. automodule:: dulwich.diff_tree - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.errors.txt b/docs/build/html/_sources/api/dulwich.errors.txt deleted file mode 100644 index e17f8ee7..00000000 --- a/docs/build/html/_sources/api/dulwich.errors.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.errors module -===================== - -.. automodule:: dulwich.errors - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.fastexport.txt b/docs/build/html/_sources/api/dulwich.fastexport.txt deleted file mode 100644 index 4a0be6d7..00000000 --- a/docs/build/html/_sources/api/dulwich.fastexport.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.fastexport module -========================= - -.. automodule:: dulwich.fastexport - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.file.txt b/docs/build/html/_sources/api/dulwich.file.txt deleted file mode 100644 index f76b46ee..00000000 --- a/docs/build/html/_sources/api/dulwich.file.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.file module -=================== - -.. automodule:: dulwich.file - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.greenthreads.txt b/docs/build/html/_sources/api/dulwich.greenthreads.txt deleted file mode 100644 index ed3a4e8e..00000000 --- a/docs/build/html/_sources/api/dulwich.greenthreads.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.greenthreads module -=========================== - -.. automodule:: dulwich.greenthreads - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.hooks.txt b/docs/build/html/_sources/api/dulwich.hooks.txt deleted file mode 100644 index eaa54b45..00000000 --- a/docs/build/html/_sources/api/dulwich.hooks.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.hooks module -==================== - -.. automodule:: dulwich.hooks - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.ignore.txt b/docs/build/html/_sources/api/dulwich.ignore.txt deleted file mode 100644 index f465cd8d..00000000 --- a/docs/build/html/_sources/api/dulwich.ignore.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.ignore module -===================== - -.. automodule:: dulwich.ignore - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.index.txt b/docs/build/html/_sources/api/dulwich.index.txt deleted file mode 100644 index 1f624266..00000000 --- a/docs/build/html/_sources/api/dulwich.index.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.index module -==================== - -.. automodule:: dulwich.index - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.line_ending.txt b/docs/build/html/_sources/api/dulwich.line_ending.txt deleted file mode 100644 index 13a7b502..00000000 --- a/docs/build/html/_sources/api/dulwich.line_ending.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.line\_ending module -=========================== - -.. automodule:: dulwich.line_ending - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.log_utils.txt b/docs/build/html/_sources/api/dulwich.log_utils.txt deleted file mode 100644 index 10b42f94..00000000 --- a/docs/build/html/_sources/api/dulwich.log_utils.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.log\_utils module -========================= - -.. automodule:: dulwich.log_utils - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.lru_cache.txt b/docs/build/html/_sources/api/dulwich.lru_cache.txt deleted file mode 100644 index 48e2ff6e..00000000 --- a/docs/build/html/_sources/api/dulwich.lru_cache.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.lru\_cache module -========================= - -.. automodule:: dulwich.lru_cache - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.mailmap.txt b/docs/build/html/_sources/api/dulwich.mailmap.txt deleted file mode 100644 index 792723af..00000000 --- a/docs/build/html/_sources/api/dulwich.mailmap.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.mailmap module -====================== - -.. automodule:: dulwich.mailmap - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.object_store.txt b/docs/build/html/_sources/api/dulwich.object_store.txt deleted file mode 100644 index a460df52..00000000 --- a/docs/build/html/_sources/api/dulwich.object_store.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.object\_store module -============================ - -.. automodule:: dulwich.object_store - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.objects.txt b/docs/build/html/_sources/api/dulwich.objects.txt deleted file mode 100644 index bc5b14d4..00000000 --- a/docs/build/html/_sources/api/dulwich.objects.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.objects module -====================== - -.. automodule:: dulwich.objects - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.objectspec.txt b/docs/build/html/_sources/api/dulwich.objectspec.txt deleted file mode 100644 index 55f5ff6f..00000000 --- a/docs/build/html/_sources/api/dulwich.objectspec.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.objectspec module -========================= - -.. automodule:: dulwich.objectspec - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.pack.txt b/docs/build/html/_sources/api/dulwich.pack.txt deleted file mode 100644 index 1bc81c82..00000000 --- a/docs/build/html/_sources/api/dulwich.pack.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.pack module -=================== - -.. automodule:: dulwich.pack - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.patch.txt b/docs/build/html/_sources/api/dulwich.patch.txt deleted file mode 100644 index d4b2cd20..00000000 --- a/docs/build/html/_sources/api/dulwich.patch.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.patch module -==================== - -.. automodule:: dulwich.patch - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.porcelain.txt b/docs/build/html/_sources/api/dulwich.porcelain.txt deleted file mode 100644 index 2dd1014b..00000000 --- a/docs/build/html/_sources/api/dulwich.porcelain.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.porcelain module -======================== - -.. automodule:: dulwich.porcelain - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.protocol.txt b/docs/build/html/_sources/api/dulwich.protocol.txt deleted file mode 100644 index f28128c7..00000000 --- a/docs/build/html/_sources/api/dulwich.protocol.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.protocol module -======================= - -.. automodule:: dulwich.protocol - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.reflog.txt b/docs/build/html/_sources/api/dulwich.reflog.txt deleted file mode 100644 index 9eb7ecbd..00000000 --- a/docs/build/html/_sources/api/dulwich.reflog.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.reflog module -===================== - -.. automodule:: dulwich.reflog - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.refs.txt b/docs/build/html/_sources/api/dulwich.refs.txt deleted file mode 100644 index d495594a..00000000 --- a/docs/build/html/_sources/api/dulwich.refs.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.refs module -=================== - -.. automodule:: dulwich.refs - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.repo.txt b/docs/build/html/_sources/api/dulwich.repo.txt deleted file mode 100644 index d141835f..00000000 --- a/docs/build/html/_sources/api/dulwich.repo.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.repo module -=================== - -.. automodule:: dulwich.repo - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.server.txt b/docs/build/html/_sources/api/dulwich.server.txt deleted file mode 100644 index 36b4f03f..00000000 --- a/docs/build/html/_sources/api/dulwich.server.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.server module -===================== - -.. automodule:: dulwich.server - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.stash.txt b/docs/build/html/_sources/api/dulwich.stash.txt deleted file mode 100644 index 79ed2840..00000000 --- a/docs/build/html/_sources/api/dulwich.stash.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.stash module -==================== - -.. automodule:: dulwich.stash - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.tests.compat.server_utils.txt b/docs/build/html/_sources/api/dulwich.tests.compat.server_utils.txt deleted file mode 100644 index a0531b72..00000000 --- a/docs/build/html/_sources/api/dulwich.tests.compat.server_utils.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.compat.server\_utils module -========================================= - -.. automodule:: dulwich.tests.compat.server_utils - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.tests.compat.test_client.txt b/docs/build/html/_sources/api/dulwich.tests.compat.test_client.txt deleted file mode 100644 index ef361099..00000000 --- a/docs/build/html/_sources/api/dulwich.tests.compat.test_client.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.compat.test\_client module -======================================== - -.. automodule:: dulwich.tests.compat.test_client - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.tests.compat.test_pack.txt b/docs/build/html/_sources/api/dulwich.tests.compat.test_pack.txt deleted file mode 100644 index 329ec105..00000000 --- a/docs/build/html/_sources/api/dulwich.tests.compat.test_pack.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.compat.test\_pack module -====================================== - -.. automodule:: dulwich.tests.compat.test_pack - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.tests.compat.test_patch.txt b/docs/build/html/_sources/api/dulwich.tests.compat.test_patch.txt deleted file mode 100644 index f1615c01..00000000 --- a/docs/build/html/_sources/api/dulwich.tests.compat.test_patch.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.compat.test\_patch module -======================================= - -.. automodule:: dulwich.tests.compat.test_patch - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.tests.compat.test_repository.txt b/docs/build/html/_sources/api/dulwich.tests.compat.test_repository.txt deleted file mode 100644 index 45e5117e..00000000 --- a/docs/build/html/_sources/api/dulwich.tests.compat.test_repository.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.compat.test\_repository module -============================================ - -.. automodule:: dulwich.tests.compat.test_repository - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.tests.compat.test_server.txt b/docs/build/html/_sources/api/dulwich.tests.compat.test_server.txt deleted file mode 100644 index 74484145..00000000 --- a/docs/build/html/_sources/api/dulwich.tests.compat.test_server.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.compat.test\_server module -======================================== - -.. automodule:: dulwich.tests.compat.test_server - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.tests.compat.test_utils.txt b/docs/build/html/_sources/api/dulwich.tests.compat.test_utils.txt deleted file mode 100644 index a7e65f6d..00000000 --- a/docs/build/html/_sources/api/dulwich.tests.compat.test_utils.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.compat.test\_utils module -======================================= - -.. automodule:: dulwich.tests.compat.test_utils - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.tests.compat.test_web.txt b/docs/build/html/_sources/api/dulwich.tests.compat.test_web.txt deleted file mode 100644 index 9bf8f8b1..00000000 --- a/docs/build/html/_sources/api/dulwich.tests.compat.test_web.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.compat.test\_web module -===================================== - -.. automodule:: dulwich.tests.compat.test_web - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.tests.compat.txt b/docs/build/html/_sources/api/dulwich.tests.compat.txt deleted file mode 100644 index 2fecac20..00000000 --- a/docs/build/html/_sources/api/dulwich.tests.compat.txt +++ /dev/null @@ -1,22 +0,0 @@ -dulwich.tests.compat package -============================ - -.. automodule:: dulwich.tests.compat - :members: - :undoc-members: - :show-inheritance: - -Submodules ----------- - -.. toctree:: - - dulwich.tests.compat.server_utils - dulwich.tests.compat.test_client - dulwich.tests.compat.test_pack - dulwich.tests.compat.test_patch - dulwich.tests.compat.test_repository - dulwich.tests.compat.test_server - dulwich.tests.compat.test_utils - dulwich.tests.compat.test_web - dulwich.tests.compat.utils diff --git a/docs/build/html/_sources/api/dulwich.tests.compat.utils.txt b/docs/build/html/_sources/api/dulwich.tests.compat.utils.txt deleted file mode 100644 index 2d6252e0..00000000 --- a/docs/build/html/_sources/api/dulwich.tests.compat.utils.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.compat.utils module -================================= - -.. automodule:: dulwich.tests.compat.utils - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.tests.test_archive.txt b/docs/build/html/_sources/api/dulwich.tests.test_archive.txt deleted file mode 100644 index 1a826433..00000000 --- a/docs/build/html/_sources/api/dulwich.tests.test_archive.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_archive module -================================== - -.. automodule:: dulwich.tests.test_archive - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.tests.test_blackbox.txt b/docs/build/html/_sources/api/dulwich.tests.test_blackbox.txt deleted file mode 100644 index 82ba287a..00000000 --- a/docs/build/html/_sources/api/dulwich.tests.test_blackbox.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_blackbox module -=================================== - -.. automodule:: dulwich.tests.test_blackbox - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.tests.test_client.txt b/docs/build/html/_sources/api/dulwich.tests.test_client.txt deleted file mode 100644 index a461ee8d..00000000 --- a/docs/build/html/_sources/api/dulwich.tests.test_client.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_client module -================================= - -.. automodule:: dulwich.tests.test_client - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.tests.test_config.txt b/docs/build/html/_sources/api/dulwich.tests.test_config.txt deleted file mode 100644 index c0c2c4be..00000000 --- a/docs/build/html/_sources/api/dulwich.tests.test_config.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_config module -================================= - -.. automodule:: dulwich.tests.test_config - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.tests.test_diff_tree.txt b/docs/build/html/_sources/api/dulwich.tests.test_diff_tree.txt deleted file mode 100644 index 941f4898..00000000 --- a/docs/build/html/_sources/api/dulwich.tests.test_diff_tree.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_diff\_tree module -===================================== - -.. automodule:: dulwich.tests.test_diff_tree - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.tests.test_fastexport.txt b/docs/build/html/_sources/api/dulwich.tests.test_fastexport.txt deleted file mode 100644 index bda391e0..00000000 --- a/docs/build/html/_sources/api/dulwich.tests.test_fastexport.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_fastexport module -===================================== - -.. automodule:: dulwich.tests.test_fastexport - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.tests.test_file.txt b/docs/build/html/_sources/api/dulwich.tests.test_file.txt deleted file mode 100644 index cc853354..00000000 --- a/docs/build/html/_sources/api/dulwich.tests.test_file.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_file module -=============================== - -.. automodule:: dulwich.tests.test_file - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.tests.test_grafts.txt b/docs/build/html/_sources/api/dulwich.tests.test_grafts.txt deleted file mode 100644 index f4d492c8..00000000 --- a/docs/build/html/_sources/api/dulwich.tests.test_grafts.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_grafts module -================================= - -.. automodule:: dulwich.tests.test_grafts - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.tests.test_greenthreads.txt b/docs/build/html/_sources/api/dulwich.tests.test_greenthreads.txt deleted file mode 100644 index 5db075d1..00000000 --- a/docs/build/html/_sources/api/dulwich.tests.test_greenthreads.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_greenthreads module -======================================= - -.. automodule:: dulwich.tests.test_greenthreads - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.tests.test_hooks.txt b/docs/build/html/_sources/api/dulwich.tests.test_hooks.txt deleted file mode 100644 index 9b2dc02f..00000000 --- a/docs/build/html/_sources/api/dulwich.tests.test_hooks.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_hooks module -================================ - -.. automodule:: dulwich.tests.test_hooks - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.tests.test_ignore.txt b/docs/build/html/_sources/api/dulwich.tests.test_ignore.txt deleted file mode 100644 index 94a16a3c..00000000 --- a/docs/build/html/_sources/api/dulwich.tests.test_ignore.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_ignore module -================================= - -.. automodule:: dulwich.tests.test_ignore - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.tests.test_index.txt b/docs/build/html/_sources/api/dulwich.tests.test_index.txt deleted file mode 100644 index 883cc48e..00000000 --- a/docs/build/html/_sources/api/dulwich.tests.test_index.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_index module -================================ - -.. automodule:: dulwich.tests.test_index - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.tests.test_line_ending.txt b/docs/build/html/_sources/api/dulwich.tests.test_line_ending.txt deleted file mode 100644 index 3ee4b97b..00000000 --- a/docs/build/html/_sources/api/dulwich.tests.test_line_ending.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_line\_ending module -======================================= - -.. automodule:: dulwich.tests.test_line_ending - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.tests.test_lru_cache.txt b/docs/build/html/_sources/api/dulwich.tests.test_lru_cache.txt deleted file mode 100644 index 2e51a2f8..00000000 --- a/docs/build/html/_sources/api/dulwich.tests.test_lru_cache.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_lru\_cache module -===================================== - -.. automodule:: dulwich.tests.test_lru_cache - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.tests.test_mailmap.txt b/docs/build/html/_sources/api/dulwich.tests.test_mailmap.txt deleted file mode 100644 index e5faf0d9..00000000 --- a/docs/build/html/_sources/api/dulwich.tests.test_mailmap.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_mailmap module -================================== - -.. automodule:: dulwich.tests.test_mailmap - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.tests.test_missing_obj_finder.txt b/docs/build/html/_sources/api/dulwich.tests.test_missing_obj_finder.txt deleted file mode 100644 index 89d3574b..00000000 --- a/docs/build/html/_sources/api/dulwich.tests.test_missing_obj_finder.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_missing\_obj\_finder module -=============================================== - -.. automodule:: dulwich.tests.test_missing_obj_finder - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.tests.test_object_store.txt b/docs/build/html/_sources/api/dulwich.tests.test_object_store.txt deleted file mode 100644 index 3d2bf813..00000000 --- a/docs/build/html/_sources/api/dulwich.tests.test_object_store.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_object\_store module -======================================== - -.. automodule:: dulwich.tests.test_object_store - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.tests.test_objects.txt b/docs/build/html/_sources/api/dulwich.tests.test_objects.txt deleted file mode 100644 index faef329d..00000000 --- a/docs/build/html/_sources/api/dulwich.tests.test_objects.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_objects module -================================== - -.. automodule:: dulwich.tests.test_objects - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.tests.test_objectspec.txt b/docs/build/html/_sources/api/dulwich.tests.test_objectspec.txt deleted file mode 100644 index 475a2ab1..00000000 --- a/docs/build/html/_sources/api/dulwich.tests.test_objectspec.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_objectspec module -===================================== - -.. automodule:: dulwich.tests.test_objectspec - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.tests.test_pack.txt b/docs/build/html/_sources/api/dulwich.tests.test_pack.txt deleted file mode 100644 index 586a192c..00000000 --- a/docs/build/html/_sources/api/dulwich.tests.test_pack.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_pack module -=============================== - -.. automodule:: dulwich.tests.test_pack - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.tests.test_patch.txt b/docs/build/html/_sources/api/dulwich.tests.test_patch.txt deleted file mode 100644 index 0b270508..00000000 --- a/docs/build/html/_sources/api/dulwich.tests.test_patch.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_patch module -================================ - -.. automodule:: dulwich.tests.test_patch - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.tests.test_porcelain.txt b/docs/build/html/_sources/api/dulwich.tests.test_porcelain.txt deleted file mode 100644 index f1257f40..00000000 --- a/docs/build/html/_sources/api/dulwich.tests.test_porcelain.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_porcelain module -==================================== - -.. automodule:: dulwich.tests.test_porcelain - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.tests.test_protocol.txt b/docs/build/html/_sources/api/dulwich.tests.test_protocol.txt deleted file mode 100644 index f92179c1..00000000 --- a/docs/build/html/_sources/api/dulwich.tests.test_protocol.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_protocol module -=================================== - -.. automodule:: dulwich.tests.test_protocol - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.tests.test_reflog.txt b/docs/build/html/_sources/api/dulwich.tests.test_reflog.txt deleted file mode 100644 index 11862681..00000000 --- a/docs/build/html/_sources/api/dulwich.tests.test_reflog.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_reflog module -================================= - -.. automodule:: dulwich.tests.test_reflog - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.tests.test_refs.txt b/docs/build/html/_sources/api/dulwich.tests.test_refs.txt deleted file mode 100644 index d9a70e3f..00000000 --- a/docs/build/html/_sources/api/dulwich.tests.test_refs.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_refs module -=============================== - -.. automodule:: dulwich.tests.test_refs - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.tests.test_repository.txt b/docs/build/html/_sources/api/dulwich.tests.test_repository.txt deleted file mode 100644 index 7fa472db..00000000 --- a/docs/build/html/_sources/api/dulwich.tests.test_repository.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_repository module -===================================== - -.. automodule:: dulwich.tests.test_repository - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.tests.test_server.txt b/docs/build/html/_sources/api/dulwich.tests.test_server.txt deleted file mode 100644 index 9795a0f6..00000000 --- a/docs/build/html/_sources/api/dulwich.tests.test_server.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_server module -================================= - -.. automodule:: dulwich.tests.test_server - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.tests.test_stash.txt b/docs/build/html/_sources/api/dulwich.tests.test_stash.txt deleted file mode 100644 index 3e345342..00000000 --- a/docs/build/html/_sources/api/dulwich.tests.test_stash.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_stash module -================================ - -.. automodule:: dulwich.tests.test_stash - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.tests.test_utils.txt b/docs/build/html/_sources/api/dulwich.tests.test_utils.txt deleted file mode 100644 index f9477117..00000000 --- a/docs/build/html/_sources/api/dulwich.tests.test_utils.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_utils module -================================ - -.. automodule:: dulwich.tests.test_utils - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.tests.test_walk.txt b/docs/build/html/_sources/api/dulwich.tests.test_walk.txt deleted file mode 100644 index 3eb49fcb..00000000 --- a/docs/build/html/_sources/api/dulwich.tests.test_walk.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_walk module -=============================== - -.. automodule:: dulwich.tests.test_walk - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.tests.test_web.txt b/docs/build/html/_sources/api/dulwich.tests.test_web.txt deleted file mode 100644 index 3df6df26..00000000 --- a/docs/build/html/_sources/api/dulwich.tests.test_web.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.test\_web module -============================== - -.. automodule:: dulwich.tests.test_web - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.tests.txt b/docs/build/html/_sources/api/dulwich.tests.txt deleted file mode 100644 index 80ae3af6..00000000 --- a/docs/build/html/_sources/api/dulwich.tests.txt +++ /dev/null @@ -1,52 +0,0 @@ -dulwich.tests package -===================== - -.. automodule:: dulwich.tests - :members: - :undoc-members: - :show-inheritance: - -Subpackages ------------ - -.. toctree:: - - dulwich.tests.compat - -Submodules ----------- - -.. toctree:: - - dulwich.tests.test_archive - dulwich.tests.test_blackbox - dulwich.tests.test_client - dulwich.tests.test_config - dulwich.tests.test_diff_tree - dulwich.tests.test_fastexport - dulwich.tests.test_file - dulwich.tests.test_grafts - dulwich.tests.test_greenthreads - dulwich.tests.test_hooks - dulwich.tests.test_ignore - dulwich.tests.test_index - dulwich.tests.test_line_ending - dulwich.tests.test_lru_cache - dulwich.tests.test_mailmap - dulwich.tests.test_missing_obj_finder - dulwich.tests.test_object_store - dulwich.tests.test_objects - dulwich.tests.test_objectspec - dulwich.tests.test_pack - dulwich.tests.test_patch - dulwich.tests.test_porcelain - dulwich.tests.test_protocol - dulwich.tests.test_reflog - dulwich.tests.test_refs - dulwich.tests.test_repository - dulwich.tests.test_server - dulwich.tests.test_stash - dulwich.tests.test_utils - dulwich.tests.test_walk - dulwich.tests.test_web - dulwich.tests.utils diff --git a/docs/build/html/_sources/api/dulwich.tests.utils.txt b/docs/build/html/_sources/api/dulwich.tests.utils.txt deleted file mode 100644 index 3cb92327..00000000 --- a/docs/build/html/_sources/api/dulwich.tests.utils.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.tests.utils module -========================== - -.. automodule:: dulwich.tests.utils - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.txt b/docs/build/html/_sources/api/dulwich.txt deleted file mode 100644 index 39bef9e0..00000000 --- a/docs/build/html/_sources/api/dulwich.txt +++ /dev/null @@ -1,50 +0,0 @@ -dulwich package -=============== - -.. automodule:: dulwich - :members: - :undoc-members: - :show-inheritance: - -Subpackages ------------ - -.. toctree:: - - dulwich.contrib - dulwich.tests - -Submodules ----------- - -.. toctree:: - - dulwich.archive - dulwich.client - dulwich.config - dulwich.diff_tree - dulwich.errors - dulwich.fastexport - dulwich.file - dulwich.greenthreads - dulwich.hooks - dulwich.ignore - dulwich.index - dulwich.line_ending - dulwich.log_utils - dulwich.lru_cache - dulwich.mailmap - dulwich.object_store - dulwich.objects - dulwich.objectspec - dulwich.pack - dulwich.patch - dulwich.porcelain - dulwich.protocol - dulwich.reflog - dulwich.refs - dulwich.repo - dulwich.server - dulwich.stash - dulwich.walk - dulwich.web diff --git a/docs/build/html/_sources/api/dulwich.walk.txt b/docs/build/html/_sources/api/dulwich.walk.txt deleted file mode 100644 index 62b7b74c..00000000 --- a/docs/build/html/_sources/api/dulwich.walk.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.walk module -=================== - -.. automodule:: dulwich.walk - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/dulwich.web.txt b/docs/build/html/_sources/api/dulwich.web.txt deleted file mode 100644 index c49acd82..00000000 --- a/docs/build/html/_sources/api/dulwich.web.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich.web module -================== - -.. automodule:: dulwich.web - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/api/index.txt b/docs/build/html/_sources/api/index.txt deleted file mode 100644 index 355c3a1a..00000000 --- a/docs/build/html/_sources/api/index.txt +++ /dev/null @@ -1,14 +0,0 @@ -This is the API documentation for Dulwich. - -Module reference ----------------- - -.. toctree:: - :maxdepth: 3 - - modules - -Indices: - -* :ref:`modindex` -* :ref:`search` diff --git a/docs/build/html/_sources/api/modules.txt b/docs/build/html/_sources/api/modules.txt deleted file mode 100644 index ca2f0c3b..00000000 --- a/docs/build/html/_sources/api/modules.txt +++ /dev/null @@ -1,7 +0,0 @@ -dulwich -======= - -.. toctree:: - :maxdepth: 4 - - dulwich diff --git a/docs/build/html/_sources/index.txt b/docs/build/html/_sources/index.txt deleted file mode 100644 index 78585c8e..00000000 --- a/docs/build/html/_sources/index.txt +++ /dev/null @@ -1,37 +0,0 @@ -.. _index: - -====================================== -dulwich - Python implementation of Git -====================================== - -Overview -======== - -.. include:: ../README.rst - -Documentation -============= - -.. toctree:: - :maxdepth: 2 - - performance - protocol - - tutorial/index - - api/index - - -Changelog -========= - -.. include:: ../NEWS - -Indices and tables -================== - -* :ref:`genindex` -* :ref:`modindex` -* :ref:`search` - diff --git a/docs/build/html/_sources/performance.txt b/docs/build/html/_sources/performance.txt deleted file mode 100644 index d2fd817f..00000000 --- a/docs/build/html/_sources/performance.txt +++ /dev/null @@ -1,11 +0,0 @@ -.. _performance: - -============================== -Possible areas for improvement -============================== - -Places for improvement, ordered by difficulty / effectiveness: - -* read_zlib() should have a C equivalent (~ 4% overhead atm) -* unpack_object() should have a C equivalent - diff --git a/docs/build/html/_sources/protocol.txt b/docs/build/html/_sources/protocol.txt deleted file mode 100644 index d637a765..00000000 --- a/docs/build/html/_sources/protocol.txt +++ /dev/null @@ -1,65 +0,0 @@ -.. _protocol: - -=================== -Git Server Protocol -=================== - -Transport -========= - -The Git protocol operates over pipes or TCP/IP. When a client connects over -TCP/IP, it sends a header that tells the server which program to run and what -parameters to use. When invoked over SSH, git will run a program with the -parameters as command line arguments. - -Protocols -========= - -Basics ------- - -Git communicates with a server by piping data between a local program and a -remote program. - -A common way of sending a unit of information is a pkt_line. This is a 4 byte -size as human encoded hex (i.e. totally underusing the 4 bytes...) that tells -you the size of the payload, followed by the payload. The size includes the 4 -bytes used by the size itself. - - 0009ABCD\n - -Git can also multiplex data using the sideband. As well as 4 bytes size, there -would be a 1 byte channel number. This is in binary, so ``1`` will be ``\x01``. - -Typically Git will piggyback a list of capabilities on the first pkt_line it -sends. It will also look for capabilities in the first pkt_like it receives. -Git will degrade as much as possible when encountering a server or client with -differing capabilities. - -git-upload-pack ---------------- - -git-upload pack is used by git-ls-remote, git-clone, git-fetch and git-pull. -And i'm sure others. Typically a client will connect a local git-fetch-pack to -a remote git-upload-pack. - -Capabilities for this protocol include multi_ack, thin-pack, ofs-delta, -sideband and sideband-64k A thin pack can reference objects not in the current -pack. - -The server tells the client what refs it has. The client states which of those -SHA1's it would like. It then starts to report which SHA1's it has. The server -ACKs these allowing the client to work out when to stop sending SHA1's. This -saves a lot of transfer because the client can make decisions like "well if it -has this SHA, then it has all its parents so I don't need to care about those". -When the client stops sending shas, the server can work out an optimal pack and -then send it to the client. - -git-receive-pack ----------------- - -git-receive-pack is used by git push. Typically a client connects a local -git-send-pack to a remote git-receive-pack. - -Capabilities include report-status and delete-ref. - diff --git a/docs/build/html/_sources/tutorial/conclusion.txt b/docs/build/html/_sources/tutorial/conclusion.txt deleted file mode 100644 index 70f1f01e..00000000 --- a/docs/build/html/_sources/tutorial/conclusion.txt +++ /dev/null @@ -1,13 +0,0 @@ -.. _tutorial-conclusion: - -Conclusion -========== - -This tutorial currently only covers a small (but important) part of Dulwich. -It still needs to be extended to cover packs, refs, reflogs and network -communication. - -Dulwich is abstracting much of the Git plumbing, so there would be more to -see. - -For now, that's all folks! diff --git a/docs/build/html/_sources/tutorial/encoding.txt b/docs/build/html/_sources/tutorial/encoding.txt deleted file mode 100644 index 0dd0d7e7..00000000 --- a/docs/build/html/_sources/tutorial/encoding.txt +++ /dev/null @@ -1,26 +0,0 @@ -Encoding -======== - -You will notice that all lower-level functions in Dulwich take byte strings -rather than unicode strings. This is intentional. - -Although `C git`_ recommends the use of UTF-8 for encoding, this is not -strictly enforced and C git treats filenames as sequences of non-NUL bytes. -There are repositories in the wild that use non-UTF-8 encoding for filenames -and commit messages. - -.. _C git: https://github.com/git/git/blob/master/Documentation/i18n.txt - -The library should be able to read *all* existing git repositories, -irregardless of what encoding they use. This is the main reason why Dulwich -does not convert paths to unicode strings. - -A further consideration is that converting back and forth to unicode -is an extra performance penalty. E.g. if you are just iterating over file -contents, there is no need to consider encoded strings. Users of the library -may have specific assumptions they can make about the encoding - e.g. they -could just decide that all their data is latin-1, or the default Python -encoding. - -Higher level functions, such as the porcelain in dulwich.porcelain, will -automatically convert unicode strings to UTF-8 bytestrings. diff --git a/docs/build/html/_sources/tutorial/file-format.txt b/docs/build/html/_sources/tutorial/file-format.txt deleted file mode 100644 index dd04008c..00000000 --- a/docs/build/html/_sources/tutorial/file-format.txt +++ /dev/null @@ -1,99 +0,0 @@ -Git File format -=============== - -For a better understanding of Dulwich, we'll start by explaining most of the -Git secrets. - -Open the ".git" folder of any Git-managed repository. You'll find folders -like "branches", "hooks"... We're only interested in "objects" here. Open it. - -You'll mostly see 2 hex-digits folders. Git identifies content by its SHA-1 -digest. The 2 hex-digits plus the 38 hex-digits of files inside these folders -form the 40 characters (or 20 bytes) id of Git objects you'll manage in -Dulwich. - -We'll first study the three main objects: - -- The Commit; - -- The Tree; - -- The Blob. - -The Commit ----------- - -You're used to generate commits using Git. You have set up your name and -e-mail, and you know how to see the history using ``git log``. - -A commit file looks like this:: - - commit tree - parent - [parent if several parents from merges] - author - committer - - - -But where are the changes you committed? The commit contains a reference to a -tree. - -The Tree --------- - -A tree is a collection of file information, the state of a single directory at -a given point in time. - -A tree file looks like this:: - - tree ... - -And repeats for every file in the tree. - -Note that the SHA-1 digest is in binary form here. - -The file mode is like the octal argument you could give to the ``chmod`` -command. Except it is in extended form to tell regular files from -directories and other types. - -We now know how our files are referenced but we haven't found their actual -content yet. That's where the reference to a blob comes in. - -The Blob --------- - -A blob is simply the content of files you are versioning. - -A blob file looks like this:: - - blob - -If you change a single line, another blob will be generated by Git at commit -time. This is how Git can fastly checkout any version in time. - -On the opposite, several identical files with different filenames generate -only one blob. That's mostly how renames are so cheap and efficient in Git. - -Dulwich Objects ---------------- - -Dulwich implements these three objects with an API to easily access the -information you need, while abstracting some more secrets Git is using to -accelerate operations and reduce space. - -More About Git formats ----------------------- - -These three objects make up most of the contents of a Git repository and are -used for the history. They can either appear as simple files on disk (one file -per object) or in a ``pack`` file, which is a container for a number of these -objects. - -There is also an index of the current state of the working copy in the -repository as well as files to track the existing branches and tags. - -For a more detailed explanation of object formats and SHA-1 digests, see: -http://www-cs-students.stanford.edu/~blynn/gitmagic/ch08.html - -Just note that recent versions of Git compress object files using zlib. diff --git a/docs/build/html/_sources/tutorial/index.txt b/docs/build/html/_sources/tutorial/index.txt deleted file mode 100644 index 5a249de3..00000000 --- a/docs/build/html/_sources/tutorial/index.txt +++ /dev/null @@ -1,19 +0,0 @@ -.. _tutorial: - -======== -Tutorial -======== - -.. toctree:: - :maxdepth: 2 - - introduction - encoding - file-format - repo - object-store - remote - tag - porcelain - conclusion - diff --git a/docs/build/html/_sources/tutorial/introduction.txt b/docs/build/html/_sources/tutorial/introduction.txt deleted file mode 100644 index 9fee9d86..00000000 --- a/docs/build/html/_sources/tutorial/introduction.txt +++ /dev/null @@ -1,20 +0,0 @@ -.. _tutorial-introduction: - -Introduction -============ - -Like Git itself, Dulwich consists of two main layers; the so-called plumbing -and the porcelain. - -The plumbing is the lower layer and it deals with the Git object database and the -nitty gritty internals. The porcelain is roughly what you would expect to -be exposed to as a user of the ``git`` command-like tool. - -Dulwich has a fairly complete plumbing implementation, and a more recently -added porcelain implementation. The porcelain code lives in -``dulwich.porcelain``. - - -For the large part, this tutorial introduces you to the internal concepts of -Git and the main plumbing parts of Dulwich. The last chapter covers -the porcelain. diff --git a/docs/build/html/_sources/tutorial/object-store.txt b/docs/build/html/_sources/tutorial/object-store.txt deleted file mode 100644 index b1746d3d..00000000 --- a/docs/build/html/_sources/tutorial/object-store.txt +++ /dev/null @@ -1,189 +0,0 @@ -.. _tutorial-object-store: - -The object store -================ - -The objects are stored in the ``object store`` of the repository. - - >>> from dulwich.repo import Repo - >>> repo = Repo.init("myrepo", mkdir=True) - -Initial commit --------------- - -When you use Git, you generally add or modify content. As our repository is -empty for now, we'll start by adding a new file:: - - >>> from dulwich.objects import Blob - >>> blob = Blob.from_string(b"My file content\n") - >>> print(blob.id.decode('ascii')) - c55063a4d5d37aa1af2b2dad3a70aa34dae54dc6 - -Of course you could create a blob from an existing file using ``from_file`` -instead. - -As said in the introduction, file content is separated from file name. Let's -give this content a name:: - - >>> from dulwich.objects import Tree - >>> tree = Tree() - >>> tree.add(b"spam", 0o100644, blob.id) - -Note that "0o100644" is the octal form for a regular file with common -permissions. You can hardcode them or you can use the ``stat`` module. - -The tree state of our repository still needs to be placed in time. That's the -job of the commit:: - - >>> from dulwich.objects import Commit, parse_timezone - >>> from time import time - >>> commit = Commit() - >>> commit.tree = tree.id - >>> author = b"Your Name " - >>> commit.author = commit.committer = author - >>> commit.commit_time = commit.author_time = int(time()) - >>> tz = parse_timezone(b'-0200')[0] - >>> commit.commit_timezone = commit.author_timezone = tz - >>> commit.encoding = b"UTF-8" - >>> commit.message = b"Initial commit" - -Note that the initial commit has no parents. - -At this point, the repository is still empty because all operations happen in -memory. Let's "commit" it. - - >>> object_store = repo.object_store - >>> object_store.add_object(blob) - -Now the ".git/objects" folder contains a first SHA-1 file. Let's continue -saving the changes:: - - >>> object_store.add_object(tree) - >>> object_store.add_object(commit) - -Now the physical repository contains three objects but still has no branch. -Let's create the master branch like Git would:: - - >>> repo.refs[b'refs/heads/master'] = commit.id - -The master branch now has a commit where to start. When we commit to master, we -are also moving HEAD, which is Git's currently checked out branch: - - >>> head = repo.refs[b'HEAD'] - >>> head == commit.id - True - >>> head == repo.refs[b'refs/heads/master'] - True - -How did that work? As it turns out, HEAD is a special kind of ref called a -symbolic ref, and it points at master. Most functions on the refs container -work transparently with symbolic refs, but we can also take a peek inside HEAD: - - >>> import sys - >>> print(repo.refs.read_ref(b'HEAD').decode(sys.getfilesystemencoding())) - ref: refs/heads/master - -Normally, you won't need to use read_ref. If you want to change what ref HEAD -points to, in order to check out another branch, just use set_symbolic_ref. - -Now our repository is officially tracking a branch named "master" referring to a -single commit. - -Playing again with Git ----------------------- - -At this point you can come back to the shell, go into the "myrepo" folder and -type ``git status`` to let Git confirm that this is a regular repository on -branch "master". - -Git will tell you that the file "spam" is deleted, which is normal because -Git is comparing the repository state with the current working copy. And we -have absolutely no working copy using Dulwich because we don't need it at -all! - -You can checkout the last state using ``git checkout -f``. The force flag -will prevent Git from complaining that there are uncommitted changes in the -working copy. - -The file ``spam`` appears and with no surprise contains the same bytes as the -blob:: - - $ cat spam - My file content - -Changing a File and Committing it ---------------------------------- - -Now we have a first commit, the next one will show a difference. - -As seen in the introduction, it's about making a path in a tree point to a -new blob. The old blob will remain to compute the diff. The tree is altered -and the new commit'task is to point to this new version. - -Let's first build the blob:: - - >>> from dulwich.objects import Blob - >>> spam = Blob.from_string(b"My new file content\n") - >>> print(spam.id.decode('ascii')) - 16ee2682887a962f854ebd25a61db16ef4efe49f - -An alternative is to alter the previously constructed blob object:: - - >>> blob.data = b"My new file content\n" - >>> print(blob.id.decode('ascii')) - 16ee2682887a962f854ebd25a61db16ef4efe49f - -In any case, update the blob id known as "spam". You also have the -opportunity of changing its mode:: - - >>> tree[b"spam"] = (0o100644, spam.id) - -Now let's record the change:: - - >>> from dulwich.objects import Commit - >>> from time import time - >>> c2 = Commit() - >>> c2.tree = tree.id - >>> c2.parents = [commit.id] - >>> c2.author = c2.committer = b"John Doe " - >>> c2.commit_time = c2.author_time = int(time()) - >>> c2.commit_timezone = c2.author_timezone = 0 - >>> c2.encoding = b"UTF-8" - >>> c2.message = b'Changing "spam"' - -In this new commit we record the changed tree id, and most important, the -previous commit as the parent. Parents are actually a list because a commit -may happen to have several parents after merging branches. - -Let's put the objects in the object store:: - - >>> repo.object_store.add_object(spam) - >>> repo.object_store.add_object(tree) - >>> repo.object_store.add_object(c2) - -You can already ask git to introspect this commit using ``git show`` and the -value of ``c2.id`` as an argument. You'll see the difference will the -previous blob recorded as "spam". - -The diff between the previous head and the new one can be printed using -write_tree_diff:: - - >>> from dulwich.patch import write_tree_diff - >>> from io import BytesIO - >>> out = BytesIO() - >>> write_tree_diff(out, repo.object_store, commit.tree, tree.id) - >>> import sys; _ = sys.stdout.write(out.getvalue().decode('ascii')) - diff --git a/spam b/spam - index c55063a..16ee268 100644 - --- a/spam - +++ b/spam - @@ -1 +1 @@ - -My file content - +My new file content - -You won't see it using git log because the head is still the previous -commit. It's easy to remedy:: - - >>> repo.refs[b'refs/heads/master'] = c2.id - -Now all git tools will work as expected. diff --git a/docs/build/html/_sources/tutorial/porcelain.txt b/docs/build/html/_sources/tutorial/porcelain.txt deleted file mode 100644 index b85e29e5..00000000 --- a/docs/build/html/_sources/tutorial/porcelain.txt +++ /dev/null @@ -1,40 +0,0 @@ -Porcelain -========= - -The ``porcelain`` is the higher level interface, built on top of the lower -level implementation covered in previous chapters of this tutorial. The -``dulwich.porcelain`` module in Dulwich is aimed to closely resemble -the Git command-line API that you are familiar with. - -Basic concepts --------------- -The porcelain operations are implemented as top-level functions in the -``dulwich.porcelain`` module. Most arguments can either be strings or -more complex Dulwich objects; e.g. a repository argument will either take -a string with a path to the repository or an instance of a ``Repo`` object. - -Initializing a new repository ------------------------------ - - >>> from dulwich import porcelain - - >>> repo = porcelain.init("myrepo") - -Clone a repository ------------------- - - >>> porcelain.clone("git://github.com/jelmer/dulwich", "dulwich-clone") - -Commit changes --------------- - - >>> r = porcelain.init("testrepo") - >>> open("testrepo/testfile", "w").write("data") - >>> porcelain.add(r, "testfile") - >>> porcelain.commit(r, b"A sample commit") - -Push changes ------------- - - >>> tr = porcelain.init("targetrepo") - >>> r = porcelain.push("testrepo", "targetrepo", "master") diff --git a/docs/build/html/_sources/tutorial/remote.txt b/docs/build/html/_sources/tutorial/remote.txt deleted file mode 100644 index 727c3f41..00000000 --- a/docs/build/html/_sources/tutorial/remote.txt +++ /dev/null @@ -1,84 +0,0 @@ -.. _tutorial-remote: - -Most of the tests in this file require a Dulwich server, so let's start one: - - >>> from dulwich.repo import Repo - >>> from dulwich.server import DictBackend, TCPGitServer - >>> import threading - >>> repo = Repo.init("remote", mkdir=True) - >>> cid = repo.do_commit(b"message", committer=b"Jelmer ") - >>> backend = DictBackend({b'/': repo}) - >>> dul_server = TCPGitServer(backend, b'localhost', 0) - >>> threading.Thread(target=dul_server.serve).start() - >>> server_address, server_port=dul_server.socket.getsockname() - -Remote repositories -=================== - -The interface for remote Git repositories is different from that -for local repositories. - -The Git smart server protocol provides three basic operations: - - * upload-pack - provides a pack with objects requested by the client - * receive-pack - imports a pack with objects provided by the client - * upload-archive - provides a tarball with the contents of a specific revision - -The smart server protocol can be accessed over either plain TCP (git://), -SSH (git+ssh://) or tunneled over HTTP (http://). - -Dulwich provides support for accessing remote repositories in -``dulwich.client``. To create a new client, you can construct -one manually:: - - >>> from dulwich.client import TCPGitClient - >>> client = TCPGitClient(server_address, server_port) - -Retrieving raw pack files -------------------------- - -The client object can then be used to retrieve a pack. The ``fetch_pack`` -method takes a ``determine_wants`` callback argument, which allows the -client to determine which objects it wants to end up with:: - - >>> def determine_wants(refs): - ... # retrieve all objects - ... return refs.values() - -Another required object is a "graph walker", which is used to determine -which objects that the client already has should not be sent again -by the server. Here in the tutorial we'll just use a dummy graph walker -which claims that the client doesn't have any objects:: - - >>> class DummyGraphWalker(object): - ... def ack(self, sha): pass - ... def next(self): pass - ... def __next__(self): pass - -With the ``determine_wants`` function in place, we can now fetch a pack, -which we will write to a ``BytesIO`` object:: - - >>> from io import BytesIO - >>> f = BytesIO() - >>> result = client.fetch_pack(b"/", determine_wants, - ... DummyGraphWalker(), pack_data=f.write) - -``f`` will now contain a full pack file:: - - >>> print(f.getvalue()[:4].decode('ascii')) - PACK - -Fetching objects into a local repository ----------------------------------------- - -It is also possible to fetch from a remote repository into a local repository, -in which case Dulwich takes care of providing the right graph walker, and -importing the received pack file into the local repository:: - - >>> from dulwich.repo import Repo - >>> local = Repo.init("local", mkdir=True) - >>> remote_refs = client.fetch(b"/", local) - -Let's shut down the server now that all tests have been run:: - - >>> dul_server.shutdown() diff --git a/docs/build/html/_sources/tutorial/repo.txt b/docs/build/html/_sources/tutorial/repo.txt deleted file mode 100644 index 1597ea3e..00000000 --- a/docs/build/html/_sources/tutorial/repo.txt +++ /dev/null @@ -1,101 +0,0 @@ -.. _tutorial-repo: - -The repository -============== - -After this introduction, let's start directly with code:: - - >>> from dulwich.repo import Repo - -The access to a repository is through the Repo object. You can open an -existing repository or you can create a new one. There are two types of Git -repositories: - - Regular Repositories -- They are the ones you create using ``git init`` and - you daily use. They contain a ``.git`` folder. - - Bare Repositories -- There is no ".git" folder. The top-level folder - contains itself the "branches", "hooks"... folders. These are used for - published repositories (mirrors). They do not have a working tree. - -Creating a repository ---------------------- - -Let's create a folder and turn it into a repository, like ``git init`` would:: - - >>> from os import mkdir - >>> import sys - >>> mkdir("myrepo") - >>> repo = Repo.init("myrepo") - >>> repo - - -You can already look at the structure of the "myrepo/.git" folder, though it -is mostly empty for now. - -Opening an existing repository ------------------------------- - -To reopen an existing repository, simply pass its path to the constructor -of ``Repo``:: - - >>> repo = Repo("myrepo") - >>> repo - - -Opening the index ------------------ - -The index is used as a staging area. Once you do a commit, -the files tracked in the index will be recorded as the contents of the new -commit. As mentioned earlier, only non-bare repositories have a working tree, -so only non-bare repositories will have an index, too. To open the index, simply -call:: - - >>> index = repo.open_index() - >>> print(index.path) - myrepo/.git/index - -Since the repository was just created, the index will be empty:: - - >>> list(index) - [] - -Staging new files ------------------ - -The repository allows "staging" files. Only files can be staged - directories -aren't tracked explicitly by git. Let's create a simple text file and stage it:: - - >>> f = open('myrepo/foo', 'wb') - >>> _ = f.write(b"monty") - >>> f.close() - - >>> repo.stage([b"foo"]) - -It will now show up in the index:: - - >>> print(",".join([f.decode(sys.getfilesystemencoding()) for f in repo.open_index()])) - foo - - -Creating new commits --------------------- - -Now that we have staged a change, we can commit it. The easiest way to -do this is by using ``Repo.do_commit``. It is also possible to manipulate -the lower-level objects involved in this, but we'll leave that for a -separate chapter of the tutorial. - -To create a simple commit on the current branch, it is only necessary -to specify the message. The committer and author will be retrieved from the -repository configuration or global configuration if they are not specified:: - - >>> commit_id = repo.do_commit( - ... b"The first commit", committer=b"Jelmer Vernooij ") - -``do_commit`` returns the SHA1 of the commit. Since the commit was to the -default branch, the repository's head will now be set to that commit:: - - >>> repo.head() == commit_id - True diff --git a/docs/build/html/_sources/tutorial/tag.txt b/docs/build/html/_sources/tutorial/tag.txt deleted file mode 100644 index 663e9a00..00000000 --- a/docs/build/html/_sources/tutorial/tag.txt +++ /dev/null @@ -1,57 +0,0 @@ -.. _tutorial-tag: - -Tagging -======= - -This tutorial will demonstrate how to add a tag to a commit via dulwich. - -First let's initialize the repository: - - >>> from dulwich.repo import Repo - >>> _repo = Repo("myrepo", mkdir=True) - -Next we build the commit object and add it to the object store: - - >>> from dulwich.objects import Blob, Tree, Commit, parse_timezone - >>> permissions = 0100644 - >>> author = "John Smith" - >>> blob = Blob.from_string("empty") - >>> tree = Tree() - >>> tree.add(tag, permissions, blob.id) - >>> commit = Commit() - >>> commit.tree = tree.id - >>> commit.author = commit.committer = author - >>> commit.commit_time = commit.author_time = int(time()) - >>> tz = parse_timezone('-0200')[0] - >>> commit.commit_timezone = commit.author_timezone = tz - >>> commit.encoding = "UTF-8" - >>> commit.message = 'Tagging repo: ' + message - -Add objects to the repo store instance: - - >>> object_store = _repo.object_store - >>> object_store.add_object(blob) - >>> object_store.add_object(tree) - >>> object_store.add_object(commit) - >>> master_branch = 'master' - >>> _repo.refs['refs/heads/' + master_branch] = commit.id - -Finally, add the tag top the repo: - - >>> _repo['refs/tags/' + commit] = commit.id - -Alternatively, we can use the tag object if we'd like to annotate the tag: - - >>> from dulwich.objects import Blob, Tree, Commit, parse_timezone, Tag - >>> tag_message = "Tag Annotation" - >>> tag = Tag() - >>> tag.tagger = author - >>> tag.message = message - >>> tag.name = "v0.1" - >>> tag.object = (Commit, commit.id) - >>> tag.tag_time = commit.author_time - >>> tag.tag_timezone = tz - >>> object_store.add_object(tag) - >>> _repo['refs/tags/' + tag] = tag.id - - diff --git a/dulwich.egg-info/PKG-INFO b/dulwich.egg-info/PKG-INFO index 2d25463b..029a76f5 100644 --- a/dulwich.egg-info/PKG-INFO +++ b/dulwich.egg-info/PKG-INFO @@ -1,125 +1,125 @@ Metadata-Version: 2.1 Name: dulwich -Version: 0.19.14 +Version: 0.19.15 Summary: Python Git Library Home-page: https://www.dulwich.io/ Author: Jelmer Vernooij Author-email: jelmer@jelmer.uk License: Apachev2 or later or GPLv2 Project-URL: Bug Tracker, https://github.com/dulwich/dulwich/issues Project-URL: GitHub, https://github.com/dulwich/dulwich Project-URL: Repository, https://www.dulwich.io/code/ Description: .. image:: https://travis-ci.org/dulwich/dulwich.png?branch=master :alt: Build Status :target: https://travis-ci.org/dulwich/dulwich .. image:: https://ci.appveyor.com/api/projects/status/mob7g4vnrfvvoweb?svg=true :alt: Windows Build Status :target: https://ci.appveyor.com/project/jelmer/dulwich/branch/master This is the Dulwich project. It aims to provide an interface to git repos (both local and remote) that doesn't call out to git directly but instead uses pure Python. **Main website**: **License**: Apache License, version 2 or GNU General Public License, version 2 or later. The project is named after the part of London that Mr. and Mrs. Git live in in the particular Monty Python sketch. Installation ------------ By default, Dulwich' setup.py will attempt to build and install the optional C extensions. The reason for this is that they significantly improve the performance since some low-level operations that are executed often are much slower in CPython. If you don't want to install the C bindings, specify the --pure argument to setup.py:: $ python setup.py --pure install or if you are installing from pip:: $ pip install dulwich --global-option="--pure" Note that you can also specify --global-option in a `requirements.txt `_ file, e.g. like this:: dulwich --global-option=--pure Getting started --------------- Dulwich comes with both a lower-level API and higher-level plumbing ("porcelain"). For example, to use the lower level API to access the commit message of the last commit:: >>> from dulwich.repo import Repo >>> r = Repo('.') >>> r.head() '57fbe010446356833a6ad1600059d80b1e731e15' >>> c = r[r.head()] >>> c >>> c.message 'Add note about encoding.\n' And to print it using porcelain:: >>> from dulwich import porcelain >>> porcelain.log('.', max_entries=1) -------------------------------------------------- commit: 57fbe010446356833a6ad1600059d80b1e731e15 Author: Jelmer Vernooij Date: Sat Apr 29 2017 23:57:34 +0000 Add note about encoding. Further documentation --------------------- The dulwich documentation can be found in docs/ and built by running ``make doc``. It can also be found `on the web `_. Help ---- There is a *#dulwich* IRC channel on the `Freenode `_, and `dulwich-announce `_ and `dulwich-discuss `_ mailing lists. Contributing ------------ For a full list of contributors, see the git logs or `AUTHORS `_. If you'd like to contribute to Dulwich, see the `CONTRIBUTING `_ file and `list of open issues `_. Supported versions of Python ---------------------------- At the moment, Dulwich supports (and is tested on) CPython 2.7, 3.4, 3.5, 3.6, 3.7 and Pypy. Keywords: git vcs Platform: UNKNOWN Classifier: Development Status :: 4 - Beta Classifier: License :: OSI Approved :: Apache Software License Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Programming Language :: Python :: Implementation :: PyPy Classifier: Operating System :: POSIX Classifier: Operating System :: Microsoft :: Windows Classifier: Topic :: Software Development :: Version Control Provides-Extra: fastimport Provides-Extra: https Provides-Extra: pgp diff --git a/dulwich.egg-info/SOURCES.txt b/dulwich.egg-info/SOURCES.txt index 126d8f72..1fcfc237 100644 --- a/dulwich.egg-info/SOURCES.txt +++ b/dulwich.egg-info/SOURCES.txt @@ -1,396 +1,220 @@ .coveragerc .gitignore .mailmap .testr.conf .travis.yml AUTHORS CONTRIBUTING.rst COPYING MANIFEST.in Makefile NEWS README.rst README.swift.rst TODO appveyor.yml build.cmd dulwich.cfg requirements.txt setup.cfg setup.py tox.ini bin/dul-receive-pack bin/dul-upload-pack bin/dulwich devscripts/PREAMBLE.c devscripts/PREAMBLE.py devscripts/replace-preamble.sh docs/Makefile docs/conf.py docs/index.txt docs/make.bat docs/performance.txt docs/protocol.txt -docs/api/dulwich.archive.txt -docs/api/dulwich.client.txt -docs/api/dulwich.config.txt -docs/api/dulwich.contrib.paramiko_vendor.txt -docs/api/dulwich.contrib.release_robot.txt -docs/api/dulwich.contrib.swift.txt -docs/api/dulwich.contrib.test_release_robot.txt -docs/api/dulwich.contrib.test_swift.txt -docs/api/dulwich.contrib.test_swift_smoke.txt -docs/api/dulwich.contrib.txt -docs/api/dulwich.diff_tree.txt -docs/api/dulwich.errors.txt -docs/api/dulwich.fastexport.txt -docs/api/dulwich.file.txt -docs/api/dulwich.greenthreads.txt -docs/api/dulwich.hooks.txt -docs/api/dulwich.ignore.txt -docs/api/dulwich.index.txt -docs/api/dulwich.line_ending.txt -docs/api/dulwich.log_utils.txt -docs/api/dulwich.lru_cache.txt -docs/api/dulwich.mailmap.txt -docs/api/dulwich.object_store.txt -docs/api/dulwich.objects.txt -docs/api/dulwich.objectspec.txt -docs/api/dulwich.pack.txt -docs/api/dulwich.patch.txt -docs/api/dulwich.porcelain.txt -docs/api/dulwich.protocol.txt -docs/api/dulwich.reflog.txt -docs/api/dulwich.refs.txt -docs/api/dulwich.repo.txt -docs/api/dulwich.server.txt -docs/api/dulwich.stash.txt -docs/api/dulwich.tests.compat.server_utils.txt -docs/api/dulwich.tests.compat.test_client.txt -docs/api/dulwich.tests.compat.test_pack.txt -docs/api/dulwich.tests.compat.test_patch.txt -docs/api/dulwich.tests.compat.test_repository.txt -docs/api/dulwich.tests.compat.test_server.txt -docs/api/dulwich.tests.compat.test_utils.txt -docs/api/dulwich.tests.compat.test_web.txt -docs/api/dulwich.tests.compat.txt -docs/api/dulwich.tests.compat.utils.txt -docs/api/dulwich.tests.test_archive.txt -docs/api/dulwich.tests.test_blackbox.txt -docs/api/dulwich.tests.test_client.txt -docs/api/dulwich.tests.test_config.txt -docs/api/dulwich.tests.test_diff_tree.txt -docs/api/dulwich.tests.test_fastexport.txt -docs/api/dulwich.tests.test_file.txt -docs/api/dulwich.tests.test_grafts.txt -docs/api/dulwich.tests.test_greenthreads.txt -docs/api/dulwich.tests.test_hooks.txt -docs/api/dulwich.tests.test_ignore.txt -docs/api/dulwich.tests.test_index.txt -docs/api/dulwich.tests.test_line_ending.txt -docs/api/dulwich.tests.test_lru_cache.txt -docs/api/dulwich.tests.test_mailmap.txt -docs/api/dulwich.tests.test_missing_obj_finder.txt -docs/api/dulwich.tests.test_object_store.txt -docs/api/dulwich.tests.test_objects.txt -docs/api/dulwich.tests.test_objectspec.txt -docs/api/dulwich.tests.test_pack.txt -docs/api/dulwich.tests.test_patch.txt -docs/api/dulwich.tests.test_porcelain.txt -docs/api/dulwich.tests.test_protocol.txt -docs/api/dulwich.tests.test_reflog.txt -docs/api/dulwich.tests.test_refs.txt -docs/api/dulwich.tests.test_repository.txt -docs/api/dulwich.tests.test_server.txt -docs/api/dulwich.tests.test_stash.txt -docs/api/dulwich.tests.test_utils.txt -docs/api/dulwich.tests.test_walk.txt -docs/api/dulwich.tests.test_web.txt -docs/api/dulwich.tests.txt -docs/api/dulwich.tests.utils.txt -docs/api/dulwich.txt -docs/api/dulwich.walk.txt -docs/api/dulwich.web.txt docs/api/index.txt -docs/api/modules.txt -docs/build/html/_sources/index.txt -docs/build/html/_sources/performance.txt -docs/build/html/_sources/protocol.txt -docs/build/html/_sources/api/dulwich.archive.txt -docs/build/html/_sources/api/dulwich.client.txt -docs/build/html/_sources/api/dulwich.config.txt -docs/build/html/_sources/api/dulwich.contrib.paramiko_vendor.txt -docs/build/html/_sources/api/dulwich.contrib.release_robot.txt -docs/build/html/_sources/api/dulwich.contrib.swift.txt -docs/build/html/_sources/api/dulwich.contrib.test_release_robot.txt -docs/build/html/_sources/api/dulwich.contrib.test_swift.txt -docs/build/html/_sources/api/dulwich.contrib.test_swift_smoke.txt -docs/build/html/_sources/api/dulwich.contrib.txt -docs/build/html/_sources/api/dulwich.diff_tree.txt -docs/build/html/_sources/api/dulwich.errors.txt -docs/build/html/_sources/api/dulwich.fastexport.txt -docs/build/html/_sources/api/dulwich.file.txt -docs/build/html/_sources/api/dulwich.greenthreads.txt -docs/build/html/_sources/api/dulwich.hooks.txt -docs/build/html/_sources/api/dulwich.ignore.txt -docs/build/html/_sources/api/dulwich.index.txt -docs/build/html/_sources/api/dulwich.line_ending.txt -docs/build/html/_sources/api/dulwich.log_utils.txt -docs/build/html/_sources/api/dulwich.lru_cache.txt -docs/build/html/_sources/api/dulwich.mailmap.txt -docs/build/html/_sources/api/dulwich.object_store.txt -docs/build/html/_sources/api/dulwich.objects.txt -docs/build/html/_sources/api/dulwich.objectspec.txt -docs/build/html/_sources/api/dulwich.pack.txt -docs/build/html/_sources/api/dulwich.patch.txt -docs/build/html/_sources/api/dulwich.porcelain.txt -docs/build/html/_sources/api/dulwich.protocol.txt -docs/build/html/_sources/api/dulwich.reflog.txt -docs/build/html/_sources/api/dulwich.refs.txt -docs/build/html/_sources/api/dulwich.repo.txt -docs/build/html/_sources/api/dulwich.server.txt -docs/build/html/_sources/api/dulwich.stash.txt -docs/build/html/_sources/api/dulwich.tests.compat.server_utils.txt -docs/build/html/_sources/api/dulwich.tests.compat.test_client.txt -docs/build/html/_sources/api/dulwich.tests.compat.test_pack.txt -docs/build/html/_sources/api/dulwich.tests.compat.test_patch.txt -docs/build/html/_sources/api/dulwich.tests.compat.test_repository.txt -docs/build/html/_sources/api/dulwich.tests.compat.test_server.txt -docs/build/html/_sources/api/dulwich.tests.compat.test_utils.txt -docs/build/html/_sources/api/dulwich.tests.compat.test_web.txt -docs/build/html/_sources/api/dulwich.tests.compat.txt -docs/build/html/_sources/api/dulwich.tests.compat.utils.txt -docs/build/html/_sources/api/dulwich.tests.test_archive.txt -docs/build/html/_sources/api/dulwich.tests.test_blackbox.txt -docs/build/html/_sources/api/dulwich.tests.test_client.txt -docs/build/html/_sources/api/dulwich.tests.test_config.txt -docs/build/html/_sources/api/dulwich.tests.test_diff_tree.txt -docs/build/html/_sources/api/dulwich.tests.test_fastexport.txt -docs/build/html/_sources/api/dulwich.tests.test_file.txt -docs/build/html/_sources/api/dulwich.tests.test_grafts.txt -docs/build/html/_sources/api/dulwich.tests.test_greenthreads.txt -docs/build/html/_sources/api/dulwich.tests.test_hooks.txt -docs/build/html/_sources/api/dulwich.tests.test_ignore.txt -docs/build/html/_sources/api/dulwich.tests.test_index.txt -docs/build/html/_sources/api/dulwich.tests.test_line_ending.txt -docs/build/html/_sources/api/dulwich.tests.test_lru_cache.txt -docs/build/html/_sources/api/dulwich.tests.test_mailmap.txt -docs/build/html/_sources/api/dulwich.tests.test_missing_obj_finder.txt -docs/build/html/_sources/api/dulwich.tests.test_object_store.txt -docs/build/html/_sources/api/dulwich.tests.test_objects.txt -docs/build/html/_sources/api/dulwich.tests.test_objectspec.txt -docs/build/html/_sources/api/dulwich.tests.test_pack.txt -docs/build/html/_sources/api/dulwich.tests.test_patch.txt -docs/build/html/_sources/api/dulwich.tests.test_porcelain.txt -docs/build/html/_sources/api/dulwich.tests.test_protocol.txt -docs/build/html/_sources/api/dulwich.tests.test_reflog.txt -docs/build/html/_sources/api/dulwich.tests.test_refs.txt -docs/build/html/_sources/api/dulwich.tests.test_repository.txt -docs/build/html/_sources/api/dulwich.tests.test_server.txt -docs/build/html/_sources/api/dulwich.tests.test_stash.txt -docs/build/html/_sources/api/dulwich.tests.test_utils.txt -docs/build/html/_sources/api/dulwich.tests.test_walk.txt -docs/build/html/_sources/api/dulwich.tests.test_web.txt -docs/build/html/_sources/api/dulwich.tests.txt -docs/build/html/_sources/api/dulwich.tests.utils.txt -docs/build/html/_sources/api/dulwich.txt -docs/build/html/_sources/api/dulwich.walk.txt -docs/build/html/_sources/api/dulwich.web.txt -docs/build/html/_sources/api/index.txt -docs/build/html/_sources/api/modules.txt -docs/build/html/_sources/tutorial/conclusion.txt -docs/build/html/_sources/tutorial/encoding.txt -docs/build/html/_sources/tutorial/file-format.txt -docs/build/html/_sources/tutorial/index.txt -docs/build/html/_sources/tutorial/introduction.txt -docs/build/html/_sources/tutorial/object-store.txt -docs/build/html/_sources/tutorial/porcelain.txt -docs/build/html/_sources/tutorial/remote.txt -docs/build/html/_sources/tutorial/repo.txt -docs/build/html/_sources/tutorial/tag.txt docs/tutorial/.gitignore docs/tutorial/Makefile docs/tutorial/conclusion.txt docs/tutorial/encoding.txt docs/tutorial/file-format.txt docs/tutorial/index.txt docs/tutorial/introduction.txt docs/tutorial/object-store.txt docs/tutorial/porcelain.txt docs/tutorial/remote.txt docs/tutorial/repo.txt docs/tutorial/tag.txt dulwich/__init__.py dulwich/_diff_tree.c dulwich/_objects.c dulwich/_pack.c dulwich/archive.py dulwich/client.py dulwich/config.py dulwich/diff_tree.py dulwich/errors.py dulwich/fastexport.py dulwich/file.py dulwich/greenthreads.py dulwich/hooks.py dulwich/ignore.py dulwich/index.py dulwich/line_ending.py dulwich/log_utils.py dulwich/lru_cache.py dulwich/mailmap.py dulwich/object_store.py dulwich/objects.py dulwich/objectspec.py dulwich/pack.py dulwich/patch.py dulwich/porcelain.py dulwich/protocol.py dulwich/reflog.py dulwich/refs.py dulwich/repo.py dulwich/server.py dulwich/stash.py dulwich/stdint.h dulwich/walk.py dulwich/web.py dulwich.egg-info/PKG-INFO dulwich.egg-info/SOURCES.txt dulwich.egg-info/dependency_links.txt dulwich.egg-info/requires.txt dulwich.egg-info/top_level.txt dulwich/contrib/README.md dulwich/contrib/__init__.py dulwich/contrib/paramiko_vendor.py dulwich/contrib/release_robot.py dulwich/contrib/swift.py dulwich/contrib/test_release_robot.py dulwich/contrib/test_swift.py dulwich/contrib/test_swift_smoke.py dulwich/tests/__init__.py dulwich/tests/test_archive.py dulwich/tests/test_blackbox.py dulwich/tests/test_client.py dulwich/tests/test_config.py dulwich/tests/test_diff_tree.py dulwich/tests/test_fastexport.py dulwich/tests/test_file.py dulwich/tests/test_grafts.py dulwich/tests/test_greenthreads.py dulwich/tests/test_hooks.py dulwich/tests/test_ignore.py dulwich/tests/test_index.py dulwich/tests/test_line_ending.py dulwich/tests/test_lru_cache.py dulwich/tests/test_mailmap.py dulwich/tests/test_missing_obj_finder.py dulwich/tests/test_object_store.py dulwich/tests/test_objects.py dulwich/tests/test_objectspec.py dulwich/tests/test_pack.py dulwich/tests/test_patch.py dulwich/tests/test_porcelain.py dulwich/tests/test_protocol.py dulwich/tests/test_reflog.py dulwich/tests/test_refs.py dulwich/tests/test_repository.py dulwich/tests/test_server.py dulwich/tests/test_stash.py dulwich/tests/test_utils.py dulwich/tests/test_walk.py dulwich/tests/test_web.py dulwich/tests/utils.py dulwich/tests/compat/__init__.py dulwich/tests/compat/server_utils.py dulwich/tests/compat/test_client.py dulwich/tests/compat/test_pack.py dulwich/tests/compat/test_patch.py dulwich/tests/compat/test_repository.py dulwich/tests/compat/test_server.py dulwich/tests/compat/test_utils.py dulwich/tests/compat/test_web.py dulwich/tests/compat/utils.py dulwich/tests/data/blobs/11/11111111111111111111111111111111111111 dulwich/tests/data/blobs/6f/670c0fb53f9463760b7295fbb814e965fb20c8 dulwich/tests/data/blobs/95/4a536f7819d40e6f637f849ee187dd10066349 dulwich/tests/data/blobs/e6/9de29bb2d1d6434b8b29ae775ad8c2e48c5391 dulwich/tests/data/commits/0d/89f20333fbb1d2f3a94da77f4981373d8f4310 dulwich/tests/data/commits/5d/ac377bdded4c9aeb8dff595f0faeebcc8498cc dulwich/tests/data/commits/60/dacdc733de308bb77bb76ce0fb0f9b44c9769e dulwich/tests/data/indexes/index dulwich/tests/data/packs/pack-bc63ddad95e7321ee734ea11a7a62d314e0d7481.idx dulwich/tests/data/packs/pack-bc63ddad95e7321ee734ea11a7a62d314e0d7481.pack dulwich/tests/data/repos/.gitattributes dulwich/tests/data/repos/issue88_expect_ack_nak_client.export dulwich/tests/data/repos/issue88_expect_ack_nak_other.export dulwich/tests/data/repos/issue88_expect_ack_nak_server.export dulwich/tests/data/repos/server_new.export dulwich/tests/data/repos/server_old.export dulwich/tests/data/repos/a.git/HEAD dulwich/tests/data/repos/a.git/packed-refs dulwich/tests/data/repos/a.git/objects/28/237f4dc30d0d462658d6b937b08a0f0b6ef55a dulwich/tests/data/repos/a.git/objects/2a/72d929692c41d8554c07f6301757ba18a65d91 dulwich/tests/data/repos/a.git/objects/4e/f30bbfe26431a69c3820d3a683df54d688f2ec dulwich/tests/data/repos/a.git/objects/4f/2e6529203aa6d44b5af6e3292c837ceda003f9 dulwich/tests/data/repos/a.git/objects/7d/9a07d797595ef11344549b8d08198e48c15364 dulwich/tests/data/repos/a.git/objects/a2/96d0bb611188cabb256919f36bc30117cca005 dulwich/tests/data/repos/a.git/objects/a9/0fa2d900a17e99b433217e988c4eb4a2e9a097 dulwich/tests/data/repos/a.git/objects/b0/931cadc54336e78a1d980420e3268903b57a50 dulwich/tests/data/repos/a.git/objects/ff/d47d45845a8f6576491e1edb97e3fe6a850e7f dulwich/tests/data/repos/a.git/refs/heads/master dulwich/tests/data/repos/a.git/refs/tags/mytag dulwich/tests/data/repos/empty.git/HEAD dulwich/tests/data/repos/empty.git/config dulwich/tests/data/repos/empty.git/objects/info/.gitignore dulwich/tests/data/repos/empty.git/objects/pack/.gitignore dulwich/tests/data/repos/empty.git/refs/heads/.gitignore dulwich/tests/data/repos/empty.git/refs/tags/.gitignore dulwich/tests/data/repos/ooo_merge.git/HEAD dulwich/tests/data/repos/ooo_merge.git/objects/29/69be3e8ee1c0222396a5611407e4769f14e54b dulwich/tests/data/repos/ooo_merge.git/objects/38/74e9c60a6d149c44c928140f250d81e6381520 dulwich/tests/data/repos/ooo_merge.git/objects/6f/670c0fb53f9463760b7295fbb814e965fb20c8 dulwich/tests/data/repos/ooo_merge.git/objects/70/c190eb48fa8bbb50ddc692a17b44cb781af7f6 dulwich/tests/data/repos/ooo_merge.git/objects/76/01d7f6231db6a57f7bbb79ee52e4d462fd44d1 dulwich/tests/data/repos/ooo_merge.git/objects/90/182552c4a85a45ec2a835cadc3451bebdfe870 dulwich/tests/data/repos/ooo_merge.git/objects/95/4a536f7819d40e6f637f849ee187dd10066349 dulwich/tests/data/repos/ooo_merge.git/objects/b2/a2766a2879c209ab1176e7e778b81ae422eeaa dulwich/tests/data/repos/ooo_merge.git/objects/f5/07291b64138b875c28e03469025b1ea20bc614 dulwich/tests/data/repos/ooo_merge.git/objects/f9/e39b120c68182a4ba35349f832d0e4e61f485c dulwich/tests/data/repos/ooo_merge.git/objects/fb/5b0425c7ce46959bec94d54b9a157645e114f5 dulwich/tests/data/repos/ooo_merge.git/refs/heads/master dulwich/tests/data/repos/refs.git/HEAD dulwich/tests/data/repos/refs.git/packed-refs dulwich/tests/data/repos/refs.git/objects/3b/9e5457140e738c2dcd39bf6d7acf88379b90d1 dulwich/tests/data/repos/refs.git/objects/3e/c9c43c84ff242e3ef4a9fc5bc111fd780a76a8 dulwich/tests/data/repos/refs.git/objects/42/d06bd4b77fed026b154d16493e5deab78f02ec dulwich/tests/data/repos/refs.git/objects/a1/8114c31713746a33a2e70d9914d1ef3e781425 dulwich/tests/data/repos/refs.git/objects/cd/a609072918d7b70057b6bef9f4c2537843fcfe dulwich/tests/data/repos/refs.git/objects/df/6800012397fb85c56e7418dd4eb9405dee075c dulwich/tests/data/repos/refs.git/refs/heads/40-char-ref-aaaaaaaaaaaaaaaaaa dulwich/tests/data/repos/refs.git/refs/heads/loop dulwich/tests/data/repos/refs.git/refs/heads/master dulwich/tests/data/repos/refs.git/refs/tags/refs-0.2 dulwich/tests/data/repos/simple_merge.git/HEAD dulwich/tests/data/repos/simple_merge.git/objects/0d/89f20333fbb1d2f3a94da77f4981373d8f4310 dulwich/tests/data/repos/simple_merge.git/objects/1b/6318f651a534b38f9c7aedeebbd56c1e896853 dulwich/tests/data/repos/simple_merge.git/objects/29/69be3e8ee1c0222396a5611407e4769f14e54b dulwich/tests/data/repos/simple_merge.git/objects/4c/ffe90e0a41ad3f5190079d7c8f036bde29cbe6 dulwich/tests/data/repos/simple_merge.git/objects/5d/ac377bdded4c9aeb8dff595f0faeebcc8498cc dulwich/tests/data/repos/simple_merge.git/objects/60/dacdc733de308bb77bb76ce0fb0f9b44c9769e dulwich/tests/data/repos/simple_merge.git/objects/6f/670c0fb53f9463760b7295fbb814e965fb20c8 dulwich/tests/data/repos/simple_merge.git/objects/70/c190eb48fa8bbb50ddc692a17b44cb781af7f6 dulwich/tests/data/repos/simple_merge.git/objects/90/182552c4a85a45ec2a835cadc3451bebdfe870 dulwich/tests/data/repos/simple_merge.git/objects/95/4a536f7819d40e6f637f849ee187dd10066349 dulwich/tests/data/repos/simple_merge.git/objects/ab/64bbdcc51b170d21588e5c5d391ee5c0c96dfd dulwich/tests/data/repos/simple_merge.git/objects/d4/bdad6549dfedf25d3b89d21f506aff575b28a7 dulwich/tests/data/repos/simple_merge.git/objects/d8/0c186a03f423a81b39df39dc87fd269736ca86 dulwich/tests/data/repos/simple_merge.git/objects/e6/9de29bb2d1d6434b8b29ae775ad8c2e48c5391 dulwich/tests/data/repos/simple_merge.git/refs/heads/master dulwich/tests/data/repos/submodule/dotgit dulwich/tests/data/tags/71/033db03a03c6a36721efcf1968dd8f8e0cf023 dulwich/tests/data/trees/70/c190eb48fa8bbb50ddc692a17b44cb781af7f6 examples/clone.py examples/config.py examples/diff.py examples/latest_change.py examples/memoryrepo.py \ No newline at end of file diff --git a/dulwich/__init__.py b/dulwich/__init__.py index 10721e24..526be8aa 100644 --- a/dulwich/__init__.py +++ b/dulwich/__init__.py @@ -1,25 +1,25 @@ # __init__.py -- The git module of dulwich # Copyright (C) 2007 James Westby # Copyright (C) 2008 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. # """Python implementation of the Git file formats and protocols.""" -__version__ = (0, 19, 14) +__version__ = (0, 19, 15) diff --git a/dulwich/_diff_tree.c b/dulwich/_diff_tree.c index 3481ddd6..068b4f63 100644 --- a/dulwich/_diff_tree.c +++ b/dulwich/_diff_tree.c @@ -1,506 +1,505 @@ /* * Copyright (C) 2010 Google, Inc. * * 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. */ #define PY_SSIZE_T_CLEAN #include #include #ifdef _MSC_VER typedef unsigned short mode_t; #endif #if PY_MAJOR_VERSION < 3 typedef long Py_hash_t; #endif #if PY_MAJOR_VERSION >= 3 #define PyInt_FromLong PyLong_FromLong #define PyInt_AsLong PyLong_AsLong #define PyInt_AS_LONG PyLong_AS_LONG #define PyString_AS_STRING PyBytes_AS_STRING #define PyString_AsStringAndSize PyBytes_AsStringAndSize #define PyString_Check PyBytes_Check #define PyString_CheckExact PyBytes_CheckExact #define PyString_FromStringAndSize PyBytes_FromStringAndSize #define PyString_FromString PyBytes_FromString #define PyString_GET_SIZE PyBytes_GET_SIZE #define PyString_Size PyBytes_Size #define _PyString_Join _PyBytes_Join #endif static PyObject *tree_entry_cls = NULL, *null_entry = NULL, *defaultdict_cls = NULL, *int_cls = NULL; static int block_size; /** * Free an array of PyObject pointers, decrementing any references. */ static void free_objects(PyObject **objs, Py_ssize_t n) { Py_ssize_t i; for (i = 0; i < n; i++) Py_XDECREF(objs[i]); PyMem_Free(objs); } /** * Get the entries of a tree, prepending the given path. * * Args: * path: The path to prepend, without trailing slashes. * path_len: The length of path. * tree: The Tree object to iterate. * n: Set to the length of result. * Returns: A (C) array of PyObject pointers to TreeEntry objects for each path * in tree. */ static PyObject **tree_entries(char *path, Py_ssize_t path_len, PyObject *tree, Py_ssize_t *n) { PyObject *iteritems, *items, **result = NULL; PyObject *old_entry, *name, *sha; Py_ssize_t i = 0, name_len, new_path_len; char *new_path; if (tree == Py_None) { *n = 0; result = PyMem_New(PyObject*, 0); if (!result) { PyErr_NoMemory(); return NULL; } return result; } iteritems = PyObject_GetAttrString(tree, "iteritems"); if (!iteritems) return NULL; items = PyObject_CallFunctionObjArgs(iteritems, Py_True, NULL); Py_DECREF(iteritems); if (items == NULL) { return NULL; } /* The C implementation of iteritems returns a list, so depend on that. */ if (!PyList_Check(items)) { PyErr_SetString(PyExc_TypeError, "Tree.iteritems() did not return a list"); return NULL; } *n = PyList_Size(items); result = PyMem_New(PyObject*, *n); if (!result) { PyErr_NoMemory(); goto error; } for (i = 0; i < *n; i++) { old_entry = PyList_GetItem(items, i); if (!old_entry) goto error; sha = PyTuple_GetItem(old_entry, 2); if (!sha) goto error; name = PyTuple_GET_ITEM(old_entry, 0); name_len = PyString_Size(name); if (PyErr_Occurred()) goto error; new_path_len = name_len; if (path_len) new_path_len += path_len + 1; new_path = PyMem_Malloc(new_path_len); if (!new_path) { PyErr_NoMemory(); goto error; } if (path_len) { memcpy(new_path, path, path_len); new_path[path_len] = '/'; memcpy(new_path + path_len + 1, PyString_AS_STRING(name), name_len); } else { memcpy(new_path, PyString_AS_STRING(name), name_len); } #if PY_MAJOR_VERSION >= 3 result[i] = PyObject_CallFunction(tree_entry_cls, "y#OO", new_path, new_path_len, PyTuple_GET_ITEM(old_entry, 1), sha); #else result[i] = PyObject_CallFunction(tree_entry_cls, "s#OO", new_path, new_path_len, PyTuple_GET_ITEM(old_entry, 1), sha); #endif PyMem_Free(new_path); if (!result[i]) { goto error; } } Py_DECREF(items); return result; error: if (result) free_objects(result, i); Py_DECREF(items); return NULL; } /** * Use strcmp to compare the paths of two TreeEntry objects. */ static int entry_path_cmp(PyObject *entry1, PyObject *entry2) { PyObject *path1 = NULL, *path2 = NULL; int result = 0; path1 = PyObject_GetAttrString(entry1, "path"); if (!path1) goto done; if (!PyString_Check(path1)) { PyErr_SetString(PyExc_TypeError, "path is not a (byte)string"); goto done; } path2 = PyObject_GetAttrString(entry2, "path"); if (!path2) goto done; if (!PyString_Check(path2)) { PyErr_SetString(PyExc_TypeError, "path is not a (byte)string"); goto done; } result = strcmp(PyString_AS_STRING(path1), PyString_AS_STRING(path2)); done: Py_XDECREF(path1); Py_XDECREF(path2); return result; } static PyObject *py_merge_entries(PyObject *self, PyObject *args) { PyObject *tree1, *tree2, **entries1 = NULL, **entries2 = NULL; PyObject *e1, *e2, *pair, *result = NULL; - Py_ssize_t n1 = 0, n2 = 0, i1 = 0, i2 = 0; - int path_len; + Py_ssize_t n1 = 0, n2 = 0, i1 = 0, i2 = 0, path_len; char *path_str; int cmp; #if PY_MAJOR_VERSION >= 3 if (!PyArg_ParseTuple(args, "y#OO", &path_str, &path_len, &tree1, &tree2)) #else if (!PyArg_ParseTuple(args, "s#OO", &path_str, &path_len, &tree1, &tree2)) #endif return NULL; entries1 = tree_entries(path_str, path_len, tree1, &n1); if (!entries1) goto error; entries2 = tree_entries(path_str, path_len, tree2, &n2); if (!entries2) goto error; result = PyList_New(0); if (!result) goto error; while (i1 < n1 && i2 < n2) { cmp = entry_path_cmp(entries1[i1], entries2[i2]); if (PyErr_Occurred()) goto error; if (!cmp) { e1 = entries1[i1++]; e2 = entries2[i2++]; } else if (cmp < 0) { e1 = entries1[i1++]; e2 = null_entry; } else { e1 = null_entry; e2 = entries2[i2++]; } pair = PyTuple_Pack(2, e1, e2); if (!pair) goto error; PyList_Append(result, pair); Py_DECREF(pair); } while (i1 < n1) { pair = PyTuple_Pack(2, entries1[i1++], null_entry); if (!pair) goto error; PyList_Append(result, pair); Py_DECREF(pair); } while (i2 < n2) { pair = PyTuple_Pack(2, null_entry, entries2[i2++]); if (!pair) goto error; PyList_Append(result, pair); Py_DECREF(pair); } goto done; error: Py_XDECREF(result); result = NULL; done: if (entries1) free_objects(entries1, n1); if (entries2) free_objects(entries2, n2); return result; } static PyObject *py_is_tree(PyObject *self, PyObject *args) { PyObject *entry, *mode, *result; long lmode; if (!PyArg_ParseTuple(args, "O", &entry)) return NULL; mode = PyObject_GetAttrString(entry, "mode"); if (!mode) return NULL; if (mode == Py_None) { result = Py_False; Py_INCREF(result); } else { lmode = PyInt_AsLong(mode); if (lmode == -1 && PyErr_Occurred()) { Py_DECREF(mode); return NULL; } result = PyBool_FromLong(S_ISDIR((mode_t)lmode)); } Py_DECREF(mode); return result; } static Py_hash_t add_hash(PyObject *get, PyObject *set, char *str, int n) { PyObject *str_obj = NULL, *hash_obj = NULL, *value = NULL, *set_value = NULL; Py_hash_t hash; /* It would be nice to hash without copying str into a PyString, but that * isn't exposed by the API. */ str_obj = PyString_FromStringAndSize(str, n); if (!str_obj) goto error; hash = PyObject_Hash(str_obj); if (hash == -1) goto error; hash_obj = PyInt_FromLong(hash); if (!hash_obj) goto error; value = PyObject_CallFunctionObjArgs(get, hash_obj, NULL); if (!value) goto error; set_value = PyObject_CallFunction(set, "(Ol)", hash_obj, PyInt_AS_LONG(value) + n); if (!set_value) goto error; Py_DECREF(str_obj); Py_DECREF(hash_obj); Py_DECREF(value); Py_DECREF(set_value); return 0; error: Py_XDECREF(str_obj); Py_XDECREF(hash_obj); Py_XDECREF(value); Py_XDECREF(set_value); return -1; } static PyObject *py_count_blocks(PyObject *self, PyObject *args) { PyObject *obj, *chunks = NULL, *chunk, *counts = NULL, *get = NULL, *set = NULL; char *chunk_str, *block = NULL; Py_ssize_t num_chunks, chunk_len; int i, j, n = 0; char c; if (!PyArg_ParseTuple(args, "O", &obj)) goto error; counts = PyObject_CallFunctionObjArgs(defaultdict_cls, int_cls, NULL); if (!counts) goto error; get = PyObject_GetAttrString(counts, "__getitem__"); set = PyObject_GetAttrString(counts, "__setitem__"); chunks = PyObject_CallMethod(obj, "as_raw_chunks", NULL); if (!chunks) goto error; if (!PyList_Check(chunks)) { PyErr_SetString(PyExc_TypeError, "as_raw_chunks() did not return a list"); goto error; } num_chunks = PyList_GET_SIZE(chunks); block = PyMem_New(char, block_size); if (!block) { PyErr_NoMemory(); goto error; } for (i = 0; i < num_chunks; i++) { chunk = PyList_GET_ITEM(chunks, i); if (!PyString_Check(chunk)) { PyErr_SetString(PyExc_TypeError, "chunk is not a string"); goto error; } if (PyString_AsStringAndSize(chunk, &chunk_str, &chunk_len) == -1) goto error; for (j = 0; j < chunk_len; j++) { c = chunk_str[j]; block[n++] = c; if (c == '\n' || n == block_size) { if (add_hash(get, set, block, n) == -1) goto error; n = 0; } } } if (n && add_hash(get, set, block, n) == -1) goto error; Py_DECREF(chunks); Py_DECREF(get); Py_DECREF(set); PyMem_Free(block); return counts; error: Py_XDECREF(chunks); Py_XDECREF(get); Py_XDECREF(set); Py_XDECREF(counts); PyMem_Free(block); return NULL; } static PyMethodDef py_diff_tree_methods[] = { { "_is_tree", (PyCFunction)py_is_tree, METH_VARARGS, NULL }, { "_merge_entries", (PyCFunction)py_merge_entries, METH_VARARGS, NULL }, { "_count_blocks", (PyCFunction)py_count_blocks, METH_VARARGS, NULL }, { NULL, NULL, 0, NULL } }; static PyObject * moduleinit(void) { PyObject *m, *objects_mod = NULL, *diff_tree_mod = NULL; PyObject *block_size_obj = NULL; #if PY_MAJOR_VERSION >= 3 static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "_diff_tree", /* m_name */ NULL, /* m_doc */ -1, /* m_size */ py_diff_tree_methods, /* m_methods */ NULL, /* m_reload */ NULL, /* m_traverse */ NULL, /* m_clear*/ NULL, /* m_free */ }; m = PyModule_Create(&moduledef); #else m = Py_InitModule("_diff_tree", py_diff_tree_methods); #endif if (!m) goto error; objects_mod = PyImport_ImportModule("dulwich.objects"); if (!objects_mod) goto error; tree_entry_cls = PyObject_GetAttrString(objects_mod, "TreeEntry"); Py_DECREF(objects_mod); if (!tree_entry_cls) goto error; diff_tree_mod = PyImport_ImportModule("dulwich.diff_tree"); if (!diff_tree_mod) goto error; null_entry = PyObject_GetAttrString(diff_tree_mod, "_NULL_ENTRY"); if (!null_entry) goto error; block_size_obj = PyObject_GetAttrString(diff_tree_mod, "_BLOCK_SIZE"); if (!block_size_obj) goto error; block_size = (int)PyInt_AsLong(block_size_obj); if (PyErr_Occurred()) goto error; defaultdict_cls = PyObject_GetAttrString(diff_tree_mod, "defaultdict"); if (!defaultdict_cls) goto error; /* This is kind of hacky, but I don't know of a better way to get the * PyObject* version of int. */ int_cls = PyDict_GetItemString(PyEval_GetBuiltins(), "int"); if (!int_cls) { PyErr_SetString(PyExc_NameError, "int"); goto error; } Py_DECREF(diff_tree_mod); return m; error: Py_XDECREF(objects_mod); Py_XDECREF(diff_tree_mod); Py_XDECREF(null_entry); Py_XDECREF(block_size_obj); Py_XDECREF(defaultdict_cls); Py_XDECREF(int_cls); return NULL; } #if PY_MAJOR_VERSION >= 3 PyMODINIT_FUNC PyInit__diff_tree(void) { return moduleinit(); } #else PyMODINIT_FUNC init_diff_tree(void) { moduleinit(); } #endif diff --git a/dulwich/diff_tree.py b/dulwich/diff_tree.py index 7166c97a..a1e8d63c 100644 --- a/dulwich/diff_tree.py +++ b/dulwich/diff_tree.py @@ -1,623 +1,624 @@ # diff_tree.py -- Utilities for diffing files and trees. # Copyright (C) 2010 Google, Inc. # # 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. # """Utilities for diffing files and trees.""" import sys from collections import ( defaultdict, namedtuple, ) from io import BytesIO from itertools import chain import stat from dulwich.objects import ( S_ISGITLINK, TreeEntry, ) # TreeChange type constants. CHANGE_ADD = 'add' CHANGE_MODIFY = 'modify' CHANGE_DELETE = 'delete' CHANGE_RENAME = 'rename' CHANGE_COPY = 'copy' CHANGE_UNCHANGED = 'unchanged' RENAME_CHANGE_TYPES = (CHANGE_RENAME, CHANGE_COPY) _NULL_ENTRY = TreeEntry(None, None, None) _MAX_SCORE = 100 RENAME_THRESHOLD = 60 MAX_FILES = 200 REWRITE_THRESHOLD = None class TreeChange(namedtuple('TreeChange', ['type', 'old', 'new'])): """Named tuple a single change between two trees.""" @classmethod def add(cls, new): return cls(CHANGE_ADD, _NULL_ENTRY, new) @classmethod def delete(cls, old): return cls(CHANGE_DELETE, old, _NULL_ENTRY) def _tree_entries(path, tree): result = [] if not tree: return result for entry in tree.iteritems(name_order=True): result.append(entry.in_path(path)) return result def _merge_entries(path, tree1, tree2): """Merge the entries of two trees. Args: path: A path to prepend to all tree entry names. tree1: The first Tree object to iterate, or None. tree2: The second Tree object to iterate, or None. Returns: A list of pairs of TreeEntry objects for each pair of entries in the trees. If an entry exists in one tree but not the other, the other entry will have all attributes set to None. If neither entry's path is None, they are guaranteed to match. """ entries1 = _tree_entries(path, tree1) entries2 = _tree_entries(path, tree2) i1 = i2 = 0 len1 = len(entries1) len2 = len(entries2) result = [] while i1 < len1 and i2 < len2: entry1 = entries1[i1] entry2 = entries2[i2] if entry1.path < entry2.path: result.append((entry1, _NULL_ENTRY)) i1 += 1 elif entry1.path > entry2.path: result.append((_NULL_ENTRY, entry2)) i2 += 1 else: result.append((entry1, entry2)) i1 += 1 i2 += 1 for i in range(i1, len1): result.append((entries1[i], _NULL_ENTRY)) for i in range(i2, len2): result.append((_NULL_ENTRY, entries2[i])) return result def _is_tree(entry): mode = entry.mode if mode is None: return False return stat.S_ISDIR(mode) def walk_trees(store, tree1_id, tree2_id, prune_identical=False): """Recursively walk all the entries of two trees. Iteration is depth-first pre-order, as in e.g. os.walk. Args: store: An ObjectStore for looking up objects. tree1_id: The SHA of the first Tree object to iterate, or None. tree2_id: The SHA of the second Tree object to iterate, or None. param prune_identical: If True, identical subtrees will not be walked. Returns: Iterator over Pairs of TreeEntry objects for each pair of entries in the trees and their subtrees recursively. If an entry exists in one tree but not the other, the other entry will have all attributes set to None. If neither entry's path is None, they are guaranteed to match. """ # This could be fairly easily generalized to >2 trees if we find a use # case. mode1 = tree1_id and stat.S_IFDIR or None mode2 = tree2_id and stat.S_IFDIR or None todo = [(TreeEntry(b'', mode1, tree1_id), TreeEntry(b'', mode2, tree2_id))] while todo: entry1, entry2 = todo.pop() is_tree1 = _is_tree(entry1) is_tree2 = _is_tree(entry2) if prune_identical and is_tree1 and is_tree2 and entry1 == entry2: continue tree1 = is_tree1 and store[entry1.sha] or None tree2 = is_tree2 and store[entry2.sha] or None path = entry1.path or entry2.path todo.extend(reversed(_merge_entries(path, tree1, tree2))) yield entry1, entry2 def _skip_tree(entry, include_trees): if entry.mode is None or (not include_trees and stat.S_ISDIR(entry.mode)): return _NULL_ENTRY return entry def tree_changes(store, tree1_id, tree2_id, want_unchanged=False, rename_detector=None, include_trees=False, change_type_same=False): """Find the differences between the contents of two trees. Args: store: An ObjectStore for looking up objects. tree1_id: The SHA of the source tree. tree2_id: The SHA of the target tree. want_unchanged: If True, include TreeChanges for unmodified entries as well. include_trees: Whether to include trees rename_detector: RenameDetector object for detecting renames. change_type_same: Whether to report change types in the same entry or as delete+add. Returns: Iterator over TreeChange instances for each change between the source and target tree. """ - if include_trees and rename_detector is not None: - raise NotImplementedError( - 'rename_detector and include_trees are mutually exclusive') if (rename_detector is not None and tree1_id is not None and tree2_id is not None): for change in rename_detector.changes_with_renames( - tree1_id, tree2_id, want_unchanged=want_unchanged): + tree1_id, tree2_id, want_unchanged=want_unchanged, + include_trees=include_trees): yield change return entries = walk_trees(store, tree1_id, tree2_id, prune_identical=(not want_unchanged)) for entry1, entry2 in entries: if entry1 == entry2 and not want_unchanged: continue # Treat entries for trees as missing. entry1 = _skip_tree(entry1, include_trees) entry2 = _skip_tree(entry2, include_trees) if entry1 != _NULL_ENTRY and entry2 != _NULL_ENTRY: if (stat.S_IFMT(entry1.mode) != stat.S_IFMT(entry2.mode) and not change_type_same): # File type changed: report as delete/add. yield TreeChange.delete(entry1) entry1 = _NULL_ENTRY change_type = CHANGE_ADD elif entry1 == entry2: change_type = CHANGE_UNCHANGED else: change_type = CHANGE_MODIFY elif entry1 != _NULL_ENTRY: change_type = CHANGE_DELETE elif entry2 != _NULL_ENTRY: change_type = CHANGE_ADD else: # Both were None because at least one was a tree. continue yield TreeChange(change_type, entry1, entry2) def _all_eq(seq, key, value): for e in seq: if key(e) != value: return False return True def _all_same(seq, key): return _all_eq(seq[1:], key, key(seq[0])) def tree_changes_for_merge(store, parent_tree_ids, tree_id, rename_detector=None): """Get the tree changes for a merge tree relative to all its parents. Args: store: An ObjectStore for looking up objects. parent_tree_ids: An iterable of the SHAs of the parent trees. tree_id: The SHA of the merge tree. rename_detector: RenameDetector object for detecting renames. Returns: Iterator over lists of TreeChange objects, one per conflicted path in the merge. Each list contains one element per parent, with the TreeChange for that path relative to that parent. An element may be None if it never existed in one parent and was deleted in two others. A path is only included in the output if it is a conflict, i.e. its SHA in the merge tree is not found in any of the parents, or in the case of deletes, if not all of the old SHAs match. """ all_parent_changes = [tree_changes(store, t, tree_id, rename_detector=rename_detector) for t in parent_tree_ids] num_parents = len(parent_tree_ids) changes_by_path = defaultdict(lambda: [None] * num_parents) # Organize by path. for i, parent_changes in enumerate(all_parent_changes): for change in parent_changes: if change.type == CHANGE_DELETE: path = change.old.path else: path = change.new.path changes_by_path[path][i] = change def old_sha(c): return c.old.sha def change_type(c): return c.type # Yield only conflicting changes. for _, changes in sorted(changes_by_path.items()): assert len(changes) == num_parents have = [c for c in changes if c is not None] if _all_eq(have, change_type, CHANGE_DELETE): if not _all_same(have, old_sha): yield changes elif not _all_same(have, change_type): yield changes elif None not in changes: # If no change was found relative to one parent, that means the SHA # must have matched the SHA in that parent, so it is not a # conflict. yield changes _BLOCK_SIZE = 64 def _count_blocks(obj): """Count the blocks in an object. Splits the data into blocks either on lines or <=64-byte chunks of lines. Args: obj: The object to count blocks for. Returns: A dict of block hashcode -> total bytes occurring. """ block_counts = defaultdict(int) block = BytesIO() n = 0 # Cache attrs as locals to avoid expensive lookups in the inner loop. block_write = block.write block_seek = block.seek block_truncate = block.truncate block_getvalue = block.getvalue for c in chain(*obj.as_raw_chunks()): if sys.version_info[0] == 3: c = c.to_bytes(1, 'big') block_write(c) n += 1 if c == b'\n' or n == _BLOCK_SIZE: value = block_getvalue() block_counts[hash(value)] += len(value) block_seek(0) block_truncate() n = 0 if n > 0: last_block = block_getvalue() block_counts[hash(last_block)] += len(last_block) return block_counts def _common_bytes(blocks1, blocks2): """Count the number of common bytes in two block count dicts. Args: block1: The first dict of block hashcode -> total bytes. block2: The second dict of block hashcode -> total bytes. Returns: The number of bytes in common between blocks1 and blocks2. This is only approximate due to possible hash collisions. """ # Iterate over the smaller of the two dicts, since this is symmetrical. if len(blocks1) > len(blocks2): blocks1, blocks2 = blocks2, blocks1 score = 0 for block, count1 in blocks1.items(): count2 = blocks2.get(block) if count2: score += min(count1, count2) return score def _similarity_score(obj1, obj2, block_cache=None): """Compute a similarity score for two objects. Args: obj1: The first object to score. obj2: The second object to score. block_cache: An optional dict of SHA to block counts to cache results between calls. Returns: The similarity score between the two objects, defined as the number of bytes in common between the two objects divided by the maximum size, scaled to the range 0-100. """ if block_cache is None: block_cache = {} if obj1.id not in block_cache: block_cache[obj1.id] = _count_blocks(obj1) if obj2.id not in block_cache: block_cache[obj2.id] = _count_blocks(obj2) common_bytes = _common_bytes(block_cache[obj1.id], block_cache[obj2.id]) max_size = max(obj1.raw_length(), obj2.raw_length()) if not max_size: return _MAX_SCORE return int(float(common_bytes) * _MAX_SCORE / max_size) def _tree_change_key(entry): # Sort by old path then new path. If only one exists, use it for both keys. path1 = entry.old.path path2 = entry.new.path if path1 is None: path1 = path2 if path2 is None: path2 = path1 return (path1, path2) class RenameDetector(object): """Object for handling rename detection between two trees.""" def __init__(self, store, rename_threshold=RENAME_THRESHOLD, max_files=MAX_FILES, rewrite_threshold=REWRITE_THRESHOLD, find_copies_harder=False): """Initialize the rename detector. Args: store: An ObjectStore for looking up objects. rename_threshold: The threshold similarity score for considering an add/delete pair to be a rename/copy; see _similarity_score. max_files: The maximum number of adds and deletes to consider, or None for no limit. The detector is guaranteed to compare no more than max_files ** 2 add/delete pairs. This limit is provided because rename detection can be quadratic in the project size. If the limit is exceeded, no content rename detection is attempted. rewrite_threshold: The threshold similarity score below which a modify should be considered a delete/add, or None to not break modifies; see _similarity_score. find_copies_harder: If True, consider unmodified files when detecting copies. """ self._store = store self._rename_threshold = rename_threshold self._rewrite_threshold = rewrite_threshold self._max_files = max_files self._find_copies_harder = find_copies_harder self._want_unchanged = False def _reset(self): self._adds = [] self._deletes = [] self._changes = [] def _should_split(self, change): if (self._rewrite_threshold is None or change.type != CHANGE_MODIFY or change.old.sha == change.new.sha): return False old_obj = self._store[change.old.sha] new_obj = self._store[change.new.sha] return _similarity_score(old_obj, new_obj) < self._rewrite_threshold def _add_change(self, change): if change.type == CHANGE_ADD: self._adds.append(change) elif change.type == CHANGE_DELETE: self._deletes.append(change) elif self._should_split(change): self._deletes.append(TreeChange.delete(change.old)) self._adds.append(TreeChange.add(change.new)) elif ((self._find_copies_harder and change.type == CHANGE_UNCHANGED) or change.type == CHANGE_MODIFY): # Treat all modifies as potential deletes for rename detection, # but don't split them (to avoid spurious renames). Setting # find_copies_harder means we treat unchanged the same as # modified. self._deletes.append(change) else: self._changes.append(change) def _collect_changes(self, tree1_id, tree2_id): want_unchanged = self._find_copies_harder or self._want_unchanged for change in tree_changes(self._store, tree1_id, tree2_id, - want_unchanged=want_unchanged): + want_unchanged=want_unchanged, + include_trees=self._include_trees): self._add_change(change) def _prune(self, add_paths, delete_paths): self._adds = [a for a in self._adds if a.new.path not in add_paths] self._deletes = [d for d in self._deletes if d.old.path not in delete_paths] def _find_exact_renames(self): add_map = defaultdict(list) for add in self._adds: add_map[add.new.sha].append(add.new) delete_map = defaultdict(list) for delete in self._deletes: # Keep track of whether the delete was actually marked as a delete. # If not, it needs to be marked as a copy. is_delete = delete.type == CHANGE_DELETE delete_map[delete.old.sha].append((delete.old, is_delete)) add_paths = set() delete_paths = set() for sha, sha_deletes in delete_map.items(): sha_adds = add_map[sha] for (old, is_delete), new in zip(sha_deletes, sha_adds): if stat.S_IFMT(old.mode) != stat.S_IFMT(new.mode): continue if is_delete: delete_paths.add(old.path) add_paths.add(new.path) new_type = is_delete and CHANGE_RENAME or CHANGE_COPY self._changes.append(TreeChange(new_type, old, new)) num_extra_adds = len(sha_adds) - len(sha_deletes) # TODO(dborowitz): Less arbitrary way of dealing with extra copies. old = sha_deletes[0][0] if num_extra_adds > 0: for new in sha_adds[-num_extra_adds:]: add_paths.add(new.path) self._changes.append(TreeChange(CHANGE_COPY, old, new)) self._prune(add_paths, delete_paths) def _should_find_content_renames(self): return len(self._adds) * len(self._deletes) <= self._max_files ** 2 def _rename_type(self, check_paths, delete, add): if check_paths and delete.old.path == add.new.path: # If the paths match, this must be a split modify, so make sure it # comes out as a modify. return CHANGE_MODIFY elif delete.type != CHANGE_DELETE: # If it's in deletes but not marked as a delete, it must have been # added due to find_copies_harder, and needs to be marked as a # copy. return CHANGE_COPY return CHANGE_RENAME def _find_content_rename_candidates(self): candidates = self._candidates = [] # TODO: Optimizations: # - Compare object sizes before counting blocks. # - Skip if delete's S_IFMT differs from all adds. # - Skip if adds or deletes is empty. # Match C git's behavior of not attempting to find content renames if # the matrix size exceeds the threshold. if not self._should_find_content_renames(): return block_cache = {} check_paths = self._rename_threshold is not None for delete in self._deletes: if S_ISGITLINK(delete.old.mode): continue # Git links don't exist in this repo. old_sha = delete.old.sha old_obj = self._store[old_sha] block_cache[old_sha] = _count_blocks(old_obj) for add in self._adds: if stat.S_IFMT(delete.old.mode) != stat.S_IFMT(add.new.mode): continue new_obj = self._store[add.new.sha] score = _similarity_score(old_obj, new_obj, block_cache=block_cache) if score > self._rename_threshold: new_type = self._rename_type(check_paths, delete, add) rename = TreeChange(new_type, delete.old, add.new) candidates.append((-score, rename)) def _choose_content_renames(self): # Sort scores from highest to lowest, but keep names in ascending # order. self._candidates.sort() delete_paths = set() add_paths = set() for _, change in self._candidates: new_path = change.new.path if new_path in add_paths: continue old_path = change.old.path orig_type = change.type if old_path in delete_paths: change = TreeChange(CHANGE_COPY, change.old, change.new) # If the candidate was originally a copy, that means it came from a # modified or unchanged path, so we don't want to prune it. if orig_type != CHANGE_COPY: delete_paths.add(old_path) add_paths.add(new_path) self._changes.append(change) self._prune(add_paths, delete_paths) def _join_modifies(self): if self._rewrite_threshold is None: return modifies = {} delete_map = dict((d.old.path, d) for d in self._deletes) for add in self._adds: path = add.new.path delete = delete_map.get(path) if (delete is not None and stat.S_IFMT(delete.old.mode) == stat.S_IFMT(add.new.mode)): modifies[path] = TreeChange(CHANGE_MODIFY, delete.old, add.new) self._adds = [a for a in self._adds if a.new.path not in modifies] self._deletes = [a for a in self._deletes if a.new.path not in modifies] self._changes += modifies.values() def _sorted_changes(self): result = [] result.extend(self._adds) result.extend(self._deletes) result.extend(self._changes) result.sort(key=_tree_change_key) return result def _prune_unchanged(self): if self._want_unchanged: return self._deletes = [ d for d in self._deletes if d.type != CHANGE_UNCHANGED] - def changes_with_renames(self, tree1_id, tree2_id, want_unchanged=False): + def changes_with_renames(self, tree1_id, tree2_id, want_unchanged=False, + include_trees=False): """Iterate TreeChanges between two tree SHAs, with rename detection.""" self._reset() self._want_unchanged = want_unchanged + self._include_trees = include_trees self._collect_changes(tree1_id, tree2_id) self._find_exact_renames() self._find_content_rename_candidates() self._choose_content_renames() self._join_modifies() self._prune_unchanged() return self._sorted_changes() # Hold on to the pure-python implementations for testing. _is_tree_py = _is_tree _merge_entries_py = _merge_entries _count_blocks_py = _count_blocks try: # Try to import C versions from dulwich._diff_tree import _is_tree, _merge_entries, _count_blocks except ImportError: pass diff --git a/dulwich/index.py b/dulwich/index.py index 1b2289f6..3101a27f 100644 --- a/dulwich/index.py +++ b/dulwich/index.py @@ -1,841 +1,842 @@ # 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. 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. 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) + if mode & 0o100: + ret |= 0o111 return ret class Index(object): """A Git Index file.""" def __init__(self, filename): """Open an 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. 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. 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 + return entry.sha, cleanup_mode(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. 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. 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. 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. 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. 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. 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 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 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 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 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. 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. 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. 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. Args: root_path: Root filesystem path tree_path: Git tree path as bytes 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. Args: fs_path: File system path. fs_encoding: File system encoding 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 Args: path: Path to create an index entry for object_store: Optional object store to save new blobs in 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. 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. Args: index: Index file root_path: Root path to access from include_deleted: Include deleted entries with sha and mode set to None 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. Args: index: Index file root_path: Root path to access from include_deleted: Include deleted entries with sha and mode set to None 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'. 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/object_store.py b/dulwich/object_store.py index 3a073823..5cfea792 100644 --- a/dulwich/object_store.py +++ b/dulwich/object_store.py @@ -1,1383 +1,1385 @@ # 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. 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. 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. 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. 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): + include_trees=False, change_type_same=False, + rename_detector=None): """Find the differences between the contents of two trees 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. 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): + change_type_same=change_type_same, + rename_detector=rename_detector): 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. 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. 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. get_tagged: Function that returns a dict of pointed-to sha -> tag sha for including tags. get_parents: Optional function for getting the parents of a commit. 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. 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. 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. 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. 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. Args: heads: commits to start from common: commits to end at, or empty set to walk repository completely get_parents: Optional function for getting the parents of a commit. 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. 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. 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. Args: objects: Iterable over (object, path) tuples, should support __len__. 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. 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 packs directory. 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. Args: read_all: Read function that blocks until the number of requested bytes are read. read_some: Read function that returns at least one byte, but may not return the number of bytes requested. 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 packs directory. 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. 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. 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. 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. 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. 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. 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. Args: read_all: Read function that blocks until the number of requested bytes are read. 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. 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 the underlying object store, not if it would be yielded by the iterator. 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 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. 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. 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 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. 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. Args: object_store: Object store containing at least all objects to be sent 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. 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. 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. Args: object_store: Object store to store new objects in and retrieve old ones from. 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/patch.py b/dulwich/patch.py index ea1bdfe1..3cc4eba2 100644 --- a/dulwich/patch.py +++ b/dulwich/patch.py @@ -1,374 +1,374 @@ # patch.py -- For dealing with packed-style patches. # Copyright (C) 2009-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 git am-style patches. These patches are basically unified diffs with some extra metadata tacked on. """ from difflib import SequenceMatcher import email.parser import time from dulwich.objects import ( Blob, Commit, S_ISGITLINK, ) FIRST_FEW_BYTES = 8000 def write_commit_patch(f, commit, contents, progress, version=None, encoding=None): """Write a individual file patch. Args: commit: Commit object progress: Tuple with current patch number and total. Returns: tuple with filename and contents """ encoding = encoding or getattr(f, "encoding", "ascii") if isinstance(contents, str): contents = contents.encode(encoding) (num, total) = progress f.write(b"From " + commit.id + b" " + time.ctime(commit.commit_time).encode(encoding) + b"\n") f.write(b"From: " + commit.author + b"\n") f.write(b"Date: " + time.strftime("%a, %d %b %Y %H:%M:%S %Z").encode(encoding) + b"\n") f.write(("Subject: [PATCH %d/%d] " % (num, total)).encode(encoding) + commit.message + b"\n") f.write(b"\n") f.write(b"---\n") try: import subprocess p = subprocess.Popen(["diffstat"], stdout=subprocess.PIPE, stdin=subprocess.PIPE) except (ImportError, OSError): pass # diffstat not available? else: (diffstat, _) = p.communicate(contents) f.write(diffstat) f.write(b"\n") f.write(contents) f.write(b"-- \n") if version is None: from dulwich import __version__ as dulwich_version f.write(b"Dulwich %d.%d.%d\n" % dulwich_version) else: f.write(version.encode(encoding) + b"\n") def get_summary(commit): """Determine the summary line for use in a filename. Args: commit: Commit Returns: Summary string """ decoded = commit.message.decode(errors='replace') return decoded.splitlines()[0].replace(" ", "-") # Unified Diff def _format_range_unified(start, stop): 'Convert range to the "ed" format' # Per the diff spec at http://www.unix.org/single_unix_specification/ beginning = start + 1 # lines start numbering with one length = stop - start if length == 1: return '{}'.format(beginning) if not length: beginning -= 1 # empty ranges begin at line just before the range return '{},{}'.format(beginning, length) def unified_diff(a, b, fromfile='', tofile='', fromfiledate='', tofiledate='', n=3, lineterm='\n'): """difflib.unified_diff that can detect "No newline at end of file" as original "git diff" does. Based on the same function in Python2.7 difflib.py """ started = False for group in SequenceMatcher(None, a, b).get_grouped_opcodes(n): if not started: started = True fromdate = '\t{}'.format(fromfiledate) if fromfiledate else '' todate = '\t{}'.format(tofiledate) if tofiledate else '' yield '--- {}{}{}'.format( fromfile.decode("ascii"), fromdate, lineterm ).encode('ascii') yield '+++ {}{}{}'.format( tofile.decode("ascii"), todate, lineterm ).encode('ascii') first, last = group[0], group[-1] file1_range = _format_range_unified(first[1], last[2]) file2_range = _format_range_unified(first[3], last[4]) yield '@@ -{} +{} @@{}'.format( file1_range, file2_range, lineterm ).encode('ascii') for tag, i1, i2, j1, j2 in group: if tag == 'equal': for line in a[i1:i2]: yield b' ' + line continue if tag in ('replace', 'delete'): for line in a[i1:i2]: if not line[-1:] == b'\n': line += b'\n\\ No newline at end of file\n' yield b'-' + line if tag in ('replace', 'insert'): for line in b[j1:j2]: if not line[-1:] == b'\n': line += b'\n\\ No newline at end of file\n' yield b'+' + line def is_binary(content): """See if the first few bytes contain any null characters. Args: content: Bytestring to check for binary content """ return b'\0' in content[:FIRST_FEW_BYTES] def shortid(hexsha): if hexsha is None: return b"0" * 7 else: return hexsha[:7] def patch_filename(p, root): if p is None: return b"/dev/null" else: return root + b"/" + p def write_object_diff(f, store, old_file, new_file, diff_binary=False): """Write the diff for an object. Args: f: File-like object to write to store: Store to retrieve objects from, if necessary old_file: (path, mode, hexsha) tuple new_file: (path, mode, hexsha) tuple diff_binary: Whether to diff files even if they are considered binary files by is_binary(). Note: the tuple elements should be None for nonexistant files """ (old_path, old_mode, old_id) = old_file (new_path, new_mode, new_id) = new_file patched_old_path = patch_filename(old_path, b"a") patched_new_path = patch_filename(new_path, b"b") def content(mode, hexsha): if hexsha is None: return Blob.from_string(b'') elif S_ISGITLINK(mode): - return Blob.from_string(b"Submodule commit " + hexsha + b"\n") + return Blob.from_string(b"Subproject commit " + hexsha + b"\n") else: return store[hexsha] def lines(content): if not content: return [] else: return content.splitlines() f.writelines(gen_diff_header( (old_path, new_path), (old_mode, new_mode), (old_id, new_id))) old_content = content(old_mode, old_id) new_content = content(new_mode, new_id) if not diff_binary and ( is_binary(old_content.data) or is_binary(new_content.data)): binary_diff = ( b"Binary files " + patched_old_path + b" and " + patched_new_path + b" differ\n" ) f.write(binary_diff) else: f.writelines(unified_diff(lines(old_content), lines(new_content), patched_old_path, patched_new_path)) # TODO(jelmer): Support writing unicode, rather than bytes. def gen_diff_header(paths, modes, shas): """Write a blob diff header. Args: paths: Tuple with old and new path modes: Tuple with old and new modes shas: Tuple with old and new shas """ (old_path, new_path) = paths (old_mode, new_mode) = modes (old_sha, new_sha) = shas if old_path is None and new_path is not None: old_path = new_path if new_path is None and old_path is not None: new_path = old_path old_path = patch_filename(old_path, b"a") new_path = patch_filename(new_path, b"b") yield b"diff --git " + old_path + b" " + new_path + b"\n" if old_mode != new_mode: if new_mode is not None: if old_mode is not None: yield ("old file mode %o\n" % old_mode).encode('ascii') yield ("new file mode %o\n" % new_mode).encode('ascii') else: yield ("deleted file mode %o\n" % old_mode).encode('ascii') yield b"index " + shortid(old_sha) + b".." + shortid(new_sha) if new_mode is not None and old_mode is not None: yield (" %o" % new_mode).encode('ascii') yield b"\n" # TODO(jelmer): Support writing unicode, rather than bytes. def write_blob_diff(f, old_file, new_file): """Write blob diff. Args: f: File-like object to write to old_file: (path, mode, hexsha) tuple (None if nonexisting) new_file: (path, mode, hexsha) tuple (None if nonexisting) Note: The use of write_object_diff is recommended over this function. """ (old_path, old_mode, old_blob) = old_file (new_path, new_mode, new_blob) = new_file patched_old_path = patch_filename(old_path, b"a") patched_new_path = patch_filename(new_path, b"b") def lines(blob): if blob is not None: return blob.splitlines() else: return [] f.writelines(gen_diff_header( (old_path, new_path), (old_mode, new_mode), (getattr(old_blob, "id", None), getattr(new_blob, "id", None)))) old_contents = lines(old_blob) new_contents = lines(new_blob) f.writelines(unified_diff(old_contents, new_contents, patched_old_path, patched_new_path)) def write_tree_diff(f, store, old_tree, new_tree, diff_binary=False): """Write tree diff. Args: f: File-like object to write to. old_tree: Old tree id new_tree: New tree id diff_binary: Whether to diff files even if they are considered binary files by is_binary(). """ changes = store.tree_changes(old_tree, new_tree) for (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) in changes: write_object_diff(f, store, (oldpath, oldmode, oldsha), (newpath, newmode, newsha), diff_binary=diff_binary) def git_am_patch_split(f, encoding=None): """Parse a git-am-style patch and split it up into bits. Args: f: File-like object to parse encoding: Encoding to use when creating Git objects Returns: Tuple with commit object, diff contents and git version """ encoding = encoding or getattr(f, "encoding", "ascii") encoding = encoding or "ascii" contents = f.read() if (isinstance(contents, bytes) and getattr(email.parser, "BytesParser", None)): parser = email.parser.BytesParser() msg = parser.parsebytes(contents) else: parser = email.parser.Parser() msg = parser.parsestr(contents) return parse_patch_message(msg, encoding) def parse_patch_message(msg, encoding=None): """Extract a Commit object and patch from an e-mail message. Args: msg: An email message (email.message.Message) encoding: Encoding to use to encode Git commits Returns: Tuple with commit object, diff contents and git version """ c = Commit() c.author = msg["from"].encode(encoding) c.committer = msg["from"].encode(encoding) try: patch_tag_start = msg["subject"].index("[PATCH") except ValueError: subject = msg["subject"] else: close = msg["subject"].index("] ", patch_tag_start) subject = msg["subject"][close+2:] c.message = (subject.replace("\n", "") + "\n").encode(encoding) first = True body = msg.get_payload(decode=True) lines = body.splitlines(True) line_iter = iter(lines) for line in line_iter: if line == b"---\n": break if first: if line.startswith(b"From: "): c.author = line[len(b"From: "):].rstrip() else: c.message += b"\n" + line first = False else: c.message += line diff = b"" for line in line_iter: if line == b"-- \n": break diff += line try: version = next(line_iter).rstrip(b"\n") except StopIteration: version = None return c, diff, version diff --git a/dulwich/porcelain.py b/dulwich/porcelain.py index 5ad41e8c..ccb6c155 100644 --- a/dulwich/porcelain.py +++ b/dulwich/porcelain.py @@ -1,1583 +1,1591 @@ # porcelain.py -- Porcelain-like layer on top of Dulwich # Copyright (C) 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. # """Simple wrapper that provides porcelain-like functions on top of Dulwich. Currently implemented: * archive * add * branch{_create,_delete,_list} * check-ignore * checkout * clone * commit * commit-tree * daemon * describe * diff-tree * fetch * init * ls-files * ls-remote * ls-tree * pull * push * rm * remote{_add} * receive-pack * reset * rev-list * tag{_create,_delete,_list} * upload-pack * update-server-info * status * symbolic-ref These functions are meant to behave similarly to the git subcommands. Differences in behaviour are considered bugs. Functions should generally accept both unicode strings and bytestrings """ from collections import namedtuple from contextlib import ( closing, contextmanager, ) from io import BytesIO, RawIOBase import datetime import os import posixpath import shutil import stat import sys import time from dulwich.archive import ( tar_stream, ) from dulwich.client import ( get_transport_and_path, ) from dulwich.config import ( StackedConfig, ) from dulwich.diff_tree import ( CHANGE_ADD, CHANGE_DELETE, CHANGE_MODIFY, CHANGE_RENAME, CHANGE_COPY, RENAME_CHANGE_TYPES, ) from dulwich.errors import ( SendPackError, UpdateRefsError, ) from dulwich.ignore import IgnoreFilterManager from dulwich.index import ( blob_from_path_and_stat, get_unstaged_changes, ) from dulwich.object_store import ( tree_lookup_path, ) from dulwich.objects import ( Commit, Tag, format_timezone, parse_timezone, pretty_format_tree_entry, ) from dulwich.objectspec import ( parse_commit, parse_object, parse_ref, parse_reftuples, parse_tree, ) from dulwich.pack import ( write_pack_index, write_pack_objects, ) from dulwich.patch import write_tree_diff from dulwich.protocol import ( Protocol, ZERO_SHA, ) from dulwich.refs import ( ANNOTATED_TAG_SUFFIX, LOCAL_BRANCH_PREFIX, strip_peeled_refs, ) from dulwich.repo import (BaseRepo, Repo) from dulwich.server import ( FileSystemBackend, TCPGitServer, ReceivePackHandler, UploadPackHandler, update_server_info as server_update_server_info, ) # Module level tuple definition for status output GitStatus = namedtuple('GitStatus', 'staged unstaged untracked') class NoneStream(RawIOBase): """Fallback if stdout or stderr are unavailable, does nothing.""" def read(self, size=-1): return None def readall(self): return None def readinto(self, b): return None def write(self, b): return None if sys.version_info[0] == 2: default_bytes_out_stream = sys.stdout or NoneStream() default_bytes_err_stream = sys.stderr or NoneStream() else: default_bytes_out_stream = ( getattr(sys.stdout, 'buffer', None) or NoneStream()) default_bytes_err_stream = ( getattr(sys.stderr, 'buffer', None) or NoneStream()) DEFAULT_ENCODING = 'utf-8' class RemoteExists(Exception): """Raised when the remote already exists.""" def open_repo(path_or_repo): """Open an argument that can be a repository or a path for a repository.""" if isinstance(path_or_repo, BaseRepo): return path_or_repo return Repo(path_or_repo) @contextmanager def _noop_context_manager(obj): """Context manager that has the same api as closing but does nothing.""" yield obj def open_repo_closing(path_or_repo): """Open an argument that can be a repository or a path for a repository. returns a context manager that will close the repo on exit if the argument is a path, else does nothing if the argument is a repo. """ if isinstance(path_or_repo, BaseRepo): return _noop_context_manager(path_or_repo) return closing(Repo(path_or_repo)) def path_to_tree_path(repopath, path): """Convert a path to a path usable in an index, e.g. bytes and relative to the repository root. Args: repopath: Repository path, absolute or relative to the cwd path: A path, absolute or relative to the cwd Returns: A path formatted for use in e.g. an index """ if not isinstance(path, bytes): path = path.encode(sys.getfilesystemencoding()) if not isinstance(repopath, bytes): repopath = repopath.encode(sys.getfilesystemencoding()) treepath = os.path.relpath(path, repopath) if treepath.startswith(b'..'): raise ValueError('Path not in repo') if os.path.sep != '/': treepath = treepath.replace(os.path.sep.encode('ascii'), b'/') return treepath def archive(repo, committish=None, outstream=default_bytes_out_stream, errstream=default_bytes_err_stream): """Create an archive. Args: repo: Path of repository for which to generate an archive. committish: Commit SHA1 or ref to use outstream: Output stream (defaults to stdout) errstream: Error stream (defaults to stderr) """ if committish is None: committish = "HEAD" with open_repo_closing(repo) as repo_obj: c = parse_commit(repo_obj, committish) for chunk in tar_stream( repo_obj.object_store, repo_obj.object_store[c.tree], c.commit_time): outstream.write(chunk) def update_server_info(repo="."): """Update server info files for a repository. Args: repo: path to the repository """ with open_repo_closing(repo) as r: server_update_server_info(r) def symbolic_ref(repo, ref_name, force=False): """Set git symbolic ref into HEAD. Args: repo: path to the repository ref_name: short name of the new ref force: force settings without checking if it exists in refs/heads """ with open_repo_closing(repo) as repo_obj: ref_path = _make_branch_ref(ref_name) if not force and ref_path not in repo_obj.refs.keys(): raise ValueError('fatal: ref `%s` is not a ref' % ref_name) repo_obj.refs.set_symbolic_ref(b'HEAD', ref_path) def commit(repo=".", message=None, author=None, committer=None, encoding=None): """Create a new commit. Args: repo: Path to repository message: Optional commit message author: Optional author name and email committer: Optional committer name and email Returns: SHA1 of the new commit """ # FIXME: Support --all argument # FIXME: Support --signoff argument if getattr(message, 'encode', None): message = message.encode(encoding or DEFAULT_ENCODING) if getattr(author, 'encode', None): author = author.encode(encoding or DEFAULT_ENCODING) if getattr(committer, 'encode', None): committer = committer.encode(encoding or DEFAULT_ENCODING) with open_repo_closing(repo) as r: return r.do_commit( message=message, author=author, committer=committer, encoding=encoding) def commit_tree(repo, tree, message=None, author=None, committer=None): """Create a new commit object. Args: repo: Path to repository tree: An existing tree object author: Optional author name and email committer: Optional committer name and email """ with open_repo_closing(repo) as r: return r.do_commit( message=message, tree=tree, committer=committer, author=author) def init(path=".", bare=False): """Create a new git repository. Args: path: Path to repository. bare: Whether to create a bare repository. Returns: A Repo instance """ if not os.path.exists(path): os.mkdir(path) if bare: return Repo.init_bare(path) else: return Repo.init(path) def clone(source, target=None, bare=False, checkout=None, errstream=default_bytes_err_stream, outstream=None, origin=b"origin", depth=None, **kwargs): """Clone a local or remote git repository. Args: source: Path or URL for source repository target: Path to target repository (optional) bare: Whether or not to create a bare repository checkout: Whether or not to check-out HEAD after cloning errstream: Optional stream to write progress to outstream: Optional stream to write progress to (deprecated) origin: Name of remote from the repository used to clone depth: Depth to fetch at Returns: The new repository """ # TODO(jelmer): This code overlaps quite a bit with Repo.clone if outstream is not None: import warnings warnings.warn( "outstream= has been deprecated in favour of errstream=.", DeprecationWarning, stacklevel=3) errstream = outstream if checkout is None: checkout = (not bare) if checkout and bare: raise ValueError("checkout and bare are incompatible") if target is None: target = source.split("/")[-1] if not os.path.exists(target): os.mkdir(target) if bare: r = Repo.init_bare(target) else: r = Repo.init(target) reflog_message = b'clone: from ' + source.encode('utf-8') try: fetch_result = fetch( r, source, origin, errstream=errstream, message=reflog_message, depth=depth, **kwargs) target_config = r.get_config() if not isinstance(source, bytes): source = source.encode(DEFAULT_ENCODING) target_config.set((b'remote', origin), b'url', source) target_config.set( (b'remote', origin), b'fetch', b'+refs/heads/*:refs/remotes/' + origin + b'/*') target_config.write_to_path() # TODO(jelmer): Support symref capability, # https://github.com/jelmer/dulwich/issues/485 try: head = r[fetch_result[b'HEAD']] except KeyError: head = None else: r[b'HEAD'] = head.id if checkout and not bare and head is not None: errstream.write(b'Checking out ' + head.id + b'\n') r.reset_index(head.tree) except BaseException: shutil.rmtree(target) r.close() raise return r def add(repo=".", paths=None): """Add files to the staging area. Args: repo: Repository for the files paths: Paths to add. No value passed stages all modified files. Returns: Tuple with set of added files and ignored files """ ignored = set() with open_repo_closing(repo) as r: ignore_manager = IgnoreFilterManager.from_repo(r) if not paths: paths = list( get_untracked_paths(os.getcwd(), r.path, r.open_index())) relpaths = [] if not isinstance(paths, list): paths = [paths] for p in paths: relpath = os.path.relpath(p, r.path) if relpath.startswith('..' + os.path.sep): raise ValueError('path %r is not in repo' % relpath) # FIXME: Support patterns, directories. if ignore_manager.is_ignored(relpath): ignored.add(relpath) continue relpaths.append(relpath) r.stage(relpaths) return (relpaths, ignored) def _is_subdir(subdir, parentdir): """Check whether subdir is parentdir or a subdir of parentdir If parentdir or subdir is a relative path, it will be disamgibuated relative to the pwd. """ parentdir_abs = os.path.realpath(parentdir) + os.path.sep subdir_abs = os.path.realpath(subdir) + os.path.sep return subdir_abs.startswith(parentdir_abs) # TODO: option to remove ignored files also, in line with `git clean -fdx` def clean(repo=".", target_dir=None): """Remove any untracked files from the target directory recursively Equivalent to running `git clean -fd` in target_dir. Args: repo: Repository where the files may be tracked target_dir: Directory to clean - current directory if None """ if target_dir is None: target_dir = os.getcwd() with open_repo_closing(repo) as r: if not _is_subdir(target_dir, r.path): raise ValueError("target_dir must be in the repo's working dir") index = r.open_index() ignore_manager = IgnoreFilterManager.from_repo(r) paths_in_wd = _walk_working_dir_paths(target_dir, r.path) # Reverse file visit order, so that files and subdirectories are # removed before containing directory for ap, is_dir in reversed(list(paths_in_wd)): if is_dir: # All subdirectories and files have been removed if untracked, # so dir contains no tracked files iff it is empty. is_empty = len(os.listdir(ap)) == 0 if is_empty: os.rmdir(ap) else: ip = path_to_tree_path(r.path, ap) is_tracked = ip in index rp = os.path.relpath(ap, r.path) is_ignored = ignore_manager.is_ignored(rp) if not is_tracked and not is_ignored: os.remove(ap) def remove(repo=".", paths=None, cached=False): """Remove files from the staging area. Args: repo: Repository for the files paths: Paths to remove """ with open_repo_closing(repo) as r: index = r.open_index() for p in paths: full_path = os.path.abspath(p).encode(sys.getfilesystemencoding()) tree_path = path_to_tree_path(r.path, p) try: index_sha = index[tree_path].sha except KeyError: raise Exception('%s did not match any files' % p) if not cached: try: st = os.lstat(full_path) except OSError: pass else: try: blob = blob_from_path_and_stat(full_path, st) except IOError: pass else: try: committed_sha = tree_lookup_path( r.__getitem__, r[r.head()].tree, tree_path)[1] except KeyError: committed_sha = None if blob.id != index_sha and index_sha != committed_sha: raise Exception( 'file has staged content differing ' 'from both the file and head: %s' % p) if index_sha != committed_sha: raise Exception( 'file has staged changes: %s' % p) os.remove(full_path) del index[tree_path] index.write() rm = remove def commit_decode(commit, contents, default_encoding=DEFAULT_ENCODING): - if commit.encoding is not None: - return contents.decode(commit.encoding, "replace") - return contents.decode(default_encoding, "replace") + if commit.encoding: + encoding = commit.encoding.decode('ascii') + else: + encoding = default_encoding + return contents.decode(encoding, "replace") + + +def commit_encode(commit, contents, default_encoding=DEFAULT_ENCODING): + if commit.encoding: + encoding = commit.encoding.decode('ascii') + else: + encoding = default_encoding + return contents.encode(encoding) def print_commit(commit, decode, outstream=sys.stdout): """Write a human-readable commit log entry. Args: commit: A `Commit` object outstream: A stream file to write to """ outstream.write("-" * 50 + "\n") outstream.write("commit: " + commit.id.decode('ascii') + "\n") if len(commit.parents) > 1: outstream.write( "merge: " + "...".join([c.decode('ascii') for c in commit.parents[1:]]) + "\n") outstream.write("Author: " + decode(commit.author) + "\n") if commit.author != commit.committer: outstream.write("Committer: " + decode(commit.committer) + "\n") time_tuple = time.gmtime(commit.author_time + commit.author_timezone) time_str = time.strftime("%a %b %d %Y %H:%M:%S", time_tuple) timezone_str = format_timezone(commit.author_timezone).decode('ascii') outstream.write("Date: " + time_str + " " + timezone_str + "\n") outstream.write("\n") outstream.write(decode(commit.message) + "\n") outstream.write("\n") def print_tag(tag, decode, outstream=sys.stdout): """Write a human-readable tag. Args: tag: A `Tag` object decode: Function for decoding bytes to unicode string outstream: A stream to write to """ outstream.write("Tagger: " + decode(tag.tagger) + "\n") time_tuple = time.gmtime(tag.tag_time + tag.tag_timezone) time_str = time.strftime("%a %b %d %Y %H:%M:%S", time_tuple) timezone_str = format_timezone(tag.tag_timezone).decode('ascii') outstream.write("Date: " + time_str + " " + timezone_str + "\n") outstream.write("\n") outstream.write(decode(tag.message) + "\n") outstream.write("\n") def show_blob(repo, blob, decode, outstream=sys.stdout): """Write a blob to a stream. Args: repo: A `Repo` object blob: A `Blob` object decode: Function for decoding bytes to unicode string outstream: A stream file to write to """ outstream.write(decode(blob.data)) def show_commit(repo, commit, decode, outstream=sys.stdout): """Show a commit to a stream. Args: repo: A `Repo` object commit: A `Commit` object decode: Function for decoding bytes to unicode string outstream: Stream to write to """ print_commit(commit, decode=decode, outstream=outstream) if commit.parents: parent_commit = repo[commit.parents[0]] base_tree = parent_commit.tree else: base_tree = None diffstream = BytesIO() write_tree_diff( diffstream, repo.object_store, base_tree, commit.tree) diffstream.seek(0) - outstream.write( - diffstream.getvalue().decode( - commit.encoding or DEFAULT_ENCODING, 'replace')) + outstream.write(commit_decode(commit, diffstream.getvalue())) def show_tree(repo, tree, decode, outstream=sys.stdout): """Print a tree to a stream. Args: repo: A `Repo` object tree: A `Tree` object decode: Function for decoding bytes to unicode string outstream: Stream to write to """ for n in tree: outstream.write(decode(n) + "\n") def show_tag(repo, tag, decode, outstream=sys.stdout): """Print a tag to a stream. Args: repo: A `Repo` object tag: A `Tag` object decode: Function for decoding bytes to unicode string outstream: Stream to write to """ print_tag(tag, decode, outstream) show_object(repo, repo[tag.object[1]], decode, outstream) def show_object(repo, obj, decode, outstream): return { b"tree": show_tree, b"blob": show_blob, b"commit": show_commit, b"tag": show_tag, }[obj.type_name](repo, obj, decode, outstream) def print_name_status(changes): """Print a simple status summary, listing changed files. """ for change in changes: if not change: continue if isinstance(change, list): change = change[0] if change.type == CHANGE_ADD: path1 = change.new.path path2 = '' kind = 'A' elif change.type == CHANGE_DELETE: path1 = change.old.path path2 = '' kind = 'D' elif change.type == CHANGE_MODIFY: path1 = change.new.path path2 = '' kind = 'M' elif change.type in RENAME_CHANGE_TYPES: path1 = change.old.path path2 = change.new.path if change.type == CHANGE_RENAME: kind = 'R' elif change.type == CHANGE_COPY: kind = 'C' yield '%-8s%-20s%-20s' % (kind, path1, path2) def log(repo=".", paths=None, outstream=sys.stdout, max_entries=None, reverse=False, name_status=False): """Write commit logs. Args: repo: Path to repository paths: Optional set of specific paths to print entries for outstream: Stream to write log output to reverse: Reverse order in which entries are printed name_status: Print name status max_entries: Optional maximum number of entries to display """ with open_repo_closing(repo) as r: walker = r.get_walker( max_entries=max_entries, paths=paths, reverse=reverse) for entry in walker: def decode(x): return commit_decode(entry.commit, x) print_commit(entry.commit, decode, outstream) if name_status: outstream.writelines( [l+'\n' for l in print_name_status(entry.changes())]) # TODO(jelmer): better default for encoding? def show(repo=".", objects=None, outstream=sys.stdout, default_encoding=DEFAULT_ENCODING): """Print the changes in a commit. Args: repo: Path to repository objects: Objects to show (defaults to [HEAD]) outstream: Stream to write to default_encoding: Default encoding to use if none is set in the commit """ if objects is None: objects = ["HEAD"] if not isinstance(objects, list): objects = [objects] with open_repo_closing(repo) as r: for objectish in objects: o = parse_object(r, objectish) if isinstance(o, Commit): def decode(x): return commit_decode(o, x, default_encoding) else: def decode(x): return x.decode(default_encoding) show_object(r, o, decode, outstream) def diff_tree(repo, old_tree, new_tree, outstream=sys.stdout): """Compares the content and mode of blobs found via two tree objects. Args: repo: Path to repository old_tree: Id of old tree new_tree: Id of new tree outstream: Stream to write to """ with open_repo_closing(repo) as r: write_tree_diff(outstream, r.object_store, old_tree, new_tree) def rev_list(repo, commits, outstream=sys.stdout): """Lists commit objects in reverse chronological order. Args: repo: Path to repository commits: Commits over which to iterate outstream: Stream to write to """ with open_repo_closing(repo) as r: for entry in r.get_walker(include=[r[c].id for c in commits]): outstream.write(entry.commit.id + b"\n") def tag(*args, **kwargs): import warnings warnings.warn("tag has been deprecated in favour of tag_create.", DeprecationWarning) return tag_create(*args, **kwargs) def tag_create( repo, tag, author=None, message=None, annotated=False, objectish="HEAD", tag_time=None, tag_timezone=None, sign=False): """Creates a tag in git via dulwich calls: Args: repo: Path to repository tag: tag string author: tag author (optional, if annotated is set) message: tag message (optional) annotated: whether to create an annotated tag objectish: object the tag should point at, defaults to HEAD tag_time: Optional time for annotated tag tag_timezone: Optional timezone for annotated tag sign: GPG Sign the tag """ with open_repo_closing(repo) as r: object = parse_object(r, objectish) if annotated: # Create the tag object tag_obj = Tag() if author is None: # TODO(jelmer): Don't use repo private method. author = r._get_user_identity(r.get_config_stack()) tag_obj.tagger = author tag_obj.message = message tag_obj.name = tag tag_obj.object = (type(object), object.id) if tag_time is None: tag_time = int(time.time()) tag_obj.tag_time = tag_time if tag_timezone is None: # TODO(jelmer) Use current user timezone rather than UTC tag_timezone = 0 elif isinstance(tag_timezone, str): tag_timezone = parse_timezone(tag_timezone) tag_obj.tag_timezone = tag_timezone if sign: import gpg with gpg.Context(armor=True) as c: tag_obj.signature, unused_result = c.sign( tag_obj.as_raw_string()) r.object_store.add_object(tag_obj) tag_id = tag_obj.id else: tag_id = object.id r.refs[_make_tag_ref(tag)] = tag_id def list_tags(*args, **kwargs): import warnings warnings.warn("list_tags has been deprecated in favour of tag_list.", DeprecationWarning) return tag_list(*args, **kwargs) def tag_list(repo, outstream=sys.stdout): """List all tags. Args: repo: Path to repository outstream: Stream to write tags to """ with open_repo_closing(repo) as r: tags = sorted(r.refs.as_dict(b"refs/tags")) return tags def tag_delete(repo, name): """Remove a tag. Args: repo: Path to repository name: Name of tag to remove """ with open_repo_closing(repo) as r: if isinstance(name, bytes): names = [name] elif isinstance(name, list): names = name else: raise TypeError("Unexpected tag name type %r" % name) for name in names: del r.refs[_make_tag_ref(name)] def reset(repo, mode, treeish="HEAD"): """Reset current HEAD to the specified state. Args: repo: Path to repository mode: Mode ("hard", "soft", "mixed") treeish: Treeish to reset to """ if mode != "hard": raise ValueError("hard is the only mode currently supported") with open_repo_closing(repo) as r: tree = parse_tree(r, treeish) r.reset_index(tree.id) def push(repo, remote_location, refspecs, outstream=default_bytes_out_stream, errstream=default_bytes_err_stream, **kwargs): """Remote push with dulwich via dulwich.client Args: repo: Path to repository remote_location: Location of the remote refspecs: Refs to push to remote outstream: A stream file to write output errstream: A stream file to write errors """ # Open the repo with open_repo_closing(repo) as r: # Get the client and path client, path = get_transport_and_path( remote_location, config=r.get_config_stack(), **kwargs) selected_refs = [] def update_refs(refs): selected_refs.extend(parse_reftuples(r.refs, refs, refspecs)) new_refs = {} # TODO: Handle selected_refs == {None: None} for (lh, rh, force) in selected_refs: if lh is None: new_refs[rh] = ZERO_SHA else: new_refs[rh] = r.refs[lh] return new_refs err_encoding = getattr(errstream, 'encoding', None) or DEFAULT_ENCODING remote_location_bytes = client.get_url(path).encode(err_encoding) try: client.send_pack( path, update_refs, generate_pack_data=r.object_store.generate_pack_data, progress=errstream.write) errstream.write( b"Push to " + remote_location_bytes + b" successful.\n") except (UpdateRefsError, SendPackError) as e: errstream.write(b"Push to " + remote_location_bytes + b" failed -> " + e.message.encode(err_encoding) + b"\n") def pull(repo, remote_location=None, refspecs=None, outstream=default_bytes_out_stream, errstream=default_bytes_err_stream, **kwargs): """Pull from remote via dulwich.client Args: repo: Path to repository remote_location: Location of the remote refspec: refspecs to fetch outstream: A stream file to write to output errstream: A stream file to write to errors """ # Open the repo with open_repo_closing(repo) as r: if remote_location is None: # TODO(jelmer): Lookup 'remote' for current branch in config raise NotImplementedError( "looking up remote from branch config not supported yet") if refspecs is None: refspecs = [b"HEAD"] selected_refs = [] def determine_wants(remote_refs): selected_refs.extend( parse_reftuples(remote_refs, r.refs, refspecs)) return [remote_refs[lh] for (lh, rh, force) in selected_refs] client, path = get_transport_and_path( remote_location, config=r.get_config_stack(), **kwargs) fetch_result = client.fetch( path, r, progress=errstream.write, determine_wants=determine_wants) for (lh, rh, force) in selected_refs: r.refs[rh] = fetch_result.refs[lh] if selected_refs: r[b'HEAD'] = fetch_result.refs[selected_refs[0][1]] # Perform 'git checkout .' - syncs staged changes tree = r[b"HEAD"].tree r.reset_index(tree=tree) def status(repo=".", ignored=False): """Returns staged, unstaged, and untracked changes relative to the HEAD. Args: repo: Path to repository or repository object ignored: Whether to include ignored files in `untracked` Returns: GitStatus tuple, staged - dict with lists of staged paths (diff index/HEAD) unstaged - list of unstaged paths (diff index/working-tree) untracked - list of untracked, un-ignored & non-.git paths """ with open_repo_closing(repo) as r: # 1. Get status of staged tracked_changes = get_tree_changes(r) # 2. Get status of unstaged index = r.open_index() normalizer = r.get_blob_normalizer() filter_callback = normalizer.checkin_normalize unstaged_changes = list( get_unstaged_changes(index, r.path, filter_callback) ) ignore_manager = IgnoreFilterManager.from_repo(r) untracked_paths = get_untracked_paths(r.path, r.path, index) if ignored: untracked_changes = list(untracked_paths) else: untracked_changes = [ p for p in untracked_paths if not ignore_manager.is_ignored(p)] return GitStatus(tracked_changes, unstaged_changes, untracked_changes) def _walk_working_dir_paths(frompath, basepath): """Get path, is_dir for files in working dir from frompath Args: frompath: Path to begin walk basepath: Path to compare to """ for dirpath, dirnames, filenames in os.walk(frompath): # Skip .git and below. if '.git' in dirnames: dirnames.remove('.git') if dirpath != basepath: continue if '.git' in filenames: filenames.remove('.git') if dirpath != basepath: continue if dirpath != frompath: yield dirpath, True for filename in filenames: filepath = os.path.join(dirpath, filename) yield filepath, False def get_untracked_paths(frompath, basepath, index): """Get untracked paths. Args: ;param frompath: Path to walk basepath: Path to compare to index: Index to check against """ for ap, is_dir in _walk_working_dir_paths(frompath, basepath): if not is_dir: ip = path_to_tree_path(basepath, ap) if ip not in index: yield os.path.relpath(ap, frompath) def get_tree_changes(repo): """Return add/delete/modify changes to tree by comparing index to HEAD. Args: repo: repo path or object Returns: dict with lists for each type of change """ with open_repo_closing(repo) as r: index = r.open_index() # Compares the Index to the HEAD & determines changes # Iterate through the changes and report add/delete/modify # TODO: call out to dulwich.diff_tree somehow. tracked_changes = { 'add': [], 'delete': [], 'modify': [], } try: tree_id = r[b'HEAD'].tree except KeyError: tree_id = None for change in index.changes_from_tree(r.object_store, tree_id): if not change[0][0]: tracked_changes['add'].append(change[0][1]) elif not change[0][1]: tracked_changes['delete'].append(change[0][0]) elif change[0][0] == change[0][1]: tracked_changes['modify'].append(change[0][0]) else: raise AssertionError('git mv ops not yet supported') return tracked_changes def daemon(path=".", address=None, port=None): """Run a daemon serving Git requests over TCP/IP. Args: path: Path to the directory to serve. address: Optional address to listen on (defaults to ::) port: Optional port to listen on (defaults to TCP_GIT_PORT) """ # TODO(jelmer): Support git-daemon-export-ok and --export-all. backend = FileSystemBackend(path) server = TCPGitServer(backend, address, port) server.serve_forever() def web_daemon(path=".", address=None, port=None): """Run a daemon serving Git requests over HTTP. Args: path: Path to the directory to serve address: Optional address to listen on (defaults to ::) port: Optional port to listen on (defaults to 80) """ from dulwich.web import ( make_wsgi_chain, make_server, WSGIRequestHandlerLogger, WSGIServerLogger) backend = FileSystemBackend(path) app = make_wsgi_chain(backend) server = make_server(address, port, app, handler_class=WSGIRequestHandlerLogger, server_class=WSGIServerLogger) server.serve_forever() def upload_pack(path=".", inf=None, outf=None): """Upload a pack file after negotiating its contents using smart protocol. Args: path: Path to the repository inf: Input stream to communicate with client outf: Output stream to communicate with client """ if outf is None: outf = getattr(sys.stdout, 'buffer', sys.stdout) if inf is None: inf = getattr(sys.stdin, 'buffer', sys.stdin) path = os.path.expanduser(path) backend = FileSystemBackend(path) def send_fn(data): outf.write(data) outf.flush() proto = Protocol(inf.read, send_fn) handler = UploadPackHandler(backend, [path], proto) # FIXME: Catch exceptions and write a single-line summary to outf. handler.handle() return 0 def receive_pack(path=".", inf=None, outf=None): """Receive a pack file after negotiating its contents using smart protocol. Args: path: Path to the repository inf: Input stream to communicate with client outf: Output stream to communicate with client """ if outf is None: outf = getattr(sys.stdout, 'buffer', sys.stdout) if inf is None: inf = getattr(sys.stdin, 'buffer', sys.stdin) path = os.path.expanduser(path) backend = FileSystemBackend(path) def send_fn(data): outf.write(data) outf.flush() proto = Protocol(inf.read, send_fn) handler = ReceivePackHandler(backend, [path], proto) # FIXME: Catch exceptions and write a single-line summary to outf. handler.handle() return 0 def _make_branch_ref(name): if getattr(name, 'encode', None): name = name.encode(DEFAULT_ENCODING) return LOCAL_BRANCH_PREFIX + name def _make_tag_ref(name): if getattr(name, 'encode', None): name = name.encode(DEFAULT_ENCODING) return b"refs/tags/" + name def branch_delete(repo, name): """Delete a branch. Args: repo: Path to the repository name: Name of the branch """ with open_repo_closing(repo) as r: if isinstance(name, list): names = name else: names = [name] for name in names: del r.refs[_make_branch_ref(name)] def branch_create(repo, name, objectish=None, force=False): """Create a branch. Args: repo: Path to the repository name: Name of the new branch objectish: Target object to point new branch at (defaults to HEAD) force: Force creation of branch, even if it already exists """ with open_repo_closing(repo) as r: if objectish is None: objectish = "HEAD" object = parse_object(r, objectish) refname = _make_branch_ref(name) ref_message = b"branch: Created from " + objectish.encode('utf-8') if force: r.refs.set_if_equals(refname, None, object.id, message=ref_message) else: if not r.refs.add_if_new(refname, object.id, message=ref_message): raise KeyError("Branch with name %s already exists." % name) def branch_list(repo): """List all branches. Args: repo: Path to the repository """ with open_repo_closing(repo) as r: return r.refs.keys(base=LOCAL_BRANCH_PREFIX) def active_branch(repo): """Return the active branch in the repository, if any. Args: repo: Repository to open Returns: branch name Raises: KeyError: if the repository does not have a working tree IndexError: if HEAD is floating """ with open_repo_closing(repo) as r: active_ref = r.refs.follow(b'HEAD')[0][1] if not active_ref.startswith(LOCAL_BRANCH_PREFIX): raise ValueError(active_ref) return active_ref[len(LOCAL_BRANCH_PREFIX):] def fetch(repo, remote_location, remote_name=b'origin', outstream=sys.stdout, errstream=default_bytes_err_stream, message=None, depth=None, prune=False, prune_tags=False, **kwargs): """Fetch objects from a remote server. Args: repo: Path to the repository remote_location: String identifying a remote server remote_name: Name for remote server outstream: Output stream (defaults to stdout) errstream: Error stream (defaults to stderr) message: Reflog message (defaults to b"fetch: from ") depth: Depth to fetch at prune: Prune remote removed refs prune_tags: Prune reomte removed tags Returns: Dictionary with refs on the remote """ if message is None: message = b'fetch: from ' + remote_location.encode("utf-8") with open_repo_closing(repo) as r: client, path = get_transport_and_path( remote_location, config=r.get_config_stack(), **kwargs) fetch_result = client.fetch(path, r, progress=errstream.write, depth=depth) stripped_refs = strip_peeled_refs(fetch_result.refs) branches = { n[len(LOCAL_BRANCH_PREFIX):]: v for (n, v) in stripped_refs.items() if n.startswith(LOCAL_BRANCH_PREFIX)} r.refs.import_refs( b'refs/remotes/' + remote_name, branches, message=message, prune=prune) tags = { n[len(b'refs/tags/'):]: v for (n, v) in stripped_refs.items() if n.startswith(b'refs/tags/') and not n.endswith(ANNOTATED_TAG_SUFFIX)} r.refs.import_refs( b'refs/tags', tags, message=message, prune=prune_tags) return fetch_result.refs def ls_remote(remote, config=None, **kwargs): """List the refs in a remote. Args: remote: Remote repository location config: Configuration to use Returns: Dictionary with remote refs """ if config is None: config = StackedConfig.default() client, host_path = get_transport_and_path(remote, config=config, **kwargs) return client.get_refs(host_path) def repack(repo): """Repack loose files in a repository. Currently this only packs loose objects. Args: repo: Path to the repository """ with open_repo_closing(repo) as r: r.object_store.pack_loose_objects() def pack_objects(repo, object_ids, packf, idxf, delta_window_size=None): """Pack objects into a file. Args: repo: Path to the repository object_ids: List of object ids to write packf: File-like object to write to idxf: File-like object to write to (can be None) """ with open_repo_closing(repo) as r: entries, data_sum = write_pack_objects( packf, r.object_store.iter_shas((oid, None) for oid in object_ids), delta_window_size=delta_window_size) if idxf is not None: entries = sorted([(k, v[0], v[1]) for (k, v) in entries.items()]) write_pack_index(idxf, entries, data_sum) def ls_tree(repo, treeish=b"HEAD", outstream=sys.stdout, recursive=False, name_only=False): """List contents of a tree. Args: repo: Path to the repository tree_ish: Tree id to list outstream: Output stream (defaults to stdout) recursive: Whether to recursively list files name_only: Only print item name """ def list_tree(store, treeid, base): for (name, mode, sha) in store[treeid].iteritems(): if base: name = posixpath.join(base, name) if name_only: outstream.write(name + b"\n") else: outstream.write(pretty_format_tree_entry(name, mode, sha)) if stat.S_ISDIR(mode) and recursive: list_tree(store, sha, name) with open_repo_closing(repo) as r: tree = parse_tree(r, treeish) list_tree(r.object_store, tree.id, "") def remote_add(repo, name, url): """Add a remote. Args: repo: Path to the repository name: Remote name url: Remote URL """ if not isinstance(name, bytes): name = name.encode(DEFAULT_ENCODING) if not isinstance(url, bytes): url = url.encode(DEFAULT_ENCODING) with open_repo_closing(repo) as r: c = r.get_config() section = (b'remote', name) if c.has_section(section): raise RemoteExists(section) c.set(section, b"url", url) c.write_to_path() def check_ignore(repo, paths, no_index=False): """Debug gitignore files. Args: repo: Path to the repository paths: List of paths to check for no_index: Don't check index Returns: List of ignored files """ with open_repo_closing(repo) as r: index = r.open_index() ignore_manager = IgnoreFilterManager.from_repo(r) for path in paths: if not no_index and path_to_tree_path(r.path, path) in index: continue if os.path.isabs(path): path = os.path.relpath(path, r.path) if ignore_manager.is_ignored(path): yield path def update_head(repo, target, detached=False, new_branch=None): """Update HEAD to point at a new branch/commit. Note that this does not actually update the working tree. Args: repo: Path to the repository detach: Create a detached head target: Branch or committish to switch to new_branch: New branch to create """ with open_repo_closing(repo) as r: if new_branch is not None: to_set = _make_branch_ref(new_branch) else: to_set = b"HEAD" if detached: # TODO(jelmer): Provide some way so that the actual ref gets # updated rather than what it points to, so the delete isn't # necessary. del r.refs[to_set] r.refs[to_set] = parse_commit(r, target).id else: r.refs.set_symbolic_ref(to_set, parse_ref(r, target)) if new_branch is not None: r.refs.set_symbolic_ref(b"HEAD", to_set) def check_mailmap(repo, contact): """Check canonical name and email of contact. Args: repo: Path to the repository contact: Contact name and/or email Returns: Canonical contact data """ with open_repo_closing(repo) as r: from dulwich.mailmap import Mailmap import errno try: mailmap = Mailmap.from_path(os.path.join(r.path, '.mailmap')) except IOError as e: if e.errno != errno.ENOENT: raise mailmap = Mailmap() return mailmap.lookup(contact) def fsck(repo): """Check a repository. Args: repo: A path to the repository Returns: Iterator over errors/warnings """ with open_repo_closing(repo) as r: # TODO(jelmer): check pack files # TODO(jelmer): check graph # TODO(jelmer): check refs for sha in r.object_store: o = r.object_store[sha] try: o.check() except Exception as e: yield (sha, e) def stash_list(repo): """List all stashes in a repository.""" with open_repo_closing(repo) as r: from dulwich.stash import Stash stash = Stash.from_repo(r) return enumerate(list(stash.stashes())) def stash_push(repo): """Push a new stash onto the stack.""" with open_repo_closing(repo) as r: from dulwich.stash import Stash stash = Stash.from_repo(r) stash.push() def stash_pop(repo): """Pop a new stash from the stack.""" with open_repo_closing(repo) as r: from dulwich.stash import Stash stash = Stash.from_repo(r) stash.pop() def ls_files(repo): """List all files in an index.""" with open_repo_closing(repo) as r: return sorted(r.open_index()) def describe(repo): """Describe the repository version. Args: projdir: git repository root Returns: a string description of the current git revision Examples: "gabcdefh", "v0.1" or "v0.1-5-gabcdefh". """ # Get the repository with open_repo_closing(repo) as r: # Get a list of all tags refs = r.get_refs() tags = {} for key, value in refs.items(): key = key.decode() obj = r.get_object(value) if u'tags' not in key: continue _, tag = key.rsplit(u'/', 1) try: commit = obj.object except AttributeError: continue else: commit = r.get_object(commit[1]) tags[tag] = [ datetime.datetime(*time.gmtime(commit.commit_time)[:6]), commit.id.decode('ascii'), ] sorted_tags = sorted(tags.items(), key=lambda tag: tag[1][0], reverse=True) # If there are no tags, return the current commit if len(sorted_tags) == 0: return 'g{}'.format(r[r.head()].id.decode('ascii')[:7]) # We're now 0 commits from the top commit_count = 0 # Get the latest commit latest_commit = r[r.head()] # Walk through all commits walker = r.get_walker() for entry in walker: # Check if tag commit_id = entry.commit.id.decode('ascii') for tag in sorted_tags: tag_name = tag[0] tag_commit = tag[1][1] if commit_id == tag_commit: if commit_count == 0: return tag_name else: return '{}-{}-g{}'.format( tag_name, commit_count, latest_commit.id.decode('ascii')[:7]) commit_count += 1 # Return plain commit if no parent tag can be found return 'g{}'.format(latest_commit.id.decode('ascii')[:7]) def get_object_by_path(repo, path, committish=None): """Get an object by path. Args: repo: A path to the repository path: Path to look up committish: Commit to look up path in Returns: A `ShaFile` object """ if committish is None: committish = "HEAD" # Get the repository with open_repo_closing(repo) as r: commit = parse_commit(r, committish) base_tree = commit.tree if not isinstance(path, bytes): - path = path.encode(commit.encoding or DEFAULT_ENCODING) + path = commit_encode(commit, path) (mode, sha) = tree_lookup_path( r.object_store.__getitem__, base_tree, path) return r[sha] def write_tree(repo): """Write a tree object from the index. Args: repo: Repository for which to write tree Returns: tree id for the tree that was written """ with open_repo_closing(repo) as r: return r.open_index().commit(r.object_store) diff --git a/dulwich/tests/test_index.py b/dulwich/tests/test_index.py index fe0f9764..34bb8ccf 100644 --- a/dulwich/tests/test_index.py +++ b/dulwich/tests/test_index.py @@ -1,758 +1,762 @@ # -*- coding: utf-8 -*- # test_index.py -- Tests for the git index # encoding: utf-8 # Copyright (C) 2008-2009 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. # """Tests for the index.""" from io import BytesIO import os import shutil import stat import struct import sys import tempfile import warnings from dulwich.index import ( Index, build_index_from_tree, cleanup_mode, commit_tree, get_unstaged_changes, index_entry_from_stat, read_index, read_index_dict, validate_path_element_default, validate_path_element_ntfs, write_cache_time, write_index, write_index_dict, _tree_to_fs_path, _fs_to_tree_path, ) from dulwich.object_store import ( MemoryObjectStore, ) from dulwich.objects import ( Blob, Commit, Tree, S_IFGITLINK, ) from dulwich.repo import Repo from dulwich.tests import ( TestCase, skipIf, ) from dulwich.tests.utils import ( setup_warning_catcher, ) def can_symlink(): """Return whether running process can create symlinks.""" if sys.platform != 'win32': # Platforms other than Windows should allow symlinks without issues. return True if not hasattr(os, 'symlink'): # Older Python versions do not have `os.symlink` on Windows. return False test_source = tempfile.mkdtemp() test_target = test_source + 'can_symlink' try: os.symlink(test_source, test_target) except OSError: return False return True class IndexTestCase(TestCase): datadir = os.path.join(os.path.dirname(__file__), 'data/indexes') def get_simple_index(self, name): return Index(os.path.join(self.datadir, name)) class SimpleIndexTestCase(IndexTestCase): def test_len(self): self.assertEqual(1, len(self.get_simple_index("index"))) def test_iter(self): self.assertEqual([b'bla'], list(self.get_simple_index("index"))) def test_iterobjects(self): self.assertEqual( [(b'bla', b'e69de29bb2d1d6434b8b29ae775ad8c2e48c5391', 33188)], list(self.get_simple_index("index").iterobjects())) def test_iterblobs(self): warnings.simplefilter("always", UserWarning) self.addCleanup(warnings.resetwarnings) warnings_list, restore_warnings = setup_warning_catcher() self.addCleanup(restore_warnings) self.assertEqual( [(b'bla', b'e69de29bb2d1d6434b8b29ae775ad8c2e48c5391', 33188)], list(self.get_simple_index("index").iterblobs())) expected_warning = PendingDeprecationWarning( 'Use iterobjects() instead.') for w in warnings_list: if (type(w) == type(expected_warning) and w.args == expected_warning.args): break else: raise AssertionError( 'Expected warning %r not in %r' % (expected_warning, warnings_list)) def test_getitem(self): self.assertEqual( ((1230680220, 0), (1230680220, 0), 2050, 3761020, 33188, 1000, 1000, 0, b'e69de29bb2d1d6434b8b29ae775ad8c2e48c5391', 0), self.get_simple_index("index")[b"bla"]) def test_empty(self): i = self.get_simple_index("notanindex") self.assertEqual(0, len(i)) self.assertFalse(os.path.exists(i._filename)) def test_against_empty_tree(self): i = self.get_simple_index("index") changes = list(i.changes_from_tree(MemoryObjectStore(), None)) self.assertEqual(1, len(changes)) (oldname, newname), (oldmode, newmode), (oldsha, newsha) = changes[0] self.assertEqual(b'bla', newname) self.assertEqual(b'e69de29bb2d1d6434b8b29ae775ad8c2e48c5391', newsha) class SimpleIndexWriterTestCase(IndexTestCase): def setUp(self): IndexTestCase.setUp(self) self.tempdir = tempfile.mkdtemp() def tearDown(self): IndexTestCase.tearDown(self) shutil.rmtree(self.tempdir) def test_simple_write(self): entries = [(b'barbla', (1230680220, 0), (1230680220, 0), 2050, 3761020, 33188, 1000, 1000, 0, b'e69de29bb2d1d6434b8b29ae775ad8c2e48c5391', 0)] filename = os.path.join(self.tempdir, 'test-simple-write-index') with open(filename, 'wb+') as x: write_index(x, entries) with open(filename, 'rb') as x: self.assertEqual(entries, list(read_index(x))) class ReadIndexDictTests(IndexTestCase): def setUp(self): IndexTestCase.setUp(self) self.tempdir = tempfile.mkdtemp() def tearDown(self): IndexTestCase.tearDown(self) shutil.rmtree(self.tempdir) def test_simple_write(self): entries = { b'barbla': ((1230680220, 0), (1230680220, 0), 2050, 3761020, 33188, 1000, 1000, 0, b'e69de29bb2d1d6434b8b29ae775ad8c2e48c5391', 0)} filename = os.path.join(self.tempdir, 'test-simple-write-index') with open(filename, 'wb+') as x: write_index_dict(x, entries) with open(filename, 'rb') as x: self.assertEqual(entries, read_index_dict(x)) class CommitTreeTests(TestCase): def setUp(self): super(CommitTreeTests, self).setUp() self.store = MemoryObjectStore() def test_single_blob(self): blob = Blob() blob.data = b"foo" self.store.add_object(blob) blobs = [(b"bla", blob.id, stat.S_IFREG)] rootid = commit_tree(self.store, blobs) self.assertEqual(rootid, b"1a1e80437220f9312e855c37ac4398b68e5c1d50") self.assertEqual((stat.S_IFREG, blob.id), self.store[rootid][b"bla"]) self.assertEqual(set([rootid, blob.id]), set(self.store._data.keys())) def test_nested(self): blob = Blob() blob.data = b"foo" self.store.add_object(blob) blobs = [(b"bla/bar", blob.id, stat.S_IFREG)] rootid = commit_tree(self.store, blobs) self.assertEqual(rootid, b"d92b959b216ad0d044671981196781b3258fa537") dirid = self.store[rootid][b"bla"][1] self.assertEqual(dirid, b"c1a1deb9788150829579a8b4efa6311e7b638650") self.assertEqual((stat.S_IFDIR, dirid), self.store[rootid][b"bla"]) self.assertEqual((stat.S_IFREG, blob.id), self.store[dirid][b"bar"]) self.assertEqual(set([rootid, dirid, blob.id]), set(self.store._data.keys())) class CleanupModeTests(TestCase): + def assertModeEqual(self, expected, got): + self.assertEqual(expected, got, '%o != %o' % (expected, got)) + def test_file(self): - self.assertEqual(0o100644, cleanup_mode(0o100000)) + self.assertModeEqual(0o100644, cleanup_mode(0o100000)) def test_executable(self): - self.assertEqual(0o100755, cleanup_mode(0o100711)) + self.assertModeEqual(0o100755, cleanup_mode(0o100711)) + self.assertModeEqual(0o100755, cleanup_mode(0o100700)) def test_symlink(self): - self.assertEqual(0o120000, cleanup_mode(0o120711)) + self.assertModeEqual(0o120000, cleanup_mode(0o120711)) def test_dir(self): - self.assertEqual(0o040000, cleanup_mode(0o40531)) + self.assertModeEqual(0o040000, cleanup_mode(0o40531)) def test_submodule(self): - self.assertEqual(0o160000, cleanup_mode(0o160744)) + self.assertModeEqual(0o160000, cleanup_mode(0o160744)) class WriteCacheTimeTests(TestCase): def test_write_string(self): f = BytesIO() self.assertRaises(TypeError, write_cache_time, f, "foo") def test_write_int(self): f = BytesIO() write_cache_time(f, 434343) self.assertEqual(struct.pack(">LL", 434343, 0), f.getvalue()) def test_write_tuple(self): f = BytesIO() write_cache_time(f, (434343, 21)) self.assertEqual(struct.pack(">LL", 434343, 21), f.getvalue()) def test_write_float(self): f = BytesIO() write_cache_time(f, 434343.000000021) self.assertEqual(struct.pack(">LL", 434343, 21), f.getvalue()) class IndexEntryFromStatTests(TestCase): def test_simple(self): st = os.stat_result( (16877, 131078, 64769, 154, 1000, 1000, 12288, 1323629595, 1324180496, 1324180496)) entry = index_entry_from_stat(st, "22" * 20, 0) self.assertEqual(entry, ( 1324180496, 1324180496, 64769, 131078, 16384, 1000, 1000, 12288, '2222222222222222222222222222222222222222', 0)) def test_override_mode(self): st = os.stat_result( (stat.S_IFREG + 0o644, 131078, 64769, 154, 1000, 1000, 12288, 1323629595, 1324180496, 1324180496)) entry = index_entry_from_stat( st, "22" * 20, 0, mode=stat.S_IFREG + 0o755) self.assertEqual(entry, ( 1324180496, 1324180496, 64769, 131078, 33261, 1000, 1000, 12288, '2222222222222222222222222222222222222222', 0)) class BuildIndexTests(TestCase): def assertReasonableIndexEntry(self, index_entry, mode, filesize, sha): self.assertEqual(index_entry[4], mode) # mode self.assertEqual(index_entry[7], filesize) # filesize self.assertEqual(index_entry[8], sha) # sha def assertFileContents(self, path, contents, symlink=False): if symlink: self.assertEqual(os.readlink(path), contents) else: with open(path, 'rb') as f: self.assertEqual(f.read(), contents) def test_empty(self): repo_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, repo_dir) with Repo.init(repo_dir) as repo: tree = Tree() repo.object_store.add_object(tree) build_index_from_tree( repo.path, repo.index_path(), repo.object_store, tree.id) # Verify index entries index = repo.open_index() self.assertEqual(len(index), 0) # Verify no files self.assertEqual(['.git'], os.listdir(repo.path)) def test_git_dir(self): repo_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, repo_dir) with Repo.init(repo_dir) as repo: # Populate repo filea = Blob.from_string(b'file a') filee = Blob.from_string(b'd') tree = Tree() tree[b'.git/a'] = (stat.S_IFREG | 0o644, filea.id) tree[b'c/e'] = (stat.S_IFREG | 0o644, filee.id) repo.object_store.add_objects( [(o, None) for o in [filea, filee, tree]]) build_index_from_tree( repo.path, repo.index_path(), repo.object_store, tree.id) # Verify index entries index = repo.open_index() self.assertEqual(len(index), 1) # filea apath = os.path.join(repo.path, '.git', 'a') self.assertFalse(os.path.exists(apath)) # filee epath = os.path.join(repo.path, 'c', 'e') self.assertTrue(os.path.exists(epath)) self.assertReasonableIndexEntry( index[b'c/e'], stat.S_IFREG | 0o644, 1, filee.id) self.assertFileContents(epath, b'd') def test_nonempty(self): repo_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, repo_dir) with Repo.init(repo_dir) as repo: # Populate repo filea = Blob.from_string(b'file a') fileb = Blob.from_string(b'file b') filed = Blob.from_string(b'file d') tree = Tree() tree[b'a'] = (stat.S_IFREG | 0o644, filea.id) tree[b'b'] = (stat.S_IFREG | 0o644, fileb.id) tree[b'c/d'] = (stat.S_IFREG | 0o644, filed.id) repo.object_store.add_objects( [(o, None) for o in [filea, fileb, filed, tree]]) build_index_from_tree( repo.path, repo.index_path(), repo.object_store, tree.id) # Verify index entries index = repo.open_index() self.assertEqual(len(index), 3) # filea apath = os.path.join(repo.path, 'a') self.assertTrue(os.path.exists(apath)) self.assertReasonableIndexEntry( index[b'a'], stat.S_IFREG | 0o644, 6, filea.id) self.assertFileContents(apath, b'file a') # fileb bpath = os.path.join(repo.path, 'b') self.assertTrue(os.path.exists(bpath)) self.assertReasonableIndexEntry( index[b'b'], stat.S_IFREG | 0o644, 6, fileb.id) self.assertFileContents(bpath, b'file b') # filed dpath = os.path.join(repo.path, 'c', 'd') self.assertTrue(os.path.exists(dpath)) self.assertReasonableIndexEntry( index[b'c/d'], stat.S_IFREG | 0o644, 6, filed.id) self.assertFileContents(dpath, b'file d') # Verify no extra files self.assertEqual( ['.git', 'a', 'b', 'c'], sorted(os.listdir(repo.path))) self.assertEqual( ['d'], sorted(os.listdir(os.path.join(repo.path, 'c')))) @skipIf(not getattr(os, 'sync', None), 'Requires sync support') def test_norewrite(self): repo_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, repo_dir) with Repo.init(repo_dir) as repo: # Populate repo filea = Blob.from_string(b'file a') filea_path = os.path.join(repo_dir, 'a') tree = Tree() tree[b'a'] = (stat.S_IFREG | 0o644, filea.id) repo.object_store.add_objects([(o, None) for o in [filea, tree]]) # First Write build_index_from_tree(repo.path, repo.index_path(), repo.object_store, tree.id) # Use sync as metadata can be cached on some FS os.sync() mtime = os.stat(filea_path).st_mtime # Test Rewrite build_index_from_tree(repo.path, repo.index_path(), repo.object_store, tree.id) os.sync() self.assertEqual(mtime, os.stat(filea_path).st_mtime) # Modify content with open(filea_path, 'wb') as fh: fh.write(b'test a') os.sync() mtime = os.stat(filea_path).st_mtime # Test rewrite build_index_from_tree(repo.path, repo.index_path(), repo.object_store, tree.id) os.sync() with open(filea_path, 'rb') as fh: self.assertEqual(b'file a', fh.read()) @skipIf(not can_symlink(), 'Requires symlink support') def test_symlink(self): repo_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, repo_dir) with Repo.init(repo_dir) as repo: # Populate repo filed = Blob.from_string(b'file d') filee = Blob.from_string(b'd') tree = Tree() tree[b'c/d'] = (stat.S_IFREG | 0o644, filed.id) tree[b'c/e'] = (stat.S_IFLNK, filee.id) # symlink repo.object_store.add_objects( [(o, None) for o in [filed, filee, tree]]) build_index_from_tree( repo.path, repo.index_path(), repo.object_store, tree.id) # Verify index entries index = repo.open_index() # symlink to d epath = os.path.join(repo.path, 'c', 'e') self.assertTrue(os.path.exists(epath)) self.assertReasonableIndexEntry( index[b'c/e'], stat.S_IFLNK, 0 if sys.platform == 'win32' else 1, filee.id) self.assertFileContents(epath, 'd', symlink=True) def test_no_decode_encode(self): repo_dir = tempfile.mkdtemp() repo_dir_bytes = repo_dir.encode(sys.getfilesystemencoding()) self.addCleanup(shutil.rmtree, repo_dir) with Repo.init(repo_dir) as repo: # Populate repo file = Blob.from_string(b'foo') tree = Tree() latin1_name = u'À'.encode('latin1') latin1_path = os.path.join(repo_dir_bytes, latin1_name) utf8_name = u'À'.encode('utf8') utf8_path = os.path.join(repo_dir_bytes, utf8_name) tree[latin1_name] = (stat.S_IFREG | 0o644, file.id) tree[utf8_name] = (stat.S_IFREG | 0o644, file.id) repo.object_store.add_objects( [(o, None) for o in [file, tree]]) try: os.path.exists(latin1_path) except UnicodeDecodeError: # This happens e.g. with python3.6 on Windows. # It implicitly decodes using utf8, which doesn't work. self.skipTest('can not implicitly convert as utf8') build_index_from_tree( repo.path, repo.index_path(), repo.object_store, tree.id) # Verify index entries index = repo.open_index() self.assertIn(latin1_name, index) self.assertIn(utf8_name, index) self.assertTrue(os.path.exists(latin1_path)) self.assertTrue(os.path.exists(utf8_path)) def test_git_submodule(self): repo_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, repo_dir) with Repo.init(repo_dir) as repo: filea = Blob.from_string(b'file alalala') subtree = Tree() subtree[b'a'] = (stat.S_IFREG | 0o644, filea.id) c = Commit() c.tree = subtree.id c.committer = c.author = b'Somebody ' c.commit_time = c.author_time = 42342 c.commit_timezone = c.author_timezone = 0 c.parents = [] c.message = b'Subcommit' tree = Tree() tree[b'c'] = (S_IFGITLINK, c.id) repo.object_store.add_objects( [(o, None) for o in [tree]]) build_index_from_tree( repo.path, repo.index_path(), repo.object_store, tree.id) # Verify index entries index = repo.open_index() self.assertEqual(len(index), 1) # filea apath = os.path.join(repo.path, 'c/a') self.assertFalse(os.path.exists(apath)) # dir c cpath = os.path.join(repo.path, 'c') self.assertTrue(os.path.isdir(cpath)) self.assertEqual(index[b'c'][4], S_IFGITLINK) # mode self.assertEqual(index[b'c'][8], c.id) # sha def test_git_submodule_exists(self): repo_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, repo_dir) with Repo.init(repo_dir) as repo: filea = Blob.from_string(b'file alalala') subtree = Tree() subtree[b'a'] = (stat.S_IFREG | 0o644, filea.id) c = Commit() c.tree = subtree.id c.committer = c.author = b'Somebody ' c.commit_time = c.author_time = 42342 c.commit_timezone = c.author_timezone = 0 c.parents = [] c.message = b'Subcommit' tree = Tree() tree[b'c'] = (S_IFGITLINK, c.id) os.mkdir(os.path.join(repo_dir, 'c')) repo.object_store.add_objects( [(o, None) for o in [tree]]) build_index_from_tree( repo.path, repo.index_path(), repo.object_store, tree.id) # Verify index entries index = repo.open_index() self.assertEqual(len(index), 1) # filea apath = os.path.join(repo.path, 'c/a') self.assertFalse(os.path.exists(apath)) # dir c cpath = os.path.join(repo.path, 'c') self.assertTrue(os.path.isdir(cpath)) self.assertEqual(index[b'c'][4], S_IFGITLINK) # mode self.assertEqual(index[b'c'][8], c.id) # sha class GetUnstagedChangesTests(TestCase): def test_get_unstaged_changes(self): """Unit test for get_unstaged_changes.""" repo_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, repo_dir) with Repo.init(repo_dir) as repo: # Commit a dummy file then modify it foo1_fullpath = os.path.join(repo_dir, 'foo1') with open(foo1_fullpath, 'wb') as f: f.write(b'origstuff') foo2_fullpath = os.path.join(repo_dir, 'foo2') with open(foo2_fullpath, 'wb') as f: f.write(b'origstuff') repo.stage(['foo1', 'foo2']) repo.do_commit(b'test status', author=b'author ', committer=b'committer ') with open(foo1_fullpath, 'wb') as f: f.write(b'newstuff') # modify access and modify time of path os.utime(foo1_fullpath, (0, 0)) changes = get_unstaged_changes(repo.open_index(), repo_dir) self.assertEqual(list(changes), [b'foo1']) def test_get_unstaged_deleted_changes(self): """Unit test for get_unstaged_changes.""" repo_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, repo_dir) with Repo.init(repo_dir) as repo: # Commit a dummy file then remove it foo1_fullpath = os.path.join(repo_dir, 'foo1') with open(foo1_fullpath, 'wb') as f: f.write(b'origstuff') repo.stage(['foo1']) repo.do_commit(b'test status', author=b'author ', committer=b'committer ') os.unlink(foo1_fullpath) changes = get_unstaged_changes(repo.open_index(), repo_dir) self.assertEqual(list(changes), [b'foo1']) def test_get_unstaged_changes_removed_replaced_by_directory(self): """Unit test for get_unstaged_changes.""" repo_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, repo_dir) with Repo.init(repo_dir) as repo: # Commit a dummy file then modify it foo1_fullpath = os.path.join(repo_dir, 'foo1') with open(foo1_fullpath, 'wb') as f: f.write(b'origstuff') repo.stage(['foo1']) repo.do_commit(b'test status', author=b'author ', committer=b'committer ') os.remove(foo1_fullpath) os.mkdir(foo1_fullpath) changes = get_unstaged_changes(repo.open_index(), repo_dir) self.assertEqual(list(changes), [b'foo1']) @skipIf(not can_symlink(), 'Requires symlink support') def test_get_unstaged_changes_removed_replaced_by_link(self): """Unit test for get_unstaged_changes.""" repo_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, repo_dir) with Repo.init(repo_dir) as repo: # Commit a dummy file then modify it foo1_fullpath = os.path.join(repo_dir, 'foo1') with open(foo1_fullpath, 'wb') as f: f.write(b'origstuff') repo.stage(['foo1']) repo.do_commit(b'test status', author=b'author ', committer=b'committer ') os.remove(foo1_fullpath) os.symlink(os.path.dirname(foo1_fullpath), foo1_fullpath) changes = get_unstaged_changes(repo.open_index(), repo_dir) self.assertEqual(list(changes), [b'foo1']) class TestValidatePathElement(TestCase): def test_default(self): self.assertTrue(validate_path_element_default(b"bla")) self.assertTrue(validate_path_element_default(b".bla")) self.assertFalse(validate_path_element_default(b".git")) self.assertFalse(validate_path_element_default(b".giT")) self.assertFalse(validate_path_element_default(b"..")) self.assertTrue(validate_path_element_default(b"git~1")) def test_ntfs(self): self.assertTrue(validate_path_element_ntfs(b"bla")) self.assertTrue(validate_path_element_ntfs(b".bla")) self.assertFalse(validate_path_element_ntfs(b".git")) self.assertFalse(validate_path_element_ntfs(b".giT")) self.assertFalse(validate_path_element_ntfs(b"..")) self.assertFalse(validate_path_element_ntfs(b"git~1")) class TestTreeFSPathConversion(TestCase): def test_tree_to_fs_path(self): tree_path = u'délwíçh/foo'.encode('utf8') fs_path = _tree_to_fs_path(b'/prefix/path', tree_path) self.assertEqual( fs_path, os.path.join(u'/prefix/path', u'délwíçh', u'foo').encode('utf8')) def test_fs_to_tree_path_str(self): fs_path = os.path.join(os.path.join(u'délwíçh', u'foo')) tree_path = _fs_to_tree_path(fs_path, "utf-8") self.assertEqual(tree_path, u'délwíçh/foo'.encode("utf-8")) def test_fs_to_tree_path_bytes(self): fs_path = os.path.join(os.path.join(u'délwíçh', u'foo').encode('utf8')) tree_path = _fs_to_tree_path(fs_path, "utf-8") self.assertEqual(tree_path, u'délwíçh/foo'.encode('utf8')) diff --git a/dulwich/tests/test_patch.py b/dulwich/tests/test_patch.py index 0c407277..8deeab81 100644 --- a/dulwich/tests/test_patch.py +++ b/dulwich/tests/test_patch.py @@ -1,552 +1,552 @@ # test_patch.py -- tests for patch.py # Copyright (C) 2010 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. # """Tests for patch.py.""" from io import BytesIO, StringIO from dulwich.objects import ( Blob, Commit, S_IFGITLINK, Tree, ) from dulwich.object_store import ( MemoryObjectStore, ) from dulwich.patch import ( get_summary, git_am_patch_split, write_blob_diff, write_commit_patch, write_object_diff, write_tree_diff, ) from dulwich.tests import ( SkipTest, TestCase, ) class WriteCommitPatchTests(TestCase): def test_simple_bytesio(self): f = BytesIO() c = Commit() c.committer = c.author = b"Jelmer " c.commit_time = c.author_time = 1271350201 c.commit_timezone = c.author_timezone = 0 c.message = b"This is the first line\nAnd this is the second line.\n" c.tree = Tree().id write_commit_patch(f, c, b"CONTENTS", (1, 1), version="custom") f.seek(0) lines = f.readlines() self.assertTrue(lines[0].startswith( b"From 0b0d34d1b5b596c928adc9a727a4b9e03d025298")) self.assertEqual(lines[1], b"From: Jelmer \n") self.assertTrue(lines[2].startswith(b"Date: ")) self.assertEqual([ b"Subject: [PATCH 1/1] This is the first line\n", b"And this is the second line.\n", b"\n", b"\n", b"---\n"], lines[3:8]) self.assertEqual([ b"CONTENTS-- \n", b"custom\n"], lines[-2:]) if len(lines) >= 12: # diffstat may not be present self.assertEqual(lines[8], b" 0 files changed\n") class ReadGitAmPatch(TestCase): def test_extract_string(self): text = b"""\ From ff643aae102d8870cac88e8f007e70f58f3a7363 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Thu, 15 Apr 2010 15:40:28 +0200 Subject: [PATCH 1/2] Remove executable bit from prey.ico (triggers a warning). --- pixmaps/prey.ico | Bin 9662 -> 9662 bytes 1 files changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 pixmaps/prey.ico -- 1.7.0.4 """ # noqa: W291 c, diff, version = git_am_patch_split( StringIO(text.decode("utf-8")), "utf-8") self.assertEqual(b"Jelmer Vernooij ", c.committer) self.assertEqual(b"Jelmer Vernooij ", c.author) self.assertEqual(b"Remove executable bit from prey.ico " b"(triggers a warning).\n", c.message) self.assertEqual(b""" pixmaps/prey.ico | Bin 9662 -> 9662 bytes 1 files changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 pixmaps/prey.ico """, diff) self.assertEqual(b"1.7.0.4", version) def test_extract_bytes(self): text = b"""\ From ff643aae102d8870cac88e8f007e70f58f3a7363 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Thu, 15 Apr 2010 15:40:28 +0200 Subject: [PATCH 1/2] Remove executable bit from prey.ico (triggers a warning). --- pixmaps/prey.ico | Bin 9662 -> 9662 bytes 1 files changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 pixmaps/prey.ico -- 1.7.0.4 """ # noqa: W291 c, diff, version = git_am_patch_split(BytesIO(text)) self.assertEqual(b"Jelmer Vernooij ", c.committer) self.assertEqual(b"Jelmer Vernooij ", c.author) self.assertEqual(b"Remove executable bit from prey.ico " b"(triggers a warning).\n", c.message) self.assertEqual(b""" pixmaps/prey.ico | Bin 9662 -> 9662 bytes 1 files changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 pixmaps/prey.ico """, diff) self.assertEqual(b"1.7.0.4", version) def test_extract_spaces(self): text = b"""From ff643aae102d8870cac88e8f007e70f58f3a7363 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Thu, 15 Apr 2010 15:40:28 +0200 Subject: [Dulwich-users] [PATCH] Added unit tests for dulwich.object_store.tree_lookup_path. * dulwich/tests/test_object_store.py (TreeLookupPathTests): This test case contains a few tests that ensure the tree_lookup_path function works as expected. --- pixmaps/prey.ico | Bin 9662 -> 9662 bytes 1 files changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 pixmaps/prey.ico -- 1.7.0.4 """ # noqa: W291 c, diff, version = git_am_patch_split(BytesIO(text), "utf-8") self.assertEqual(b'''\ Added unit tests for dulwich.object_store.tree_lookup_path. * dulwich/tests/test_object_store.py (TreeLookupPathTests): This test case contains a few tests that ensure the tree_lookup_path function works as expected. ''', c.message) def test_extract_pseudo_from_header(self): text = b"""From ff643aae102d8870cac88e8f007e70f58f3a7363 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Thu, 15 Apr 2010 15:40:28 +0200 Subject: [Dulwich-users] [PATCH] Added unit tests for dulwich.object_store.tree_lookup_path. From: Jelmer Vernooij * dulwich/tests/test_object_store.py (TreeLookupPathTests): This test case contains a few tests that ensure the tree_lookup_path function works as expected. --- pixmaps/prey.ico | Bin 9662 -> 9662 bytes 1 files changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 pixmaps/prey.ico -- 1.7.0.4 """ # noqa: W291 c, diff, version = git_am_patch_split(BytesIO(text), "utf-8") self.assertEqual(b"Jelmer Vernooij ", c.author) self.assertEqual(b'''\ Added unit tests for dulwich.object_store.tree_lookup_path. * dulwich/tests/test_object_store.py (TreeLookupPathTests): This test case contains a few tests that ensure the tree_lookup_path function works as expected. ''', c.message) def test_extract_no_version_tail(self): text = b"""\ From ff643aae102d8870cac88e8f007e70f58f3a7363 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Thu, 15 Apr 2010 15:40:28 +0200 Subject: [Dulwich-users] [PATCH] Added unit tests for dulwich.object_store.tree_lookup_path. From: Jelmer Vernooij --- pixmaps/prey.ico | Bin 9662 -> 9662 bytes 1 files changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 pixmaps/prey.ico """ c, diff, version = git_am_patch_split(BytesIO(text), "utf-8") self.assertEqual(None, version) def test_extract_mercurial(self): raise SkipTest( "git_am_patch_split doesn't handle Mercurial patches " "properly yet") expected_diff = """\ diff --git a/dulwich/tests/test_patch.py b/dulwich/tests/test_patch.py --- a/dulwich/tests/test_patch.py +++ b/dulwich/tests/test_patch.py @@ -158,7 +158,7 @@ ''' c, diff, version = git_am_patch_split(BytesIO(text)) - self.assertIs(None, version) + self.assertEqual(None, version) class DiffTests(TestCase): """ # noqa: W291,W293 text = """\ From dulwich-users-bounces+jelmer=samba.org@lists.launchpad.net \ Mon Nov 29 00:58:18 2010 Date: Sun, 28 Nov 2010 17:57:27 -0600 From: Augie Fackler To: dulwich-users Subject: [Dulwich-users] [PATCH] test_patch: fix tests on Python 2.6 Content-Transfer-Encoding: 8bit Change-Id: I5e51313d4ae3a65c3f00c665002a7489121bb0d6 %s _______________________________________________ Mailing list: https://launchpad.net/~dulwich-users Post to : dulwich-users@lists.launchpad.net Unsubscribe : https://launchpad.net/~dulwich-users More help : https://help.launchpad.net/ListHelp """ % expected_diff # noqa: W291 c, diff, version = git_am_patch_split(BytesIO(text)) self.assertEqual(expected_diff, diff) self.assertEqual(None, version) class DiffTests(TestCase): """Tests for write_blob_diff and write_tree_diff.""" def test_blob_diff(self): f = BytesIO() write_blob_diff( f, (b"foo.txt", 0o644, Blob.from_string(b"old\nsame\n")), (b"bar.txt", 0o644, Blob.from_string(b"new\nsame\n"))) self.assertEqual([ b"diff --git a/foo.txt b/bar.txt", b"index 3b0f961..a116b51 644", b"--- a/foo.txt", b"+++ b/bar.txt", b"@@ -1,2 +1,2 @@", b"-old", b"+new", b" same" ], f.getvalue().splitlines()) def test_blob_add(self): f = BytesIO() write_blob_diff( f, (None, None, None), (b"bar.txt", 0o644, Blob.from_string(b"new\nsame\n"))) self.assertEqual([ b'diff --git a/bar.txt b/bar.txt', b'new file mode 644', b'index 0000000..a116b51', b'--- /dev/null', b'+++ b/bar.txt', b'@@ -0,0 +1,2 @@', b'+new', b'+same' ], f.getvalue().splitlines()) def test_blob_remove(self): f = BytesIO() write_blob_diff( f, (b"bar.txt", 0o644, Blob.from_string(b"new\nsame\n")), (None, None, None)) self.assertEqual([ b'diff --git a/bar.txt b/bar.txt', b'deleted file mode 644', b'index a116b51..0000000', b'--- a/bar.txt', b'+++ /dev/null', b'@@ -1,2 +0,0 @@', b'-new', b'-same' ], f.getvalue().splitlines()) def test_tree_diff(self): f = BytesIO() store = MemoryObjectStore() added = Blob.from_string(b"add\n") removed = Blob.from_string(b"removed\n") changed1 = Blob.from_string(b"unchanged\nremoved\n") changed2 = Blob.from_string(b"unchanged\nadded\n") unchanged = Blob.from_string(b"unchanged\n") tree1 = Tree() tree1.add(b"removed.txt", 0o644, removed.id) tree1.add(b"changed.txt", 0o644, changed1.id) tree1.add(b"unchanged.txt", 0o644, changed1.id) tree2 = Tree() tree2.add(b"added.txt", 0o644, added.id) tree2.add(b"changed.txt", 0o644, changed2.id) tree2.add(b"unchanged.txt", 0o644, changed1.id) store.add_objects([(o, None) for o in [ tree1, tree2, added, removed, changed1, changed2, unchanged]]) write_tree_diff(f, store, tree1.id, tree2.id) self.assertEqual([ b'diff --git a/added.txt b/added.txt', b'new file mode 644', b'index 0000000..76d4bb8', b'--- /dev/null', b'+++ b/added.txt', b'@@ -0,0 +1 @@', b'+add', b'diff --git a/changed.txt b/changed.txt', b'index bf84e48..1be2436 644', b'--- a/changed.txt', b'+++ b/changed.txt', b'@@ -1,2 +1,2 @@', b' unchanged', b'-removed', b'+added', b'diff --git a/removed.txt b/removed.txt', b'deleted file mode 644', b'index 2c3f0b3..0000000', b'--- a/removed.txt', b'+++ /dev/null', b'@@ -1 +0,0 @@', b'-removed', ], f.getvalue().splitlines()) def test_tree_diff_submodule(self): f = BytesIO() store = MemoryObjectStore() tree1 = Tree() tree1.add(b"asubmodule", S_IFGITLINK, b"06d0bdd9e2e20377b3180e4986b14c8549b393e4") tree2 = Tree() tree2.add(b"asubmodule", S_IFGITLINK, b"cc975646af69f279396d4d5e1379ac6af80ee637") store.add_objects([(o, None) for o in [tree1, tree2]]) write_tree_diff(f, store, tree1.id, tree2.id) self.assertEqual([ b'diff --git a/asubmodule b/asubmodule', b'index 06d0bdd..cc97564 160000', b'--- a/asubmodule', b'+++ b/asubmodule', b'@@ -1 +1 @@', - b'-Submodule commit 06d0bdd9e2e20377b3180e4986b14c8549b393e4', - b'+Submodule commit cc975646af69f279396d4d5e1379ac6af80ee637', + b'-Subproject commit 06d0bdd9e2e20377b3180e4986b14c8549b393e4', + b'+Subproject commit cc975646af69f279396d4d5e1379ac6af80ee637', ], f.getvalue().splitlines()) def test_object_diff_blob(self): f = BytesIO() b1 = Blob.from_string(b"old\nsame\n") b2 = Blob.from_string(b"new\nsame\n") store = MemoryObjectStore() store.add_objects([(b1, None), (b2, None)]) write_object_diff(f, store, (b"foo.txt", 0o644, b1.id), (b"bar.txt", 0o644, b2.id)) self.assertEqual([ b"diff --git a/foo.txt b/bar.txt", b"index 3b0f961..a116b51 644", b"--- a/foo.txt", b"+++ b/bar.txt", b"@@ -1,2 +1,2 @@", b"-old", b"+new", b" same" ], f.getvalue().splitlines()) def test_object_diff_add_blob(self): f = BytesIO() store = MemoryObjectStore() b2 = Blob.from_string(b"new\nsame\n") store.add_object(b2) write_object_diff(f, store, (None, None, None), (b"bar.txt", 0o644, b2.id)) self.assertEqual([ b'diff --git a/bar.txt b/bar.txt', b'new file mode 644', b'index 0000000..a116b51', b'--- /dev/null', b'+++ b/bar.txt', b'@@ -0,0 +1,2 @@', b'+new', b'+same' ], f.getvalue().splitlines()) def test_object_diff_remove_blob(self): f = BytesIO() b1 = Blob.from_string(b"new\nsame\n") store = MemoryObjectStore() store.add_object(b1) write_object_diff(f, store, (b"bar.txt", 0o644, b1.id), (None, None, None)) self.assertEqual([ b'diff --git a/bar.txt b/bar.txt', b'deleted file mode 644', b'index a116b51..0000000', b'--- a/bar.txt', b'+++ /dev/null', b'@@ -1,2 +0,0 @@', b'-new', b'-same' ], f.getvalue().splitlines()) def test_object_diff_bin_blob_force(self): f = BytesIO() # Prepare two slightly different PNG headers b1 = Blob.from_string( b"\x89\x50\x4e\x47\x0d\x0a\x1a\x0a" b"\x00\x00\x00\x0d\x49\x48\x44\x52" b"\x00\x00\x01\xd5\x00\x00\x00\x9f" b"\x08\x04\x00\x00\x00\x05\x04\x8b") b2 = Blob.from_string( b"\x89\x50\x4e\x47\x0d\x0a\x1a\x0a" b"\x00\x00\x00\x0d\x49\x48\x44\x52" b"\x00\x00\x01\xd5\x00\x00\x00\x9f" b"\x08\x03\x00\x00\x00\x98\xd3\xb3") store = MemoryObjectStore() store.add_objects([(b1, None), (b2, None)]) write_object_diff( f, store, (b'foo.png', 0o644, b1.id), (b'bar.png', 0o644, b2.id), diff_binary=True) self.assertEqual([ b'diff --git a/foo.png b/bar.png', b'index f73e47d..06364b7 644', b'--- a/foo.png', b'+++ b/bar.png', b'@@ -1,4 +1,4 @@', b' \x89PNG', b' \x1a', b' \x00\x00\x00', b'-IHDR\x00\x00\x01\xd5\x00\x00\x00' b'\x9f\x08\x04\x00\x00\x00\x05\x04\x8b', b'\\ No newline at end of file', b'+IHDR\x00\x00\x01\xd5\x00\x00\x00\x9f' b'\x08\x03\x00\x00\x00\x98\xd3\xb3', b'\\ No newline at end of file' ], f.getvalue().splitlines()) def test_object_diff_bin_blob(self): f = BytesIO() # Prepare two slightly different PNG headers b1 = Blob.from_string( b"\x89\x50\x4e\x47\x0d\x0a\x1a\x0a" b"\x00\x00\x00\x0d\x49\x48\x44\x52" b"\x00\x00\x01\xd5\x00\x00\x00\x9f" b"\x08\x04\x00\x00\x00\x05\x04\x8b") b2 = Blob.from_string( b"\x89\x50\x4e\x47\x0d\x0a\x1a\x0a" b"\x00\x00\x00\x0d\x49\x48\x44\x52" b"\x00\x00\x01\xd5\x00\x00\x00\x9f" b"\x08\x03\x00\x00\x00\x98\xd3\xb3") store = MemoryObjectStore() store.add_objects([(b1, None), (b2, None)]) write_object_diff(f, store, (b'foo.png', 0o644, b1.id), (b'bar.png', 0o644, b2.id)) self.assertEqual([ b'diff --git a/foo.png b/bar.png', b'index f73e47d..06364b7 644', b'Binary files a/foo.png and b/bar.png differ' ], f.getvalue().splitlines()) def test_object_diff_add_bin_blob(self): f = BytesIO() b2 = Blob.from_string( b'\x89\x50\x4e\x47\x0d\x0a\x1a\x0a' b'\x00\x00\x00\x0d\x49\x48\x44\x52' b'\x00\x00\x01\xd5\x00\x00\x00\x9f' b'\x08\x03\x00\x00\x00\x98\xd3\xb3') store = MemoryObjectStore() store.add_object(b2) write_object_diff(f, store, (None, None, None), (b'bar.png', 0o644, b2.id)) self.assertEqual([ b'diff --git a/bar.png b/bar.png', b'new file mode 644', b'index 0000000..06364b7', b'Binary files /dev/null and b/bar.png differ' ], f.getvalue().splitlines()) def test_object_diff_remove_bin_blob(self): f = BytesIO() b1 = Blob.from_string( b'\x89\x50\x4e\x47\x0d\x0a\x1a\x0a' b'\x00\x00\x00\x0d\x49\x48\x44\x52' b'\x00\x00\x01\xd5\x00\x00\x00\x9f' b'\x08\x04\x00\x00\x00\x05\x04\x8b') store = MemoryObjectStore() store.add_object(b1) write_object_diff(f, store, (b'foo.png', 0o644, b1.id), (None, None, None)) self.assertEqual([ b'diff --git a/foo.png b/foo.png', b'deleted file mode 644', b'index f73e47d..0000000', b'Binary files a/foo.png and /dev/null differ' ], f.getvalue().splitlines()) def test_object_diff_kind_change(self): f = BytesIO() b1 = Blob.from_string(b"new\nsame\n") store = MemoryObjectStore() store.add_object(b1) write_object_diff( f, store, (b"bar.txt", 0o644, b1.id), (b"bar.txt", 0o160000, b"06d0bdd9e2e20377b3180e4986b14c8549b393e4")) self.assertEqual([ b'diff --git a/bar.txt b/bar.txt', b'old file mode 644', b'new file mode 160000', b'index a116b51..06d0bdd 160000', b'--- a/bar.txt', b'+++ b/bar.txt', b'@@ -1,2 +1 @@', b'-new', b'-same', - b'+Submodule commit 06d0bdd9e2e20377b3180e4986b14c8549b393e4', + b'+Subproject commit 06d0bdd9e2e20377b3180e4986b14c8549b393e4', ], f.getvalue().splitlines()) class GetSummaryTests(TestCase): def test_simple(self): c = Commit() c.committer = c.author = b"Jelmer " c.commit_time = c.author_time = 1271350201 c.commit_timezone = c.author_timezone = 0 c.message = b"This is the first line\nAnd this is the second line.\n" c.tree = Tree().id self.assertEqual('This-is-the-first-line', get_summary(c)) diff --git a/dulwich/tests/test_porcelain.py b/dulwich/tests/test_porcelain.py index 896520be..721a9a30 100644 --- a/dulwich/tests/test_porcelain.py +++ b/dulwich/tests/test_porcelain.py @@ -1,1809 +1,1829 @@ # test_porcelain.py -- porcelain tests # Copyright (C) 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. # """Tests for dulwich.porcelain.""" from io import BytesIO try: from StringIO import StringIO except ImportError: from io import StringIO import errno import os import shutil import tarfile import tempfile import time from dulwich import porcelain from dulwich.diff_tree import tree_changes from dulwich.objects import ( Blob, Tag, Tree, ZERO_SHA, ) from dulwich.repo import ( NoIndexPresent, Repo, ) from dulwich.tests import ( TestCase, ) from dulwich.tests.utils import ( build_commit_graph, make_commit, make_object, ) def flat_walk_dir(dir_to_walk): for dirpath, _, filenames in os.walk(dir_to_walk): rel_dirpath = os.path.relpath(dirpath, dir_to_walk) if not dirpath == dir_to_walk: yield rel_dirpath for filename in filenames: if dirpath == dir_to_walk: yield filename else: yield os.path.join(rel_dirpath, filename) class PorcelainTestCase(TestCase): def setUp(self): super(PorcelainTestCase, self).setUp() self.test_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, self.test_dir) self.repo_path = os.path.join(self.test_dir, 'repo') self.repo = Repo.init(self.repo_path, mkdir=True) self.addCleanup(self.repo.close) class ArchiveTests(PorcelainTestCase): """Tests for the archive command.""" def test_simple(self): c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]]) self.repo.refs[b"refs/heads/master"] = c3.id out = BytesIO() err = BytesIO() porcelain.archive(self.repo.path, b"refs/heads/master", outstream=out, errstream=err) self.assertEqual(b"", err.getvalue()) tf = tarfile.TarFile(fileobj=out) self.addCleanup(tf.close) self.assertEqual([], tf.getnames()) class UpdateServerInfoTests(PorcelainTestCase): def test_simple(self): c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]]) self.repo.refs[b"refs/heads/foo"] = c3.id porcelain.update_server_info(self.repo.path) self.assertTrue(os.path.exists( os.path.join(self.repo.controldir(), 'info', 'refs'))) class CommitTests(PorcelainTestCase): def test_custom_author(self): c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]]) self.repo.refs[b"refs/heads/foo"] = c3.id sha = porcelain.commit( self.repo.path, message=b"Some message", author=b"Joe ", committer=b"Bob ") self.assertTrue(isinstance(sha, bytes)) self.assertEqual(len(sha), 40) def test_unicode(self): c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]]) self.repo.refs[b"refs/heads/foo"] = c3.id sha = porcelain.commit( self.repo.path, message="Some message", author="Joe ", committer="Bob ") self.assertTrue(isinstance(sha, bytes)) self.assertEqual(len(sha), 40) class CleanTests(PorcelainTestCase): def put_files(self, tracked, ignored, untracked, empty_dirs): """Put the described files in the wd """ all_files = tracked | ignored | untracked for file_path in all_files: abs_path = os.path.join(self.repo.path, file_path) # File may need to be written in a dir that doesn't exist yet, so # create the parent dir(s) as necessary parent_dir = os.path.dirname(abs_path) try: os.makedirs(parent_dir) except OSError as err: if not err.errno == errno.EEXIST: raise err with open(abs_path, 'w') as f: f.write('') with open(os.path.join(self.repo.path, '.gitignore'), 'w') as f: f.writelines(ignored) for dir_path in empty_dirs: os.mkdir(os.path.join(self.repo.path, 'empty_dir')) files_to_add = [os.path.join(self.repo.path, t) for t in tracked] porcelain.add(repo=self.repo.path, paths=files_to_add) porcelain.commit(repo=self.repo.path, message="init commit") def assert_wd(self, expected_paths): """Assert paths of files and dirs in wd are same as expected_paths """ control_dir_rel = os.path.relpath( self.repo._controldir, self.repo.path) # normalize paths to simplify comparison across platforms found_paths = { os.path.normpath(p) for p in flat_walk_dir(self.repo.path) if not p.split(os.sep)[0] == control_dir_rel} norm_expected_paths = {os.path.normpath(p) for p in expected_paths} self.assertEqual(found_paths, norm_expected_paths) def test_from_root(self): self.put_files( tracked={ 'tracked_file', 'tracked_dir/tracked_file', '.gitignore'}, ignored={ 'ignored_file'}, untracked={ 'untracked_file', 'tracked_dir/untracked_dir/untracked_file', 'untracked_dir/untracked_dir/untracked_file'}, empty_dirs={ 'empty_dir'}) porcelain.clean(repo=self.repo.path, target_dir=self.repo.path) self.assert_wd({ 'tracked_file', 'tracked_dir/tracked_file', '.gitignore', 'ignored_file', 'tracked_dir'}) def test_from_subdir(self): self.put_files( tracked={ 'tracked_file', 'tracked_dir/tracked_file', '.gitignore'}, ignored={ 'ignored_file'}, untracked={ 'untracked_file', 'tracked_dir/untracked_dir/untracked_file', 'untracked_dir/untracked_dir/untracked_file'}, empty_dirs={ 'empty_dir'}) porcelain.clean( repo=self.repo, target_dir=os.path.join(self.repo.path, 'untracked_dir')) self.assert_wd({ 'tracked_file', 'tracked_dir/tracked_file', '.gitignore', 'ignored_file', 'untracked_file', 'tracked_dir/untracked_dir/untracked_file', 'empty_dir', 'untracked_dir', 'tracked_dir', 'tracked_dir/untracked_dir'}) class CloneTests(PorcelainTestCase): def test_simple_local(self): f1_1 = make_object(Blob, data=b'f1') commit_spec = [[1], [2, 1], [3, 1, 2]] trees = {1: [(b'f1', f1_1), (b'f2', f1_1)], 2: [(b'f1', f1_1), (b'f2', f1_1)], 3: [(b'f1', f1_1), (b'f2', f1_1)], } c1, c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees) self.repo.refs[b"refs/heads/master"] = c3.id self.repo.refs[b"refs/tags/foo"] = c3.id target_path = tempfile.mkdtemp() errstream = BytesIO() self.addCleanup(shutil.rmtree, target_path) r = porcelain.clone(self.repo.path, target_path, checkout=False, errstream=errstream) self.addCleanup(r.close) self.assertEqual(r.path, target_path) target_repo = Repo(target_path) self.assertEqual(0, len(target_repo.open_index())) self.assertEqual(c3.id, target_repo.refs[b'refs/tags/foo']) self.assertTrue(b'f1' not in os.listdir(target_path)) self.assertTrue(b'f2' not in os.listdir(target_path)) c = r.get_config() encoded_path = self.repo.path if not isinstance(encoded_path, bytes): encoded_path = encoded_path.encode('utf-8') self.assertEqual(encoded_path, c.get((b'remote', b'origin'), b'url')) self.assertEqual( b'+refs/heads/*:refs/remotes/origin/*', c.get((b'remote', b'origin'), b'fetch')) def test_simple_local_with_checkout(self): f1_1 = make_object(Blob, data=b'f1') commit_spec = [[1], [2, 1], [3, 1, 2]] trees = {1: [(b'f1', f1_1), (b'f2', f1_1)], 2: [(b'f1', f1_1), (b'f2', f1_1)], 3: [(b'f1', f1_1), (b'f2', f1_1)], } c1, c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees) self.repo.refs[b"refs/heads/master"] = c3.id target_path = tempfile.mkdtemp() errstream = BytesIO() self.addCleanup(shutil.rmtree, target_path) with porcelain.clone(self.repo.path, target_path, checkout=True, errstream=errstream) as r: self.assertEqual(r.path, target_path) with Repo(target_path) as r: self.assertEqual(r.head(), c3.id) self.assertTrue('f1' in os.listdir(target_path)) self.assertTrue('f2' in os.listdir(target_path)) def test_bare_local_with_checkout(self): f1_1 = make_object(Blob, data=b'f1') commit_spec = [[1], [2, 1], [3, 1, 2]] trees = {1: [(b'f1', f1_1), (b'f2', f1_1)], 2: [(b'f1', f1_1), (b'f2', f1_1)], 3: [(b'f1', f1_1), (b'f2', f1_1)], } c1, c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees) self.repo.refs[b"refs/heads/master"] = c3.id target_path = tempfile.mkdtemp() errstream = BytesIO() self.addCleanup(shutil.rmtree, target_path) with porcelain.clone( self.repo.path, target_path, bare=True, errstream=errstream) as r: self.assertEqual(r.path, target_path) with Repo(target_path) as r: r.head() self.assertRaises(NoIndexPresent, r.open_index) self.assertFalse(b'f1' in os.listdir(target_path)) self.assertFalse(b'f2' in os.listdir(target_path)) def test_no_checkout_with_bare(self): f1_1 = make_object(Blob, data=b'f1') commit_spec = [[1]] trees = {1: [(b'f1', f1_1), (b'f2', f1_1)]} (c1, ) = build_commit_graph(self.repo.object_store, commit_spec, trees) self.repo.refs[b"refs/heads/master"] = c1.id self.repo.refs[b"HEAD"] = c1.id target_path = tempfile.mkdtemp() errstream = BytesIO() self.addCleanup(shutil.rmtree, target_path) self.assertRaises( ValueError, porcelain.clone, self.repo.path, target_path, checkout=True, bare=True, errstream=errstream) def test_no_head_no_checkout(self): f1_1 = make_object(Blob, data=b'f1') commit_spec = [[1]] trees = {1: [(b'f1', f1_1), (b'f2', f1_1)]} (c1, ) = build_commit_graph(self.repo.object_store, commit_spec, trees) self.repo.refs[b"refs/heads/master"] = c1.id target_path = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, target_path) errstream = BytesIO() r = porcelain.clone( self.repo.path, target_path, checkout=True, errstream=errstream) r.close() def test_no_head_no_checkout_outstream_errstream_autofallback(self): f1_1 = make_object(Blob, data=b'f1') commit_spec = [[1]] trees = {1: [(b'f1', f1_1), (b'f2', f1_1)]} (c1, ) = build_commit_graph(self.repo.object_store, commit_spec, trees) self.repo.refs[b"refs/heads/master"] = c1.id target_path = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, target_path) errstream = porcelain.NoneStream() r = porcelain.clone( self.repo.path, target_path, checkout=True, errstream=errstream) r.close() def test_source_broken(self): target_path = tempfile.mkdtemp() self.assertRaises( Exception, porcelain.clone, '/nonexistant/repo', target_path) self.assertFalse(os.path.exists(target_path)) class InitTests(TestCase): def test_non_bare(self): repo_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, repo_dir) porcelain.init(repo_dir) def test_bare(self): repo_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, repo_dir) porcelain.init(repo_dir, bare=True) class AddTests(PorcelainTestCase): def test_add_default_paths(self): # create a file for initial commit fullpath = os.path.join(self.repo.path, 'blah') with open(fullpath, 'w') as f: f.write("\n") porcelain.add(repo=self.repo.path, paths=[fullpath]) porcelain.commit(repo=self.repo.path, message=b'test', author=b'test ', committer=b'test ') # Add a second test file and a file in a directory with open(os.path.join(self.repo.path, 'foo'), 'w') as f: f.write("\n") os.mkdir(os.path.join(self.repo.path, 'adir')) with open(os.path.join(self.repo.path, 'adir', 'afile'), 'w') as f: f.write("\n") cwd = os.getcwd() try: os.chdir(self.repo.path) porcelain.add(self.repo.path) finally: os.chdir(cwd) # Check that foo was added and nothing in .git was modified index = self.repo.open_index() self.assertEqual(sorted(index), [b'adir/afile', b'blah', b'foo']) def test_add_default_paths_subdir(self): os.mkdir(os.path.join(self.repo.path, 'foo')) with open(os.path.join(self.repo.path, 'blah'), 'w') as f: f.write("\n") with open(os.path.join(self.repo.path, 'foo', 'blie'), 'w') as f: f.write("\n") cwd = os.getcwd() try: os.chdir(os.path.join(self.repo.path, 'foo')) porcelain.add(repo=self.repo.path) porcelain.commit(repo=self.repo.path, message=b'test', author=b'test ', committer=b'test ') finally: os.chdir(cwd) index = self.repo.open_index() self.assertEqual(sorted(index), [b'foo/blie']) def test_add_file(self): fullpath = os.path.join(self.repo.path, 'foo') with open(fullpath, 'w') as f: f.write("BAR") porcelain.add(self.repo.path, paths=[fullpath]) self.assertIn(b"foo", self.repo.open_index()) def test_add_ignored(self): with open(os.path.join(self.repo.path, '.gitignore'), 'w') as f: f.write("foo") with open(os.path.join(self.repo.path, 'foo'), 'w') as f: f.write("BAR") with open(os.path.join(self.repo.path, 'bar'), 'w') as f: f.write("BAR") (added, ignored) = porcelain.add(self.repo.path, paths=[ os.path.join(self.repo.path, "foo"), os.path.join(self.repo.path, "bar")]) self.assertIn(b"bar", self.repo.open_index()) self.assertEqual(set(['bar']), set(added)) self.assertEqual(set(['foo']), ignored) def test_add_file_absolute_path(self): # Absolute paths are (not yet) supported with open(os.path.join(self.repo.path, 'foo'), 'w') as f: f.write("BAR") porcelain.add(self.repo, paths=[os.path.join(self.repo.path, "foo")]) self.assertIn(b"foo", self.repo.open_index()) def test_add_not_in_repo(self): with open(os.path.join(self.test_dir, 'foo'), 'w') as f: f.write("BAR") self.assertRaises( ValueError, porcelain.add, self.repo, paths=[os.path.join(self.test_dir, "foo")]) self.assertRaises( ValueError, porcelain.add, self.repo, paths=["../foo"]) self.assertEqual([], list(self.repo.open_index())) def test_add_file_clrf_conversion(self): # Set the right configuration to the repo c = self.repo.get_config() c.set("core", "autocrlf", "input") c.write_to_path() # Add a file with CRLF line-ending fullpath = os.path.join(self.repo.path, 'foo') with open(fullpath, 'wb') as f: f.write(b"line1\r\nline2") porcelain.add(self.repo.path, paths=[fullpath]) # The line-endings should have been converted to LF index = self.repo.open_index() self.assertIn(b"foo", index) entry = index[b"foo"] blob = self.repo[entry.sha] self.assertEqual(blob.data, b"line1\nline2") class RemoveTests(PorcelainTestCase): def test_remove_file(self): fullpath = os.path.join(self.repo.path, 'foo') with open(fullpath, 'w') as f: f.write("BAR") porcelain.add(self.repo.path, paths=[fullpath]) porcelain.commit(repo=self.repo, message=b'test', author=b'test ', committer=b'test ') self.assertTrue(os.path.exists(os.path.join(self.repo.path, 'foo'))) cwd = os.getcwd() try: os.chdir(self.repo.path) porcelain.remove(self.repo.path, paths=["foo"]) finally: os.chdir(cwd) self.assertFalse(os.path.exists(os.path.join(self.repo.path, 'foo'))) def test_remove_file_staged(self): fullpath = os.path.join(self.repo.path, 'foo') with open(fullpath, 'w') as f: f.write("BAR") cwd = os.getcwd() try: os.chdir(self.repo.path) porcelain.add(self.repo.path, paths=[fullpath]) self.assertRaises(Exception, porcelain.rm, self.repo.path, paths=["foo"]) finally: os.chdir(cwd) class LogTests(PorcelainTestCase): def test_simple(self): c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]]) self.repo.refs[b"HEAD"] = c3.id outstream = StringIO() porcelain.log(self.repo.path, outstream=outstream) self.assertEqual(3, outstream.getvalue().count("-" * 50)) def test_max_entries(self): c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]]) self.repo.refs[b"HEAD"] = c3.id outstream = StringIO() porcelain.log(self.repo.path, outstream=outstream, max_entries=1) self.assertEqual(1, outstream.getvalue().count("-" * 50)) class ShowTests(PorcelainTestCase): def test_nolist(self): c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]]) self.repo.refs[b"HEAD"] = c3.id outstream = StringIO() porcelain.show(self.repo.path, objects=c3.id, outstream=outstream) self.assertTrue(outstream.getvalue().startswith("-" * 50)) def test_simple(self): c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]]) self.repo.refs[b"HEAD"] = c3.id outstream = StringIO() porcelain.show(self.repo.path, objects=[c3.id], outstream=outstream) self.assertTrue(outstream.getvalue().startswith("-" * 50)) def test_blob(self): b = Blob.from_string(b"The Foo\n") self.repo.object_store.add_object(b) outstream = StringIO() porcelain.show(self.repo.path, objects=[b.id], outstream=outstream) self.assertEqual(outstream.getvalue(), "The Foo\n") def test_commit_no_parent(self): a = Blob.from_string(b"The Foo\n") ta = Tree() ta.add(b"somename", 0o100644, a.id) ca = make_commit(tree=ta.id) self.repo.object_store.add_objects([(a, None), (ta, None), (ca, None)]) outstream = StringIO() porcelain.show(self.repo.path, objects=[ca.id], outstream=outstream) self.assertMultiLineEqual(outstream.getvalue(), """\ -------------------------------------------------- commit: 344da06c1bb85901270b3e8875c988a027ec087d Author: Test Author Committer: Test Committer Date: Fri Jan 01 2010 00:00:00 +0000 Test message. diff --git a/somename b/somename new file mode 100644 index 0000000..ea5c7bf --- /dev/null +++ b/somename @@ -0,0 +1 @@ +The Foo """) def test_tag(self): a = Blob.from_string(b"The Foo\n") ta = Tree() ta.add(b"somename", 0o100644, a.id) ca = make_commit(tree=ta.id) self.repo.object_store.add_objects([(a, None), (ta, None), (ca, None)]) porcelain.tag_create( self.repo.path, b"tryme", b'foo ', b'bar', annotated=True, objectish=ca.id, tag_time=1552854211, tag_timezone=0) outstream = StringIO() porcelain.show(self.repo, objects=[b'refs/tags/tryme'], outstream=outstream) self.maxDiff = None self.assertMultiLineEqual(outstream.getvalue(), """\ Tagger: foo Date: Sun Mar 17 2019 20:23:31 +0000 bar -------------------------------------------------- commit: 344da06c1bb85901270b3e8875c988a027ec087d Author: Test Author Committer: Test Committer Date: Fri Jan 01 2010 00:00:00 +0000 Test message. diff --git a/somename b/somename new file mode 100644 index 0000000..ea5c7bf --- /dev/null +++ b/somename @@ -0,0 +1 @@ +The Foo """) def test_commit_with_change(self): a = Blob.from_string(b"The Foo\n") ta = Tree() ta.add(b"somename", 0o100644, a.id) ca = make_commit(tree=ta.id) b = Blob.from_string(b"The Bar\n") tb = Tree() tb.add(b"somename", 0o100644, b.id) cb = make_commit(tree=tb.id, parents=[ca.id]) self.repo.object_store.add_objects( [(a, None), (b, None), (ta, None), (tb, None), (ca, None), (cb, None)]) outstream = StringIO() porcelain.show(self.repo.path, objects=[cb.id], outstream=outstream) self.assertMultiLineEqual(outstream.getvalue(), """\ -------------------------------------------------- commit: 2c6b6c9cb72c130956657e1fdae58e5b103744fa Author: Test Author Committer: Test Committer Date: Fri Jan 01 2010 00:00:00 +0000 Test message. diff --git a/somename b/somename index ea5c7bf..fd38bcb 100644 --- a/somename +++ b/somename @@ -1 +1 @@ -The Foo +The Bar """) class SymbolicRefTests(PorcelainTestCase): def test_set_wrong_symbolic_ref(self): c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]]) self.repo.refs[b"HEAD"] = c3.id self.assertRaises(ValueError, porcelain.symbolic_ref, self.repo.path, b'foobar') def test_set_force_wrong_symbolic_ref(self): c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]]) self.repo.refs[b"HEAD"] = c3.id porcelain.symbolic_ref(self.repo.path, b'force_foobar', force=True) # test if we actually changed the file with self.repo.get_named_file('HEAD') as f: new_ref = f.read() self.assertEqual(new_ref, b'ref: refs/heads/force_foobar\n') def test_set_symbolic_ref(self): c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]]) self.repo.refs[b"HEAD"] = c3.id porcelain.symbolic_ref(self.repo.path, b'master') def test_set_symbolic_ref_other_than_master(self): c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]], attrs=dict(refs='develop')) self.repo.refs[b"HEAD"] = c3.id self.repo.refs[b"refs/heads/develop"] = c3.id porcelain.symbolic_ref(self.repo.path, b'develop') # test if we actually changed the file with self.repo.get_named_file('HEAD') as f: new_ref = f.read() self.assertEqual(new_ref, b'ref: refs/heads/develop\n') class DiffTreeTests(PorcelainTestCase): def test_empty(self): c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]]) self.repo.refs[b"HEAD"] = c3.id outstream = BytesIO() porcelain.diff_tree(self.repo.path, c2.tree, c3.tree, outstream=outstream) self.assertEqual(outstream.getvalue(), b"") class CommitTreeTests(PorcelainTestCase): def test_simple(self): c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]]) b = Blob() b.data = b"foo the bar" t = Tree() t.add(b"somename", 0o100644, b.id) self.repo.object_store.add_object(t) self.repo.object_store.add_object(b) sha = porcelain.commit_tree( self.repo.path, t.id, message=b"Withcommit.", author=b"Joe ", committer=b"Jane ") self.assertTrue(isinstance(sha, bytes)) self.assertEqual(len(sha), 40) class RevListTests(PorcelainTestCase): def test_simple(self): c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]]) outstream = BytesIO() porcelain.rev_list( self.repo.path, [c3.id], outstream=outstream) self.assertEqual( c3.id + b"\n" + c2.id + b"\n" + c1.id + b"\n", outstream.getvalue()) class TagCreateTests(PorcelainTestCase): def test_annotated(self): c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]]) self.repo.refs[b"HEAD"] = c3.id porcelain.tag_create(self.repo.path, b"tryme", b'foo ', b'bar', annotated=True) tags = self.repo.refs.as_dict(b"refs/tags") self.assertEqual(list(tags.keys()), [b"tryme"]) tag = self.repo[b'refs/tags/tryme'] self.assertTrue(isinstance(tag, Tag)) self.assertEqual(b"foo ", tag.tagger) self.assertEqual(b"bar", tag.message) self.assertLess(time.time() - tag.tag_time, 5) def test_unannotated(self): c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]]) self.repo.refs[b"HEAD"] = c3.id porcelain.tag_create(self.repo.path, b"tryme", annotated=False) tags = self.repo.refs.as_dict(b"refs/tags") self.assertEqual(list(tags.keys()), [b"tryme"]) self.repo[b'refs/tags/tryme'] self.assertEqual(list(tags.values()), [self.repo.head()]) def test_unannotated_unicode(self): c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]]) self.repo.refs[b"HEAD"] = c3.id porcelain.tag_create(self.repo.path, "tryme", annotated=False) tags = self.repo.refs.as_dict(b"refs/tags") self.assertEqual(list(tags.keys()), [b"tryme"]) self.repo[b'refs/tags/tryme'] self.assertEqual(list(tags.values()), [self.repo.head()]) class TagListTests(PorcelainTestCase): def test_empty(self): tags = porcelain.tag_list(self.repo.path) self.assertEqual([], tags) def test_simple(self): self.repo.refs[b"refs/tags/foo"] = b"aa" * 20 self.repo.refs[b"refs/tags/bar/bla"] = b"bb" * 20 tags = porcelain.tag_list(self.repo.path) self.assertEqual([b"bar/bla", b"foo"], tags) class TagDeleteTests(PorcelainTestCase): def test_simple(self): [c1] = build_commit_graph(self.repo.object_store, [[1]]) self.repo[b"HEAD"] = c1.id porcelain.tag_create(self.repo, b'foo') self.assertTrue(b"foo" in porcelain.tag_list(self.repo)) porcelain.tag_delete(self.repo, b'foo') self.assertFalse(b"foo" in porcelain.tag_list(self.repo)) class ResetTests(PorcelainTestCase): def test_hard_head(self): fullpath = os.path.join(self.repo.path, 'foo') with open(fullpath, 'w') as f: f.write("BAR") porcelain.add(self.repo.path, paths=[fullpath]) porcelain.commit(self.repo.path, message=b"Some message", committer=b"Jane ", author=b"John ") with open(os.path.join(self.repo.path, 'foo'), 'wb') as f: f.write(b"OOH") porcelain.reset(self.repo, "hard", b"HEAD") index = self.repo.open_index() changes = list(tree_changes(self.repo, index.commit(self.repo.object_store), self.repo[b'HEAD'].tree)) self.assertEqual([], changes) def test_hard_commit(self): fullpath = os.path.join(self.repo.path, 'foo') with open(fullpath, 'w') as f: f.write("BAR") porcelain.add(self.repo.path, paths=[fullpath]) sha = porcelain.commit(self.repo.path, message=b"Some message", committer=b"Jane ", author=b"John ") with open(fullpath, 'wb') as f: f.write(b"BAZ") porcelain.add(self.repo.path, paths=[fullpath]) porcelain.commit(self.repo.path, message=b"Some other message", committer=b"Jane ", author=b"John ") porcelain.reset(self.repo, "hard", sha) index = self.repo.open_index() changes = list(tree_changes(self.repo, index.commit(self.repo.object_store), self.repo[sha].tree)) self.assertEqual([], changes) class PushTests(PorcelainTestCase): def test_simple(self): """ Basic test of porcelain push where self.repo is the remote. First clone the remote, commit a file to the clone, then push the changes back to the remote. """ outstream = BytesIO() errstream = BytesIO() porcelain.commit(repo=self.repo.path, message=b'init', author=b'author ', committer=b'committer ') # Setup target repo cloned from temp test repo clone_path = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, clone_path) target_repo = porcelain.clone(self.repo.path, target=clone_path, errstream=errstream) try: self.assertEqual(target_repo[b'HEAD'], self.repo[b'HEAD']) finally: target_repo.close() # create a second file to be pushed back to origin handle, fullpath = tempfile.mkstemp(dir=clone_path) os.close(handle) porcelain.add(repo=clone_path, paths=[fullpath]) porcelain.commit(repo=clone_path, message=b'push', author=b'author ', committer=b'committer ') # Setup a non-checked out branch in the remote refs_path = b"refs/heads/foo" new_id = self.repo[b'HEAD'].id self.assertNotEqual(new_id, ZERO_SHA) self.repo.refs[refs_path] = new_id # Push to the remote porcelain.push(clone_path, self.repo.path, b"HEAD:" + refs_path, outstream=outstream, errstream=errstream) # Check that the target and source with Repo(clone_path) as r_clone: self.assertEqual({ b'HEAD': new_id, b'refs/heads/foo': r_clone[b'HEAD'].id, b'refs/heads/master': new_id, }, self.repo.get_refs()) self.assertEqual(r_clone[b'HEAD'].id, self.repo[refs_path].id) # Get the change in the target repo corresponding to the add # this will be in the foo branch. change = list(tree_changes(self.repo, self.repo[b'HEAD'].tree, self.repo[b'refs/heads/foo'].tree))[0] self.assertEqual(os.path.basename(fullpath), change.new.path.decode('ascii')) def test_delete(self): """Basic test of porcelain push, removing a branch. """ outstream = BytesIO() errstream = BytesIO() porcelain.commit(repo=self.repo.path, message=b'init', author=b'author ', committer=b'committer ') # Setup target repo cloned from temp test repo clone_path = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, clone_path) target_repo = porcelain.clone(self.repo.path, target=clone_path, errstream=errstream) target_repo.close() # Setup a non-checked out branch in the remote refs_path = b"refs/heads/foo" new_id = self.repo[b'HEAD'].id self.assertNotEqual(new_id, ZERO_SHA) self.repo.refs[refs_path] = new_id # Push to the remote porcelain.push(clone_path, self.repo.path, b":" + refs_path, outstream=outstream, errstream=errstream) self.assertEqual({ b'HEAD': new_id, b'refs/heads/master': new_id, }, self.repo.get_refs()) class PullTests(PorcelainTestCase): def setUp(self): super(PullTests, self).setUp() # create a file for initial commit handle, fullpath = tempfile.mkstemp(dir=self.repo.path) os.close(handle) porcelain.add(repo=self.repo.path, paths=fullpath) porcelain.commit(repo=self.repo.path, message=b'test', author=b'test ', committer=b'test ') # Setup target repo self.target_path = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, self.target_path) target_repo = porcelain.clone(self.repo.path, target=self.target_path, errstream=BytesIO()) target_repo.close() # create a second file to be pushed handle, fullpath = tempfile.mkstemp(dir=self.repo.path) os.close(handle) porcelain.add(repo=self.repo.path, paths=fullpath) porcelain.commit(repo=self.repo.path, message=b'test2', author=b'test2 ', committer=b'test2 ') self.assertTrue(b'refs/heads/master' in self.repo.refs) self.assertTrue(b'refs/heads/master' in target_repo.refs) def test_simple(self): outstream = BytesIO() errstream = BytesIO() # Pull changes into the cloned repo porcelain.pull(self.target_path, self.repo.path, b'refs/heads/master', outstream=outstream, errstream=errstream) # Check the target repo for pushed changes with Repo(self.target_path) as r: self.assertEqual(r[b'HEAD'].id, self.repo[b'HEAD'].id) def test_no_refspec(self): outstream = BytesIO() errstream = BytesIO() # Pull changes into the cloned repo porcelain.pull(self.target_path, self.repo.path, outstream=outstream, errstream=errstream) # Check the target repo for pushed changes with Repo(self.target_path) as r: self.assertEqual(r[b'HEAD'].id, self.repo[b'HEAD'].id) class StatusTests(PorcelainTestCase): def test_empty(self): results = porcelain.status(self.repo) self.assertEqual( {'add': [], 'delete': [], 'modify': []}, results.staged) self.assertEqual([], results.unstaged) def test_status_base(self): """Integration test for `status` functionality.""" # Commit a dummy file then modify it fullpath = os.path.join(self.repo.path, 'foo') with open(fullpath, 'w') as f: f.write('origstuff') porcelain.add(repo=self.repo.path, paths=[fullpath]) porcelain.commit(repo=self.repo.path, message=b'test status', author=b'author ', committer=b'committer ') # modify access and modify time of path os.utime(fullpath, (0, 0)) with open(fullpath, 'wb') as f: f.write(b'stuff') # Make a dummy file and stage it filename_add = 'bar' fullpath = os.path.join(self.repo.path, filename_add) with open(fullpath, 'w') as f: f.write('stuff') porcelain.add(repo=self.repo.path, paths=fullpath) results = porcelain.status(self.repo) self.assertEqual(results.staged['add'][0], filename_add.encode('ascii')) self.assertEqual(results.unstaged, [b'foo']) def test_status_all(self): del_path = os.path.join(self.repo.path, 'foo') mod_path = os.path.join(self.repo.path, 'bar') add_path = os.path.join(self.repo.path, 'baz') us_path = os.path.join(self.repo.path, 'blye') ut_path = os.path.join(self.repo.path, 'blyat') with open(del_path, 'w') as f: f.write('origstuff') with open(mod_path, 'w') as f: f.write('origstuff') with open(us_path, 'w') as f: f.write('origstuff') porcelain.add(repo=self.repo.path, paths=[del_path, mod_path, us_path]) porcelain.commit(repo=self.repo.path, message=b'test status', author=b'author ', committer=b'committer ') porcelain.remove(self.repo.path, [del_path]) with open(add_path, 'w') as f: f.write('origstuff') with open(mod_path, 'w') as f: f.write('more_origstuff') with open(us_path, 'w') as f: f.write('more_origstuff') porcelain.add(repo=self.repo.path, paths=[add_path, mod_path]) with open(us_path, 'w') as f: f.write('\norigstuff') with open(ut_path, 'w') as f: f.write('origstuff') results = porcelain.status(self.repo.path) self.assertDictEqual( {'add': [b'baz'], 'delete': [b'foo'], 'modify': [b'bar']}, results.staged) self.assertListEqual(results.unstaged, [b'blye']) self.assertListEqual(results.untracked, ['blyat']) def test_status_crlf_mismatch(self): # First make a commit as if the file has been added on a Linux system # or with core.autocrlf=True file_path = os.path.join(self.repo.path, 'crlf') with open(file_path, 'wb') as f: f.write(b'line1\nline2') porcelain.add(repo=self.repo.path, paths=[file_path]) porcelain.commit(repo=self.repo.path, message=b'test status', author=b'author ', committer=b'committer ') # Then update the file as if it was created by CGit on a Windows # system with core.autocrlf=true with open(file_path, 'wb') as f: f.write(b'line1\r\nline2') results = porcelain.status(self.repo) self.assertDictEqual( {'add': [], 'delete': [], 'modify': []}, results.staged) self.assertListEqual(results.unstaged, [b'crlf']) self.assertListEqual(results.untracked, []) def test_status_crlf_convert(self): # First make a commit as if the file has been added on a Linux system # or with core.autocrlf=True file_path = os.path.join(self.repo.path, 'crlf') with open(file_path, 'wb') as f: f.write(b'line1\nline2') porcelain.add(repo=self.repo.path, paths=[file_path]) porcelain.commit(repo=self.repo.path, message=b'test status', author=b'author ', committer=b'committer ') # Then update the file as if it was created by CGit on a Windows # system with core.autocrlf=true with open(file_path, 'wb') as f: f.write(b'line1\r\nline2') # TODO: It should be set automatically by looking at the configuration c = self.repo.get_config() c.set("core", "autocrlf", True) c.write_to_path() results = porcelain.status(self.repo) self.assertDictEqual( {'add': [], 'delete': [], 'modify': []}, results.staged) self.assertListEqual(results.unstaged, []) self.assertListEqual(results.untracked, []) def test_get_tree_changes_add(self): """Unit test for get_tree_changes add.""" # Make a dummy file, stage filename = 'bar' fullpath = os.path.join(self.repo.path, filename) with open(fullpath, 'w') as f: f.write('stuff') porcelain.add(repo=self.repo.path, paths=fullpath) porcelain.commit(repo=self.repo.path, message=b'test status', author=b'author ', committer=b'committer ') filename = 'foo' fullpath = os.path.join(self.repo.path, filename) with open(fullpath, 'w') as f: f.write('stuff') porcelain.add(repo=self.repo.path, paths=fullpath) changes = porcelain.get_tree_changes(self.repo.path) self.assertEqual(changes['add'][0], filename.encode('ascii')) self.assertEqual(len(changes['add']), 1) self.assertEqual(len(changes['modify']), 0) self.assertEqual(len(changes['delete']), 0) def test_get_tree_changes_modify(self): """Unit test for get_tree_changes modify.""" # Make a dummy file, stage, commit, modify filename = 'foo' fullpath = os.path.join(self.repo.path, filename) with open(fullpath, 'w') as f: f.write('stuff') porcelain.add(repo=self.repo.path, paths=fullpath) porcelain.commit(repo=self.repo.path, message=b'test status', author=b'author ', committer=b'committer ') with open(fullpath, 'w') as f: f.write('otherstuff') porcelain.add(repo=self.repo.path, paths=fullpath) changes = porcelain.get_tree_changes(self.repo.path) self.assertEqual(changes['modify'][0], filename.encode('ascii')) self.assertEqual(len(changes['add']), 0) self.assertEqual(len(changes['modify']), 1) self.assertEqual(len(changes['delete']), 0) def test_get_tree_changes_delete(self): """Unit test for get_tree_changes delete.""" # Make a dummy file, stage, commit, remove filename = 'foo' fullpath = os.path.join(self.repo.path, filename) with open(fullpath, 'w') as f: f.write('stuff') porcelain.add(repo=self.repo.path, paths=fullpath) porcelain.commit(repo=self.repo.path, message=b'test status', author=b'author ', committer=b'committer ') cwd = os.getcwd() try: os.chdir(self.repo.path) porcelain.remove(repo=self.repo.path, paths=[filename]) finally: os.chdir(cwd) changes = porcelain.get_tree_changes(self.repo.path) self.assertEqual(changes['delete'][0], filename.encode('ascii')) self.assertEqual(len(changes['add']), 0) self.assertEqual(len(changes['modify']), 0) self.assertEqual(len(changes['delete']), 1) def test_get_untracked_paths(self): with open(os.path.join(self.repo.path, '.gitignore'), 'w') as f: f.write('ignored\n') with open(os.path.join(self.repo.path, 'ignored'), 'w') as f: f.write('blah\n') with open(os.path.join(self.repo.path, 'notignored'), 'w') as f: f.write('blah\n') self.assertEqual( set(['ignored', 'notignored', '.gitignore']), set(porcelain.get_untracked_paths(self.repo.path, self.repo.path, self.repo.open_index()))) self.assertEqual(set(['.gitignore', 'notignored']), set(porcelain.status(self.repo).untracked)) self.assertEqual(set(['.gitignore', 'notignored', 'ignored']), set(porcelain.status(self.repo, ignored=True) .untracked)) def test_get_untracked_paths_nested(self): with open(os.path.join(self.repo.path, 'notignored'), 'w') as f: f.write('blah\n') subrepo = Repo.init(os.path.join(self.repo.path, 'nested'), mkdir=True) with open(os.path.join(subrepo.path, 'another'), 'w') as f: f.write('foo\n') self.assertEqual( set(['notignored']), set(porcelain.get_untracked_paths(self.repo.path, self.repo.path, self.repo.open_index()))) self.assertEqual( set(['another']), set(porcelain.get_untracked_paths(subrepo.path, subrepo.path, subrepo.open_index()))) # TODO(jelmer): Add test for dulwich.porcelain.daemon class UploadPackTests(PorcelainTestCase): """Tests for upload_pack.""" def test_upload_pack(self): outf = BytesIO() exitcode = porcelain.upload_pack( self.repo.path, BytesIO(b"0000"), outf) outlines = outf.getvalue().splitlines() self.assertEqual([b"0000"], outlines) self.assertEqual(0, exitcode) class ReceivePackTests(PorcelainTestCase): """Tests for receive_pack.""" def test_receive_pack(self): filename = 'foo' fullpath = os.path.join(self.repo.path, filename) with open(fullpath, 'w') as f: f.write('stuff') porcelain.add(repo=self.repo.path, paths=fullpath) self.repo.do_commit(message=b'test status', author=b'author ', committer=b'committer ', author_timestamp=1402354300, commit_timestamp=1402354300, author_timezone=0, commit_timezone=0) outf = BytesIO() exitcode = porcelain.receive_pack( self.repo.path, BytesIO(b"0000"), outf) outlines = outf.getvalue().splitlines() self.assertEqual([ b'0091319b56ce3aee2d489f759736a79cc552c9bb86d9 HEAD\x00 report-status ' # noqa: E501 b'delete-refs quiet ofs-delta side-band-64k ' b'no-done symref=HEAD:refs/heads/master', b'003f319b56ce3aee2d489f759736a79cc552c9bb86d9 refs/heads/master', b'0000'], outlines) self.assertEqual(0, exitcode) class BranchListTests(PorcelainTestCase): def test_standard(self): self.assertEqual(set([]), set(porcelain.branch_list(self.repo))) def test_new_branch(self): [c1] = build_commit_graph(self.repo.object_store, [[1]]) self.repo[b"HEAD"] = c1.id porcelain.branch_create(self.repo, b"foo") self.assertEqual( set([b"master", b"foo"]), set(porcelain.branch_list(self.repo))) class BranchCreateTests(PorcelainTestCase): def test_branch_exists(self): [c1] = build_commit_graph(self.repo.object_store, [[1]]) self.repo[b"HEAD"] = c1.id porcelain.branch_create(self.repo, b"foo") self.assertRaises(KeyError, porcelain.branch_create, self.repo, b"foo") porcelain.branch_create(self.repo, b"foo", force=True) def test_new_branch(self): [c1] = build_commit_graph(self.repo.object_store, [[1]]) self.repo[b"HEAD"] = c1.id porcelain.branch_create(self.repo, b"foo") self.assertEqual( set([b"master", b"foo"]), set(porcelain.branch_list(self.repo))) class BranchDeleteTests(PorcelainTestCase): def test_simple(self): [c1] = build_commit_graph(self.repo.object_store, [[1]]) self.repo[b"HEAD"] = c1.id porcelain.branch_create(self.repo, b'foo') self.assertTrue(b"foo" in porcelain.branch_list(self.repo)) porcelain.branch_delete(self.repo, b'foo') self.assertFalse(b"foo" in porcelain.branch_list(self.repo)) def test_simple_unicode(self): [c1] = build_commit_graph(self.repo.object_store, [[1]]) self.repo[b"HEAD"] = c1.id porcelain.branch_create(self.repo, 'foo') self.assertTrue(b"foo" in porcelain.branch_list(self.repo)) porcelain.branch_delete(self.repo, 'foo') self.assertFalse(b"foo" in porcelain.branch_list(self.repo)) class FetchTests(PorcelainTestCase): def test_simple(self): outstream = BytesIO() errstream = BytesIO() # create a file for initial commit handle, fullpath = tempfile.mkstemp(dir=self.repo.path) os.close(handle) porcelain.add(repo=self.repo.path, paths=fullpath) porcelain.commit(repo=self.repo.path, message=b'test', author=b'test ', committer=b'test ') # Setup target repo target_path = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, target_path) target_repo = porcelain.clone(self.repo.path, target=target_path, errstream=errstream) # create a second file to be pushed handle, fullpath = tempfile.mkstemp(dir=self.repo.path) os.close(handle) porcelain.add(repo=self.repo.path, paths=fullpath) porcelain.commit(repo=self.repo.path, message=b'test2', author=b'test2 ', committer=b'test2 ') self.assertFalse(self.repo[b'HEAD'].id in target_repo) target_repo.close() # Fetch changes into the cloned repo porcelain.fetch(target_path, self.repo.path, outstream=outstream, errstream=errstream) # Assert that fetch updated the local image of the remote self.assert_correct_remote_refs( target_repo.get_refs(), self.repo.get_refs()) # Check the target repo for pushed changes with Repo(target_path) as r: self.assertTrue(self.repo[b'HEAD'].id in r) def test_with_remote_name(self): remote_name = b'origin' outstream = BytesIO() errstream = BytesIO() # create a file for initial commit handle, fullpath = tempfile.mkstemp(dir=self.repo.path) os.close(handle) porcelain.add(repo=self.repo.path, paths=fullpath) porcelain.commit(repo=self.repo.path, message=b'test', author=b'test ', committer=b'test ') # Setup target repo target_path = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, target_path) target_repo = porcelain.clone(self.repo.path, target=target_path, errstream=errstream) # Capture current refs target_refs = target_repo.get_refs() # create a second file to be pushed handle, fullpath = tempfile.mkstemp(dir=self.repo.path) os.close(handle) porcelain.add(repo=self.repo.path, paths=fullpath) porcelain.commit(repo=self.repo.path, message=b'test2', author=b'test2 ', committer=b'test2 ') self.assertFalse(self.repo[b'HEAD'].id in target_repo) target_repo.close() # Fetch changes into the cloned repo porcelain.fetch(target_path, self.repo.path, remote_name=remote_name, outstream=outstream, errstream=errstream) # Assert that fetch updated the local image of the remote self.assert_correct_remote_refs( target_repo.get_refs(), self.repo.get_refs()) # Check the target repo for pushed changes, as well as updates # for the refs with Repo(target_path) as r: self.assertTrue(self.repo[b'HEAD'].id in r) self.assertNotEqual(self.repo.get_refs(), target_refs) def assert_correct_remote_refs( self, local_refs, remote_refs, remote_name=b'origin'): """Assert that known remote refs corresponds to actual remote refs.""" local_ref_prefix = b'refs/heads' remote_ref_prefix = b'refs/remotes/' + remote_name locally_known_remote_refs = { k[len(remote_ref_prefix) + 1:]: v for k, v in local_refs.items() if k.startswith(remote_ref_prefix)} normalized_remote_refs = { k[len(local_ref_prefix) + 1:]: v for k, v in remote_refs.items() if k.startswith(local_ref_prefix)} self.assertEqual(locally_known_remote_refs, normalized_remote_refs) class RepackTests(PorcelainTestCase): def test_empty(self): porcelain.repack(self.repo) def test_simple(self): handle, fullpath = tempfile.mkstemp(dir=self.repo.path) os.close(handle) porcelain.add(repo=self.repo.path, paths=fullpath) porcelain.repack(self.repo) class LsTreeTests(PorcelainTestCase): def test_empty(self): porcelain.commit(repo=self.repo.path, message=b'test status', author=b'author ', committer=b'committer ') f = StringIO() porcelain.ls_tree(self.repo, b"HEAD", outstream=f) self.assertEqual(f.getvalue(), "") def test_simple(self): # Commit a dummy file then modify it fullpath = os.path.join(self.repo.path, 'foo') with open(fullpath, 'w') as f: f.write('origstuff') porcelain.add(repo=self.repo.path, paths=[fullpath]) porcelain.commit(repo=self.repo.path, message=b'test status', author=b'author ', committer=b'committer ') f = StringIO() porcelain.ls_tree(self.repo, b"HEAD", outstream=f) self.assertEqual( f.getvalue(), '100644 blob 8b82634d7eae019850bb883f06abf428c58bc9aa\tfoo\n') def test_recursive(self): # Create a directory then write a dummy file in it dirpath = os.path.join(self.repo.path, 'adir') filepath = os.path.join(dirpath, 'afile') os.mkdir(dirpath) with open(filepath, 'w') as f: f.write('origstuff') porcelain.add(repo=self.repo.path, paths=[filepath]) porcelain.commit(repo=self.repo.path, message=b'test status', author=b'author ', committer=b'committer ') f = StringIO() porcelain.ls_tree(self.repo, b"HEAD", outstream=f) self.assertEqual( f.getvalue(), '40000 tree b145cc69a5e17693e24d8a7be0016ed8075de66d\tadir\n') f = StringIO() porcelain.ls_tree(self.repo, b"HEAD", outstream=f, recursive=True) self.assertEqual( f.getvalue(), '40000 tree b145cc69a5e17693e24d8a7be0016ed8075de66d\tadir\n' '100644 blob 8b82634d7eae019850bb883f06abf428c58bc9aa\tadir' '/afile\n') class LsRemoteTests(PorcelainTestCase): def test_empty(self): self.assertEqual({}, porcelain.ls_remote(self.repo.path)) def test_some(self): cid = porcelain.commit(repo=self.repo.path, message=b'test status', author=b'author ', committer=b'committer ') self.assertEqual({ b'refs/heads/master': cid, b'HEAD': cid}, porcelain.ls_remote(self.repo.path)) class LsFilesTests(PorcelainTestCase): def test_empty(self): self.assertEqual([], list(porcelain.ls_files(self.repo))) def test_simple(self): # Commit a dummy file then modify it fullpath = os.path.join(self.repo.path, 'foo') with open(fullpath, 'w') as f: f.write('origstuff') porcelain.add(repo=self.repo.path, paths=[fullpath]) self.assertEqual([b'foo'], list(porcelain.ls_files(self.repo))) class RemoteAddTests(PorcelainTestCase): def test_new(self): porcelain.remote_add( self.repo, 'jelmer', 'git://jelmer.uk/code/dulwich') c = self.repo.get_config() self.assertEqual( c.get((b'remote', b'jelmer'), b'url'), b'git://jelmer.uk/code/dulwich') def test_exists(self): porcelain.remote_add( self.repo, 'jelmer', 'git://jelmer.uk/code/dulwich') self.assertRaises(porcelain.RemoteExists, porcelain.remote_add, self.repo, 'jelmer', 'git://jelmer.uk/code/dulwich') class CheckIgnoreTests(PorcelainTestCase): def test_check_ignored(self): with open(os.path.join(self.repo.path, '.gitignore'), 'w') as f: f.write('foo') foo_path = os.path.join(self.repo.path, 'foo') with open(foo_path, 'w') as f: f.write('BAR') bar_path = os.path.join(self.repo.path, 'bar') with open(bar_path, 'w') as f: f.write('BAR') self.assertEqual( ['foo'], list(porcelain.check_ignore(self.repo, [foo_path]))) self.assertEqual( [], list(porcelain.check_ignore(self.repo, [bar_path]))) def test_check_added_abs(self): path = os.path.join(self.repo.path, 'foo') with open(path, 'w') as f: f.write('BAR') self.repo.stage(['foo']) with open(os.path.join(self.repo.path, '.gitignore'), 'w') as f: f.write('foo\n') self.assertEqual( [], list(porcelain.check_ignore(self.repo, [path]))) self.assertEqual( ['foo'], list(porcelain.check_ignore(self.repo, [path], no_index=True))) def test_check_added_rel(self): with open(os.path.join(self.repo.path, 'foo'), 'w') as f: f.write('BAR') self.repo.stage(['foo']) with open(os.path.join(self.repo.path, '.gitignore'), 'w') as f: f.write('foo\n') cwd = os.getcwd() os.mkdir(os.path.join(self.repo.path, 'bar')) os.chdir(os.path.join(self.repo.path, 'bar')) try: self.assertEqual( list(porcelain.check_ignore(self.repo, ['../foo'])), []) self.assertEqual(['../foo'], list( porcelain.check_ignore(self.repo, ['../foo'], no_index=True))) finally: os.chdir(cwd) class UpdateHeadTests(PorcelainTestCase): def test_set_to_branch(self): [c1] = build_commit_graph(self.repo.object_store, [[1]]) self.repo.refs[b"refs/heads/blah"] = c1.id porcelain.update_head(self.repo, "blah") self.assertEqual(c1.id, self.repo.head()) self.assertEqual(b'ref: refs/heads/blah', self.repo.refs.read_ref(b'HEAD')) def test_set_to_branch_detached(self): [c1] = build_commit_graph(self.repo.object_store, [[1]]) self.repo.refs[b"refs/heads/blah"] = c1.id porcelain.update_head(self.repo, "blah", detached=True) self.assertEqual(c1.id, self.repo.head()) self.assertEqual(c1.id, self.repo.refs.read_ref(b'HEAD')) def test_set_to_commit_detached(self): [c1] = build_commit_graph(self.repo.object_store, [[1]]) self.repo.refs[b"refs/heads/blah"] = c1.id porcelain.update_head(self.repo, c1.id, detached=True) self.assertEqual(c1.id, self.repo.head()) self.assertEqual(c1.id, self.repo.refs.read_ref(b'HEAD')) def test_set_new_branch(self): [c1] = build_commit_graph(self.repo.object_store, [[1]]) self.repo.refs[b"refs/heads/blah"] = c1.id porcelain.update_head(self.repo, "blah", new_branch="bar") self.assertEqual(c1.id, self.repo.head()) self.assertEqual(b'ref: refs/heads/bar', self.repo.refs.read_ref(b'HEAD')) class MailmapTests(PorcelainTestCase): def test_no_mailmap(self): self.assertEqual( b'Jelmer Vernooij ', porcelain.check_mailmap( self.repo, b'Jelmer Vernooij ')) def test_mailmap_lookup(self): with open(os.path.join(self.repo.path, '.mailmap'), 'wb') as f: f.write(b"""\ Jelmer Vernooij """) self.assertEqual( b'Jelmer Vernooij ', porcelain.check_mailmap( self.repo, b'Jelmer Vernooij ')) class FsckTests(PorcelainTestCase): def test_none(self): self.assertEqual( [], list(porcelain.fsck(self.repo))) def test_git_dir(self): obj = Tree() a = Blob() a.data = b"foo" obj.add(b".git", 0o100644, a.id) self.repo.object_store.add_objects( [(a, None), (obj, None)]) self.assertEqual( [(obj.id, 'invalid name .git')], [(sha, str(e)) for (sha, e) in porcelain.fsck(self.repo)]) class DescribeTests(PorcelainTestCase): def test_no_commits(self): self.assertRaises(KeyError, porcelain.describe, self.repo.path) def test_single_commit(self): fullpath = os.path.join(self.repo.path, 'foo') with open(fullpath, 'w') as f: f.write("BAR") porcelain.add(repo=self.repo.path, paths=[fullpath]) sha = porcelain.commit( self.repo.path, message=b"Some message", author=b"Joe ", committer=b"Bob ") self.assertEqual( 'g{}'.format(sha[:7].decode('ascii')), porcelain.describe(self.repo.path)) def test_tag(self): fullpath = os.path.join(self.repo.path, 'foo') with open(fullpath, 'w') as f: f.write("BAR") porcelain.add(repo=self.repo.path, paths=[fullpath]) porcelain.commit( self.repo.path, message=b"Some message", author=b"Joe ", committer=b"Bob ") porcelain.tag_create(self.repo.path, b"tryme", b'foo ', b'bar', annotated=True) self.assertEqual( "tryme", porcelain.describe(self.repo.path)) def test_tag_and_commit(self): fullpath = os.path.join(self.repo.path, 'foo') with open(fullpath, 'w') as f: f.write("BAR") porcelain.add(repo=self.repo.path, paths=[fullpath]) porcelain.commit( self.repo.path, message=b"Some message", author=b"Joe ", committer=b"Bob ") porcelain.tag_create(self.repo.path, b"tryme", b'foo ', b'bar', annotated=True) with open(fullpath, 'w') as f: f.write("BAR2") porcelain.add(repo=self.repo.path, paths=[fullpath]) sha = porcelain.commit( self.repo.path, message=b"Some message", author=b"Joe ", committer=b"Bob ") self.assertEqual( 'tryme-1-g{}'.format(sha[:7].decode('ascii')), porcelain.describe(self.repo.path)) class HelperTests(PorcelainTestCase): def test_path_to_tree_path_base(self): self.assertEqual( b'bar', porcelain.path_to_tree_path('/home/foo', '/home/foo/bar')) self.assertEqual(b'bar', porcelain.path_to_tree_path('.', './bar')) self.assertEqual(b'bar', porcelain.path_to_tree_path('.', 'bar')) cwd = os.getcwd() self.assertEqual( b'bar', porcelain.path_to_tree_path('.', os.path.join(cwd, 'bar'))) self.assertEqual(b'bar', porcelain.path_to_tree_path(cwd, 'bar')) def test_path_to_tree_path_syntax(self): self.assertEqual(b'bar', porcelain.path_to_tree_path(b'.', './bar')) self.assertEqual(b'bar', porcelain.path_to_tree_path('.', b'./bar')) self.assertEqual(b'bar', porcelain.path_to_tree_path(b'.', b'./bar')) def test_path_to_tree_path_error(self): with self.assertRaises(ValueError): porcelain.path_to_tree_path('/home/foo/', '/home/bar/baz') def test_path_to_tree_path_rel(self): cwd = os.getcwd() os.mkdir(os.path.join(self.repo.path, 'foo')) os.mkdir(os.path.join(self.repo.path, 'foo/bar')) try: os.chdir(os.path.join(self.repo.path, 'foo/bar')) self.assertEqual(b'bar/baz', porcelain.path_to_tree_path( '..', 'baz')) self.assertEqual(b'bar/baz', porcelain.path_to_tree_path( os.path.join(os.getcwd(), '..'), os.path.join(os.getcwd(), 'baz'))) self.assertEqual(b'bar/baz', porcelain.path_to_tree_path( '..', os.path.join(os.getcwd(), 'baz'))) self.assertEqual(b'bar/baz', porcelain.path_to_tree_path( os.path.join(os.getcwd(), '..'), 'baz')) finally: os.chdir(cwd) -class GetObjectBypathTests(PorcelainTestCase): +class GetObjectByPathTests(PorcelainTestCase): def test_simple(self): fullpath = os.path.join(self.repo.path, 'foo') with open(fullpath, 'w') as f: f.write("BAR") porcelain.add(repo=self.repo.path, paths=[fullpath]) porcelain.commit( self.repo.path, message=b"Some message", author=b"Joe ", committer=b"Bob ") self.assertEqual( b"BAR", porcelain.get_object_by_path(self.repo, 'foo').data) + self.assertEqual( + b"BAR", + porcelain.get_object_by_path(self.repo, b'foo').data) + + def test_encoding(self): + fullpath = os.path.join(self.repo.path, 'foo') + with open(fullpath, 'w') as f: + f.write("BAR") + porcelain.add(repo=self.repo.path, paths=[fullpath]) + porcelain.commit( + self.repo.path, message=b"Some message", + author=b"Joe ", + committer=b"Bob ", + encoding=b"utf-8") + self.assertEqual( + b"BAR", + porcelain.get_object_by_path(self.repo, 'foo').data) + self.assertEqual( + b"BAR", + porcelain.get_object_by_path(self.repo, b'foo').data) def test_missing(self): self.assertRaises( KeyError, porcelain.get_object_by_path, self.repo, 'foo') class WriteTreeTests(PorcelainTestCase): def test_simple(self): fullpath = os.path.join(self.repo.path, 'foo') with open(fullpath, 'w') as f: f.write("BAR") porcelain.add(repo=self.repo.path, paths=[fullpath]) self.assertEqual( b'd2092c8a9f311f0311083bf8d177f2ca0ab5b241', porcelain.write_tree(self.repo)) class ActiveBranchTests(PorcelainTestCase): def test_simple(self): self.assertEqual(b'master', porcelain.active_branch(self.repo)) diff --git a/setup.py b/setup.py index 2a75e7fd..2e5a632b 100755 --- a/setup.py +++ b/setup.py @@ -1,126 +1,126 @@ #!/usr/bin/python # encoding: utf-8 # Setup file for dulwich # Copyright (C) 2008-2016 Jelmer Vernooij try: from setuptools import setup, Extension except ImportError: from distutils.core import setup, Extension has_setuptools = False else: has_setuptools = True from distutils.core import Distribution import io import os import sys -dulwich_version_string = '0.19.14' +dulwich_version_string = '0.19.15' include_dirs = [] # Windows MSVC support if sys.platform == 'win32' and sys.version_info[:2] < (3, 6): # Include dulwich/ for fallback stdint.h include_dirs.append('dulwich') class DulwichDistribution(Distribution): def is_pure(self): if self.pure: return True def has_ext_modules(self): return not self.pure global_options = Distribution.global_options + [ ('pure', None, "use pure Python code instead of C " "extensions (slower on CPython)")] pure = False if sys.platform == 'darwin' and os.path.exists('/usr/bin/xcodebuild'): # XCode 4.0 dropped support for ppc architecture, which is hardcoded in # distutils.sysconfig import subprocess p = subprocess.Popen( ['/usr/bin/xcodebuild', '-version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, env={}) out, err = p.communicate() for line in out.splitlines(): line = line.decode("utf8") # Also parse only first digit, because 3.2.1 can't be parsed nicely if (line.startswith('Xcode') and int(line.split()[1].split('.')[0]) >= 4): os.environ['ARCHFLAGS'] = '' tests_require = ['fastimport'] if '__pypy__' not in sys.modules and not sys.platform == 'win32': tests_require.extend([ 'gevent', 'geventhttpclient', 'mock', 'setuptools>=17.1']) ext_modules = [ Extension('dulwich._objects', ['dulwich/_objects.c'], include_dirs=include_dirs), Extension('dulwich._pack', ['dulwich/_pack.c'], include_dirs=include_dirs), Extension('dulwich._diff_tree', ['dulwich/_diff_tree.c'], include_dirs=include_dirs), ] setup_kwargs = {} if has_setuptools: setup_kwargs['extras_require'] = { 'fastimport': ['fastimport'], 'https': ['urllib3[secure]>=1.24.1'], 'pgp': ['gpg'], } setup_kwargs['install_requires'] = ['urllib3>=1.24.1', 'certifi'] setup_kwargs['include_package_data'] = True setup_kwargs['test_suite'] = 'dulwich.tests.test_suite' setup_kwargs['tests_require'] = tests_require with io.open(os.path.join(os.path.dirname(__file__), "README.rst"), encoding="utf-8") as f: description = f.read() setup(name='dulwich', author="Jelmer Vernooij", author_email="jelmer@jelmer.uk", url="https://www.dulwich.io/", long_description=description, description="Python Git Library", version=dulwich_version_string, license='Apachev2 or later or GPLv2', project_urls={ "Bug Tracker": "https://github.com/dulwich/dulwich/issues", "Repository": "https://www.dulwich.io/code/", "GitHub": "https://github.com/dulwich/dulwich", }, keywords="git vcs", packages=['dulwich', 'dulwich.tests', 'dulwich.tests.compat', 'dulwich.contrib'], package_data={'': ['../docs/tutorial/*.txt']}, scripts=['bin/dulwich', 'bin/dul-receive-pack', 'bin/dul-upload-pack'], ext_modules=ext_modules, distclass=DulwichDistribution, classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Operating System :: POSIX', 'Operating System :: Microsoft :: Windows', 'Topic :: Software Development :: Version Control', ], **setup_kwargs )