diff --git a/NEWS b/NEWS index ad629c75..2c9d7897 100644 --- a/NEWS +++ b/NEWS @@ -1,2064 +1,2100 @@ +0.20.5 2020-06-22 + + * Print a clearer exception when setup.py is executed on Python < 3.5. + (Jelmer Vernooij, #783) + + * Send an empty pack to clients if they requested objects, even if they + already have those objects. Thanks to Martijn Pieters for + the detailed bug report. (Jelmer Vernooij, #781) + + * porcelain.pull: Don't ask for objects that we already have. + (Jelmer Vernooij, #782) + + * Add LCA implementation. (Kevin Hendricks) + + * Add functionality for finding the merge base. (Kevin Hendricks) + + * Check for diverged branches during push. + (Jelmer Vernooij, #494) + + * Check for fast-forward during pull. (Jelmer Vernooij, #666) + + * Return a SendPackResult object from + GitClient.send_pack(). (Jelmer Vernooij) + + * ``GitClient.send_pack`` now sets the ``ref_status`` attribute + on its return value to a dictionary mapping ref names + to error messages. Previously, it raised UpdateRefsError + if any of the refs failed to update. + (Jelmer Vernooij, #780) + + * Add a ``porcelain.Error`` object that most errors in porcelain + derive from. (Jelmer Vernooij) + + * Fix argument parsing in dulwich command-line app. + (Jelmer Vernooij, #784) + 0.20.3 2020-06-14 * Add support for remembering remote refs after push/pull. (Jelmer Vernooij, #752) * Support passing tree and output encoding to dulwich.patch.unified_diff. (Jelmer Vernooij, #763) * Fix pushing of new refs over HTTP(S) when there are no new objects to be sent. (Jelmer Vernooij, #739) * Raise new error HTTPUnauthorized when the server sends back a 401. The client can then retry with credentials. (Jelmer Vernooij, #691) * Move the guts of bin/dulwich to dulwich.cli, so it is easier to test or import. (Jelmer Vernooij) * Install dulwich script from entry_points when setuptools is available, making it slightly easier to use on Windows. (Jelmer Vernooij, #540) * Set python_requires>=3.5 in setup.py. (Manuel Jacob) 0.20.2 2020-06-01 * Brown bag release to fix uploads of Windows wheels. 0.20.1 2020-06-01 * Publish binary wheels for: Windows, Linux, Mac OS X. (Jelmer Vernooij, #711, #710, #629) 0.20.0 2020-06-01 * Drop support for Python 2. (Jelmer Vernooij) * Only return files from the loose store that look like git objects. (Nicolas Dandrimont) * Ignore agent= capability if sent by client. (Jelmer Vernooij) * Don't break when encountering block devices. (Jelmer Vernooij) * Decode URL paths in HttpGitClient using utf-8 rather than file system encoding. (Manuel Jacob) * Fix pushing from a shallow clone. (Brecht Machiels, #705) 0.19.16 2020-04-17 * Don't send "deepen None" to server if graph walker supports shallow. (Jelmer Vernooij, #747) * Support tweaking the compression level for loose objects through the "core.looseCompression" and "core.compression" settings. (Jelmer Vernooij) * Support tweaking the compression level for pack objects through the "core.packCompression" and "core.compression" settings. (Jelmer Vernooij) * Add a "dulwich.contrib.diffstat" module. (Kevin Hendricks) 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 8443f96c..fa4cd975 100644 --- a/PKG-INFO +++ b/PKG-INFO @@ -1,129 +1,129 @@ Metadata-Version: 2.1 Name: dulwich -Version: 0.20.3 +Version: 0.20.5 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/ +Project-URL: GitHub, https://github.com/dulwich/dulwich 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 3.5, 3.6, 3.7, 3.8 and Pypy. The latest release series to support Python 2.x was the 0.19 series. See the 0.19 branch in the Dulwich git repository. Keywords: git vcs Platform: UNKNOWN Classifier: Development Status :: 4 - Beta Classifier: License :: OSI Approved :: Apache Software License Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: 3.8 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 Requires-Python: >=3.5 Provides-Extra: fastimport Provides-Extra: https Provides-Extra: pgp diff --git a/dulwich.egg-info/PKG-INFO b/dulwich.egg-info/PKG-INFO index 8443f96c..fa4cd975 100644 --- a/dulwich.egg-info/PKG-INFO +++ b/dulwich.egg-info/PKG-INFO @@ -1,129 +1,129 @@ Metadata-Version: 2.1 Name: dulwich -Version: 0.20.3 +Version: 0.20.5 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/ +Project-URL: GitHub, https://github.com/dulwich/dulwich 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 3.5, 3.6, 3.7, 3.8 and Pypy. The latest release series to support Python 2.x was the 0.19 series. See the 0.19 branch in the Dulwich git repository. Keywords: git vcs Platform: UNKNOWN Classifier: Development Status :: 4 - Beta Classifier: License :: OSI Approved :: Apache Software License Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: 3.8 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 Requires-Python: >=3.5 Provides-Extra: fastimport Provides-Extra: https Provides-Extra: pgp diff --git a/dulwich.egg-info/SOURCES.txt b/dulwich.egg-info/SOURCES.txt index 656c760a..cccee472 100644 --- a/dulwich.egg-info/SOURCES.txt +++ b/dulwich.egg-info/SOURCES.txt @@ -1,225 +1,227 @@ .coveragerc .gitignore .mailmap .testr.conf AUTHORS CONTRIBUTING.rst COPYING MANIFEST.in Makefile NEWS README.rst README.swift.rst TODO build.cmd dulwich.cfg requirements.txt setup.cfg setup.py tox.ini .github/workflows/pythonpackage.yml .github/workflows/pythonpublish.yml 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/index.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/cli.py dulwich/client.py dulwich/config.py dulwich/diff_tree.py dulwich/errors.py dulwich/fastexport.py dulwich/file.py +dulwich/graph.py dulwich/greenthreads.py dulwich/hooks.py dulwich/ignore.py dulwich/index.py dulwich/lfs.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/entry_points.txt dulwich.egg-info/requires.txt dulwich.egg-info/top_level.txt dulwich/contrib/README.md dulwich/contrib/__init__.py dulwich/contrib/diffstat.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_graph.py dulwich/tests/test_greenthreads.py dulwich/tests/test_hooks.py dulwich/tests/test_ignore.py dulwich/tests/test_index.py dulwich/tests/test_lfs.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.egg-info/requires.txt b/dulwich.egg-info/requires.txt index 135cb5e9..59be6fa6 100644 --- a/dulwich.egg-info/requires.txt +++ b/dulwich.egg-info/requires.txt @@ -1,11 +1,11 @@ -certifi urllib3>=1.24.1 +certifi [fastimport] fastimport [https] urllib3[secure]>=1.24.1 [pgp] gpg diff --git a/dulwich/__init__.py b/dulwich/__init__.py index f62fdc02..92c51290 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, 20, 3) +__version__ = (0, 20, 5) diff --git a/dulwich/_diff_tree.c b/dulwich/_diff_tree.c index ebed2d7f..88d17ed9 100644 --- a/dulwich/_diff_tree.c +++ b/dulwich/_diff_tree.c @@ -1,510 +1,470 @@ /* * 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); + name_len = PyBytes_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); + memcpy(new_path + path_len + 1, PyBytes_AS_STRING(name), name_len); } else { - memcpy(new_path, PyString_AS_STRING(name), name_len); + memcpy(new_path, PyBytes_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)) { + if (!PyBytes_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)) { + if (!PyBytes_Check(path2)) { PyErr_SetString(PyExc_TypeError, "path is not a (byte)string"); goto done; } - result = strcmp(PyString_AS_STRING(path1), PyString_AS_STRING(path2)); + result = strcmp(PyBytes_AS_STRING(path1), PyBytes_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, 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; } /* Not all environments define S_ISDIR */ #if !defined(S_ISDIR) && defined(S_IFMT) && defined(S_IFDIR) #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR) #endif 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); + lmode = PyLong_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); + str_obj = PyBytes_FromStringAndSize(str, n); if (!str_obj) goto error; hash = PyObject_Hash(str_obj); if (hash == -1) goto error; - hash_obj = PyInt_FromLong(hash); + hash_obj = PyLong_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); + PyLong_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)) { + if (!PyBytes_Check(chunk)) { PyErr_SetString(PyExc_TypeError, "chunk is not a string"); goto error; } - if (PyString_AsStringAndSize(chunk, &chunk_str, &chunk_len) == -1) + if (PyBytes_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); + block_size = (int)PyLong_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/_objects.c b/dulwich/_objects.c index eb8b9e5b..34635e82 100644 --- a/dulwich/_objects.c +++ b/dulwich/_objects.c @@ -1,335 +1,309 @@ /* * Copyright (C) 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. */ #define PY_SSIZE_T_CLEAN #include #include #include -#if PY_MAJOR_VERSION >= 3 -#define PyInt_Check(obj) 0 -#define PyInt_CheckExact(obj) 0 -#define PyInt_AsLong PyLong_AsLong -#define PyString_AS_STRING PyBytes_AS_STRING -#define PyString_Check PyBytes_Check -#define PyString_FromStringAndSize PyBytes_FromStringAndSize -#endif - #if defined(__MINGW32_VERSION) || defined(__APPLE__) size_t rep_strnlen(char *text, size_t maxlen); size_t rep_strnlen(char *text, size_t maxlen) { const char *last = memchr(text, '\0', maxlen); return last ? (size_t) (last - text) : maxlen; } #define strnlen rep_strnlen #endif #define bytehex(x) (((x)<0xa)?('0'+(x)):('a'-0xa+(x))) static PyObject *tree_entry_cls; static PyObject *object_format_exception_cls; static PyObject *sha_to_pyhex(const unsigned char *sha) { char hexsha[41]; int i; for (i = 0; i < 20; i++) { hexsha[i*2] = bytehex((sha[i] & 0xF0) >> 4); hexsha[i*2+1] = bytehex(sha[i] & 0x0F); } - return PyString_FromStringAndSize(hexsha, 40); + return PyBytes_FromStringAndSize(hexsha, 40); } static PyObject *py_parse_tree(PyObject *self, PyObject *args, PyObject *kw) { char *text, *start, *end; Py_ssize_t len; int strict; size_t namelen; PyObject *ret, *item, *name, *sha, *py_strict = NULL; static char *kwlist[] = {"text", "strict", NULL}; -#if PY_MAJOR_VERSION >= 3 if (!PyArg_ParseTupleAndKeywords(args, kw, "y#|O", kwlist, &text, &len, &py_strict)) -#else - if (!PyArg_ParseTupleAndKeywords(args, kw, "s#|O", kwlist, - &text, &len, &py_strict)) -#endif return NULL; strict = py_strict ? PyObject_IsTrue(py_strict) : 0; /* TODO: currently this returns a list; if memory usage is a concern, * consider rewriting as a custom iterator object */ ret = PyList_New(0); if (ret == NULL) { return NULL; } start = text; end = text + len; while (text < end) { long mode; if (strict && text[0] == '0') { PyErr_SetString(object_format_exception_cls, "Illegal leading zero on mode"); Py_DECREF(ret); return NULL; } mode = strtol(text, &text, 8); if (*text != ' ') { PyErr_SetString(PyExc_ValueError, "Expected space"); Py_DECREF(ret); return NULL; } text++; namelen = strnlen(text, len - (text - start)); - name = PyString_FromStringAndSize(text, namelen); + name = PyBytes_FromStringAndSize(text, namelen); if (name == NULL) { Py_DECREF(ret); return NULL; } if (text + namelen + 20 >= end) { PyErr_SetString(PyExc_ValueError, "SHA truncated"); Py_DECREF(ret); Py_DECREF(name); return NULL; } sha = sha_to_pyhex((unsigned char *)text+namelen+1); if (sha == NULL) { Py_DECREF(ret); Py_DECREF(name); return NULL; } item = Py_BuildValue("(NlN)", name, mode, sha); if (item == NULL) { Py_DECREF(ret); Py_DECREF(sha); Py_DECREF(name); return NULL; } if (PyList_Append(ret, item) == -1) { Py_DECREF(ret); Py_DECREF(item); return NULL; } Py_DECREF(item); text += namelen+21; } return ret; } struct tree_item { const char *name; int mode; PyObject *tuple; }; /* Not all environments define S_ISDIR */ #if !defined(S_ISDIR) && defined(S_IFMT) && defined(S_IFDIR) #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR) #endif int cmp_tree_item(const void *_a, const void *_b) { const struct tree_item *a = _a, *b = _b; const char *remain_a, *remain_b; int ret; size_t common; if (strlen(a->name) > strlen(b->name)) { common = strlen(b->name); remain_a = a->name + common; remain_b = (S_ISDIR(b->mode)?"/":""); } else if (strlen(b->name) > strlen(a->name)) { common = strlen(a->name); remain_a = (S_ISDIR(a->mode)?"/":""); remain_b = b->name + common; } else { /* strlen(a->name) == strlen(b->name) */ common = 0; remain_a = a->name; remain_b = b->name; } ret = strncmp(a->name, b->name, common); if (ret != 0) return ret; return strcmp(remain_a, remain_b); } int cmp_tree_item_name_order(const void *_a, const void *_b) { const struct tree_item *a = _a, *b = _b; return strcmp(a->name, b->name); } static PyObject *py_sorted_tree_items(PyObject *self, PyObject *args) { struct tree_item *qsort_entries = NULL; int name_order, n = 0, i; PyObject *entries, *py_name_order, *ret, *key, *value, *py_mode, *py_sha; Py_ssize_t pos = 0, num_entries; int (*cmp)(const void *, const void *); if (!PyArg_ParseTuple(args, "OO", &entries, &py_name_order)) goto error; if (!PyDict_Check(entries)) { PyErr_SetString(PyExc_TypeError, "Argument not a dictionary"); goto error; } name_order = PyObject_IsTrue(py_name_order); if (name_order == -1) goto error; cmp = name_order ? cmp_tree_item_name_order : cmp_tree_item; num_entries = PyDict_Size(entries); if (PyErr_Occurred()) goto error; qsort_entries = PyMem_New(struct tree_item, num_entries); if (!qsort_entries) { PyErr_NoMemory(); goto error; } while (PyDict_Next(entries, &pos, &key, &value)) { - if (!PyString_Check(key)) { + if (!PyBytes_Check(key)) { PyErr_SetString(PyExc_TypeError, "Name is not a string"); goto error; } if (PyTuple_Size(value) != 2) { PyErr_SetString(PyExc_ValueError, "Tuple has invalid size"); goto error; } py_mode = PyTuple_GET_ITEM(value, 0); - if (!PyInt_Check(py_mode) && !PyLong_Check(py_mode)) { + if (!PyLong_Check(py_mode)) { PyErr_SetString(PyExc_TypeError, "Mode is not an integral type"); goto error; } py_sha = PyTuple_GET_ITEM(value, 1); - if (!PyString_Check(py_sha)) { + if (!PyBytes_Check(py_sha)) { PyErr_SetString(PyExc_TypeError, "SHA is not a string"); goto error; } - qsort_entries[n].name = PyString_AS_STRING(key); - qsort_entries[n].mode = PyInt_AsLong(py_mode); + qsort_entries[n].name = PyBytes_AS_STRING(key); + qsort_entries[n].mode = PyLong_AsLong(py_mode); qsort_entries[n].tuple = PyObject_CallFunctionObjArgs( tree_entry_cls, key, py_mode, py_sha, NULL); if (qsort_entries[n].tuple == NULL) goto error; n++; } qsort(qsort_entries, num_entries, sizeof(struct tree_item), cmp); ret = PyList_New(num_entries); if (ret == NULL) { PyErr_NoMemory(); goto error; } for (i = 0; i < num_entries; i++) { PyList_SET_ITEM(ret, i, qsort_entries[i].tuple); } PyMem_Free(qsort_entries); return ret; error: for (i = 0; i < n; i++) { Py_XDECREF(qsort_entries[i].tuple); } PyMem_Free(qsort_entries); return NULL; } static PyMethodDef py_objects_methods[] = { { "parse_tree", (PyCFunction)py_parse_tree, METH_VARARGS | METH_KEYWORDS, NULL }, { "sorted_tree_items", py_sorted_tree_items, METH_VARARGS, NULL }, { NULL, NULL, 0, NULL } }; static PyObject * moduleinit(void) { PyObject *m, *objects_mod, *errors_mod; -#if PY_MAJOR_VERSION >= 3 static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "_objects", /* m_name */ NULL, /* m_doc */ -1, /* m_size */ py_objects_methods, /* m_methods */ NULL, /* m_reload */ NULL, /* m_traverse */ NULL, /* m_clear*/ NULL, /* m_free */ }; m = PyModule_Create(&moduledef); -#else - m = Py_InitModule3("_objects", py_objects_methods, NULL); -#endif if (m == NULL) { return NULL; } errors_mod = PyImport_ImportModule("dulwich.errors"); if (errors_mod == NULL) { return NULL; } object_format_exception_cls = PyObject_GetAttrString( errors_mod, "ObjectFormatException"); Py_DECREF(errors_mod); if (object_format_exception_cls == NULL) { return NULL; } /* This is a circular import but should be safe since this module is * imported at at the very bottom of objects.py. */ objects_mod = PyImport_ImportModule("dulwich.objects"); if (objects_mod == NULL) { return NULL; } tree_entry_cls = PyObject_GetAttrString(objects_mod, "TreeEntry"); Py_DECREF(objects_mod); if (tree_entry_cls == NULL) { return NULL; } return m; } -#if PY_MAJOR_VERSION >= 3 PyMODINIT_FUNC PyInit__objects(void) { return moduleinit(); } -#else -PyMODINIT_FUNC -init_objects(void) -{ - moduleinit(); -} -#endif diff --git a/dulwich/_pack.c b/dulwich/_pack.c index f2ef0649..3ee9828d 100644 --- a/dulwich/_pack.c +++ b/dulwich/_pack.c @@ -1,314 +1,282 @@ /* * Copyright (C) 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. */ #define PY_SSIZE_T_CLEAN #include #include -#if PY_MAJOR_VERSION >= 3 -#define PyInt_FromLong PyLong_FromLong -#define PyString_AS_STRING PyBytes_AS_STRING -#define PyString_AS_STRING PyBytes_AS_STRING -#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 *PyExc_ApplyDeltaError = NULL; static int py_is_sha(PyObject *sha) { - if (!PyString_CheckExact(sha)) + if (!PyBytes_CheckExact(sha)) return 0; - if (PyString_Size(sha) != 20) + if (PyBytes_Size(sha) != 20) return 0; return 1; } static size_t get_delta_header_size(uint8_t *delta, size_t *index, size_t length) { size_t size = 0; size_t i = 0; while ((*index) < length) { uint8_t cmd = delta[*index]; (*index)++; size |= (cmd & ~0x80) << i; i += 7; if (!(cmd & 0x80)) break; } return size; } static PyObject *py_chunked_as_string(PyObject *py_buf) { if (PyList_Check(py_buf)) { - PyObject *sep = PyString_FromString(""); + PyObject *sep = PyBytes_FromString(""); if (sep == NULL) { PyErr_NoMemory(); return NULL; } - py_buf = _PyString_Join(sep, py_buf); + py_buf = _PyBytes_Join(sep, py_buf); Py_DECREF(sep); if (py_buf == NULL) { PyErr_NoMemory(); return NULL; } - } else if (PyString_Check(py_buf)) { + } else if (PyBytes_Check(py_buf)) { Py_INCREF(py_buf); } else { PyErr_SetString(PyExc_TypeError, "src_buf is not a string or a list of chunks"); return NULL; } return py_buf; } static PyObject *py_apply_delta(PyObject *self, PyObject *args) { uint8_t *src_buf, *delta; size_t src_buf_len, delta_len; size_t src_size, dest_size; size_t outindex = 0; size_t index; uint8_t *out; PyObject *ret, *py_src_buf, *py_delta, *ret_list; if (!PyArg_ParseTuple(args, "OO", &py_src_buf, &py_delta)) return NULL; py_src_buf = py_chunked_as_string(py_src_buf); if (py_src_buf == NULL) return NULL; py_delta = py_chunked_as_string(py_delta); if (py_delta == NULL) { Py_DECREF(py_src_buf); return NULL; } - src_buf = (uint8_t *)PyString_AS_STRING(py_src_buf); - src_buf_len = (size_t)PyString_GET_SIZE(py_src_buf); + src_buf = (uint8_t *)PyBytes_AS_STRING(py_src_buf); + src_buf_len = (size_t)PyBytes_GET_SIZE(py_src_buf); - delta = (uint8_t *)PyString_AS_STRING(py_delta); - delta_len = (size_t)PyString_GET_SIZE(py_delta); + delta = (uint8_t *)PyBytes_AS_STRING(py_delta); + delta_len = (size_t)PyBytes_GET_SIZE(py_delta); index = 0; src_size = get_delta_header_size(delta, &index, delta_len); if (src_size != src_buf_len) { PyErr_Format(PyExc_ApplyDeltaError, "Unexpected source buffer size: %lu vs %ld", src_size, src_buf_len); Py_DECREF(py_src_buf); Py_DECREF(py_delta); return NULL; } dest_size = get_delta_header_size(delta, &index, delta_len); - ret = PyString_FromStringAndSize(NULL, dest_size); + ret = PyBytes_FromStringAndSize(NULL, dest_size); if (ret == NULL) { PyErr_NoMemory(); Py_DECREF(py_src_buf); Py_DECREF(py_delta); return NULL; } - out = (uint8_t *)PyString_AS_STRING(ret); + out = (uint8_t *)PyBytes_AS_STRING(ret); while (index < delta_len) { uint8_t cmd = delta[index]; index++; if (cmd & 0x80) { size_t cp_off = 0, cp_size = 0; int i; for (i = 0; i < 4; i++) { if (cmd & (1 << i)) { uint8_t x = delta[index]; index++; cp_off |= x << (i * 8); } } for (i = 0; i < 3; i++) { if (cmd & (1 << (4+i))) { uint8_t x = delta[index]; index++; cp_size |= x << (i * 8); } } if (cp_size == 0) cp_size = 0x10000; if (cp_off + cp_size < cp_size || cp_off + cp_size > src_size || cp_size > dest_size) break; memcpy(out+outindex, src_buf+cp_off, cp_size); outindex += cp_size; dest_size -= cp_size; } else if (cmd != 0) { if (cmd > dest_size) break; memcpy(out+outindex, delta+index, cmd); outindex += cmd; index += cmd; dest_size -= cmd; } else { PyErr_SetString(PyExc_ApplyDeltaError, "Invalid opcode 0"); Py_DECREF(ret); Py_DECREF(py_delta); Py_DECREF(py_src_buf); return NULL; } } Py_DECREF(py_src_buf); Py_DECREF(py_delta); if (index != delta_len) { PyErr_SetString(PyExc_ApplyDeltaError, "delta not empty"); Py_DECREF(ret); return NULL; } if (dest_size != 0) { PyErr_SetString(PyExc_ApplyDeltaError, "dest size incorrect"); Py_DECREF(ret); return NULL; } ret_list = Py_BuildValue("[N]", ret); if (ret_list == NULL) { Py_DECREF(ret); return NULL; } return ret_list; } static PyObject *py_bisect_find_sha(PyObject *self, PyObject *args) { PyObject *unpack_name; char *sha; Py_ssize_t sha_len; int start, end; -#if PY_MAJOR_VERSION >= 3 if (!PyArg_ParseTuple(args, "iiy#O", &start, &end, &sha, &sha_len, &unpack_name)) -#else - if (!PyArg_ParseTuple(args, "iis#O", &start, &end, - &sha, &sha_len, &unpack_name)) -#endif return NULL; if (sha_len != 20) { PyErr_SetString(PyExc_ValueError, "Sha is not 20 bytes long"); return NULL; } if (start > end) { PyErr_SetString(PyExc_AssertionError, "start > end"); return NULL; } while (start <= end) { PyObject *file_sha; Py_ssize_t i = (start + end)/2; int cmp; file_sha = PyObject_CallFunction(unpack_name, "i", i); if (file_sha == NULL) { return NULL; } if (!py_is_sha(file_sha)) { PyErr_SetString(PyExc_TypeError, "unpack_name returned non-sha object"); Py_DECREF(file_sha); return NULL; } - cmp = memcmp(PyString_AS_STRING(file_sha), sha, 20); + cmp = memcmp(PyBytes_AS_STRING(file_sha), sha, 20); Py_DECREF(file_sha); if (cmp < 0) start = i + 1; else if (cmp > 0) end = i - 1; else { - return PyInt_FromLong(i); + return PyLong_FromLong(i); } } Py_RETURN_NONE; } static PyMethodDef py_pack_methods[] = { { "apply_delta", (PyCFunction)py_apply_delta, METH_VARARGS, NULL }, { "bisect_find_sha", (PyCFunction)py_bisect_find_sha, METH_VARARGS, NULL }, { NULL, NULL, 0, NULL } }; static PyObject * moduleinit(void) { PyObject *m; PyObject *errors_module; -#if PY_MAJOR_VERSION >= 3 static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "_pack", /* m_name */ NULL, /* m_doc */ -1, /* m_size */ py_pack_methods, /* m_methods */ NULL, /* m_reload */ NULL, /* m_traverse */ NULL, /* m_clear*/ NULL, /* m_free */ }; -#endif errors_module = PyImport_ImportModule("dulwich.errors"); if (errors_module == NULL) return NULL; PyExc_ApplyDeltaError = PyObject_GetAttrString(errors_module, "ApplyDeltaError"); Py_DECREF(errors_module); if (PyExc_ApplyDeltaError == NULL) return NULL; -#if PY_MAJOR_VERSION >= 3 m = PyModule_Create(&moduledef); -#else - m = Py_InitModule3("_pack", py_pack_methods, NULL); -#endif if (m == NULL) return NULL; return m; } -#if PY_MAJOR_VERSION >= 3 PyMODINIT_FUNC PyInit__pack(void) { return moduleinit(); } -#else -PyMODINIT_FUNC -init_pack(void) -{ - moduleinit(); -} -#endif diff --git a/dulwich/client.py b/dulwich/client.py index 13ae19dc..e9bc0639 100644 --- a/dulwich/client.py +++ b/dulwich/client.py @@ -1,1906 +1,1928 @@ # client.py -- Implementation of the client side git protocols # 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. # """Client side support for the Git protocol. The Dulwich client supports the following capabilities: * thin-pack * multi_ack_detailed * multi_ack * side-band-64k * ofs-delta * quiet * report-status * delete-refs * shallow Known capabilities that are not supported: * no-progress * include-tag """ from contextlib import closing from io import BytesIO, BufferedReader import os import select import socket import subprocess import sys +from typing import Optional, Dict, Callable, Set from urllib.parse import ( quote as urlquote, unquote as urlunquote, urlparse, urljoin, urlunsplit, urlunparse, ) import dulwich from dulwich.config import get_xdg_config_home_path from dulwich.errors import ( GitProtocolError, NotGitRepository, SendPackError, - UpdateRefsError, ) from dulwich.protocol import ( HangupException, _RBUFSIZE, agent_string, capability_agent, extract_capability_names, CAPABILITY_AGENT, CAPABILITY_DELETE_REFS, CAPABILITY_INCLUDE_TAG, CAPABILITY_MULTI_ACK, CAPABILITY_MULTI_ACK_DETAILED, CAPABILITY_OFS_DELTA, CAPABILITY_QUIET, CAPABILITY_REPORT_STATUS, CAPABILITY_SHALLOW, CAPABILITY_SYMREF, CAPABILITY_SIDE_BAND_64K, CAPABILITY_THIN_PACK, CAPABILITIES_REF, KNOWN_RECEIVE_CAPABILITIES, KNOWN_UPLOAD_CAPABILITIES, COMMAND_DEEPEN, COMMAND_SHALLOW, COMMAND_UNSHALLOW, COMMAND_DONE, COMMAND_HAVE, COMMAND_WANT, SIDE_BAND_CHANNEL_DATA, SIDE_BAND_CHANNEL_PROGRESS, SIDE_BAND_CHANNEL_FATAL, PktLineParser, Protocol, ProtocolFile, TCP_GIT_PORT, ZERO_SHA, extract_capabilities, parse_capability, ) from dulwich.pack import ( write_pack_data, write_pack_objects, ) from dulwich.refs import ( read_info_refs, ANNOTATED_TAG_SUFFIX, ) class InvalidWants(Exception): """Invalid wants.""" def __init__(self, wants): Exception.__init__( self, "requested wants not in server provided refs: %r" % wants) class HTTPUnauthorized(Exception): """Raised when authentication fails.""" def __init__(self, www_authenticate): Exception.__init__(self, "No valid credentials provided") self.www_authenticate = www_authenticate def _fileno_can_read(fileno): """Check if a file descriptor is readable. """ return len(select.select([fileno], [], [], 0)[0]) > 0 def _win32_peek_avail(handle): """Wrapper around PeekNamedPipe to check how many bytes are available. """ from ctypes import byref, wintypes, windll c_avail = wintypes.DWORD() c_message = wintypes.DWORD() success = windll.kernel32.PeekNamedPipe( handle, None, 0, None, byref(c_avail), byref(c_message)) if not success: raise OSError(wintypes.GetLastError()) return c_avail.value COMMON_CAPABILITIES = [CAPABILITY_OFS_DELTA, CAPABILITY_SIDE_BAND_64K] UPLOAD_CAPABILITIES = ([CAPABILITY_THIN_PACK, CAPABILITY_MULTI_ACK, CAPABILITY_MULTI_ACK_DETAILED, CAPABILITY_SHALLOW] + COMMON_CAPABILITIES) RECEIVE_CAPABILITIES = ( [CAPABILITY_REPORT_STATUS, CAPABILITY_DELETE_REFS] + COMMON_CAPABILITIES) class ReportStatusParser(object): """Handle status as reported by servers with 'report-status' capability.""" def __init__(self): self._done = False self._pack_status = None - self._ref_status_ok = True self._ref_statuses = [] def check(self): """Check if there were any errors and, if so, raise exceptions. Raises: SendPackError: Raised when the server could not unpack - UpdateRefsError: Raised when refs could not be updated + Returns: + iterator over refs """ if self._pack_status not in (b'unpack ok', None): raise SendPackError(self._pack_status) - if not self._ref_status_ok: - ref_status = {} - ok = set() - for status in self._ref_statuses: - if b' ' not in status: - # malformed response, move on to the next one - continue - status, ref = status.split(b' ', 1) - - if status == b'ng': - if b' ' in ref: - ref, status = ref.split(b' ', 1) - else: - ok.add(ref) - ref_status[ref] = status - # TODO(jelmer): don't assume encoding of refs is ascii. - raise UpdateRefsError(', '.join([ - refname.decode('ascii') for refname in ref_status - if refname not in ok]) + - ' failed to update', ref_status=ref_status) + for status in self._ref_statuses: + try: + status, rest = status.split(b' ', 1) + except ValueError: + # malformed response, move on to the next one + continue + if status == b'ng': + ref, error = rest.split(b' ', 1) + yield ref, error.decode('utf-8') + elif status == b'ok': + yield rest, None + else: + raise GitProtocolError('invalid ref status %r' % status) def handle_packet(self, pkt): """Handle a packet. Raises: GitProtocolError: Raised when packets are received after a flush packet. """ if self._done: raise GitProtocolError("received more data after status report") if pkt is None: self._done = True return if self._pack_status is None: self._pack_status = pkt.strip() else: ref_status = pkt.strip() self._ref_statuses.append(ref_status) - if not ref_status.startswith(b'ok '): - self._ref_status_ok = False def read_pkt_refs(proto): server_capabilities = None refs = {} # Receive refs from server for pkt in proto.read_pkt_seq(): (sha, ref) = pkt.rstrip(b'\n').split(None, 1) if sha == b'ERR': raise GitProtocolError(ref.decode('utf-8', 'replace')) if server_capabilities is None: (ref, server_capabilities) = extract_capabilities(ref) refs[ref] = sha if len(refs) == 0: return {}, set([]) if refs == {CAPABILITIES_REF: ZERO_SHA}: refs = {} return refs, set(server_capabilities) class FetchPackResult(object): """Result of a fetch-pack operation. Attributes: refs: Dictionary with all remote refs symrefs: Dictionary with remote symrefs agent: User agent string """ _FORWARDED_ATTRS = [ - 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', - 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', + 'clear', 'copy', 'fromkeys', 'get', 'items', + 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values', 'viewitems', 'viewkeys', 'viewvalues'] def __init__(self, refs, symrefs, agent, new_shallow=None, new_unshallow=None): self.refs = refs self.symrefs = symrefs self.agent = agent self.new_shallow = new_shallow self.new_unshallow = new_unshallow def _warn_deprecated(self): import warnings warnings.warn( "Use FetchPackResult.refs instead.", DeprecationWarning, stacklevel=3) def __eq__(self, other): if isinstance(other, dict): self._warn_deprecated() return (self.refs == other) return (self.refs == other.refs and self.symrefs == other.symrefs and self.agent == other.agent) def __contains__(self, name): self._warn_deprecated() return name in self.refs def __getitem__(self, name): self._warn_deprecated() return self.refs[name] def __len__(self): self._warn_deprecated() return len(self.refs) def __iter__(self): self._warn_deprecated() return iter(self.refs) def __getattribute__(self, name): if name in type(self)._FORWARDED_ATTRS: self._warn_deprecated() return getattr(self.refs, name) return super(FetchPackResult, self).__getattribute__(name) def __repr__(self): return "%s(%r, %r, %r)" % ( self.__class__.__name__, self.refs, self.symrefs, self.agent) +class SendPackResult(object): + """Result of a upload-pack operation. + + Attributes: + refs: Dictionary with all remote refs + agent: User agent string + ref_status: Optional dictionary mapping ref name to error message (if it + failed to update), or None if it was updated successfully + """ + + _FORWARDED_ATTRS = [ + 'clear', 'copy', 'fromkeys', 'get', 'items', + 'keys', 'pop', 'popitem', + 'setdefault', 'update', 'values', 'viewitems', 'viewkeys', + 'viewvalues'] + + def __init__(self, refs, agent=None, ref_status=None): + self.refs = refs + self.agent = agent + self.ref_status = ref_status + + def _warn_deprecated(self): + import warnings + warnings.warn( + "Use SendPackResult.refs instead.", + DeprecationWarning, stacklevel=3) + + def __eq__(self, other): + if isinstance(other, dict): + self._warn_deprecated() + return self.refs == other + return self.refs == other.refs and self.agent == other.agent + + def __contains__(self, name): + self._warn_deprecated() + return name in self.refs + + def __getitem__(self, name): + self._warn_deprecated() + return self.refs[name] + + def __len__(self): + self._warn_deprecated() + return len(self.refs) + + def __iter__(self): + self._warn_deprecated() + return iter(self.refs) + + def __getattribute__(self, name): + if name in type(self)._FORWARDED_ATTRS: + self._warn_deprecated() + return getattr(self.refs, name) + return super(SendPackResult, self).__getattribute__(name) + + def __repr__(self): + return "%s(%r, %r)" % ( + self.__class__.__name__, self.refs, self.agent) + + def _read_shallow_updates(proto): new_shallow = set() new_unshallow = set() for pkt in proto.read_pkt_seq(): cmd, sha = pkt.split(b' ', 1) if cmd == COMMAND_SHALLOW: new_shallow.add(sha.strip()) elif cmd == COMMAND_UNSHALLOW: new_unshallow.add(sha.strip()) else: raise GitProtocolError('unknown command %s' % pkt) return (new_shallow, new_unshallow) # TODO(durin42): this doesn't correctly degrade if the server doesn't # support some capabilities. This should work properly with servers # that don't support multi_ack. class GitClient(object): """Git smart server client.""" def __init__(self, thin_packs=True, report_activity=None, quiet=False, include_tags=False): """Create a new GitClient instance. Args: thin_packs: Whether or not thin packs should be retrieved report_activity: Optional callback for reporting transport activity. include_tags: send annotated tags when sending the objects they point to """ self._report_activity = report_activity self._report_status_parser = None self._fetch_capabilities = set(UPLOAD_CAPABILITIES) self._fetch_capabilities.add(capability_agent()) self._send_capabilities = set(RECEIVE_CAPABILITIES) self._send_capabilities.add(capability_agent()) if quiet: self._send_capabilities.add(CAPABILITY_QUIET) if not thin_packs: self._fetch_capabilities.remove(CAPABILITY_THIN_PACK) if include_tags: self._fetch_capabilities.add(CAPABILITY_INCLUDE_TAG) def get_url(self, path): """Retrieves full url to given path. Args: path: Repository path (as string) Returns: Url to path (as string) """ raise NotImplementedError(self.get_url) @classmethod def from_parsedurl(cls, parsedurl, **kwargs): """Create an instance of this client from a urlparse.parsed object. Args: parsedurl: Result of urlparse() Returns: A `GitClient` object """ raise NotImplementedError(cls.from_parsedurl) def send_pack(self, path, update_refs, generate_pack_data, progress=None): """Upload a pack to a remote repository. Args: path: Repository path (as bytestring) update_refs: Function to determine changes to remote refs. Receive dict with existing remote refs, returns dict with changed refs (name -> sha, where sha=ZERO_SHA for deletions) generate_pack_data: Function that can return a tuple with number of objects and list of pack data to include progress: Optional progress function Returns: - new_refs dictionary containing the changes that were made - {refname: new_ref}, including deleted refs. + SendPackResult object Raises: SendPackError: if server rejects the pack data - UpdateRefsError: if the server supports report-status - and rejects ref updates """ raise NotImplementedError(self.send_pack) def fetch(self, path, target, determine_wants=None, progress=None, depth=None): """Fetch into a target repository. Args: path: Path to fetch from (as bytestring) target: Target repository to fetch into determine_wants: Optional function to determine what refs to fetch. Receives dictionary of name->sha, should return list of shas to fetch. Defaults to all shas. progress: Optional progress function depth: Depth to fetch at Returns: Dictionary with all remote refs (not just those fetched) """ if determine_wants is None: determine_wants = target.object_store.determine_wants_all if CAPABILITY_THIN_PACK in self._fetch_capabilities: # TODO(jelmer): Avoid reading entire file into memory and # only processing it after the whole file has been fetched. f = BytesIO() def commit(): if f.tell(): f.seek(0) target.object_store.add_thin_pack(f.read, None) def abort(): pass else: f, commit, abort = target.object_store.add_pack() try: result = self.fetch_pack( path, determine_wants, target.get_graph_walker(), f.write, progress=progress, depth=depth) except BaseException: abort() raise else: commit() target.update_shallow(result.new_shallow, result.new_unshallow) return result def fetch_pack(self, path, determine_wants, graph_walker, pack_data, progress=None, depth=None): """Retrieve a pack from a git smart server. Args: path: Remote path to fetch from determine_wants: Function determine what refs to fetch. Receives dictionary of name->sha, should return list of shas to fetch. graph_walker: Object with next() and ack(). pack_data: Callback called for each bit of data in the pack progress: Callback for progress reports (strings) depth: Shallow fetch depth Returns: FetchPackResult object """ raise NotImplementedError(self.fetch_pack) def get_refs(self, path): """Retrieve the current refs from a git smart server. Args: path: Path to the repo to fetch from. (as bytestring) Returns: """ raise NotImplementedError(self.get_refs) - def _parse_status_report(self, proto): - unpack = proto.read_pkt_line().strip() - if unpack != b'unpack ok': - st = True - # flush remaining error data - while st is not None: - st = proto.read_pkt_line() - raise SendPackError(unpack) - statuses = [] - errs = False - ref_status = proto.read_pkt_line() - while ref_status: - ref_status = ref_status.strip() - statuses.append(ref_status) - if not ref_status.startswith(b'ok '): - errs = True - ref_status = proto.read_pkt_line() - - if errs: - ref_status = {} - ok = set() - for status in statuses: - if b' ' not in status: - # malformed response, move on to the next one - continue - status, ref = status.split(b' ', 1) - - if status == b'ng': - if b' ' in ref: - ref, status = ref.split(b' ', 1) - else: - ok.add(ref) - ref_status[ref] = status - raise UpdateRefsError(', '.join([ - refname for refname in ref_status if refname not in ok]) + - b' failed to update', ref_status=ref_status) - def _read_side_band64k_data(self, proto, channel_callbacks): """Read per-channel data. This requires the side-band-64k capability. Args: proto: Protocol object to read from channel_callbacks: Dictionary mapping channels to packet handlers to use. None for a callback discards channel data. """ for pkt in proto.read_pkt_seq(): channel = ord(pkt[:1]) pkt = pkt[1:] try: cb = channel_callbacks[channel] except KeyError: raise AssertionError('Invalid sideband channel %d' % channel) else: if cb is not None: cb(pkt) @staticmethod def _should_send_pack(new_refs): # The packfile MUST NOT be sent if the only command used is delete. return any(sha != ZERO_SHA for sha in new_refs.values()) def _handle_receive_pack_head(self, proto, capabilities, old_refs, new_refs): """Handle the head of a 'git-receive-pack' request. Args: proto: Protocol object to read from capabilities: List of negotiated capabilities old_refs: Old refs, as received from the server new_refs: Refs to change Returns: (have, want) tuple """ want = [] have = [x for x in old_refs.values() if not x == ZERO_SHA] sent_capabilities = False for refname in new_refs: if not isinstance(refname, bytes): raise TypeError('refname is not a bytestring: %r' % refname) old_sha1 = old_refs.get(refname, ZERO_SHA) if not isinstance(old_sha1, bytes): raise TypeError('old sha1 for %s is not a bytestring: %r' % (refname, old_sha1)) new_sha1 = new_refs.get(refname, ZERO_SHA) if not isinstance(new_sha1, bytes): raise TypeError('old sha1 for %s is not a bytestring %r' % (refname, new_sha1)) if old_sha1 != new_sha1: if sent_capabilities: proto.write_pkt_line(old_sha1 + b' ' + new_sha1 + b' ' + refname) else: proto.write_pkt_line( old_sha1 + b' ' + new_sha1 + b' ' + refname + b'\0' + b' '.join(sorted(capabilities))) sent_capabilities = True if new_sha1 not in have and new_sha1 != ZERO_SHA: want.append(new_sha1) proto.write_pkt_line(None) return (have, want) def _negotiate_receive_pack_capabilities(self, server_capabilities): negotiated_capabilities = ( self._send_capabilities & server_capabilities) + agent = None + for capability in server_capabilities: + k, v = parse_capability(capability) + if k == CAPABILITY_AGENT: + agent = v unknown_capabilities = ( # noqa: F841 extract_capability_names(server_capabilities) - KNOWN_RECEIVE_CAPABILITIES) # TODO(jelmer): warn about unknown capabilities - return negotiated_capabilities + return negotiated_capabilities, agent - def _handle_receive_pack_tail(self, proto, capabilities, progress=None): + def _handle_receive_pack_tail( + self, proto: Protocol, capabilities: Set[bytes], + progress: Callable[[bytes], None] = None + ) -> Optional[Dict[bytes, Optional[str]]]: """Handle the tail of a 'git-receive-pack' request. Args: proto: Protocol object to read from capabilities: List of negotiated capabilities progress: Optional progress reporting function Returns: - + dict mapping ref name to: + error message if the ref failed to update + None if it was updated successfully """ if CAPABILITY_SIDE_BAND_64K in capabilities: if progress is None: def progress(x): pass channel_callbacks = {2: progress} if CAPABILITY_REPORT_STATUS in capabilities: channel_callbacks[1] = PktLineParser( self._report_status_parser.handle_packet).parse self._read_side_band64k_data(proto, channel_callbacks) else: if CAPABILITY_REPORT_STATUS in capabilities: for pkt in proto.read_pkt_seq(): self._report_status_parser.handle_packet(pkt) if self._report_status_parser is not None: - self._report_status_parser.check() + return dict(self._report_status_parser.check()) + + return None def _negotiate_upload_pack_capabilities(self, server_capabilities): unknown_capabilities = ( # noqa: F841 extract_capability_names(server_capabilities) - KNOWN_UPLOAD_CAPABILITIES) # TODO(jelmer): warn about unknown capabilities symrefs = {} agent = None for capability in server_capabilities: k, v = parse_capability(capability) if k == CAPABILITY_SYMREF: (src, dst) = v.split(b':', 1) symrefs[src] = dst if k == CAPABILITY_AGENT: agent = v negotiated_capabilities = ( self._fetch_capabilities & server_capabilities) return (negotiated_capabilities, symrefs, agent) def _handle_upload_pack_head(self, proto, capabilities, graph_walker, wants, can_read, depth): """Handle the head of a 'git-upload-pack' request. Args: proto: Protocol object to read from capabilities: List of negotiated capabilities graph_walker: GraphWalker instance to call .ack() on wants: List of commits to fetch can_read: function that returns a boolean that indicates whether there is extra graph data to read on proto depth: Depth for request Returns: """ assert isinstance(wants, list) and isinstance(wants[0], bytes) proto.write_pkt_line(COMMAND_WANT + b' ' + wants[0] + b' ' + b' '.join(sorted(capabilities)) + b'\n') for want in wants[1:]: proto.write_pkt_line(COMMAND_WANT + b' ' + want + b'\n') if depth not in (0, None) or getattr(graph_walker, 'shallow', None): if CAPABILITY_SHALLOW not in capabilities: raise GitProtocolError( "server does not support shallow capability required for " "depth") for sha in graph_walker.shallow: proto.write_pkt_line(COMMAND_SHALLOW + b' ' + sha + b'\n') if depth is not None: proto.write_pkt_line(COMMAND_DEEPEN + b' ' + str(depth).encode('ascii') + b'\n') proto.write_pkt_line(None) if can_read is not None: (new_shallow, new_unshallow) = _read_shallow_updates(proto) else: new_shallow = new_unshallow = None else: new_shallow = new_unshallow = set() proto.write_pkt_line(None) have = next(graph_walker) while have: proto.write_pkt_line(COMMAND_HAVE + b' ' + have + b'\n') if can_read is not None and can_read(): pkt = proto.read_pkt_line() parts = pkt.rstrip(b'\n').split(b' ') if parts[0] == b'ACK': graph_walker.ack(parts[1]) if parts[2] in (b'continue', b'common'): pass elif parts[2] == b'ready': break else: raise AssertionError( "%s not in ('continue', 'ready', 'common)" % parts[2]) have = next(graph_walker) proto.write_pkt_line(COMMAND_DONE + b'\n') return (new_shallow, new_unshallow) def _handle_upload_pack_tail(self, proto, capabilities, graph_walker, pack_data, progress=None, rbufsize=_RBUFSIZE): """Handle the tail of a 'git-upload-pack' request. Args: proto: Protocol object to read from capabilities: List of negotiated capabilities graph_walker: GraphWalker instance to call .ack() on pack_data: Function to call with pack data progress: Optional progress reporting function rbufsize: Read buffer size Returns: """ pkt = proto.read_pkt_line() while pkt: parts = pkt.rstrip(b'\n').split(b' ') if parts[0] == b'ACK': graph_walker.ack(parts[1]) if len(parts) < 3 or parts[2] not in ( b'ready', b'continue', b'common'): break pkt = proto.read_pkt_line() if CAPABILITY_SIDE_BAND_64K in capabilities: if progress is None: # Just ignore progress data def progress(x): pass self._read_side_band64k_data(proto, { SIDE_BAND_CHANNEL_DATA: pack_data, SIDE_BAND_CHANNEL_PROGRESS: progress} ) else: while True: data = proto.read(rbufsize) if data == b"": break pack_data(data) def check_wants(wants, refs): """Check that a set of wants is valid. Args: wants: Set of object SHAs to fetch refs: Refs dictionary to check against Returns: """ missing = set(wants) - { v for (k, v) in refs.items() if not k.endswith(ANNOTATED_TAG_SUFFIX)} if missing: raise InvalidWants(missing) def _remote_error_from_stderr(stderr): if stderr is None: raise HangupException() lines = [line.rstrip(b'\n') for line in stderr.readlines()] for line in lines: if line.startswith(b'ERROR: '): raise GitProtocolError( line[len(b'ERROR: '):].decode('utf-8', 'replace')) raise GitProtocolError(line.decode('utf-8', 'replace')) raise HangupException(lines) class TraditionalGitClient(GitClient): """Traditional Git client.""" DEFAULT_ENCODING = 'utf-8' def __init__(self, path_encoding=DEFAULT_ENCODING, **kwargs): self._remote_path_encoding = path_encoding super(TraditionalGitClient, self).__init__(**kwargs) def _connect(self, cmd, path): """Create a connection to the server. This method is abstract - concrete implementations should implement their own variant which connects to the server and returns an initialized Protocol object with the service ready for use and a can_read function which may be used to see if reads would block. Args: cmd: The git service name to which we should connect. path: The path we should pass to the service. (as bytestirng) """ raise NotImplementedError() def send_pack(self, path, update_refs, generate_pack_data, progress=None): """Upload a pack to a remote repository. Args: path: Repository path (as bytestring) update_refs: Function to determine changes to remote refs. Receive dict with existing remote refs, returns dict with changed refs (name -> sha, where sha=ZERO_SHA for deletions) generate_pack_data: Function that can return a tuple with number of objects and pack data to upload. progress: Optional callback called with progress updates Returns: - new_refs dictionary containing the changes that were made - {refname: new_ref}, including deleted refs. + SendPackResult Raises: SendPackError: if server rejects the pack data - UpdateRefsError: if the server supports report-status - and rejects ref updates """ proto, unused_can_read, stderr = self._connect(b'receive-pack', path) with proto: try: old_refs, server_capabilities = read_pkt_refs(proto) except HangupException: _remote_error_from_stderr(stderr) - negotiated_capabilities = \ + negotiated_capabilities, agent = \ self._negotiate_receive_pack_capabilities(server_capabilities) if CAPABILITY_REPORT_STATUS in negotiated_capabilities: self._report_status_parser = ReportStatusParser() report_status_parser = self._report_status_parser try: new_refs = orig_new_refs = update_refs(dict(old_refs)) except BaseException: proto.write_pkt_line(None) raise if set(new_refs.items()).issubset(set(old_refs.items())): proto.write_pkt_line(None) - return new_refs + return SendPackResult(new_refs, agent=agent, ref_status={}) if CAPABILITY_DELETE_REFS not in server_capabilities: # Server does not support deletions. Fail later. new_refs = dict(orig_new_refs) for ref, sha in orig_new_refs.items(): if sha == ZERO_SHA: if CAPABILITY_REPORT_STATUS in negotiated_capabilities: report_status_parser._ref_statuses.append( - b'ng ' + sha + + b'ng ' + ref + b' remote does not support deleting refs') report_status_parser._ref_status_ok = False del new_refs[ref] if new_refs is None: proto.write_pkt_line(None) - return old_refs + return SendPackResult(old_refs, agent=agent, ref_status={}) if len(new_refs) == 0 and len(orig_new_refs): # NOOP - Original new refs filtered out by policy proto.write_pkt_line(None) if report_status_parser is not None: - report_status_parser.check() - return old_refs + ref_status = dict(report_status_parser.check()) + else: + ref_status = None + return SendPackResult( + old_refs, agent=agent, ref_status=ref_status) (have, want) = self._handle_receive_pack_head( proto, negotiated_capabilities, old_refs, new_refs) pack_data_count, pack_data = generate_pack_data( have, want, ofs_delta=(CAPABILITY_OFS_DELTA in negotiated_capabilities)) if self._should_send_pack(new_refs): write_pack_data(proto.write_file(), pack_data_count, pack_data) - self._handle_receive_pack_tail( + ref_status = self._handle_receive_pack_tail( proto, negotiated_capabilities, progress) - return new_refs + return SendPackResult(new_refs, agent=agent, ref_status=ref_status) def fetch_pack(self, path, determine_wants, graph_walker, pack_data, progress=None, depth=None): """Retrieve a pack from a git smart server. Args: path: Remote path to fetch from determine_wants: Function determine what refs to fetch. Receives dictionary of name->sha, should return list of shas to fetch. graph_walker: Object with next() and ack(). pack_data: Callback called for each bit of data in the pack progress: Callback for progress reports (strings) depth: Shallow fetch depth Returns: FetchPackResult object """ proto, can_read, stderr = self._connect(b'upload-pack', path) with proto: try: refs, server_capabilities = read_pkt_refs(proto) except HangupException: _remote_error_from_stderr(stderr) negotiated_capabilities, symrefs, agent = ( self._negotiate_upload_pack_capabilities( server_capabilities)) if refs is None: proto.write_pkt_line(None) return FetchPackResult(refs, symrefs, agent) try: wants = determine_wants(refs) except BaseException: proto.write_pkt_line(None) raise if wants is not None: wants = [cid for cid in wants if cid != ZERO_SHA] if not wants: proto.write_pkt_line(None) return FetchPackResult(refs, symrefs, agent) (new_shallow, new_unshallow) = self._handle_upload_pack_head( proto, negotiated_capabilities, graph_walker, wants, can_read, depth=depth) self._handle_upload_pack_tail( proto, negotiated_capabilities, graph_walker, pack_data, progress) return FetchPackResult( refs, symrefs, agent, new_shallow, new_unshallow) def get_refs(self, path): """Retrieve the current refs from a git smart server. """ # stock `git ls-remote` uses upload-pack proto, _, stderr = self._connect(b'upload-pack', path) with proto: try: refs, _ = read_pkt_refs(proto) except HangupException: _remote_error_from_stderr(stderr) proto.write_pkt_line(None) return refs def archive(self, path, committish, write_data, progress=None, write_error=None, format=None, subdirs=None, prefix=None): proto, can_read, stderr = self._connect(b'upload-archive', path) with proto: if format is not None: proto.write_pkt_line(b"argument --format=" + format) proto.write_pkt_line(b"argument " + committish) if subdirs is not None: for subdir in subdirs: proto.write_pkt_line(b"argument " + subdir) if prefix is not None: proto.write_pkt_line(b"argument --prefix=" + prefix) proto.write_pkt_line(None) try: pkt = proto.read_pkt_line() except HangupException: _remote_error_from_stderr(stderr) if pkt == b"NACK\n": return elif pkt == b"ACK\n": pass elif pkt.startswith(b"ERR "): raise GitProtocolError( pkt[4:].rstrip(b"\n").decode('utf-8', 'replace')) else: raise AssertionError("invalid response %r" % pkt) ret = proto.read_pkt_line() if ret is not None: raise AssertionError("expected pkt tail") self._read_side_band64k_data(proto, { SIDE_BAND_CHANNEL_DATA: write_data, SIDE_BAND_CHANNEL_PROGRESS: progress, SIDE_BAND_CHANNEL_FATAL: write_error}) class TCPGitClient(TraditionalGitClient): """A Git Client that works over TCP directly (i.e. git://).""" def __init__(self, host, port=None, **kwargs): if port is None: port = TCP_GIT_PORT self._host = host self._port = port super(TCPGitClient, self).__init__(**kwargs) @classmethod def from_parsedurl(cls, parsedurl, **kwargs): return cls(parsedurl.hostname, port=parsedurl.port, **kwargs) def get_url(self, path): netloc = self._host if self._port is not None and self._port != TCP_GIT_PORT: netloc += ":%d" % self._port return urlunsplit(("git", netloc, path, '', '')) def _connect(self, cmd, path): if not isinstance(cmd, bytes): raise TypeError(cmd) if not isinstance(path, bytes): path = path.encode(self._remote_path_encoding) sockaddrs = socket.getaddrinfo( self._host, self._port, socket.AF_UNSPEC, socket.SOCK_STREAM) s = None err = socket.error("no address found for %s" % self._host) for (family, socktype, proto, canonname, sockaddr) in sockaddrs: s = socket.socket(family, socktype, proto) s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) try: s.connect(sockaddr) break except socket.error as e: err = e if s is not None: s.close() s = None if s is None: raise err # -1 means system default buffering rfile = s.makefile('rb', -1) # 0 means unbuffered wfile = s.makefile('wb', 0) def close(): rfile.close() wfile.close() s.close() proto = Protocol(rfile.read, wfile.write, close, report_activity=self._report_activity) if path.startswith(b"/~"): path = path[1:] # TODO(jelmer): Alternative to ascii? proto.send_cmd( b'git-' + cmd, path, b'host=' + self._host.encode('ascii')) return proto, lambda: _fileno_can_read(s), None class SubprocessWrapper(object): """A socket-like object that talks to a subprocess via pipes.""" def __init__(self, proc): self.proc = proc self.read = BufferedReader(proc.stdout).read self.write = proc.stdin.write @property def stderr(self): return self.proc.stderr def can_read(self): if sys.platform == 'win32': from msvcrt import get_osfhandle handle = get_osfhandle(self.proc.stdout.fileno()) return _win32_peek_avail(handle) != 0 else: return _fileno_can_read(self.proc.stdout.fileno()) def close(self): self.proc.stdin.close() self.proc.stdout.close() if self.proc.stderr: self.proc.stderr.close() self.proc.wait() def find_git_command(): """Find command to run for system Git (usually C Git).""" if sys.platform == 'win32': # support .exe, .bat and .cmd try: # to avoid overhead import win32api except ImportError: # run through cmd.exe with some overhead return ['cmd', '/c', 'git'] else: status, git = win32api.FindExecutable('git') return [git] else: return ['git'] class SubprocessGitClient(TraditionalGitClient): """Git client that talks to a server using a subprocess.""" @classmethod def from_parsedurl(cls, parsedurl, **kwargs): return cls(**kwargs) git_command = None def _connect(self, service, path): if not isinstance(service, bytes): raise TypeError(service) if isinstance(path, bytes): path = path.decode(self._remote_path_encoding) if self.git_command is None: git_command = find_git_command() argv = git_command + [service.decode('ascii'), path] p = subprocess.Popen(argv, bufsize=0, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) pw = SubprocessWrapper(p) return (Protocol(pw.read, pw.write, pw.close, report_activity=self._report_activity), pw.can_read, p.stderr) class LocalGitClient(GitClient): """Git Client that just uses a local Repo.""" def __init__(self, thin_packs=True, report_activity=None, config=None): """Create a new LocalGitClient instance. Args: thin_packs: Whether or not thin packs should be retrieved report_activity: Optional callback for reporting transport activity. """ self._report_activity = report_activity # Ignore the thin_packs argument def get_url(self, path): return urlunsplit(('file', '', path, '', '')) @classmethod def from_parsedurl(cls, parsedurl, **kwargs): return cls(**kwargs) @classmethod def _open_repo(cls, path): from dulwich.repo import Repo if not isinstance(path, str): path = os.fsdecode(path) return closing(Repo(path)) def send_pack(self, path, update_refs, generate_pack_data, progress=None): """Upload a pack to a remote repository. Args: path: Repository path (as bytestring) update_refs: Function to determine changes to remote refs. Receive dict with existing remote refs, returns dict with changed refs (name -> sha, where sha=ZERO_SHA for deletions) with number of items and pack data to upload. progress: Optional progress function Returns: - new_refs dictionary containing the changes that were made - {refname: new_ref}, including deleted refs. + SendPackResult Raises: SendPackError: if server rejects the pack data - UpdateRefsError: if the server supports report-status - and rejects ref updates """ if not progress: def progress(x): pass with self._open_repo(path) as target: old_refs = target.get_refs() new_refs = update_refs(dict(old_refs)) have = [sha1 for sha1 in old_refs.values() if sha1 != ZERO_SHA] want = [] for refname, new_sha1 in new_refs.items(): if (new_sha1 not in have and new_sha1 not in want and new_sha1 != ZERO_SHA): want.append(new_sha1) if (not want and set(new_refs.items()).issubset(set(old_refs.items()))): - return new_refs + return SendPackResult(new_refs, ref_status={}) target.object_store.add_pack_data( *generate_pack_data(have, want, ofs_delta=True)) + ref_status = {} + for refname, new_sha1 in new_refs.items(): old_sha1 = old_refs.get(refname, ZERO_SHA) if new_sha1 != ZERO_SHA: if not target.refs.set_if_equals( refname, old_sha1, new_sha1): - progress('unable to set %s to %s' % - (refname, new_sha1)) + msg = 'unable to set %s to %s' % (refname, new_sha1) + progress(msg) + ref_status[refname] = msg else: if not target.refs.remove_if_equals(refname, old_sha1): progress('unable to remove %s' % refname) + ref_status[refname] = 'unable to remove' - return new_refs + return SendPackResult(new_refs, ref_status=ref_status) def fetch(self, path, target, determine_wants=None, progress=None, depth=None): """Fetch into a target repository. Args: path: Path to fetch from (as bytestring) target: Target repository to fetch into determine_wants: Optional function determine what refs to fetch. Receives dictionary of name->sha, should return list of shas to fetch. Defaults to all shas. progress: Optional progress function depth: Shallow fetch depth Returns: FetchPackResult object """ with self._open_repo(path) as r: refs = r.fetch(target, determine_wants=determine_wants, progress=progress, depth=depth) return FetchPackResult(refs, r.refs.get_symrefs(), agent_string()) def fetch_pack(self, path, determine_wants, graph_walker, pack_data, progress=None, depth=None): """Retrieve a pack from a git smart server. Args: path: Remote path to fetch from determine_wants: Function determine what refs to fetch. Receives dictionary of name->sha, should return list of shas to fetch. graph_walker: Object with next() and ack(). pack_data: Callback called for each bit of data in the pack progress: Callback for progress reports (strings) depth: Shallow fetch depth Returns: FetchPackResult object """ with self._open_repo(path) as r: objects_iter = r.fetch_objects( determine_wants, graph_walker, progress=progress, depth=depth) symrefs = r.refs.get_symrefs() agent = agent_string() # Did the process short-circuit (e.g. in a stateless RPC call)? # Note that the client still expects a 0-object pack in most cases. if objects_iter is None: return FetchPackResult(None, symrefs, agent) protocol = ProtocolFile(None, pack_data) write_pack_objects(protocol, objects_iter) return FetchPackResult(r.get_refs(), symrefs, agent) def get_refs(self, path): """Retrieve the current refs from a git smart server. """ with self._open_repo(path) as target: return target.get_refs() # What Git client to use for local access default_local_git_client_cls = LocalGitClient class SSHVendor(object): """A client side SSH implementation.""" def connect_ssh(self, host, command, username=None, port=None, password=None, key_filename=None): # This function was deprecated in 0.9.1 import warnings warnings.warn( "SSHVendor.connect_ssh has been renamed to SSHVendor.run_command", DeprecationWarning) return self.run_command(host, command, username=username, port=port, password=password, key_filename=key_filename) def run_command(self, host, command, username=None, port=None, password=None, key_filename=None): """Connect to an SSH server. Run a command remotely and return a file-like object for interaction with the remote command. Args: host: Host name command: Command to run (as argv array) username: Optional ame of user to log in as port: Optional SSH port to use password: Optional ssh password for login or private key key_filename: Optional path to private keyfile Returns: """ raise NotImplementedError(self.run_command) class StrangeHostname(Exception): """Refusing to connect to strange SSH hostname.""" def __init__(self, hostname): super(StrangeHostname, self).__init__(hostname) class SubprocessSSHVendor(SSHVendor): """SSH vendor that shells out to the local 'ssh' command.""" def run_command(self, host, command, username=None, port=None, password=None, key_filename=None): if password is not None: raise NotImplementedError( "Setting password not supported by SubprocessSSHVendor.") args = ['ssh', '-x'] if port: args.extend(['-p', str(port)]) if key_filename: args.extend(['-i', str(key_filename)]) if username: host = '%s@%s' % (username, host) if host.startswith('-'): raise StrangeHostname(hostname=host) args.append(host) proc = subprocess.Popen(args + [command], bufsize=0, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) return SubprocessWrapper(proc) class PLinkSSHVendor(SSHVendor): """SSH vendor that shells out to the local 'plink' command.""" def run_command(self, host, command, username=None, port=None, password=None, key_filename=None): if sys.platform == 'win32': args = ['plink.exe', '-ssh'] else: args = ['plink', '-ssh'] if password is not None: import warnings warnings.warn( "Invoking PLink with a password exposes the password in the " "process list.") args.extend(['-pw', str(password)]) if port: args.extend(['-P', str(port)]) if key_filename: args.extend(['-i', str(key_filename)]) if username: host = '%s@%s' % (username, host) if host.startswith('-'): raise StrangeHostname(hostname=host) args.append(host) proc = subprocess.Popen(args + [command], bufsize=0, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) return SubprocessWrapper(proc) def ParamikoSSHVendor(**kwargs): import warnings warnings.warn( "ParamikoSSHVendor has been moved to dulwich.contrib.paramiko_vendor.", DeprecationWarning) from dulwich.contrib.paramiko_vendor import ParamikoSSHVendor return ParamikoSSHVendor(**kwargs) # Can be overridden by users get_ssh_vendor = SubprocessSSHVendor class SSHGitClient(TraditionalGitClient): def __init__(self, host, port=None, username=None, vendor=None, config=None, password=None, key_filename=None, **kwargs): self.host = host self.port = port self.username = username self.password = password self.key_filename = key_filename super(SSHGitClient, self).__init__(**kwargs) self.alternative_paths = {} if vendor is not None: self.ssh_vendor = vendor else: self.ssh_vendor = get_ssh_vendor() def get_url(self, path): netloc = self.host if self.port is not None: netloc += ":%d" % self.port if self.username is not None: netloc = urlquote(self.username, '@/:') + "@" + netloc return urlunsplit(('ssh', netloc, path, '', '')) @classmethod def from_parsedurl(cls, parsedurl, **kwargs): return cls(host=parsedurl.hostname, port=parsedurl.port, username=parsedurl.username, **kwargs) def _get_cmd_path(self, cmd): cmd = self.alternative_paths.get(cmd, b'git-' + cmd) assert isinstance(cmd, bytes) return cmd def _connect(self, cmd, path): if not isinstance(cmd, bytes): raise TypeError(cmd) if isinstance(path, bytes): path = path.decode(self._remote_path_encoding) if path.startswith("/~"): path = path[1:] argv = (self._get_cmd_path(cmd).decode(self._remote_path_encoding) + " '" + path + "'") kwargs = {} if self.password is not None: kwargs['password'] = self.password if self.key_filename is not None: kwargs['key_filename'] = self.key_filename con = self.ssh_vendor.run_command( self.host, argv, port=self.port, username=self.username, **kwargs) return (Protocol(con.read, con.write, con.close, report_activity=self._report_activity), con.can_read, getattr(con, 'stderr', None)) def default_user_agent_string(): # Start user agent with "git/", because GitHub requires this. :-( See # https://github.com/jelmer/dulwich/issues/562 for details. return "git/dulwich/%s" % ".".join([str(x) for x in dulwich.__version__]) def default_urllib3_manager(config, pool_manager_cls=None, proxy_manager_cls=None, **override_kwargs): """Return `urllib3` connection pool manager. Honour detected proxy configurations. Args: config: dulwich.config.ConfigDict` instance with Git configuration. kwargs: Additional arguments for urllib3.ProxyManager Returns: `pool_manager_cls` (defaults to `urllib3.ProxyManager`) instance for proxy configurations, `proxy_manager_cls` (defaults to `urllib3.PoolManager`) instance otherwise. """ proxy_server = user_agent = None ca_certs = ssl_verify = None if config is not None: try: proxy_server = config.get(b"http", b"proxy") except KeyError: pass try: user_agent = config.get(b"http", b"useragent") except KeyError: pass # TODO(jelmer): Support per-host settings try: ssl_verify = config.get_boolean(b"http", b"sslVerify") except KeyError: ssl_verify = True try: ca_certs = config.get(b"http", b"sslCAInfo") except KeyError: ca_certs = None if user_agent is None: user_agent = default_user_agent_string() headers = {"User-agent": user_agent} kwargs = {} if ssl_verify is True: kwargs['cert_reqs'] = "CERT_REQUIRED" elif ssl_verify is False: kwargs['cert_reqs'] = 'CERT_NONE' else: # Default to SSL verification kwargs['cert_reqs'] = "CERT_REQUIRED" if ca_certs is not None: kwargs['ca_certs'] = ca_certs kwargs.update(override_kwargs) # Try really hard to find a SSL certificate path if 'ca_certs' not in kwargs and kwargs.get('cert_reqs') != 'CERT_NONE': try: import certifi except ImportError: pass else: kwargs['ca_certs'] = certifi.where() import urllib3 if proxy_server is not None: if proxy_manager_cls is None: proxy_manager_cls = urllib3.ProxyManager # `urllib3` requires a `str` object in both Python 2 and 3, while # `ConfigDict` coerces entries to `bytes` on Python 3. Compensate. if not isinstance(proxy_server, str): proxy_server = proxy_server.decode() manager = proxy_manager_cls(proxy_server, headers=headers, **kwargs) else: if pool_manager_cls is None: pool_manager_cls = urllib3.PoolManager manager = pool_manager_cls(headers=headers, **kwargs) return manager class HttpGitClient(GitClient): def __init__(self, base_url, dumb=None, pool_manager=None, config=None, username=None, password=None, **kwargs): self._base_url = base_url.rstrip("/") + "/" self._username = username self._password = password self.dumb = dumb if pool_manager is None: self.pool_manager = default_urllib3_manager(config) else: self.pool_manager = pool_manager if username is not None: # No escaping needed: ":" is not allowed in username: # https://tools.ietf.org/html/rfc2617#section-2 credentials = "%s:%s" % (username, password) import urllib3.util basic_auth = urllib3.util.make_headers(basic_auth=credentials) self.pool_manager.headers.update(basic_auth) GitClient.__init__(self, **kwargs) def get_url(self, path): return self._get_url(path).rstrip("/") @classmethod def from_parsedurl(cls, parsedurl, **kwargs): password = parsedurl.password if password is not None: kwargs['password'] = urlunquote(password) username = parsedurl.username if username is not None: kwargs['username'] = urlunquote(username) netloc = parsedurl.hostname if parsedurl.port: netloc = "%s:%s" % (netloc, parsedurl.port) if parsedurl.username: netloc = "%s@%s" % (parsedurl.username, netloc) parsedurl = parsedurl._replace(netloc=netloc) return cls(urlunparse(parsedurl), **kwargs) def __repr__(self): return "%s(%r, dumb=%r)" % ( type(self).__name__, self._base_url, self.dumb) def _get_url(self, path): if not isinstance(path, str): # urllib3.util.url._encode_invalid_chars() converts the path back # to bytes using the utf-8 codec. path = path.decode('utf-8') return urljoin(self._base_url, path).rstrip("/") + "/" def _http_request(self, url, headers=None, data=None, allow_compression=False): """Perform HTTP request. Args: url: Request URL. headers: Optional custom headers to override defaults. data: Request data. allow_compression: Allow GZipped communication. Returns: Tuple (`response`, `read`), where response is an `urllib3` response object with additional `content_type` and `redirect_location` properties, and `read` is a consumable read method for the response data. """ req_headers = self.pool_manager.headers.copy() if headers is not None: req_headers.update(headers) req_headers["Pragma"] = "no-cache" if allow_compression: req_headers["Accept-Encoding"] = "gzip" else: req_headers["Accept-Encoding"] = "identity" if data is None: resp = self.pool_manager.request("GET", url, headers=req_headers) else: resp = self.pool_manager.request("POST", url, headers=req_headers, body=data) if resp.status == 404: raise NotGitRepository() elif resp.status == 401: raise HTTPUnauthorized(resp.getheader('WWW-Authenticate')) elif resp.status != 200: raise GitProtocolError("unexpected http resp %d for %s" % (resp.status, url)) # TODO: Optimization available by adding `preload_content=False` to the # request and just passing the `read` method on instead of going via # `BytesIO`, if we can guarantee that the entire response is consumed # before issuing the next to still allow for connection reuse from the # pool. read = BytesIO(resp.data).read resp.content_type = resp.getheader("Content-Type") # Check if geturl() is available (urllib3 version >= 1.23) try: resp_url = resp.geturl() except AttributeError: # get_redirect_location() is available for urllib3 >= 1.1 resp.redirect_location = resp.get_redirect_location() else: resp.redirect_location = resp_url if resp_url != url else '' return resp, read def _discover_references(self, service, base_url): assert base_url[-1] == "/" tail = "info/refs" headers = {"Accept": "*/*"} if self.dumb is not True: tail += "?service=%s" % service.decode('ascii') url = urljoin(base_url, tail) resp, read = self._http_request(url, headers, allow_compression=True) if resp.redirect_location: # Something changed (redirect!), so let's update the base URL if not resp.redirect_location.endswith(tail): raise GitProtocolError( "Redirected from URL %s to URL %s without %s" % ( url, resp.redirect_location, tail)) base_url = resp.redirect_location[:-len(tail)] try: self.dumb = not resp.content_type.startswith("application/x-git-") if not self.dumb: proto = Protocol(read, None) # The first line should mention the service try: [pkt] = list(proto.read_pkt_seq()) except ValueError: raise GitProtocolError( "unexpected number of packets received") if pkt.rstrip(b'\n') != (b'# service=' + service): raise GitProtocolError( "unexpected first line %r from smart server" % pkt) return read_pkt_refs(proto) + (base_url, ) else: return read_info_refs(resp), set(), base_url finally: resp.close() def _smart_request(self, service, url, data): assert url[-1] == "/" url = urljoin(url, service) result_content_type = "application/x-%s-result" % service headers = { "Content-Type": "application/x-%s-request" % service, "Accept": result_content_type, "Content-Length": str(len(data)), } resp, read = self._http_request(url, headers, data) if resp.content_type != result_content_type: raise GitProtocolError("Invalid content-type from server: %s" % resp.content_type) return resp, read def send_pack(self, path, update_refs, generate_pack_data, progress=None): """Upload a pack to a remote repository. Args: path: Repository path (as bytestring) update_refs: Function to determine changes to remote refs. Receives dict with existing remote refs, returns dict with changed refs (name -> sha, where sha=ZERO_SHA for deletions) generate_pack_data: Function that can return a tuple with number of elements and pack data to upload. progress: Optional progress function Returns: - new_refs dictionary containing the changes that were made - {refname: new_ref}, including deleted refs. + SendPackResult Raises: SendPackError: if server rejects the pack data - UpdateRefsError: if the server supports report-status - and rejects ref updates """ url = self._get_url(path) old_refs, server_capabilities, url = self._discover_references( b"git-receive-pack", url) - negotiated_capabilities = self._negotiate_receive_pack_capabilities( - server_capabilities) + negotiated_capabilities, agent = ( + self._negotiate_receive_pack_capabilities(server_capabilities)) negotiated_capabilities.add(capability_agent()) if CAPABILITY_REPORT_STATUS in negotiated_capabilities: self._report_status_parser = ReportStatusParser() new_refs = update_refs(dict(old_refs)) if new_refs is None: # Determine wants function is aborting the push. - return old_refs + return SendPackResult(old_refs, agent=agent, ref_status={}) if set(new_refs.items()).issubset(set(old_refs.items())): - return new_refs + return SendPackResult(new_refs, agent=agent, ref_status={}) if self.dumb: raise NotImplementedError(self.fetch_pack) req_data = BytesIO() req_proto = Protocol(None, req_data.write) (have, want) = self._handle_receive_pack_head( req_proto, negotiated_capabilities, old_refs, new_refs) pack_data_count, pack_data = generate_pack_data( have, want, ofs_delta=(CAPABILITY_OFS_DELTA in negotiated_capabilities)) if self._should_send_pack(new_refs): write_pack_data(req_proto.write_file(), pack_data_count, pack_data) resp, read = self._smart_request("git-receive-pack", url, data=req_data.getvalue()) try: resp_proto = Protocol(read, None) - self._handle_receive_pack_tail( + ref_status = self._handle_receive_pack_tail( resp_proto, negotiated_capabilities, progress) - return new_refs + return SendPackResult( + new_refs, agent=agent, ref_status=ref_status) finally: resp.close() def fetch_pack(self, path, determine_wants, graph_walker, pack_data, progress=None, depth=None): """Retrieve a pack from a git smart server. Args: path: Path to fetch from determine_wants: Callback that returns list of commits to fetch graph_walker: Object with next() and ack(). pack_data: Callback called for each bit of data in the pack progress: Callback for progress reports (strings) depth: Depth for request Returns: FetchPackResult object """ url = self._get_url(path) refs, server_capabilities, url = self._discover_references( b"git-upload-pack", url) negotiated_capabilities, symrefs, agent = ( self._negotiate_upload_pack_capabilities( server_capabilities)) wants = determine_wants(refs) if wants is not None: wants = [cid for cid in wants if cid != ZERO_SHA] if not wants: return FetchPackResult(refs, symrefs, agent) if self.dumb: - raise NotImplementedError(self.send_pack) + raise NotImplementedError(self.fetch_pack) req_data = BytesIO() req_proto = Protocol(None, req_data.write) (new_shallow, new_unshallow) = self._handle_upload_pack_head( req_proto, negotiated_capabilities, graph_walker, wants, can_read=None, depth=depth) resp, read = self._smart_request( "git-upload-pack", url, data=req_data.getvalue()) try: resp_proto = Protocol(read, None) if new_shallow is None and new_unshallow is None: (new_shallow, new_unshallow) = _read_shallow_updates( resp_proto) self._handle_upload_pack_tail( resp_proto, negotiated_capabilities, graph_walker, pack_data, progress) return FetchPackResult( refs, symrefs, agent, new_shallow, new_unshallow) finally: resp.close() def get_refs(self, path): """Retrieve the current refs from a git smart server. """ url = self._get_url(path) refs, _, _ = self._discover_references( b"git-upload-pack", url) return refs def get_transport_and_path_from_url(url, config=None, **kwargs): """Obtain a git client from a URL. Args: url: URL to open (a unicode string) config: Optional config object thin_packs: Whether or not thin packs should be retrieved report_activity: Optional callback for reporting transport activity. Returns: Tuple with client instance and relative path. """ parsed = urlparse(url) if parsed.scheme == 'git': return (TCPGitClient.from_parsedurl(parsed, **kwargs), parsed.path) elif parsed.scheme in ('git+ssh', 'ssh'): return SSHGitClient.from_parsedurl(parsed, **kwargs), parsed.path elif parsed.scheme in ('http', 'https'): return HttpGitClient.from_parsedurl( parsed, config=config, **kwargs), parsed.path elif parsed.scheme == 'file': return default_local_git_client_cls.from_parsedurl( parsed, **kwargs), parsed.path raise ValueError("unknown scheme '%s'" % parsed.scheme) def parse_rsync_url(location): """Parse a rsync-style URL. """ if ':' in location and '@' not in location: # SSH with no user@, zero or one leading slash. (host, path) = location.split(':', 1) user = None elif ':' in location: # SSH with user@host:foo. user_host, path = location.split(':', 1) if '@' in user_host: user, host = user_host.rsplit('@', 1) else: user = None host = user_host else: raise ValueError('not a valid rsync-style URL') return (user, host, path) def get_transport_and_path(location, **kwargs): """Obtain a git client from a URL. Args: location: URL or path (a string) config: Optional config object thin_packs: Whether or not thin packs should be retrieved report_activity: Optional callback for reporting transport activity. Returns: Tuple with client instance and relative path. """ # First, try to parse it as a URL try: return get_transport_and_path_from_url(location, **kwargs) except ValueError: pass if (sys.platform == 'win32' and location[0].isalpha() and location[1:3] == ':\\'): # Windows local path return default_local_git_client_cls(**kwargs), location try: (username, hostname, path) = parse_rsync_url(location) except ValueError: # Otherwise, assume it's a local path. return default_local_git_client_cls(**kwargs), location else: return SSHGitClient(hostname, username=username, **kwargs), path DEFAULT_GIT_CREDENTIALS_PATHS = [ os.path.expanduser('~/.git-credentials'), get_xdg_config_home_path('git', 'credentials')] def get_credentials_from_store(scheme, hostname, username=None, fnames=DEFAULT_GIT_CREDENTIALS_PATHS): for fname in fnames: try: with open(fname, 'rb') as f: for line in f: parsed_line = urlparse(line) if (parsed_line.scheme == scheme and parsed_line.hostname == hostname and (username is None or parsed_line.username == username)): return parsed_line.username, parsed_line.password except FileNotFoundError: # If the file doesn't exist, try the next one. continue diff --git a/dulwich/diff_tree.py b/dulwich/diff_tree.py index f4cc38ac..a87be78a 100644 --- a/dulwich/diff_tree.py +++ b/dulwich/diff_tree.py @@ -1,627 +1,627 @@ # 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.""" 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 (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, 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()): + for c in chain.from_iterable(obj.as_raw_chunks()): 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, 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, 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 ( # type: ignore _is_tree, _merge_entries, _count_blocks, ) except ImportError: pass diff --git a/dulwich/errors.py b/dulwich/errors.py index 59f95b98..166c5972 100644 --- a/dulwich/errors.py +++ b/dulwich/errors.py @@ -1,185 +1,188 @@ # errors.py -- errors for dulwich # Copyright (C) 2007 James Westby # Copyright (C) 2009-2012 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. # """Dulwich-related exception classes and utility functions.""" import binascii class ChecksumMismatch(Exception): """A checksum didn't match the expected contents.""" def __init__(self, expected, got, extra=None): if len(expected) == 20: expected = binascii.hexlify(expected) if len(got) == 20: got = binascii.hexlify(got) self.expected = expected self.got = got self.extra = extra if self.extra is None: Exception.__init__( self, "Checksum mismatch: Expected %s, got %s" % (expected, got)) else: Exception.__init__( self, "Checksum mismatch: Expected %s, got %s; %s" % (expected, got, extra)) class WrongObjectException(Exception): """Baseclass for all the _ is not a _ exceptions on objects. Do not instantiate directly. Subclasses should define a type_name attribute that indicates what was expected if they were raised. """ def __init__(self, sha, *args, **kwargs): Exception.__init__(self, "%s is not a %s" % (sha, self.type_name)) class NotCommitError(WrongObjectException): """Indicates that the sha requested does not point to a commit.""" type_name = 'commit' class NotTreeError(WrongObjectException): """Indicates that the sha requested does not point to a tree.""" type_name = 'tree' class NotTagError(WrongObjectException): """Indicates that the sha requested does not point to a tag.""" type_name = 'tag' class NotBlobError(WrongObjectException): """Indicates that the sha requested does not point to a blob.""" type_name = 'blob' class MissingCommitError(Exception): """Indicates that a commit was not found in the repository""" def __init__(self, sha, *args, **kwargs): self.sha = sha Exception.__init__(self, "%s is not in the revision store" % sha) class ObjectMissing(Exception): """Indicates that a requested object is missing.""" def __init__(self, sha, *args, **kwargs): Exception.__init__(self, "%s is not in the pack" % sha) class ApplyDeltaError(Exception): """Indicates that applying a delta failed.""" def __init__(self, *args, **kwargs): Exception.__init__(self, *args, **kwargs) class NotGitRepository(Exception): """Indicates that no Git repository was found.""" def __init__(self, *args, **kwargs): Exception.__init__(self, *args, **kwargs) class GitProtocolError(Exception): """Git protocol exception.""" def __init__(self, *args, **kwargs): Exception.__init__(self, *args, **kwargs) class SendPackError(GitProtocolError): """An error occurred during send_pack.""" +# N.B.: UpdateRefsError is no longer used and will be result in +# Dulwich 0.21. +# remove: >= 0.21 class UpdateRefsError(GitProtocolError): """The server reported errors updating refs.""" def __init__(self, *args, **kwargs): self.ref_status = kwargs.pop('ref_status') super(UpdateRefsError, self).__init__(*args, **kwargs) class HangupException(GitProtocolError): """Hangup exception.""" def __init__(self, stderr_lines=None): if stderr_lines: super(HangupException, self).__init__( '\n'.join( [line.decode('utf-8', 'surrogateescape') for line in stderr_lines])) else: super(HangupException, self).__init__( "The remote server unexpectedly closed the connection.") self.stderr_lines = stderr_lines class UnexpectedCommandError(GitProtocolError): """Unexpected command received in a proto line.""" def __init__(self, command): if command is None: command = 'flush-pkt' else: command = 'command %s' % command super(UnexpectedCommandError, self).__init__( 'Protocol got unexpected %s' % command) class FileFormatException(Exception): """Base class for exceptions relating to reading git file formats.""" class PackedRefsException(FileFormatException): """Indicates an error parsing a packed-refs file.""" class ObjectFormatException(FileFormatException): """Indicates an error parsing an object.""" class NoIndexPresent(Exception): """No index is present.""" class CommitError(Exception): """An error occurred while performing a commit.""" class RefFormatError(Exception): """Indicates an invalid ref name.""" class HookError(Exception): """An error occurred while executing a hook.""" diff --git a/dulwich/file.py b/dulwich/file.py index 555c3bcd..c19a729d 100644 --- a/dulwich/file.py +++ b/dulwich/file.py @@ -1,190 +1,191 @@ # file.py -- Safe access to git files # 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. # """Safe access to git files.""" import io import os import sys -import tempfile def ensure_dir_exists(dirname): """Ensure a directory exists, creating if necessary.""" try: os.makedirs(dirname) except FileExistsError: pass def _fancy_rename(oldname, newname): """Rename file with temporary backup file to rollback if rename fails""" if not os.path.exists(newname): try: os.rename(oldname, newname) except OSError: raise return + # Defer the tempfile import since it pulls in a lot of other things. + import tempfile # destination file exists try: (fd, tmpfile) = tempfile.mkstemp(".tmp", prefix=oldname, dir=".") os.close(fd) os.remove(tmpfile) except OSError: # either file could not be created (e.g. permission problem) # or could not be deleted (e.g. rude virus scanner) raise try: os.rename(newname, tmpfile) except OSError: raise # no rename occurred try: os.rename(oldname, newname) except OSError: os.rename(tmpfile, newname) raise os.remove(tmpfile) def GitFile(filename, mode='rb', bufsize=-1): """Create a file object that obeys the git file locking protocol. Returns: a builtin file object or a _GitFile object Note: See _GitFile for a description of the file locking protocol. Only read-only and write-only (binary) modes are supported; r+, w+, and a are not. To read and write from the same file, you can take advantage of the fact that opening a file for write does not actually open the file you request. """ if 'a' in mode: raise IOError('append mode not supported for Git files') if '+' in mode: raise IOError('read/write mode not supported for Git files') if 'b' not in mode: raise IOError('text mode not supported for Git files') if 'w' in mode: return _GitFile(filename, mode, bufsize) else: return io.open(filename, mode, bufsize) class FileLocked(Exception): """File is already locked.""" def __init__(self, filename, lockfilename): self.filename = filename self.lockfilename = lockfilename super(FileLocked, self).__init__(filename, lockfilename) class _GitFile(object): """File that follows the git locking protocol for writes. All writes to a file foo will be written into foo.lock in the same directory, and the lockfile will be renamed to overwrite the original file on close. Note: You *must* call close() or abort() on a _GitFile for the lock to be released. Typically this will happen in a finally block. """ PROXY_PROPERTIES = set(['closed', 'encoding', 'errors', 'mode', 'name', 'newlines', 'softspace']) PROXY_METHODS = ('__iter__', 'flush', 'fileno', 'isatty', 'read', 'readline', 'readlines', 'seek', 'tell', 'truncate', 'write', 'writelines') def __init__(self, filename, mode, bufsize): self._filename = filename if isinstance(self._filename, bytes): self._lockfilename = self._filename + b'.lock' else: self._lockfilename = self._filename + '.lock' try: fd = os.open( self._lockfilename, os.O_RDWR | os.O_CREAT | os.O_EXCL | getattr(os, "O_BINARY", 0)) except FileExistsError: raise FileLocked(filename, self._lockfilename) self._file = os.fdopen(fd, mode, bufsize) self._closed = False for method in self.PROXY_METHODS: setattr(self, method, getattr(self._file, method)) def abort(self): """Close and discard the lockfile without overwriting the target. If the file is already closed, this is a no-op. """ if self._closed: return self._file.close() try: os.remove(self._lockfilename) self._closed = True except FileNotFoundError: # The file may have been removed already, which is ok. self._closed = True def close(self): """Close this file, saving the lockfile over the original. Note: If this method fails, it will attempt to delete the lockfile. However, it is not guaranteed to do so (e.g. if a filesystem becomes suddenly read-only), which will prevent future writes to this file until the lockfile is removed manually. Raises: OSError: if the original file could not be overwritten. The lock file is still closed, so further attempts to write to the same file object will raise ValueError. """ if self._closed: return os.fsync(self._file.fileno()) self._file.close() try: if getattr(os, 'replace', None) is not None: os.replace(self._lockfilename, self._filename) else: if sys.platform != 'win32': os.rename(self._lockfilename, self._filename) else: # Windows versions prior to Vista don't support atomic # renames _fancy_rename(self._lockfilename, self._filename) finally: self.abort() def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() def __getattr__(self, name): """Proxy property calls to the underlying file.""" if name in self.PROXY_PROPERTIES: return getattr(self._file, name) raise AttributeError(name) diff --git a/dulwich/graph.py b/dulwich/graph.py new file mode 100644 index 00000000..dfa2ad74 --- /dev/null +++ b/dulwich/graph.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab +# Copyright (c) 2020 Kevin B. Hendricks, Stratford Ontario Canada +# +# 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. + +""" +Implementation of merge-base following the approach of git +""" + +from collections import deque + + +def _find_lcas(lookup_parents, c1, c2s): + cands = [] + cstates = {} + + # Flags to Record State + _ANC_OF_1 = 1 # ancestor of commit 1 + _ANC_OF_2 = 2 # ancestor of commit 2 + _DNC = 4 # Do Not Consider + _LCA = 8 # potential LCA + + def _has_candidates(wlst, cstates): + for cmt in wlst: + if cmt in cstates: + if not (cstates[cmt] & _DNC): + return True + return False + + # initialize the working list + wlst = deque() + cstates[c1] = _ANC_OF_1 + wlst.append(c1) + for c2 in c2s: + cstates[c2] = _ANC_OF_2 + wlst.append(c2) + + # loop until no other LCA candidates are viable in working list + # adding any parents to the list in a breadth first manner + while _has_candidates(wlst, cstates): + cmt = wlst.popleft() + flags = cstates[cmt] + if flags == (_ANC_OF_1 | _ANC_OF_2): + # potential common ancestor + if not (flags & _LCA): + flags = flags | _LCA + cstates[cmt] = flags + cands.append(cmt) + # mark any parents of this node _DNC as all parents + # would be one level further removed common ancestors + flags = flags | _DNC + parents = lookup_parents(cmt) + if parents: + for pcmt in parents: + if pcmt in cstates: + cstates[pcmt] = cstates[pcmt] | flags + else: + cstates[pcmt] = flags + wlst.append(pcmt) + + # walk final candidates removing any superceded by _DNC by later lower LCAs + results = [] + for cmt in cands: + if not (cstates[cmt] & _DNC): + results.append(cmt) + return results + + +def find_merge_base(object_store, commit_ids): + """Find lowest common ancestors of commit_ids[0] and *any* of commits_ids[1:] + + Args: + object_store: object store + commit_ids: list of commit ids + Returns: + list of lowest common ancestor commit_ids + """ + def lookup_parents(commit_id): + return object_store[commit_id].parents + + if not commit_ids: + return [] + c1 = commit_ids[0] + if not len(commit_ids) > 1: + return [c1] + c2s = commit_ids[1:] + if c1 in c2s: + return [c1] + return _find_lcas(lookup_parents, c1, c2s) + + +def find_octopus_base(object_store, commit_ids): + """Find lowest common ancestors of *all* provided commit_ids + + Args: + object_store: Object store + commit_ids: list of commit ids + Returns: + list of lowest common ancestor commit_ids + """ + + def lookup_parents(commit_id): + return object_store[commit_id].parents + + if not commit_ids: + return [] + if len(commit_ids) <= 2: + return find_merge_base(object_store, commit_ids) + lcas = [commit_ids[0]] + others = commit_ids[1:] + for cmt in others: + next_lcas = [] + for ca in lcas: + res = _find_lcas(lookup_parents, cmt, [ca]) + next_lcas.extend(res) + lcas = next_lcas[:] + return lcas + + +def can_fast_forward(object_store, c1, c2): + """Is it possible to fast-forward from c1 to c2? + + Args: + object_store: Store to retrieve objects from + c1: Commit id for first commit + c2: Commit id for second commit + """ + if c1 == c2: + return True + + def lookup_parents(commit_id): + return object_store[commit_id].parents + + # Algorithm: Find the common ancestor + lcas = _find_lcas(lookup_parents, c1, [c2]) + return lcas == [c1] diff --git a/dulwich/hooks.py b/dulwich/hooks.py index ae89c4c6..fef044dc 100644 --- a/dulwich/hooks.py +++ b/dulwich/hooks.py @@ -1,196 +1,196 @@ # hooks.py -- for dealing with git hooks # Copyright (C) 2012-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. # """Access to hooks.""" import os import subprocess -import tempfile from dulwich.errors import ( HookError, ) class Hook(object): """Generic hook object.""" def execute(self, *args): """Execute the hook with the given args Args: args: argument list to hook Raises: HookError: hook execution failure Returns: a hook may return a useful value """ raise NotImplementedError(self.execute) class ShellHook(Hook): """Hook by executable file Implements standard githooks(5) [0]: [0] http://www.kernel.org/pub/software/scm/git/docs/githooks.html """ def __init__(self, name, path, numparam, pre_exec_callback=None, post_exec_callback=None, cwd=None): """Setup shell hook definition Args: name: name of hook for error messages path: absolute path to executable file numparam: number of requirements parameters pre_exec_callback: closure for setup before execution Defaults to None. Takes in the variable argument list from the execute functions and returns a modified argument list for the shell hook. post_exec_callback: closure for cleanup after execution Defaults to None. Takes in a boolean for hook success and the modified argument list and returns the final hook return value if applicable cwd: working directory to switch to when executing the hook """ self.name = name self.filepath = path self.numparam = numparam self.pre_exec_callback = pre_exec_callback self.post_exec_callback = post_exec_callback self.cwd = cwd def execute(self, *args): """Execute the hook with given args""" if len(args) != self.numparam: raise HookError("Hook %s executed with wrong number of args. \ Expected %d. Saw %d. args: %s" % (self.name, self.numparam, len(args), args)) if (self.pre_exec_callback is not None): args = self.pre_exec_callback(*args) try: ret = subprocess.call([self.filepath] + list(args), cwd=self.cwd) if ret != 0: if (self.post_exec_callback is not None): self.post_exec_callback(0, *args) raise HookError("Hook %s exited with non-zero status %d" % (self.name, ret)) if (self.post_exec_callback is not None): return self.post_exec_callback(1, *args) except OSError: # no file. silent failure. if (self.post_exec_callback is not None): self.post_exec_callback(0, *args) class PreCommitShellHook(ShellHook): """pre-commit shell hook""" def __init__(self, controldir): filepath = os.path.join(controldir, 'hooks', 'pre-commit') ShellHook.__init__(self, 'pre-commit', filepath, 0, cwd=controldir) class PostCommitShellHook(ShellHook): """post-commit shell hook""" def __init__(self, controldir): filepath = os.path.join(controldir, 'hooks', 'post-commit') ShellHook.__init__(self, 'post-commit', filepath, 0, cwd=controldir) class CommitMsgShellHook(ShellHook): """commit-msg shell hook Args: args[0]: commit message Returns: new commit message or None """ def __init__(self, controldir): filepath = os.path.join(controldir, 'hooks', 'commit-msg') def prepare_msg(*args): + import tempfile (fd, path) = tempfile.mkstemp() with os.fdopen(fd, 'wb') as f: f.write(args[0]) return (path,) def clean_msg(success, *args): if success: with open(args[0], 'rb') as f: new_msg = f.read() os.unlink(args[0]) return new_msg os.unlink(args[0]) ShellHook.__init__(self, 'commit-msg', filepath, 1, prepare_msg, clean_msg, controldir) class PostReceiveShellHook(ShellHook): """post-receive shell hook""" def __init__(self, controldir): self.controldir = controldir filepath = os.path.join(controldir, 'hooks', 'post-receive') ShellHook.__init__(self, 'post-receive', filepath, 0) def execute(self, client_refs): # do nothing if the script doesn't exist if not os.path.exists(self.filepath): return None try: env = os.environ.copy() env['GIT_DIR'] = self.controldir p = subprocess.Popen( self.filepath, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env ) # client_refs is a list of (oldsha, newsha, ref) in_data = '\n'.join([' '.join(ref) for ref in client_refs]) out_data, err_data = p.communicate(in_data) if (p.returncode != 0) or err_data: err_fmt = "post-receive exit code: %d\n" \ + "stdout:\n%s\nstderr:\n%s" err_msg = err_fmt % (p.returncode, out_data, err_data) raise HookError(err_msg) return out_data except OSError as err: raise HookError(repr(err)) diff --git a/dulwich/index.py b/dulwich/index.py index c7273db9..5e3780d1 100644 --- a/dulwich/index.py +++ b/dulwich/index.py @@ -1,833 +1,844 @@ # 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 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 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, 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, tree_encoding='utf-8'): """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 FileNotFoundError: oldstat = None 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': # os.readlink on Python3 on Windows requires a unicode string. 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 = os.fsencode(root_path) 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, tree_encoding='utf-8'): +def blob_from_path_and_mode(fs_path, mode, tree_encoding='utf-8'): """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 stat.S_ISLNK(st.st_mode): + if stat.S_ISLNK(mode): if sys.platform == 'win32': # os.readlink on Python3 on Windows requires a unicode string. fs_path = os.fsdecode(fs_path) blob.data = os.readlink(fs_path).encode(tree_encoding) else: blob.data = os.readlink(fs_path) else: with open(fs_path, 'rb') as f: blob.data = f.read() return blob +def blob_from_path_and_stat(fs_path, st, tree_encoding='utf-8'): + """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 + """ + return blob_from_path_and_mode(fs_path, st.st_mode, tree_encoding) + + 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 = os.fsdecode(path) 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 = os.fsencode(root_path) 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 if not stat.S_ISREG(st.st_mode) and not stat.S_ISLNK(st.st_mode): 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 FileNotFoundError: # The file was removed, so we assume that counts as # different from whatever file used to exist. yield tree_path 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): """Convert a file system path to a git tree path. Args: fs_path: File system path. Returns: Git tree path as bytes """ if not isinstance(fs_path, bytes): fs_path_bytes = os.fsencode(fs_path) 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 if stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode): 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) return None 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 (FileNotFoundError, IsADirectoryError): entry = None 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 5908b934..32878bb1 100644 --- a/dulwich/object_store.py +++ b/dulwich/object_store.py @@ -1,1418 +1,1419 @@ # 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 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, valid_hexsha, ) 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, compression_level=self.pack_compression_level) except BaseException: abort() raise else: return commit() def tree_changes(self, source, target, want_unchanged=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, 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, shallow=None, 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. shallow: Set of shallow commit SHA1s to skip 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, shallow, 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, shallow=None, 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 shallow: Set of shallow commit SHA1s to skip progress: Optional progress reporting method """ missing = self.find_missing_objects(have, want, shallow, progress) return self.iter_shas(missing) def generate_pack_data(self, have, want, shallow=None, 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 shallow: Set of shallow commit SHA1s to skip 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, shallow, 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(), shallow=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) if e in shallow: continue 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, pack_compression_level=-1): self._pack_cache = {} self.pack_compression_level = pack_compression_level @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, loose_compression_level=-1, pack_compression_level=-1): """Open an object store. Args: path: Path of the object store. loose_compression_level: zlib compression level for loose objects pack_compression_level: zlib compression level for pack objects """ super(DiskObjectStore, self).__init__( pack_compression_level=pack_compression_level) self.path = path self.pack_dir = os.path.join(self.path, PACKDIR) self._alternates = None self.loose_compression_level = loose_compression_level self.pack_compression_level = pack_compression_level def __repr__(self): return "<%s(%r)>" % (self.__class__.__name__, self.path) @classmethod def from_config(cls, path, config): try: default_compression_level = int(config.get( (b'core', ), b'compression').decode()) except KeyError: default_compression_level = -1 try: loose_compression_level = int(config.get( (b'core', ), b'looseCompression').decode()) except KeyError: loose_compression_level = default_compression_level try: pack_compression_level = int(config.get( (b'core', ), 'packCompression').decode()) except KeyError: pack_compression_level = default_compression_level return cls(path, loose_compression_level, pack_compression_level) @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 FileNotFoundError: return with f: for line in f.readlines(): line = line.rstrip(b"\n") if line[0] == b"#": continue if os.path.isabs(line): yield os.fsdecode(line) else: yield os.fsdecode(os.path.join(self.path, line)) def add_alternate_path(self, path): """Add an alternate path to this object store. """ try: os.mkdir(os.path.join(self.path, INFODIR)) except FileExistsError: pass alternates_path = os.path.join(self.path, INFODIR, "alternates") with GitFile(alternates_path, 'wb') as f: try: orig_f = open(alternates_path, 'rb') except FileNotFoundError: pass else: with orig_f: f.write(orig_f.read()) f.write(os.fsencode(path) + 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 FileNotFoundError: self.close() return [] 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)): sha = os.fsencode(base+rest) if not valid_hexsha(sha): continue yield sha def _get_loose_object(self, sha): path = self._get_shafile_path(sha) try: return ShaFile.from_path(path) except FileNotFoundError: return None 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, compression_level=self.pack_compression_level) 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 FileNotFoundError: pass 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. """ + import tempfile 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 FileNotFoundError: pass 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. """ + import tempfile 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 FileExistsError: pass 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( compression_level=self.loose_compression_level)) @classmethod def init(cls, path): try: os.mkdir(path) except FileExistsError: pass 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 = {} self.pack_compression_level = -1 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, shallow=None, progress=None, get_tagged=None, get_parents=lambda commit: commit.parents): self.object_store = object_store if shallow is None: shallow = set() 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, shallow=shallow, 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, shallow=shallow, 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 os.fsdecode(name) diff --git a/dulwich/objectspec.py b/dulwich/objectspec.py index f588d313..6446765a 100644 --- a/dulwich/objectspec.py +++ b/dulwich/objectspec.py @@ -1,234 +1,235 @@ # objectspec.py -- Object specification # Copyright (C) 2014 Jelmer Vernooij # # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Object specification.""" def to_bytes(text): if getattr(text, "encode", None) is not None: text = text.encode('ascii') return text def parse_object(repo, objectish): """Parse a string referring to an object. Args: repo: A `Repo` object objectish: A string referring to an object Returns: A git object Raises: KeyError: If the object can not be found """ objectish = to_bytes(objectish) return repo[objectish] def parse_tree(repo, treeish): """Parse a string referring to a tree. Args: repo: A `Repo` object treeish: A string referring to a tree Returns: A git object Raises: KeyError: If the object can not be found """ treeish = to_bytes(treeish) o = repo[treeish] if o.type_name == b"commit": return repo[o.tree] return o def parse_ref(container, refspec): """Parse a string referring to a reference. Args: container: A RefsContainer object refspec: A string referring to a ref Returns: A ref Raises: KeyError: If the ref can not be found """ refspec = to_bytes(refspec) possible_refs = [ refspec, b"refs/" + refspec, b"refs/tags/" + refspec, b"refs/heads/" + refspec, b"refs/remotes/" + refspec, b"refs/remotes/" + refspec + b"/HEAD" ] for ref in possible_refs: if ref in container: return ref raise KeyError(refspec) -def parse_reftuple(lh_container, rh_container, refspec): +def parse_reftuple(lh_container, rh_container, refspec, force=False): """Parse a reftuple spec. Args: lh_container: A RefsContainer object hh_container: A RefsContainer object refspec: A string Returns: A tuple with left and right ref Raises: KeyError: If one of the refs can not be found """ refspec = to_bytes(refspec) if refspec.startswith(b"+"): force = True refspec = refspec[1:] - else: - force = False if b":" in refspec: (lh, rh) = refspec.split(b":") else: lh = rh = refspec if lh == b"": lh = None else: lh = parse_ref(lh_container, lh) if rh == b"": rh = None else: try: rh = parse_ref(rh_container, rh) except KeyError: # TODO: check force? if b"/" not in rh: rh = b"refs/heads/" + rh return (lh, rh, force) -def parse_reftuples(lh_container, rh_container, refspecs): +def parse_reftuples( + lh_container, rh_container, refspecs, force=False): """Parse a list of reftuple specs to a list of reftuples. Args: lh_container: A RefsContainer object hh_container: A RefsContainer object refspecs: A list of refspecs or a string + force: Force overwriting for all reftuples Returns: A list of refs Raises: KeyError: If one of the refs can not be found """ if not isinstance(refspecs, list): refspecs = [refspecs] ret = [] # TODO: Support * in refspecs for refspec in refspecs: - ret.append(parse_reftuple(lh_container, rh_container, refspec)) + ret.append(parse_reftuple( + lh_container, rh_container, refspec, force=force)) return ret def parse_refs(container, refspecs): """Parse a list of refspecs to a list of refs. Args: container: A RefsContainer object refspecs: A list of refspecs or a string Returns: A list of refs Raises: KeyError: If one of the refs can not be found """ # TODO: Support * in refspecs if not isinstance(refspecs, list): refspecs = [refspecs] ret = [] for refspec in refspecs: ret.append(parse_ref(container, refspec)) return ret def parse_commit_range(repo, committishs): """Parse a string referring to a range of commits. Args: repo: A `Repo` object committishs: A string referring to a range of commits. Returns: An iterator over `Commit` objects Raises: KeyError: When the reference commits can not be found ValueError: If the range can not be parsed """ committishs = to_bytes(committishs) # TODO(jelmer): Support more than a single commit.. return iter([parse_commit(repo, committishs)]) class AmbiguousShortId(Exception): """The short id is ambiguous.""" def __init__(self, prefix, options): self.prefix = prefix self.options = options def scan_for_short_id(object_store, prefix): """Scan an object store for a short id.""" # TODO(jelmer): This could short-circuit looking for objects # starting with a certain prefix. ret = [] for object_id in object_store: if object_id.startswith(prefix): ret.append(object_store[object_id]) if not ret: raise KeyError(prefix) if len(ret) == 1: return ret[0] raise AmbiguousShortId(prefix, ret) def parse_commit(repo, committish): """Parse a string referring to a single commit. Args: repo: A` Repo` object commitish: A string referring to a single commit. Returns: A Commit object Raises: KeyError: When the reference commits can not be found ValueError: If the range can not be parsed """ committish = to_bytes(committish) try: return repo[committish] except KeyError: pass try: return repo[parse_ref(repo, committish)] except KeyError: pass if len(committish) >= 4 and len(committish) < 40: try: int(committish, 16) except ValueError: pass else: try: return scan_for_short_id(repo.object_store, committish) except KeyError: pass raise KeyError(committish) # TODO: parse_path_in_tree(), which handles e.g. v1.0:Documentation diff --git a/dulwich/porcelain.py b/dulwich/porcelain.py index 6d225f9a..ad6bcc37 100644 --- a/dulwich/porcelain.py +++ b/dulwich/porcelain.py @@ -1,1657 +1,1710 @@ # 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 from pathlib import Path import posixpath import shutil import stat import sys import time from typing import ( Dict, Optional, Tuple, Union, ) 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.graph import ( + can_fast_forward, ) 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, RefsContainer, ) 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 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): +class Error(Exception): + """Porcelain-based error. """ + + def __init__(self, msg, inner=None): + super(Error, self).__init__(msg) + self.inner = inner + + +class RemoteExists(Error): """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, tree_encoding=DEFAULT_ENCODING): """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 """ path = Path(path).resolve() repopath = Path(repopath).resolve() relpath = path.relative_to(repopath) if sys.platform == 'win32': return str(relpath).replace(os.path.sep, '/').encode(tree_encoding) else: return bytes(relpath) +class DivergedBranches(Error): + """Branches have diverged and fast-forward is not possible.""" + + +def check_diverged(store, current_sha, new_sha): + """Check if updating to a sha can be done with fast forwarding. + + Args: + store: Object store + current_sha: Current head sha + new_sha: New head sha + """ + try: + can = can_fast_forward(store, current_sha, new_sha) + except KeyError: + can = False + if not can: + raise DivergedBranches(current_sha, new_sha) + + 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) + raise Error('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") + raise Error("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: 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() fetch_result = fetch( r, origin, errstream=errstream, message=reflog_message, depth=depth, **kwargs) # TODO(jelmer): Support symref capability, # https://github.com/jelmer/dulwich/issues/485 try: head = r[fetch_result.refs[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: repo_path = Path(r.path).resolve() ignore_manager = IgnoreFilterManager.from_repo(r) if not paths: paths = list( get_untracked_paths( str(Path(os.getcwd()).resolve()), str(repo_path), r.open_index())) relpaths = [] if not isinstance(paths, list): paths = [paths] for p in paths: relpath = str(Path(p).resolve().relative_to(repo_path)) # 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") + raise Error("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.fsencode(os.path.abspath(p)) 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) + raise Error('%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( + raise Error( 'file has staged content differing ' 'from both the file and head: %s' % p) if index_sha != committed_sha: - raise Exception( + raise Error( '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: 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(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( [line+'\n' for line 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) + raise Error("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") + raise Error("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 get_remote_repo( repo: Repo, remote_location: Optional[Union[str, bytes]] = None ) -> Tuple[Optional[str], str]: config = repo.get_config() if remote_location is None: remote_location = get_branch_remote(repo) if isinstance(remote_location, str): encoded_location = remote_location.encode() else: encoded_location = remote_location section = (b'remote', encoded_location) remote_name = None # type: Optional[str] if config.has_section(section): remote_name = encoded_location.decode() url = config.get(section, 'url') encoded_location = url else: remote_name = None config = None return (remote_name, encoded_location.decode()) def push(repo, remote_location=None, refspecs=None, outstream=default_bytes_out_stream, - errstream=default_bytes_err_stream, **kwargs): + errstream=default_bytes_err_stream, + force=False, **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 + force: Force overwriting refs """ # Open the repo with open_repo_closing(repo) as r: (remote_name, remote_location) = get_remote_repo(r, remote_location) # Get the client and path client, path = get_transport_and_path( remote_location, config=r.get_config_stack(), **kwargs) selected_refs = [] remote_changed_refs = {} def update_refs(refs): - selected_refs.extend(parse_reftuples(r.refs, refs, refspecs)) + selected_refs.extend(parse_reftuples( + r.refs, refs, refspecs, force=force)) new_refs = {} # TODO: Handle selected_refs == {None: None} - for (lh, rh, force) in selected_refs: + for (lh, rh, force_ref) in selected_refs: if lh is None: new_refs[rh] = ZERO_SHA remote_changed_refs[rh] = None else: + if not force_ref: + check_diverged(r.object_store, refs[rh], r.refs[lh]) new_refs[rh] = r.refs[lh] remote_changed_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( + result = client.send_pack( path, update_refs, generate_pack_data=r.generate_pack_data, progress=errstream.write) errstream.write( b"Push to " + remote_location_bytes + b" successful.\n") - except UpdateRefsError as e: - errstream.write(b"Push to " + remote_location_bytes + - b" failed -> " + e.message.encode(err_encoding) + - b"\n") except SendPackError as e: - errstream.write(b"Push to " + remote_location_bytes + - b" failed -> " + e.args[0] + b"\n") + raise Error( + "Push to " + remote_location_bytes + + " failed -> " + e.args[0].decode(), inner=e) + + for ref, error in (result.ref_status or {}).items(): + if status is not None: + errstream.write( + b"Push of ref %s failed: %s" % + (ref, error.encode(err_encoding))) + else: + errstream.write(b'Ref %s updated' % ref) if remote_name is not None: _import_remote_refs(r.refs, remote_name, remote_changed_refs) def pull(repo, remote_location=None, refspecs=None, outstream=default_bytes_out_stream, - errstream=default_bytes_err_stream, **kwargs): + errstream=default_bytes_err_stream, fast_forward=True, + force=False, **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: (remote_name, remote_location) = get_remote_repo(r, remote_location) 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] + parse_reftuples(remote_refs, r.refs, refspecs, force=force)) + return [ + remote_refs[lh] for (lh, rh, force_ref) in selected_refs + if remote_refs[lh] not in r.object_store] 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: + for (lh, rh, force_ref) in selected_refs: + try: + check_diverged( + r.object_store, r.refs[rh], fetch_result.refs[lh]) + except DivergedBranches: + if fast_forward: + raise + else: + raise NotImplementedError('merge is not yet supported') 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) if remote_name is not None: _import_remote_refs(r.refs, remote_name, fetch_result.refs) 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') + raise NotImplementedError('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) + raise Error( + "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 get_branch_remote(repo): """Return the active branch's remote name, if any. Args: repo: Repository to open Returns: remote name Raises: KeyError: if the repository does not have a working tree """ with open_repo_closing(repo) as r: branch_name = active_branch(r.path) config = r.get_config() try: remote_name = config.get((b'branch', branch_name), b'remote') except KeyError: remote_name = b'origin' return remote_name def _import_remote_refs( refs_container: RefsContainer, remote_name: str, refs: Dict[str, str], message: Optional[bytes] = None, prune: bool = False, prune_tags: bool = False): stripped_refs = strip_peeled_refs(refs) branches = { n[len(LOCAL_BRANCH_PREFIX):]: v for (n, v) in stripped_refs.items() if n.startswith(LOCAL_BRANCH_PREFIX)} refs_container.import_refs( b'refs/remotes/' + remote_name.encode(), 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)} refs_container.import_refs( b'refs/tags', tags, message=message, prune=prune_tags) def fetch(repo, remote_location=None, outstream=sys.stdout, errstream=default_bytes_err_stream, - message=None, depth=None, prune=False, prune_tags=False, **kwargs): + message=None, depth=None, prune=False, prune_tags=False, force=False, + **kwargs): """Fetch objects from a remote server. Args: repo: Path to the repository remote_location: String identifying a 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 """ with open_repo_closing(repo) as r: (remote_name, remote_location) = get_remote_repo(r, remote_location) if message is None: message = b'fetch: from ' + remote_location.encode("utf-8") 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) if remote_name is not None: _import_remote_refs( r.refs, remote_name, fetch_result.refs, message, prune=prune, prune_tags=prune_tags) return fetch_result 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 try: mailmap = Mailmap.from_path(os.path.join(r.path, '.mailmap')) except FileNotFoundError: 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 = 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/server.py b/dulwich/server.py index 7a4e1859..10e2bf36 100644 --- a/dulwich/server.py +++ b/dulwich/server.py @@ -1,1219 +1,1226 @@ # server.py -- Implementation of the server side git protocols # Copyright (C) 2008 John Carr # Coprygith (C) 2011-2012 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. # """Git smart network protocol server implementation. For more detailed implementation on the network protocol, see the Documentation/technical directory in the cgit distribution, and in particular: * Documentation/technical/protocol-capabilities.txt * Documentation/technical/pack-protocol.txt Currently supported capabilities: * include-tag * thin-pack * multi_ack_detailed * multi_ack * side-band-64k * ofs-delta * no-progress * report-status * delete-refs * shallow * symref """ import collections import os import socket import sys import time from typing import List, Tuple, Dict, Optional, Iterable import zlib import socketserver from dulwich.archive import tar_stream from dulwich.errors import ( ApplyDeltaError, ChecksumMismatch, GitProtocolError, HookError, NotGitRepository, UnexpectedCommandError, ObjectFormatException, ) from dulwich import log_utils from dulwich.objects import ( Commit, valid_hexsha, ) from dulwich.pack import ( write_pack_objects, ) from dulwich.protocol import ( # noqa: F401 BufferedPktLineWriter, capability_agent, CAPABILITIES_REF, CAPABILITY_AGENT, CAPABILITY_DELETE_REFS, CAPABILITY_INCLUDE_TAG, CAPABILITY_MULTI_ACK_DETAILED, CAPABILITY_MULTI_ACK, CAPABILITY_NO_DONE, CAPABILITY_NO_PROGRESS, CAPABILITY_OFS_DELTA, CAPABILITY_QUIET, CAPABILITY_REPORT_STATUS, CAPABILITY_SHALLOW, CAPABILITY_SIDE_BAND_64K, CAPABILITY_THIN_PACK, COMMAND_DEEPEN, COMMAND_DONE, COMMAND_HAVE, COMMAND_SHALLOW, COMMAND_UNSHALLOW, COMMAND_WANT, MULTI_ACK, MULTI_ACK_DETAILED, Protocol, ProtocolFile, ReceivableProtocol, SIDE_BAND_CHANNEL_DATA, SIDE_BAND_CHANNEL_PROGRESS, SIDE_BAND_CHANNEL_FATAL, SINGLE_ACK, TCP_GIT_PORT, ZERO_SHA, ack_type, extract_capabilities, extract_want_line_capabilities, symref_capabilities, ) from dulwich.refs import ( ANNOTATED_TAG_SUFFIX, write_info_refs, ) from dulwich.repo import ( BaseRepo, Repo, ) logger = log_utils.getLogger(__name__) class Backend(object): """A backend for the Git smart server implementation.""" def open_repository(self, path): """Open the repository at a path. Args: path: Path to the repository Raises: NotGitRepository: no git repository was found at path Returns: Instance of BackendRepo """ raise NotImplementedError(self.open_repository) class BackendRepo(object): """Repository abstraction used by the Git server. The methods required here are a subset of those provided by dulwich.repo.Repo. """ object_store = None refs = None def get_refs(self) -> Dict[bytes, bytes]: """ Get all the refs in the repository Returns: dict of name -> sha """ raise NotImplementedError def get_peeled(self, name: bytes) -> Optional[bytes]: """Return the cached peeled value of a ref, if available. Args: name: Name of the ref to peel Returns: The peeled value of the ref. If the ref is known not point to a tag, this will be the SHA the ref refers to. If no cached information about a tag is available, this method may return None, but it should attempt to peel the tag if possible. """ return None def fetch_objects(self, determine_wants, graph_walker, progress, get_tagged=None): """ Yield the objects required for a list of commits. Args: progress: is a callback to send progress messages to the client get_tagged: Function that returns a dict of pointed-to sha -> tag sha for including tags. """ raise NotImplementedError class DictBackend(Backend): """Trivial backend that looks up Git repositories in a dictionary.""" def __init__(self, repos): self.repos = repos def open_repository(self, path: str) -> BaseRepo: logger.debug('Opening repository at %s', path) try: return self.repos[path] except KeyError: raise NotGitRepository( "No git repository was found at %(path)s" % dict(path=path) ) class FileSystemBackend(Backend): """Simple backend looking up Git repositories in the local file system.""" def __init__(self, root=os.sep): super(FileSystemBackend, self).__init__() self.root = (os.path.abspath(root) + os.sep).replace( os.sep * 2, os.sep) def open_repository(self, path): logger.debug('opening repository at %s', path) abspath = os.path.abspath(os.path.join(self.root, path)) + os.sep normcase_abspath = os.path.normcase(abspath) normcase_root = os.path.normcase(self.root) if not normcase_abspath.startswith(normcase_root): raise NotGitRepository( "Path %r not inside root %r" % (path, self.root)) return Repo(abspath) class Handler(object): """Smart protocol command handler base class.""" - def __init__(self, backend, proto, http_req=None): + def __init__(self, backend, proto, stateless_rpc=None): self.backend = backend self.proto = proto - self.http_req = http_req + self.stateless_rpc = stateless_rpc def handle(self): raise NotImplementedError(self.handle) class PackHandler(Handler): """Protocol handler for packs.""" - def __init__(self, backend, proto, http_req=None): - super(PackHandler, self).__init__(backend, proto, http_req) + def __init__(self, backend, proto, stateless_rpc=None): + super(PackHandler, self).__init__(backend, proto, stateless_rpc) self._client_capabilities = None # Flags needed for the no-done capability self._done_received = False @classmethod def capability_line(cls, capabilities): logger.info('Sending capabilities: %s', capabilities) return b"".join([b" " + c for c in capabilities]) @classmethod def capabilities(cls) -> Iterable[bytes]: raise NotImplementedError(cls.capabilities) @classmethod def innocuous_capabilities(cls) -> Iterable[bytes]: return [CAPABILITY_INCLUDE_TAG, CAPABILITY_THIN_PACK, CAPABILITY_NO_PROGRESS, CAPABILITY_OFS_DELTA, capability_agent()] @classmethod def required_capabilities(cls) -> Iterable[bytes]: """Return a list of capabilities that we require the client to have.""" return [] def set_client_capabilities(self, caps: Iterable[bytes]) -> None: allowable_caps = set(self.innocuous_capabilities()) allowable_caps.update(self.capabilities()) for cap in caps: if cap.startswith(CAPABILITY_AGENT + b'='): continue if cap not in allowable_caps: raise GitProtocolError('Client asked for capability %r that ' 'was not advertised.' % cap) for cap in self.required_capabilities(): if cap not in caps: raise GitProtocolError('Client does not support required ' 'capability %r.' % cap) self._client_capabilities = set(caps) logger.info('Client capabilities: %s', caps) def has_capability(self, cap: bytes) -> bool: if self._client_capabilities is None: raise GitProtocolError('Server attempted to access capability %r ' 'before asking client' % cap) return cap in self._client_capabilities def notify_done(self) -> None: self._done_received = True class UploadPackHandler(PackHandler): """Protocol handler for uploading a pack to the client.""" - def __init__(self, backend, args, proto, http_req=None, + def __init__(self, backend, args, proto, stateless_rpc=None, advertise_refs=False): super(UploadPackHandler, self).__init__( - backend, proto, http_req=http_req) + backend, proto, stateless_rpc=stateless_rpc) self.repo = backend.open_repository(args[0]) self._graph_walker = None self.advertise_refs = advertise_refs # A state variable for denoting that the have list is still # being processed, and the client is not accepting any other # data (such as side-band, see the progress method here). self._processing_have_lines = False @classmethod def capabilities(cls): return [CAPABILITY_MULTI_ACK_DETAILED, CAPABILITY_MULTI_ACK, CAPABILITY_SIDE_BAND_64K, CAPABILITY_THIN_PACK, CAPABILITY_OFS_DELTA, CAPABILITY_NO_PROGRESS, CAPABILITY_INCLUDE_TAG, CAPABILITY_SHALLOW, CAPABILITY_NO_DONE] @classmethod def required_capabilities(cls): return (CAPABILITY_SIDE_BAND_64K, CAPABILITY_THIN_PACK, CAPABILITY_OFS_DELTA) def progress(self, message): if (self.has_capability(CAPABILITY_NO_PROGRESS) or self._processing_have_lines): return self.proto.write_sideband(SIDE_BAND_CHANNEL_PROGRESS, message) def get_tagged(self, refs=None, repo=None): """Get a dict of peeled values of tags to their original tag shas. Args: refs: dict of refname -> sha of possible tags; defaults to all of the backend's refs. repo: optional Repo instance for getting peeled refs; defaults to the backend's repo, if available Returns: dict of peeled_sha -> tag_sha, where tag_sha is the sha of a tag whose peeled value is peeled_sha. """ if not self.has_capability(CAPABILITY_INCLUDE_TAG): return {} if refs is None: refs = self.repo.get_refs() if repo is None: repo = getattr(self.repo, "repo", None) if repo is None: # Bail if we don't have a Repo available; this is ok since # clients must be able to handle if the server doesn't include # all relevant tags. # TODO: fix behavior when missing return {} # TODO(jelmer): Integrate this with the refs logic in # Repo.fetch_objects tagged = {} for name, sha in refs.items(): peeled_sha = repo.get_peeled(name) if peeled_sha != sha: tagged[peeled_sha] = sha return tagged def handle(self): def write(x): return self.proto.write_sideband(SIDE_BAND_CHANNEL_DATA, x) graph_walker = _ProtocolGraphWalker( self, self.repo.object_store, self.repo.get_peeled, self.repo.refs.get_symrefs) + wants = [] + + def wants_wrapper(refs): + wants.extend(graph_walker.determine_wants(refs)) + return wants + objects_iter = self.repo.fetch_objects( - graph_walker.determine_wants, graph_walker, self.progress, + wants_wrapper, graph_walker, self.progress, get_tagged=self.get_tagged) # Note the fact that client is only processing responses related # to the have lines it sent, and any other data (including side- # band) will be be considered a fatal error. self._processing_have_lines = True # Did the process short-circuit (e.g. in a stateless RPC call)? Note # that the client still expects a 0-object pack in most cases. # Also, if it also happens that the object_iter is instantiated # with a graph walker with an implementation that talks over the # wire (which is this instance of this class) this will actually # iterate through everything and write things out to the wire. - if len(objects_iter) == 0: + if len(wants) == 0: return # The provided haves are processed, and it is safe to send side- # band data now. self._processing_have_lines = False if not graph_walker.handle_done( not self.has_capability(CAPABILITY_NO_DONE), self._done_received): return self.progress( ("counting objects: %d, done.\n" % len(objects_iter)).encode( 'ascii')) write_pack_objects(ProtocolFile(None, write), objects_iter) # we are done self.proto.write_pkt_line(None) def _split_proto_line(line, allowed): """Split a line read from the wire. Args: line: The line read from the wire. allowed: An iterable of command names that should be allowed. Command names not listed below as possible return values will be ignored. If None, any commands from the possible return values are allowed. Returns: a tuple having one of the following forms: ('want', obj_id) ('have', obj_id) ('done', None) (None, None) (for a flush-pkt) Raises: UnexpectedCommandError: if the line cannot be parsed into one of the allowed return values. """ if not line: fields = [None] else: fields = line.rstrip(b'\n').split(b' ', 1) command = fields[0] if allowed is not None and command not in allowed: raise UnexpectedCommandError(command) if len(fields) == 1 and command in (COMMAND_DONE, None): return (command, None) elif len(fields) == 2: if command in (COMMAND_WANT, COMMAND_HAVE, COMMAND_SHALLOW, COMMAND_UNSHALLOW): if not valid_hexsha(fields[1]): raise GitProtocolError("Invalid sha") return tuple(fields) elif command == COMMAND_DEEPEN: return command, int(fields[1]) raise GitProtocolError('Received invalid line from client: %r' % line) def _find_shallow(store, heads, depth): """Find shallow commits according to a given depth. Args: store: An ObjectStore for looking up objects. heads: Iterable of head SHAs to start walking from. depth: The depth of ancestors to include. A depth of one includes only the heads themselves. Returns: A tuple of (shallow, not_shallow), sets of SHAs that should be considered shallow and unshallow according to the arguments. Note that these sets may overlap if a commit is reachable along multiple paths. """ parents = {} def get_parents(sha): result = parents.get(sha, None) if not result: result = store[sha].parents parents[sha] = result return result todo = [] # stack of (sha, depth) for head_sha in heads: obj = store.peel_sha(head_sha) if isinstance(obj, Commit): todo.append((obj.id, 1)) not_shallow = set() shallow = set() while todo: sha, cur_depth = todo.pop() if cur_depth < depth: not_shallow.add(sha) new_depth = cur_depth + 1 todo.extend((p, new_depth) for p in get_parents(sha)) else: shallow.add(sha) return shallow, not_shallow def _want_satisfied(store, haves, want, earliest): o = store[want] pending = collections.deque([o]) known = set([want]) while pending: commit = pending.popleft() if commit.id in haves: return True if commit.type_name != b"commit": # non-commit wants are assumed to be satisfied continue for parent in commit.parents: if parent in known: continue known.add(parent) parent_obj = store[parent] # TODO: handle parents with later commit times than children if parent_obj.commit_time >= earliest: pending.append(parent_obj) return False def _all_wants_satisfied(store, haves, wants): """Check whether all the current wants are satisfied by a set of haves. Args: store: Object store to retrieve objects from haves: A set of commits we know the client has. wants: A set of commits the client wants Note: Wants are specified with set_wants rather than passed in since in the current interface they are determined outside this class. """ haves = set(haves) if haves: earliest = min([store[h].commit_time for h in haves]) else: earliest = 0 for want in wants: if not _want_satisfied(store, haves, want, earliest): return False return True class _ProtocolGraphWalker(object): """A graph walker that knows the git protocol. As a graph walker, this class implements ack(), next(), and reset(). It also contains some base methods for interacting with the wire and walking the commit tree. The work of determining which acks to send is passed on to the implementation instance stored in _impl. The reason for this is that we do not know at object creation time what ack level the protocol requires. A call to set_ack_type() is required to set up the implementation, before any calls to next() or ack() are made. """ def __init__(self, handler, object_store, get_peeled, get_symrefs): self.handler = handler self.store = object_store self.get_peeled = get_peeled self.get_symrefs = get_symrefs self.proto = handler.proto - self.http_req = handler.http_req + self.stateless_rpc = handler.stateless_rpc self.advertise_refs = handler.advertise_refs self._wants = [] self.shallow = set() self.client_shallow = set() self.unshallow = set() self._cached = False self._cache = [] self._cache_index = 0 self._impl = None def determine_wants(self, heads): """Determine the wants for a set of heads. The given heads are advertised to the client, who then specifies which - refs he wants using 'want' lines. This portion of the protocol is the + refs they want using 'want' lines. This portion of the protocol is the same regardless of ack type, and in fact is used to set the ack type of the ProtocolGraphWalker. If the client has the 'shallow' capability, this method also reads and responds to the 'shallow' and 'deepen' lines from the client. These are not part of the wants per se, but they set up necessary state for walking the graph. Additionally, later code depends on this method consuming everything up to the first 'have' line. Args: heads: a dict of refname->SHA1 to advertise Returns: a list of SHA1s requested by the client """ symrefs = self.get_symrefs() values = set(heads.values()) - if self.advertise_refs or not self.http_req: + if self.advertise_refs or not self.stateless_rpc: for i, (ref, sha) in enumerate(sorted(heads.items())): try: peeled_sha = self.get_peeled(ref) except KeyError: # Skip refs that are inaccessible # TODO(jelmer): Integrate with Repo.fetch_objects refs # logic. continue line = sha + b' ' + ref if not i: line += (b'\x00' + self.handler.capability_line( self.handler.capabilities() + symref_capabilities(symrefs.items()))) self.proto.write_pkt_line(line + b'\n') if peeled_sha != sha: self.proto.write_pkt_line( peeled_sha + b' ' + ref + ANNOTATED_TAG_SUFFIX + b'\n') # i'm done.. self.proto.write_pkt_line(None) if self.advertise_refs: return [] # Now client will sending want want want commands want = self.proto.read_pkt_line() if not want: return [] line, caps = extract_want_line_capabilities(want) self.handler.set_client_capabilities(caps) self.set_ack_type(ack_type(caps)) allowed = (COMMAND_WANT, COMMAND_SHALLOW, COMMAND_DEEPEN, None) command, sha = _split_proto_line(line, allowed) want_revs = [] while command == COMMAND_WANT: if sha not in values: raise GitProtocolError( 'Client wants invalid object %s' % sha) want_revs.append(sha) command, sha = self.read_proto_line(allowed) self.set_wants(want_revs) if command in (COMMAND_SHALLOW, COMMAND_DEEPEN): self.unread_proto_line(command, sha) self._handle_shallow_request(want_revs) - if self.http_req and self.proto.eof(): + if self.stateless_rpc and self.proto.eof(): # The client may close the socket at this point, expecting a # flush-pkt from the server. We might be ready to send a packfile # at this point, so we need to explicitly short-circuit in this # case. return [] return want_revs def unread_proto_line(self, command, value): if isinstance(value, int): value = str(value).encode('ascii') self.proto.unread_pkt_line(command + b' ' + value) def ack(self, have_ref): if len(have_ref) != 40: raise ValueError("invalid sha %r" % have_ref) return self._impl.ack(have_ref) def reset(self): self._cached = True self._cache_index = 0 def next(self): if not self._cached: - if not self._impl and self.http_req: + if not self._impl and self.stateless_rpc: return None return next(self._impl) self._cache_index += 1 if self._cache_index > len(self._cache): return None return self._cache[self._cache_index] __next__ = next def read_proto_line(self, allowed): """Read a line from the wire. Args: allowed: An iterable of command names that should be allowed. Returns: A tuple of (command, value); see _split_proto_line. Raises: UnexpectedCommandError: If an error occurred reading the line. """ return _split_proto_line(self.proto.read_pkt_line(), allowed) def _handle_shallow_request(self, wants): while True: command, val = self.read_proto_line( (COMMAND_DEEPEN, COMMAND_SHALLOW)) if command == COMMAND_DEEPEN: depth = val break self.client_shallow.add(val) self.read_proto_line((None,)) # consume client's flush-pkt shallow, not_shallow = _find_shallow(self.store, wants, depth) # Update self.shallow instead of reassigning it since we passed a # reference to it before this method was called. self.shallow.update(shallow - not_shallow) new_shallow = self.shallow - self.client_shallow unshallow = self.unshallow = not_shallow & self.client_shallow for sha in sorted(new_shallow): self.proto.write_pkt_line(COMMAND_SHALLOW + b' ' + sha) for sha in sorted(unshallow): self.proto.write_pkt_line(COMMAND_UNSHALLOW + b' ' + sha) self.proto.write_pkt_line(None) def notify_done(self): # relay the message down to the handler. self.handler.notify_done() def send_ack(self, sha, ack_type=b''): if ack_type: ack_type = b' ' + ack_type self.proto.write_pkt_line(b'ACK ' + sha + ack_type + b'\n') def send_nak(self): self.proto.write_pkt_line(b'NAK\n') def handle_done(self, done_required, done_received): # Delegate this to the implementation. return self._impl.handle_done(done_required, done_received) def set_wants(self, wants): self._wants = wants def all_wants_satisfied(self, haves): """Check whether all the current wants are satisfied by a set of haves. Args: haves: A set of commits we know the client has. Note: Wants are specified with set_wants rather than passed in since in the current interface they are determined outside this class. """ return _all_wants_satisfied(self.store, haves, self._wants) def set_ack_type(self, ack_type): impl_classes = { MULTI_ACK: MultiAckGraphWalkerImpl, MULTI_ACK_DETAILED: MultiAckDetailedGraphWalkerImpl, SINGLE_ACK: SingleAckGraphWalkerImpl, } self._impl = impl_classes[ack_type](self) _GRAPH_WALKER_COMMANDS = (COMMAND_HAVE, COMMAND_DONE, None) class SingleAckGraphWalkerImpl(object): """Graph walker implementation that speaks the single-ack protocol.""" def __init__(self, walker): self.walker = walker self._common = [] def ack(self, have_ref): if not self._common: self.walker.send_ack(have_ref) self._common.append(have_ref) def next(self): command, sha = self.walker.read_proto_line(_GRAPH_WALKER_COMMANDS) if command in (None, COMMAND_DONE): # defer the handling of done self.walker.notify_done() return None elif command == COMMAND_HAVE: return sha __next__ = next def handle_done(self, done_required, done_received): if not self._common: self.walker.send_nak() if done_required and not done_received: # we are not done, especially when done is required; skip # the pack for this request and especially do not handle # the done. return False if not done_received and not self._common: # Okay we are not actually done then since the walker picked # up no haves. This is usually triggered when client attempts # to pull from a source that has no common base_commit. # See: test_server.MultiAckDetailedGraphWalkerImplTestCase.\ # test_multi_ack_stateless_nodone return False return True class MultiAckGraphWalkerImpl(object): """Graph walker implementation that speaks the multi-ack protocol.""" def __init__(self, walker): self.walker = walker self._found_base = False self._common = [] def ack(self, have_ref): self._common.append(have_ref) if not self._found_base: self.walker.send_ack(have_ref, b'continue') if self.walker.all_wants_satisfied(self._common): self._found_base = True # else we blind ack within next def next(self): while True: command, sha = self.walker.read_proto_line(_GRAPH_WALKER_COMMANDS) if command is None: self.walker.send_nak() # in multi-ack mode, a flush-pkt indicates the client wants to # flush but more have lines are still coming continue elif command == COMMAND_DONE: self.walker.notify_done() return None elif command == COMMAND_HAVE: if self._found_base: # blind ack self.walker.send_ack(sha, b'continue') return sha __next__ = next def handle_done(self, done_required, done_received): if done_required and not done_received: # we are not done, especially when done is required; skip # the pack for this request and especially do not handle # the done. return False if not done_received and not self._common: # Okay we are not actually done then since the walker picked # up no haves. This is usually triggered when client attempts # to pull from a source that has no common base_commit. # See: test_server.MultiAckDetailedGraphWalkerImplTestCase.\ # test_multi_ack_stateless_nodone return False # don't nak unless no common commits were found, even if not # everything is satisfied if self._common: self.walker.send_ack(self._common[-1]) else: self.walker.send_nak() return True class MultiAckDetailedGraphWalkerImpl(object): """Graph walker implementation speaking the multi-ack-detailed protocol.""" def __init__(self, walker): self.walker = walker self._common = [] def ack(self, have_ref): # Should only be called iff have_ref is common self._common.append(have_ref) self.walker.send_ack(have_ref, b'common') def next(self): while True: command, sha = self.walker.read_proto_line(_GRAPH_WALKER_COMMANDS) if command is None: if self.walker.all_wants_satisfied(self._common): self.walker.send_ack(self._common[-1], b'ready') self.walker.send_nak() - if self.walker.http_req: + if self.walker.stateless_rpc: # The HTTP version of this request a flush-pkt always # signifies an end of request, so we also return # nothing here as if we are done (but not really, as # it depends on whether no-done capability was # specified and that's handled in handle_done which # may or may not call post_nodone_check depending on # that). return None elif command == COMMAND_DONE: # Let the walker know that we got a done. self.walker.notify_done() break elif command == COMMAND_HAVE: # return the sha and let the caller ACK it with the # above ack method. return sha # don't nak unless no common commits were found, even if not # everything is satisfied __next__ = next def handle_done(self, done_required, done_received): if done_required and not done_received: # we are not done, especially when done is required; skip # the pack for this request and especially do not handle # the done. return False if not done_received and not self._common: # Okay we are not actually done then since the walker picked # up no haves. This is usually triggered when client attempts # to pull from a source that has no common base_commit. # See: test_server.MultiAckDetailedGraphWalkerImplTestCase.\ # test_multi_ack_stateless_nodone return False # don't nak unless no common commits were found, even if not # everything is satisfied if self._common: self.walker.send_ack(self._common[-1]) else: self.walker.send_nak() return True class ReceivePackHandler(PackHandler): """Protocol handler for downloading a pack from the client.""" - def __init__(self, backend, args, proto, http_req=None, + def __init__(self, backend, args, proto, stateless_rpc=None, advertise_refs=False): super(ReceivePackHandler, self).__init__( - backend, proto, http_req=http_req) + backend, proto, stateless_rpc=stateless_rpc) self.repo = backend.open_repository(args[0]) self.advertise_refs = advertise_refs @classmethod def capabilities(cls) -> Iterable[bytes]: return [CAPABILITY_REPORT_STATUS, CAPABILITY_DELETE_REFS, CAPABILITY_QUIET, CAPABILITY_OFS_DELTA, CAPABILITY_SIDE_BAND_64K, CAPABILITY_NO_DONE] def _apply_pack( self, refs: List[Tuple[bytes, bytes, bytes]] ) -> List[Tuple[bytes, bytes]]: all_exceptions = (IOError, OSError, ChecksumMismatch, ApplyDeltaError, AssertionError, socket.error, zlib.error, ObjectFormatException) status = [] will_send_pack = False for command in refs: if command[1] != ZERO_SHA: will_send_pack = True if will_send_pack: # TODO: more informative error messages than just the exception # string try: recv = getattr(self.proto, "recv", None) self.repo.object_store.add_thin_pack(self.proto.read, recv) status.append((b'unpack', b'ok')) except all_exceptions as e: status.append( (b'unpack', str(e).replace('\n', '').encode('utf-8'))) # The pack may still have been moved in, but it may contain # broken objects. We trust a later GC to clean it up. else: # The git protocol want to find a status entry related to unpack # process even if no pack data has been sent. status.append((b'unpack', b'ok')) for oldsha, sha, ref in refs: ref_status = b'ok' try: if sha == ZERO_SHA: if CAPABILITY_DELETE_REFS not in self.capabilities(): raise GitProtocolError( 'Attempted to delete refs without delete-refs ' 'capability.') try: self.repo.refs.remove_if_equals(ref, oldsha) except all_exceptions: ref_status = b'failed to delete' else: try: self.repo.refs.set_if_equals(ref, oldsha, sha) except all_exceptions: ref_status = b'failed to write' except KeyError: ref_status = b'bad ref' status.append((ref, ref_status)) return status def _report_status(self, status: List[Tuple[bytes, bytes]]) -> None: if self.has_capability(CAPABILITY_SIDE_BAND_64K): writer = BufferedPktLineWriter( lambda d: self.proto.write_sideband(SIDE_BAND_CHANNEL_DATA, d)) write = writer.write def flush(): writer.flush() self.proto.write_pkt_line(None) else: write = self.proto.write_pkt_line def flush(): pass for name, msg in status: if name == b'unpack': write(b'unpack ' + msg + b'\n') elif msg == b'ok': write(b'ok ' + name + b'\n') else: write(b'ng ' + name + b' ' + msg + b'\n') write(None) flush() def _on_post_receive(self, client_refs): hook = self.repo.hooks.get('post-receive', None) if not hook: return try: output = hook.execute(client_refs) if output: self.proto.write_sideband(SIDE_BAND_CHANNEL_PROGRESS, output) except HookError as err: self.proto.write_sideband(SIDE_BAND_CHANNEL_FATAL, repr(err)) def handle(self) -> None: - if self.advertise_refs or not self.http_req: + if self.advertise_refs or not self.stateless_rpc: refs = sorted(self.repo.get_refs().items()) symrefs = sorted(self.repo.refs.get_symrefs().items()) if not refs: refs = [(CAPABILITIES_REF, ZERO_SHA)] self.proto.write_pkt_line( refs[0][1] + b' ' + refs[0][0] + b'\0' + self.capability_line( self.capabilities() + symref_capabilities(symrefs)) + b'\n') for i in range(1, len(refs)): ref = refs[i] self.proto.write_pkt_line(ref[1] + b' ' + ref[0] + b'\n') self.proto.write_pkt_line(None) if self.advertise_refs: return client_refs = [] ref = self.proto.read_pkt_line() # if ref is none then client doesnt want to send us anything.. if ref is None: return ref, caps = extract_capabilities(ref) self.set_client_capabilities(caps) # client will now send us a list of (oldsha, newsha, ref) while ref: client_refs.append(ref.split()) ref = self.proto.read_pkt_line() # backend can now deal with this refs and read a pack using self.read status = self._apply_pack(client_refs) self._on_post_receive(client_refs) # when we have read all the pack from the client, send a status report # if the client asked for it if self.has_capability(CAPABILITY_REPORT_STATUS): self._report_status(status) class UploadArchiveHandler(Handler): - def __init__(self, backend, args, proto, http_req=None): - super(UploadArchiveHandler, self).__init__(backend, proto, http_req) + def __init__(self, backend, args, proto, stateless_rpc=None): + super(UploadArchiveHandler, self).__init__( + backend, proto, stateless_rpc) self.repo = backend.open_repository(args[0]) def handle(self): def write(x): return self.proto.write_sideband(SIDE_BAND_CHANNEL_DATA, x) arguments = [] for pkt in self.proto.read_pkt_seq(): (key, value) = pkt.split(b' ', 1) if key != b'argument': raise GitProtocolError('unknown command %s' % key) arguments.append(value.rstrip(b'\n')) prefix = b'' format = 'tar' i = 0 store = self.repo.object_store while i < len(arguments): argument = arguments[i] if argument == b'--prefix': i += 1 prefix = arguments[i] elif argument == b'--format': i += 1 format = arguments[i].decode('ascii') else: commit_sha = self.repo.refs[argument] tree = store[store[commit_sha].tree] i += 1 self.proto.write_pkt_line(b'ACK\n') self.proto.write_pkt_line(None) for chunk in tar_stream( store, tree, mtime=time.time(), prefix=prefix, format=format): write(chunk) self.proto.write_pkt_line(None) # Default handler classes for git services. DEFAULT_HANDLERS = { b'git-upload-pack': UploadPackHandler, b'git-receive-pack': ReceivePackHandler, b'git-upload-archive': UploadArchiveHandler, } class TCPGitRequestHandler(socketserver.StreamRequestHandler): def __init__(self, handlers, *args, **kwargs): self.handlers = handlers socketserver.StreamRequestHandler.__init__(self, *args, **kwargs) def handle(self): proto = ReceivableProtocol(self.connection.recv, self.wfile.write) command, args = proto.read_cmd() logger.info('Handling %s request, args=%s', command, args) cls = self.handlers.get(command, None) if not callable(cls): raise GitProtocolError('Invalid service %s' % command) h = cls(self.server.backend, args, proto) h.handle() class TCPGitServer(socketserver.TCPServer): allow_reuse_address = True serve = socketserver.TCPServer.serve_forever def _make_handler(self, *args, **kwargs): return TCPGitRequestHandler(self.handlers, *args, **kwargs) def __init__(self, backend, listen_addr, port=TCP_GIT_PORT, handlers=None): self.handlers = dict(DEFAULT_HANDLERS) if handlers is not None: self.handlers.update(handlers) self.backend = backend logger.info('Listening for TCP connections on %s:%d', listen_addr, port) socketserver.TCPServer.__init__(self, (listen_addr, port), self._make_handler) def verify_request(self, request, client_address): logger.info('Handling request from %s', client_address) return True def handle_error(self, request, client_address): logger.exception('Exception happened during processing of request ' 'from %s', client_address) def main(argv=sys.argv): """Entry point for starting a TCP git server.""" import optparse parser = optparse.OptionParser() parser.add_option("-l", "--listen_address", dest="listen_address", default="localhost", help="Binding IP address.") parser.add_option("-p", "--port", dest="port", type=int, default=TCP_GIT_PORT, help="Binding TCP port.") options, args = parser.parse_args(argv) log_utils.default_logging_config() if len(args) > 1: gitdir = args[1] else: gitdir = '.' # TODO(jelmer): Support git-daemon-export-ok and --export-all. backend = FileSystemBackend(gitdir) server = TCPGitServer(backend, options.listen_address, options.port) server.serve_forever() def serve_command(handler_cls, argv=sys.argv, backend=None, inf=sys.stdin, outf=sys.stdout): """Serve a single command. This is mostly useful for the implementation of commands used by e.g. git+ssh. Args: handler_cls: `Handler` class to use for the request argv: execv-style command-line arguments. Defaults to sys.argv. backend: `Backend` to use inf: File-like object to read from, defaults to standard input. outf: File-like object to write to, defaults to standard output. Returns: Exit code for use with sys.exit. 0 on success, 1 on failure. """ if backend is None: backend = FileSystemBackend() def send_fn(data): outf.write(data) outf.flush() proto = Protocol(inf.read, send_fn) handler = handler_cls(backend, argv[1:], proto) # FIXME: Catch exceptions and write a single-line summary to outf. handler.handle() return 0 def generate_info_refs(repo): """Generate an info refs file.""" refs = repo.get_refs() return write_info_refs(refs, repo.object_store) def generate_objects_info_packs(repo): """Generate an index for for packs.""" for pack in repo.object_store.packs: yield ( b'P ' + os.fsencode(pack.data.filename) + b'\n') def update_server_info(repo): """Generate server info for dumb file access. This generates info/refs and objects/info/packs, similar to "git update-server-info". """ repo._put_named_file( os.path.join('info', 'refs'), b"".join(generate_info_refs(repo))) repo._put_named_file( os.path.join('objects', 'info', 'packs'), b"".join(generate_objects_info_packs(repo))) if __name__ == '__main__': main() diff --git a/dulwich/tests/__init__.py b/dulwich/tests/__init__.py index f46cff60..f7a98c8a 100644 --- a/dulwich/tests/__init__.py +++ b/dulwich/tests/__init__.py @@ -1,198 +1,199 @@ # __init__.py -- The tests for dulwich # Copyright (C) 2007 James Westby # # 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.""" import doctest import os import shutil import subprocess import sys import tempfile # If Python itself provides an exception, use that import unittest from unittest import ( # noqa: F401 SkipTest, TestCase as _TestCase, skipIf, expectedFailure, ) class TestCase(_TestCase): def setUp(self): super(TestCase, self).setUp() self._old_home = os.environ.get("HOME") os.environ["HOME"] = "/nonexistant" def tearDown(self): super(TestCase, self).tearDown() if self._old_home: os.environ["HOME"] = self._old_home else: del os.environ["HOME"] class BlackboxTestCase(TestCase): """Blackbox testing.""" # TODO(jelmer): Include more possible binary paths. bin_directories = [os.path.abspath(os.path.join( os.path.dirname(__file__), "..", "..", "bin")), '/usr/bin', '/usr/local/bin'] def bin_path(self, name): """Determine the full path of a binary. Args: name: Name of the script Returns: Full path """ for d in self.bin_directories: p = os.path.join(d, name) if os.path.isfile(p): return p else: raise SkipTest("Unable to find binary %s" % name) def run_command(self, name, args): """Run a Dulwich command. Args: name: Name of the command, as it exists in bin/ args: Arguments to the command """ env = dict(os.environ) env["PYTHONPATH"] = os.pathsep.join(sys.path) # Since they don't have any extensions, Windows can't recognize # executablility of the Python files in /bin. Even then, we'd have to # expect the user to set up file associations for .py files. # # Save us from all that headache and call python with the bin script. argv = [sys.executable, self.bin_path(name)] + args return subprocess.Popen( argv, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE, env=env) def self_test_suite(): names = [ 'archive', 'blackbox', 'client', 'config', 'diff_tree', 'fastexport', 'file', 'grafts', + 'graph', 'greenthreads', 'hooks', 'ignore', 'index', 'lfs', 'line_ending', 'lru_cache', 'mailmap', 'objects', 'objectspec', 'object_store', 'missing_obj_finder', 'pack', 'patch', 'porcelain', 'protocol', 'reflog', 'refs', 'repository', 'server', 'stash', 'utils', 'walk', 'web', ] module_names = ['dulwich.tests.test_' + name for name in names] loader = unittest.TestLoader() return loader.loadTestsFromNames(module_names) def tutorial_test_suite(): import dulwich.client # noqa: F401 import dulwich.config # noqa: F401 import dulwich.index # noqa: F401 import dulwich.reflog # noqa: F401 import dulwich.repo # noqa: F401 import dulwich.server # noqa: F401 import dulwich.patch # noqa: F401 tutorial = [ 'introduction', 'file-format', 'repo', 'object-store', 'remote', 'conclusion', ] tutorial_files = ["../../docs/tutorial/%s.txt" % name for name in tutorial] def setup(test): test.__old_cwd = os.getcwd() test.tempdir = tempfile.mkdtemp() test.globs.update({'tempdir': test.tempdir}) os.chdir(test.tempdir) def teardown(test): os.chdir(test.__old_cwd) shutil.rmtree(test.tempdir) return doctest.DocFileSuite( module_relative=True, package='dulwich.tests', setUp=setup, tearDown=teardown, *tutorial_files) def nocompat_test_suite(): result = unittest.TestSuite() result.addTests(self_test_suite()) result.addTests(tutorial_test_suite()) from dulwich.contrib import test_suite as contrib_test_suite result.addTests(contrib_test_suite()) return result def compat_test_suite(): result = unittest.TestSuite() from dulwich.tests.compat import test_suite as compat_test_suite result.addTests(compat_test_suite()) return result def test_suite(): result = unittest.TestSuite() result.addTests(self_test_suite()) if sys.platform != 'win32': result.addTests(tutorial_test_suite()) from dulwich.tests.compat import test_suite as compat_test_suite result.addTests(compat_test_suite()) from dulwich.contrib import test_suite as contrib_test_suite result.addTests(contrib_test_suite()) return result diff --git a/dulwich/tests/compat/test_client.py b/dulwich/tests/compat/test_client.py index fd62764a..a17baa03 100644 --- a/dulwich/tests/compat/test_client.py +++ b/dulwich/tests/compat/test_client.py @@ -1,613 +1,617 @@ # test_client.py -- Compatibilty tests for git client. # 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. # """Compatibilty tests between the Dulwich client and the cgit server.""" import copy from io import BytesIO import os import select import signal import stat import subprocess import sys import tarfile import tempfile import threading from urllib.parse import unquote import http.server from dulwich import ( client, - errors, file, index, protocol, objects, repo, ) from dulwich.tests import ( SkipTest, expectedFailure, ) from dulwich.tests.compat.utils import ( CompatTestCase, check_for_daemon, import_repo_to_dir, rmtree_ro, run_git_or_fail, _DEFAULT_GIT, ) if sys.platform == 'win32': import ctypes class DulwichClientTestBase(object): """Tests for client/server compatibility.""" def setUp(self): self.gitroot = os.path.dirname( import_repo_to_dir('server_new.export').rstrip(os.sep)) self.dest = os.path.join(self.gitroot, 'dest') file.ensure_dir_exists(self.dest) run_git_or_fail(['init', '--quiet', '--bare'], cwd=self.dest) def tearDown(self): rmtree_ro(self.gitroot) def assertDestEqualsSrc(self): repo_dir = os.path.join(self.gitroot, 'server_new.export') dest_repo_dir = os.path.join(self.gitroot, 'dest') with repo.Repo(repo_dir) as src: with repo.Repo(dest_repo_dir) as dest: self.assertReposEqual(src, dest) def _client(self): raise NotImplementedError() def _build_path(self): raise NotImplementedError() def _do_send_pack(self): c = self._client() srcpath = os.path.join(self.gitroot, 'server_new.export') with repo.Repo(srcpath) as src: sendrefs = dict(src.get_refs()) del sendrefs[b'HEAD'] c.send_pack(self._build_path('/dest'), lambda _: sendrefs, src.generate_pack_data) def test_send_pack(self): self._do_send_pack() self.assertDestEqualsSrc() def test_send_pack_nothing_to_send(self): self._do_send_pack() self.assertDestEqualsSrc() # nothing to send, but shouldn't raise either. self._do_send_pack() @staticmethod def _add_file(repo, tree_id, filename, contents): tree = repo[tree_id] blob = objects.Blob() blob.data = contents.encode('utf-8') repo.object_store.add_object(blob) tree.add(filename.encode('utf-8'), stat.S_IFREG | 0o644, blob.id) repo.object_store.add_object(tree) return tree.id def test_send_pack_from_shallow_clone(self): c = self._client() server_new_path = os.path.join(self.gitroot, 'server_new.export') run_git_or_fail(['config', 'http.uploadpack', 'true'], cwd=server_new_path) run_git_or_fail(['config', 'http.receivepack', 'true'], cwd=server_new_path) remote_path = self._build_path('/server_new.export') with repo.Repo(self.dest) as local: result = c.fetch(remote_path, local, depth=1) for r in result.refs.items(): local.refs.set_if_equals(r[0], None, r[1]) tree_id = local[local.head()].tree for filename, contents in [('bar', 'bar contents'), ('zop', 'zop contents')]: tree_id = self._add_file(local, tree_id, filename, contents) commit_id = local.do_commit( message=b"add " + filename.encode('utf-8'), committer=b"Joe Example ", tree=tree_id) sendrefs = dict(local.get_refs()) del sendrefs[b'HEAD'] c.send_pack(remote_path, lambda _: sendrefs, local.generate_pack_data) with repo.Repo(server_new_path) as remote: self.assertEqual(remote.head(), commit_id) def test_send_without_report_status(self): c = self._client() c._send_capabilities.remove(b'report-status') srcpath = os.path.join(self.gitroot, 'server_new.export') with repo.Repo(srcpath) as src: sendrefs = dict(src.get_refs()) del sendrefs[b'HEAD'] c.send_pack(self._build_path('/dest'), lambda _: sendrefs, src.generate_pack_data) self.assertDestEqualsSrc() def make_dummy_commit(self, dest): b = objects.Blob.from_string(b'hi') dest.object_store.add_object(b) t = index.commit_tree(dest.object_store, [(b'hi', b.id, 0o100644)]) c = objects.Commit() c.author = c.committer = b'Foo Bar ' c.author_time = c.commit_time = 0 c.author_timezone = c.commit_timezone = 0 c.message = b'hi' c.tree = t dest.object_store.add_object(c) return c.id def disable_ff_and_make_dummy_commit(self): # disable non-fast-forward pushes to the server dest = repo.Repo(os.path.join(self.gitroot, 'dest')) run_git_or_fail(['config', 'receive.denyNonFastForwards', 'true'], cwd=dest.path) commit_id = self.make_dummy_commit(dest) return dest, commit_id def compute_send(self, src): sendrefs = dict(src.get_refs()) del sendrefs[b'HEAD'] return sendrefs, src.generate_pack_data def test_send_pack_one_error(self): dest, dummy_commit = self.disable_ff_and_make_dummy_commit() dest.refs[b'refs/heads/master'] = dummy_commit repo_dir = os.path.join(self.gitroot, 'server_new.export') with repo.Repo(repo_dir) as src: sendrefs, gen_pack = self.compute_send(src) c = self._client() - try: - c.send_pack(self._build_path('/dest'), lambda _: sendrefs, - gen_pack) - except errors.UpdateRefsError as e: - self.assertEqual('refs/heads/master failed to update', - e.args[0]) - self.assertEqual({b'refs/heads/branch': b'ok', - b'refs/heads/master': b'non-fast-forward'}, - e.ref_status) + result = c.send_pack( + self._build_path('/dest'), lambda _: sendrefs, gen_pack) + self.assertEqual({b'refs/heads/branch': None, + b'refs/heads/master': 'non-fast-forward'}, + result.ref_status) def test_send_pack_multiple_errors(self): dest, dummy = self.disable_ff_and_make_dummy_commit() # set up for two non-ff errors branch, master = b'refs/heads/branch', b'refs/heads/master' dest.refs[branch] = dest.refs[master] = dummy repo_dir = os.path.join(self.gitroot, 'server_new.export') with repo.Repo(repo_dir) as src: sendrefs, gen_pack = self.compute_send(src) c = self._client() - try: - c.send_pack(self._build_path('/dest'), lambda _: sendrefs, - gen_pack) - except errors.UpdateRefsError as e: - self.assertIn( - str(e), - ['{0}, {1} failed to update'.format( - branch.decode('ascii'), master.decode('ascii')), - '{1}, {0} failed to update'.format( - branch.decode('ascii'), master.decode('ascii'))]) - self.assertEqual({branch: b'non-fast-forward', - master: b'non-fast-forward'}, - e.ref_status) + result = c.send_pack( + self._build_path('/dest'), lambda _: sendrefs, gen_pack) + self.assertEqual({branch: 'non-fast-forward', + master: 'non-fast-forward'}, + result.ref_status) def test_archive(self): c = self._client() f = BytesIO() c.archive(self._build_path('/server_new.export'), b'HEAD', f.write) f.seek(0) tf = tarfile.open(fileobj=f) self.assertEqual(['baz', 'foo'], tf.getnames()) def test_fetch_pack(self): c = self._client() with repo.Repo(os.path.join(self.gitroot, 'dest')) as dest: result = c.fetch(self._build_path('/server_new.export'), dest) for r in result.refs.items(): dest.refs.set_if_equals(r[0], None, r[1]) self.assertDestEqualsSrc() def test_fetch_pack_depth(self): c = self._client() with repo.Repo(os.path.join(self.gitroot, 'dest')) as dest: result = c.fetch(self._build_path('/server_new.export'), dest, depth=1) for r in result.refs.items(): dest.refs.set_if_equals(r[0], None, r[1]) self.assertEqual( dest.get_shallow(), set([b'35e0b59e187dd72a0af294aedffc213eaa4d03ff', b'514dc6d3fbfe77361bcaef320c4d21b72bc10be9'])) def test_repeat(self): c = self._client() with repo.Repo(os.path.join(self.gitroot, 'dest')) as dest: result = c.fetch(self._build_path('/server_new.export'), dest) for r in result.refs.items(): dest.refs.set_if_equals(r[0], None, r[1]) self.assertDestEqualsSrc() result = c.fetch(self._build_path('/server_new.export'), dest) for r in result.refs.items(): dest.refs.set_if_equals(r[0], None, r[1]) self.assertDestEqualsSrc() + def test_fetch_empty_pack(self): + c = self._client() + with repo.Repo(os.path.join(self.gitroot, 'dest')) as dest: + result = c.fetch(self._build_path('/server_new.export'), dest) + for r in result.refs.items(): + dest.refs.set_if_equals(r[0], None, r[1]) + self.assertDestEqualsSrc() + + def dw(refs): + return list(refs.values()) + result = c.fetch( + self._build_path('/server_new.export'), dest, + determine_wants=dw) + for r in result.refs.items(): + dest.refs.set_if_equals(r[0], None, r[1]) + self.assertDestEqualsSrc() + def test_incremental_fetch_pack(self): self.test_fetch_pack() dest, dummy = self.disable_ff_and_make_dummy_commit() dest.refs[b'refs/heads/master'] = dummy c = self._client() repo_dir = os.path.join(self.gitroot, 'server_new.export') with repo.Repo(repo_dir) as dest: result = c.fetch(self._build_path('/dest'), dest) for r in result.refs.items(): dest.refs.set_if_equals(r[0], None, r[1]) self.assertDestEqualsSrc() def test_fetch_pack_no_side_band_64k(self): c = self._client() c._fetch_capabilities.remove(b'side-band-64k') with repo.Repo(os.path.join(self.gitroot, 'dest')) as dest: result = c.fetch(self._build_path('/server_new.export'), dest) for r in result.refs.items(): dest.refs.set_if_equals(r[0], None, r[1]) self.assertDestEqualsSrc() def test_fetch_pack_zero_sha(self): # zero sha1s are already present on the client, and should # be ignored c = self._client() with repo.Repo(os.path.join(self.gitroot, 'dest')) as dest: result = c.fetch( self._build_path('/server_new.export'), dest, lambda refs: [protocol.ZERO_SHA]) for r in result.refs.items(): dest.refs.set_if_equals(r[0], None, r[1]) def test_send_remove_branch(self): with repo.Repo(os.path.join(self.gitroot, 'dest')) as dest: dummy_commit = self.make_dummy_commit(dest) dest.refs[b'refs/heads/master'] = dummy_commit dest.refs[b'refs/heads/abranch'] = dummy_commit sendrefs = dict(dest.refs) sendrefs[b'refs/heads/abranch'] = b"00" * 20 del sendrefs[b'HEAD'] def gen_pack(have, want, ofs_delta=False): return 0, [] c = self._client() self.assertEqual(dest.refs[b"refs/heads/abranch"], dummy_commit) c.send_pack( self._build_path('/dest'), lambda _: sendrefs, gen_pack) self.assertFalse(b"refs/heads/abranch" in dest.refs) def test_send_new_branch_empty_pack(self): with repo.Repo(os.path.join(self.gitroot, 'dest')) as dest: dummy_commit = self.make_dummy_commit(dest) dest.refs[b'refs/heads/master'] = dummy_commit dest.refs[b'refs/heads/abranch'] = dummy_commit sendrefs = {b'refs/heads/bbranch': dummy_commit} def gen_pack(have, want, ofs_delta=False): return 0, [] c = self._client() self.assertEqual(dest.refs[b"refs/heads/abranch"], dummy_commit) c.send_pack( self._build_path('/dest'), lambda _: sendrefs, gen_pack) self.assertEqual(dummy_commit, dest.refs[b"refs/heads/abranch"]) def test_get_refs(self): c = self._client() refs = c.get_refs(self._build_path('/server_new.export')) repo_dir = os.path.join(self.gitroot, 'server_new.export') with repo.Repo(repo_dir) as dest: self.assertDictEqual(dest.refs.as_dict(), refs) class DulwichTCPClientTest(CompatTestCase, DulwichClientTestBase): def setUp(self): CompatTestCase.setUp(self) DulwichClientTestBase.setUp(self) if check_for_daemon(limit=1): raise SkipTest('git-daemon was already running on port %s' % protocol.TCP_GIT_PORT) fd, self.pidfile = tempfile.mkstemp(prefix='dulwich-test-git-client', suffix=".pid") os.fdopen(fd).close() args = [_DEFAULT_GIT, 'daemon', '--verbose', '--export-all', '--pid-file=%s' % self.pidfile, '--base-path=%s' % self.gitroot, '--enable=receive-pack', '--enable=upload-archive', '--listen=localhost', '--reuseaddr', self.gitroot] self.process = subprocess.Popen( args, cwd=self.gitroot, stdout=subprocess.PIPE, stderr=subprocess.PIPE) if not check_for_daemon(): raise SkipTest('git-daemon failed to start') def tearDown(self): with open(self.pidfile) as f: pid = int(f.read().strip()) if sys.platform == 'win32': PROCESS_TERMINATE = 1 handle = ctypes.windll.kernel32.OpenProcess( PROCESS_TERMINATE, False, pid) ctypes.windll.kernel32.TerminateProcess(handle, -1) ctypes.windll.kernel32.CloseHandle(handle) else: try: os.kill(pid, signal.SIGKILL) os.unlink(self.pidfile) except (OSError, IOError): pass self.process.wait() self.process.stdout.close() self.process.stderr.close() DulwichClientTestBase.tearDown(self) CompatTestCase.tearDown(self) def _client(self): return client.TCPGitClient('localhost') def _build_path(self, path): return path if sys.platform == 'win32': @expectedFailure def test_fetch_pack_no_side_band_64k(self): DulwichClientTestBase.test_fetch_pack_no_side_band_64k(self) class TestSSHVendor(object): @staticmethod def run_command(host, command, username=None, port=None, password=None, key_filename=None): cmd, path = command.split(' ') cmd = cmd.split('-', 1) path = path.replace("'", "") p = subprocess.Popen(cmd + [path], bufsize=0, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) return client.SubprocessWrapper(p) class DulwichMockSSHClientTest(CompatTestCase, DulwichClientTestBase): def setUp(self): CompatTestCase.setUp(self) DulwichClientTestBase.setUp(self) self.real_vendor = client.get_ssh_vendor client.get_ssh_vendor = TestSSHVendor def tearDown(self): DulwichClientTestBase.tearDown(self) CompatTestCase.tearDown(self) client.get_ssh_vendor = self.real_vendor def _client(self): return client.SSHGitClient('localhost') def _build_path(self, path): return self.gitroot + path class DulwichSubprocessClientTest(CompatTestCase, DulwichClientTestBase): def setUp(self): CompatTestCase.setUp(self) DulwichClientTestBase.setUp(self) def tearDown(self): DulwichClientTestBase.tearDown(self) CompatTestCase.tearDown(self) def _client(self): return client.SubprocessGitClient() def _build_path(self, path): return self.gitroot + path class GitHTTPRequestHandler(http.server.SimpleHTTPRequestHandler): """HTTP Request handler that calls out to 'git http-backend'.""" # Make rfile unbuffered -- we need to read one line and then pass # the rest to a subprocess, so we can't use buffered input. rbufsize = 0 def do_POST(self): self.run_backend() def do_GET(self): self.run_backend() def send_head(self): return self.run_backend() def log_request(self, code='-', size='-'): # Let's be quiet, the test suite is noisy enough already pass def run_backend(self): """Call out to git http-backend.""" # Based on CGIHTTPServer.CGIHTTPRequestHandler.run_cgi: # Copyright (c) 2001-2010 Python Software Foundation; # All Rights Reserved # Licensed under the Python Software Foundation License. rest = self.path # find an explicit query string, if present. i = rest.rfind('?') if i >= 0: rest, query = rest[:i], rest[i+1:] else: query = '' env = copy.deepcopy(os.environ) env['SERVER_SOFTWARE'] = self.version_string() env['SERVER_NAME'] = self.server.server_name env['GATEWAY_INTERFACE'] = 'CGI/1.1' env['SERVER_PROTOCOL'] = self.protocol_version env['SERVER_PORT'] = str(self.server.server_port) env['GIT_PROJECT_ROOT'] = self.server.root_path env["GIT_HTTP_EXPORT_ALL"] = "1" env['REQUEST_METHOD'] = self.command uqrest = unquote(rest) env['PATH_INFO'] = uqrest env['SCRIPT_NAME'] = "/" if query: env['QUERY_STRING'] = query host = self.address_string() if host != self.client_address[0]: env['REMOTE_HOST'] = host env['REMOTE_ADDR'] = self.client_address[0] authorization = self.headers.get("authorization") if authorization: authorization = authorization.split() if len(authorization) == 2: import base64 import binascii env['AUTH_TYPE'] = authorization[0] if authorization[0].lower() == "basic": try: authorization = base64.decodestring(authorization[1]) except binascii.Error: pass else: authorization = authorization.split(':') if len(authorization) == 2: env['REMOTE_USER'] = authorization[0] # XXX REMOTE_IDENT content_type = self.headers.get('content-type') if content_type: env['CONTENT_TYPE'] = content_type length = self.headers.get('content-length') if length: env['CONTENT_LENGTH'] = length referer = self.headers.get('referer') if referer: env['HTTP_REFERER'] = referer accept = [] for line in self.headers.getallmatchingheaders('accept'): if line[:1] in "\t\n\r ": accept.append(line.strip()) else: accept = accept + line[7:].split(',') env['HTTP_ACCEPT'] = ','.join(accept) ua = self.headers.get('user-agent') if ua: env['HTTP_USER_AGENT'] = ua co = self.headers.get('cookie') if co: env['HTTP_COOKIE'] = co # XXX Other HTTP_* headers # Since we're setting the env in the parent, provide empty # values to override previously set values for k in ('QUERY_STRING', 'REMOTE_HOST', 'CONTENT_LENGTH', 'HTTP_USER_AGENT', 'HTTP_COOKIE', 'HTTP_REFERER'): env.setdefault(k, "") self.wfile.write(b"HTTP/1.1 200 Script output follows\r\n") self.wfile.write( ("Server: %s\r\n" % self.server.server_name).encode('ascii')) self.wfile.write( ("Date: %s\r\n" % self.date_time_string()).encode('ascii')) decoded_query = query.replace('+', ' ') try: nbytes = int(length) except (TypeError, ValueError): nbytes = 0 if self.command.lower() == "post" and nbytes > 0: data = self.rfile.read(nbytes) else: data = None env['CONTENT_LENGTH'] = '0' # throw away additional data [see bug #427345] while select.select([self.rfile._sock], [], [], 0)[0]: if not self.rfile._sock.recv(1): break args = ['http-backend'] if '=' not in decoded_query: args.append(decoded_query) stdout = run_git_or_fail( args, input=data, env=env, stderr=subprocess.PIPE) self.wfile.write(stdout) class HTTPGitServer(http.server.HTTPServer): allow_reuse_address = True def __init__(self, server_address, root_path): http.server.HTTPServer.__init__( self, server_address, GitHTTPRequestHandler) self.root_path = root_path self.server_name = "localhost" def get_url(self): return 'http://%s:%s/' % (self.server_name, self.server_port) class DulwichHttpClientTest(CompatTestCase, DulwichClientTestBase): min_git_version = (1, 7, 0, 2) def setUp(self): CompatTestCase.setUp(self) DulwichClientTestBase.setUp(self) self._httpd = HTTPGitServer(("localhost", 0), self.gitroot) self.addCleanup(self._httpd.shutdown) threading.Thread(target=self._httpd.serve_forever).start() run_git_or_fail(['config', 'http.uploadpack', 'true'], cwd=self.dest) run_git_or_fail(['config', 'http.receivepack', 'true'], cwd=self.dest) def tearDown(self): DulwichClientTestBase.tearDown(self) CompatTestCase.tearDown(self) self._httpd.shutdown() self._httpd.socket.close() def _client(self): return client.HttpGitClient(self._httpd.get_url()) def _build_path(self, path): return path def test_archive(self): raise SkipTest("exporting archives not supported over http") diff --git a/dulwich/tests/compat/test_repository.py b/dulwich/tests/compat/test_repository.py index 6078c78b..807b50b9 100644 --- a/dulwich/tests/compat/test_repository.py +++ b/dulwich/tests/compat/test_repository.py @@ -1,219 +1,221 @@ # test_repo.py -- Git repo compatibility tests # 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. # """Compatibility tests for dulwich repositories.""" from io import BytesIO from itertools import chain import os import tempfile from dulwich.objects import ( hex_to_sha, ) from dulwich.repo import ( check_ref_format, Repo, ) from dulwich.tests.compat.utils import ( require_git_version, rmtree_ro, run_git_or_fail, CompatTestCase, ) class ObjectStoreTestCase(CompatTestCase): """Tests for git repository compatibility.""" def setUp(self): super(ObjectStoreTestCase, self).setUp() self._repo = self.import_repo('server_new.export') def _run_git(self, args): return run_git_or_fail(args, cwd=self._repo.path) def _parse_refs(self, output): refs = {} for line in BytesIO(output): fields = line.rstrip(b'\n').split(b' ') self.assertEqual(3, len(fields)) refname, type_name, sha = fields check_ref_format(refname[5:]) hex_to_sha(sha) refs[refname] = (type_name, sha) return refs def _parse_objects(self, output): return set(s.rstrip(b'\n').split(b' ')[0] for s in BytesIO(output)) def test_bare(self): self.assertTrue(self._repo.bare) self.assertFalse(os.path.exists(os.path.join(self._repo.path, '.git'))) def test_head(self): output = self._run_git(['rev-parse', 'HEAD']) head_sha = output.rstrip(b'\n') hex_to_sha(head_sha) self.assertEqual(head_sha, self._repo.refs[b'HEAD']) def test_refs(self): output = self._run_git( ['for-each-ref', '--format=%(refname) %(objecttype) %(objectname)']) expected_refs = self._parse_refs(output) actual_refs = {} for refname, sha in self._repo.refs.as_dict().items(): if refname == b'HEAD': continue # handled in test_head obj = self._repo[sha] self.assertEqual(sha, obj.id) actual_refs[refname] = (obj.type_name, obj.id) self.assertEqual(expected_refs, actual_refs) # TODO(dborowitz): peeled ref tests def _get_loose_shas(self): output = self._run_git( ['rev-list', '--all', '--objects', '--unpacked']) return self._parse_objects(output) def _get_all_shas(self): output = self._run_git(['rev-list', '--all', '--objects']) return self._parse_objects(output) def assertShasMatch(self, expected_shas, actual_shas_iter): actual_shas = set() for sha in actual_shas_iter: obj = self._repo[sha] self.assertEqual(sha, obj.id) actual_shas.add(sha) self.assertEqual(expected_shas, actual_shas) def test_loose_objects(self): # TODO(dborowitz): This is currently not very useful since # fast-imported repos only contained packed objects. expected_shas = self._get_loose_shas() self.assertShasMatch(expected_shas, self._repo.object_store._iter_loose_objects()) def test_packed_objects(self): expected_shas = self._get_all_shas() - self._get_loose_shas() - self.assertShasMatch(expected_shas, - chain(*self._repo.object_store.packs)) + self.assertShasMatch( + expected_shas, + chain.from_iterable(self._repo.object_store.packs) + ) def test_all_objects(self): expected_shas = self._get_all_shas() self.assertShasMatch(expected_shas, iter(self._repo.object_store)) class WorkingTreeTestCase(ObjectStoreTestCase): """Test for compatibility with git-worktree.""" min_git_version = (2, 5, 0) def create_new_worktree(self, repo_dir, branch): """Create a new worktree using git-worktree. Args: repo_dir: The directory of the main working tree. branch: The branch or commit to checkout in the new worktree. Returns: The path to the new working tree. """ temp_dir = tempfile.mkdtemp() run_git_or_fail(['worktree', 'add', temp_dir, branch], cwd=repo_dir) self.addCleanup(rmtree_ro, temp_dir) return temp_dir def setUp(self): super(WorkingTreeTestCase, self).setUp() self._worktree_path = self.create_new_worktree( self._repo.path, 'branch') self._worktree_repo = Repo(self._worktree_path) self.addCleanup(self._worktree_repo.close) self._mainworktree_repo = self._repo self._number_of_working_tree = 2 self._repo = self._worktree_repo def test_refs(self): super(WorkingTreeTestCase, self).test_refs() self.assertEqual(self._mainworktree_repo.refs.allkeys(), self._repo.refs.allkeys()) def test_head_equality(self): self.assertNotEqual(self._repo.refs[b'HEAD'], self._mainworktree_repo.refs[b'HEAD']) def test_bare(self): self.assertFalse(self._repo.bare) self.assertTrue(os.path.isfile(os.path.join(self._repo.path, '.git'))) def _parse_worktree_list(self, output): worktrees = [] for line in BytesIO(output): fields = line.rstrip(b'\n').split() worktrees.append(tuple(f.decode() for f in fields)) return worktrees def test_git_worktree_list(self): # 'git worktree list' was introduced in 2.7.0 require_git_version((2, 7, 0)) output = run_git_or_fail(['worktree', 'list'], cwd=self._repo.path) worktrees = self._parse_worktree_list(output) self.assertEqual(len(worktrees), self._number_of_working_tree) self.assertEqual(worktrees[0][1], '(bare)') self.assertTrue( os.path.samefile(worktrees[0][0], self._mainworktree_repo.path)) output = run_git_or_fail( ['worktree', 'list'], cwd=self._mainworktree_repo.path) worktrees = self._parse_worktree_list(output) self.assertEqual(len(worktrees), self._number_of_working_tree) self.assertEqual(worktrees[0][1], '(bare)') self.assertTrue(os.path.samefile( worktrees[0][0], self._mainworktree_repo.path)) class InitNewWorkingDirectoryTestCase(WorkingTreeTestCase): """Test compatibility of Repo.init_new_working_directory.""" min_git_version = (2, 5, 0) def setUp(self): super(InitNewWorkingDirectoryTestCase, self).setUp() self._other_worktree = self._repo worktree_repo_path = tempfile.mkdtemp() self.addCleanup(rmtree_ro, worktree_repo_path) self._repo = Repo._init_new_working_directory( worktree_repo_path, self._mainworktree_repo) self.addCleanup(self._repo.close) self._number_of_working_tree = 3 def test_head_equality(self): self.assertEqual(self._repo.refs[b'HEAD'], self._mainworktree_repo.refs[b'HEAD']) def test_bare(self): self.assertFalse(self._repo.bare) self.assertTrue(os.path.isfile(os.path.join(self._repo.path, '.git'))) diff --git a/dulwich/tests/compat/test_server.py b/dulwich/tests/compat/test_server.py index df06dc69..a901656e 100644 --- a/dulwich/tests/compat/test_server.py +++ b/dulwich/tests/compat/test_server.py @@ -1,100 +1,100 @@ # test_server.py -- Compatibility tests for git server. # 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. # """Compatibility tests between Dulwich and the cgit server. Warning: these tests should be fairly stable, but when writing/debugging new tests, deadlocks may freeze the test process such that it cannot be Ctrl-C'ed. On POSIX systems, you can kill the tests with Ctrl-Z, "kill %". """ import threading import os import sys from dulwich.server import ( DictBackend, TCPGitServer, ) from dulwich.tests import skipIf from dulwich.tests.compat.server_utils import ( ServerTests, NoSideBand64kReceivePackHandler, ) from dulwich.tests.compat.utils import ( CompatTestCase, require_git_version, ) @skipIf(sys.platform == 'win32', 'Broken on windows, with very long fail time.') class GitServerTestCase(ServerTests, CompatTestCase): """Tests for client/server compatibility. This server test case does not use side-band-64k in git-receive-pack. """ protocol = 'git' def _handlers(self): return {b'git-receive-pack': NoSideBand64kReceivePackHandler} def _check_server(self, dul_server): receive_pack_handler_cls = dul_server.handlers[b'git-receive-pack'] caps = receive_pack_handler_cls.capabilities() self.assertFalse(b'side-band-64k' in caps) def _start_server(self, repo): backend = DictBackend({b'/': repo}) dul_server = TCPGitServer(backend, b'localhost', 0, handlers=self._handlers()) self._check_server(dul_server) self.addCleanup(dul_server.shutdown) self.addCleanup(dul_server.server_close) threading.Thread(target=dul_server.serve).start() self._server = dul_server _, port = self._server.socket.getsockname() return port @skipIf(sys.platform == 'win32', 'Broken on windows, with very long fail time.') class GitServerSideBand64kTestCase(GitServerTestCase): """Tests for client/server compatibility with side-band-64k support.""" # side-band-64k in git-receive-pack was introduced in git 1.7.0.2 min_git_version = (1, 7, 0, 2) def setUp(self): super(GitServerSideBand64kTestCase, self).setUp() - # side-band-64k is broken in the widows client. + # side-band-64k is broken in the windows client. # https://github.com/msysgit/git/issues/101 # Fix has landed for the 1.9.3 release. if os.name == 'nt': require_git_version((1, 9, 3)) def _handlers(self): return None # default handlers include side-band-64k def _check_server(self, server): receive_pack_handler_cls = server.handlers[b'git-receive-pack'] caps = receive_pack_handler_cls.capabilities() self.assertTrue(b'side-band-64k' in caps) diff --git a/dulwich/tests/test_client.py b/dulwich/tests/test_client.py index 052e3dc2..a15ccc41 100644 --- a/dulwich/tests/test_client.py +++ b/dulwich/tests/test_client.py @@ -1,1350 +1,1359 @@ # test_client.py -- Tests for the git protocol, client side # Copyright (C) 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. # from io import BytesIO import base64 import os import sys import shutil import tempfile import warnings from urllib.parse import ( quote as urlquote, urlparse, ) import dulwich from dulwich import ( client, ) from dulwich.client import ( InvalidWants, LocalGitClient, TraditionalGitClient, TCPGitClient, SSHGitClient, HttpGitClient, FetchPackResult, ReportStatusParser, SendPackError, StrangeHostname, SubprocessSSHVendor, PLinkSSHVendor, - UpdateRefsError, check_wants, default_urllib3_manager, get_credentials_from_store, get_transport_and_path, get_transport_and_path_from_url, parse_rsync_url, ) from dulwich.config import ( ConfigDict, ) from dulwich.tests import ( TestCase, ) from dulwich.protocol import ( TCP_GIT_PORT, Protocol, ) from dulwich.pack import ( pack_objects_to_data, write_pack_data, write_pack_objects, ) from dulwich.objects import ( Commit, Tree ) from dulwich.repo import ( MemoryRepo, Repo, ) from dulwich.tests import skipIf from dulwich.tests.utils import ( open_repo, tear_down_repo, setup_warning_catcher, ) class DummyClient(TraditionalGitClient): def __init__(self, can_read, read, write): self.can_read = can_read self.read = read self.write = write TraditionalGitClient.__init__(self) def _connect(self, service, path): return Protocol(self.read, self.write), self.can_read, None class DummyPopen(): def __init__(self, *args, **kwards): self.stdin = BytesIO(b"stdin") self.stdout = BytesIO(b"stdout") self.stderr = BytesIO(b"stderr") self.returncode = 0 self.args = args self.kwargs = kwards def communicate(self, *args, **kwards): return ('Running', '') def wait(self, *args, **kwards): return False # TODO(durin42): add unit-level tests of GitClient class GitClientTests(TestCase): def setUp(self): super(GitClientTests, self).setUp() self.rout = BytesIO() self.rin = BytesIO() self.client = DummyClient(lambda x: True, self.rin.read, self.rout.write) def test_caps(self): agent_cap = ( 'agent=dulwich/%d.%d.%d' % dulwich.__version__).encode('ascii') self.assertEqual(set([b'multi_ack', b'side-band-64k', b'ofs-delta', b'thin-pack', b'multi_ack_detailed', b'shallow', agent_cap]), set(self.client._fetch_capabilities)) self.assertEqual( set([b'delete-refs', b'ofs-delta', b'report-status', b'side-band-64k', agent_cap]), set(self.client._send_capabilities)) def test_archive_ack(self): self.rin.write( b'0009NACK\n' b'0000') self.rin.seek(0) self.client.archive(b'bla', b'HEAD', None, None) self.assertEqual(self.rout.getvalue(), b'0011argument HEAD0000') def test_fetch_empty(self): self.rin.write(b'0000') self.rin.seek(0) def check_heads(heads): self.assertEqual(heads, {}) return [] ret = self.client.fetch_pack(b'/', check_heads, None, None) self.assertEqual({}, ret.refs) self.assertEqual({}, ret.symrefs) def test_fetch_pack_ignores_magic_ref(self): self.rin.write( b'00000000000000000000000000000000000000000000 capabilities^{}' b'\x00 multi_ack ' b'thin-pack side-band side-band-64k ofs-delta shallow no-progress ' b'include-tag\n' b'0000') self.rin.seek(0) def check_heads(heads): self.assertEqual({}, heads) return [] ret = self.client.fetch_pack(b'bla', check_heads, None, None, None) self.assertEqual({}, ret.refs) self.assertEqual({}, ret.symrefs) self.assertEqual(self.rout.getvalue(), b'0000') def test_fetch_pack_none(self): self.rin.write( b'008855dcc6bf963f922e1ed5c4bbaaefcfacef57b1d7 HEAD\x00multi_ack ' b'thin-pack side-band side-band-64k ofs-delta shallow no-progress ' b'include-tag\n' b'0000') self.rin.seek(0) ret = self.client.fetch_pack( b'bla', lambda heads: [], None, None, None) self.assertEqual( {b'HEAD': b'55dcc6bf963f922e1ed5c4bbaaefcfacef57b1d7'}, ret.refs) self.assertEqual({}, ret.symrefs) self.assertEqual(self.rout.getvalue(), b'0000') def test_send_pack_no_sideband64k_with_update_ref_error(self): # No side-bank-64k reported by server shouldn't try to parse # side band data pkts = [b'55dcc6bf963f922e1ed5c4bbaaefcfacef57b1d7 capabilities^{}' b'\x00 report-status delete-refs ofs-delta\n', b'', b"unpack ok", b"ng refs/foo/bar pre-receive hook declined", b''] for pkt in pkts: if pkt == b'': self.rin.write(b"0000") else: self.rin.write(("%04x" % (len(pkt)+4)).encode('ascii') + pkt) self.rin.seek(0) tree = Tree() commit = Commit() commit.tree = tree commit.parents = [] commit.author = commit.committer = b'test user' commit.commit_time = commit.author_time = 1174773719 commit.commit_timezone = commit.author_timezone = 0 commit.encoding = b'UTF-8' commit.message = b'test message' def update_refs(refs): return {b'refs/foo/bar': commit.id, } def generate_pack_data(have, want, ofs_delta=False): return pack_objects_to_data([(commit, None), (tree, ''), ]) - self.assertRaises(UpdateRefsError, - self.client.send_pack, "blah", - update_refs, generate_pack_data) + result = self.client.send_pack("blah", update_refs, generate_pack_data) + self.assertEqual( + {b'refs/foo/bar': 'pre-receive hook declined'}, + result.ref_status) + self.assertEqual({b'refs/foo/bar': commit.id}, result.refs) def test_send_pack_none(self): # Set ref to current value self.rin.write( b'0078310ca9477129b8586fa2afc779c1f57cf64bba6c ' b'refs/heads/master\x00 report-status delete-refs ' b'side-band-64k quiet ofs-delta\n' b'0000') self.rin.seek(0) def update_refs(refs): return { b'refs/heads/master': b'310ca9477129b8586fa2afc779c1f57cf64bba6c' } def generate_pack_data(have, want, ofs_delta=False): return 0, [] self.client.send_pack(b'/', update_refs, generate_pack_data) self.assertEqual(self.rout.getvalue(), b'0000') def test_send_pack_keep_and_delete(self): self.rin.write( b'0063310ca9477129b8586fa2afc779c1f57cf64bba6c ' b'refs/heads/master\x00report-status delete-refs ofs-delta\n' b'003f310ca9477129b8586fa2afc779c1f57cf64bba6c refs/heads/keepme\n' b'0000000eunpack ok\n' b'0019ok refs/heads/master\n' b'0000') self.rin.seek(0) def update_refs(refs): return {b'refs/heads/master': b'0' * 40} def generate_pack_data(have, want, ofs_delta=False): return 0, [] self.client.send_pack(b'/', update_refs, generate_pack_data) self.assertEqual( self.rout.getvalue(), b'008b310ca9477129b8586fa2afc779c1f57cf64bba6c ' b'0000000000000000000000000000000000000000 ' b'refs/heads/master\x00delete-refs ofs-delta report-status0000') def test_send_pack_delete_only(self): self.rin.write( b'0063310ca9477129b8586fa2afc779c1f57cf64bba6c ' b'refs/heads/master\x00report-status delete-refs ofs-delta\n' b'0000000eunpack ok\n' b'0019ok refs/heads/master\n' b'0000') self.rin.seek(0) def update_refs(refs): return {b'refs/heads/master': b'0' * 40} def generate_pack_data(have, want, ofs_delta=False): return 0, [] self.client.send_pack(b'/', update_refs, generate_pack_data) self.assertEqual( self.rout.getvalue(), b'008b310ca9477129b8586fa2afc779c1f57cf64bba6c ' b'0000000000000000000000000000000000000000 ' b'refs/heads/master\x00delete-refs ofs-delta report-status0000') def test_send_pack_new_ref_only(self): self.rin.write( b'0063310ca9477129b8586fa2afc779c1f57cf64bba6c ' b'refs/heads/master\x00report-status delete-refs ofs-delta\n' b'0000000eunpack ok\n' b'0019ok refs/heads/blah12\n' b'0000') self.rin.seek(0) def update_refs(refs): return { b'refs/heads/blah12': b'310ca9477129b8586fa2afc779c1f57cf64bba6c', b'refs/heads/master': b'310ca9477129b8586fa2afc779c1f57cf64bba6c' } def generate_pack_data(have, want, ofs_delta=False): return 0, [] f = BytesIO() write_pack_objects(f, {}) self.client.send_pack('/', update_refs, generate_pack_data) self.assertEqual( self.rout.getvalue(), b'008b0000000000000000000000000000000000000000 ' b'310ca9477129b8586fa2afc779c1f57cf64bba6c ' b'refs/heads/blah12\x00delete-refs ofs-delta report-status0000' + f.getvalue()) def test_send_pack_new_ref(self): self.rin.write( b'0064310ca9477129b8586fa2afc779c1f57cf64bba6c ' b'refs/heads/master\x00 report-status delete-refs ofs-delta\n' b'0000000eunpack ok\n' b'0019ok refs/heads/blah12\n' b'0000') self.rin.seek(0) tree = Tree() commit = Commit() commit.tree = tree commit.parents = [] commit.author = commit.committer = b'test user' commit.commit_time = commit.author_time = 1174773719 commit.commit_timezone = commit.author_timezone = 0 commit.encoding = b'UTF-8' commit.message = b'test message' def update_refs(refs): return { b'refs/heads/blah12': commit.id, b'refs/heads/master': b'310ca9477129b8586fa2afc779c1f57cf64bba6c' } def generate_pack_data(have, want, ofs_delta=False): return pack_objects_to_data([(commit, None), (tree, b''), ]) f = BytesIO() write_pack_data(f, *generate_pack_data(None, None)) self.client.send_pack(b'/', update_refs, generate_pack_data) self.assertEqual( self.rout.getvalue(), b'008b0000000000000000000000000000000000000000 ' + commit.id + b' refs/heads/blah12\x00delete-refs ofs-delta report-status0000' + f.getvalue()) def test_send_pack_no_deleteref_delete_only(self): pkts = [b'310ca9477129b8586fa2afc779c1f57cf64bba6c refs/heads/master' b'\x00 report-status ofs-delta\n', b'', b''] for pkt in pkts: if pkt == b'': self.rin.write(b"0000") else: self.rin.write(("%04x" % (len(pkt)+4)).encode('ascii') + pkt) self.rin.seek(0) def update_refs(refs): return {b'refs/heads/master': b'0' * 40} def generate_pack_data(have, want, ofs_delta=False): return 0, [] - self.assertRaises(UpdateRefsError, - self.client.send_pack, b"/", - update_refs, generate_pack_data) + result = self.client.send_pack(b"/", update_refs, generate_pack_data) + self.assertEqual( + result.ref_status, + {b'refs/heads/master': 'remote does not support deleting refs'}) + self.assertEqual( + result.refs, + {b'refs/heads/master': + b'310ca9477129b8586fa2afc779c1f57cf64bba6c'}) self.assertEqual(self.rout.getvalue(), b'0000') class TestGetTransportAndPath(TestCase): def test_tcp(self): c, path = get_transport_and_path('git://foo.com/bar/baz') self.assertTrue(isinstance(c, TCPGitClient)) self.assertEqual('foo.com', c._host) self.assertEqual(TCP_GIT_PORT, c._port) self.assertEqual('/bar/baz', path) def test_tcp_port(self): c, path = get_transport_and_path('git://foo.com:1234/bar/baz') self.assertTrue(isinstance(c, TCPGitClient)) self.assertEqual('foo.com', c._host) self.assertEqual(1234, c._port) self.assertEqual('/bar/baz', path) def test_git_ssh_explicit(self): c, path = get_transport_and_path('git+ssh://foo.com/bar/baz') self.assertTrue(isinstance(c, SSHGitClient)) self.assertEqual('foo.com', c.host) self.assertEqual(None, c.port) self.assertEqual(None, c.username) self.assertEqual('/bar/baz', path) def test_ssh_explicit(self): c, path = get_transport_and_path('ssh://foo.com/bar/baz') self.assertTrue(isinstance(c, SSHGitClient)) self.assertEqual('foo.com', c.host) self.assertEqual(None, c.port) self.assertEqual(None, c.username) self.assertEqual('/bar/baz', path) def test_ssh_port_explicit(self): c, path = get_transport_and_path( 'git+ssh://foo.com:1234/bar/baz') self.assertTrue(isinstance(c, SSHGitClient)) self.assertEqual('foo.com', c.host) self.assertEqual(1234, c.port) self.assertEqual('/bar/baz', path) def test_username_and_port_explicit_unknown_scheme(self): c, path = get_transport_and_path( 'unknown://git@server:7999/dply/stuff.git') self.assertTrue(isinstance(c, SSHGitClient)) self.assertEqual('unknown', c.host) self.assertEqual('//git@server:7999/dply/stuff.git', path) def test_username_and_port_explicit(self): c, path = get_transport_and_path( 'ssh://git@server:7999/dply/stuff.git') self.assertTrue(isinstance(c, SSHGitClient)) self.assertEqual('git', c.username) self.assertEqual('server', c.host) self.assertEqual(7999, c.port) self.assertEqual('/dply/stuff.git', path) def test_ssh_abspath_doubleslash(self): c, path = get_transport_and_path('git+ssh://foo.com//bar/baz') self.assertTrue(isinstance(c, SSHGitClient)) self.assertEqual('foo.com', c.host) self.assertEqual(None, c.port) self.assertEqual(None, c.username) self.assertEqual('//bar/baz', path) def test_ssh_port(self): c, path = get_transport_and_path( 'git+ssh://foo.com:1234/bar/baz') self.assertTrue(isinstance(c, SSHGitClient)) self.assertEqual('foo.com', c.host) self.assertEqual(1234, c.port) self.assertEqual('/bar/baz', path) def test_ssh_implicit(self): c, path = get_transport_and_path('foo:/bar/baz') self.assertTrue(isinstance(c, SSHGitClient)) self.assertEqual('foo', c.host) self.assertEqual(None, c.port) self.assertEqual(None, c.username) self.assertEqual('/bar/baz', path) def test_ssh_host(self): c, path = get_transport_and_path('foo.com:/bar/baz') self.assertTrue(isinstance(c, SSHGitClient)) self.assertEqual('foo.com', c.host) self.assertEqual(None, c.port) self.assertEqual(None, c.username) self.assertEqual('/bar/baz', path) def test_ssh_user_host(self): c, path = get_transport_and_path('user@foo.com:/bar/baz') self.assertTrue(isinstance(c, SSHGitClient)) self.assertEqual('foo.com', c.host) self.assertEqual(None, c.port) self.assertEqual('user', c.username) self.assertEqual('/bar/baz', path) def test_ssh_relpath(self): c, path = get_transport_and_path('foo:bar/baz') self.assertTrue(isinstance(c, SSHGitClient)) self.assertEqual('foo', c.host) self.assertEqual(None, c.port) self.assertEqual(None, c.username) self.assertEqual('bar/baz', path) def test_ssh_host_relpath(self): c, path = get_transport_and_path('foo.com:bar/baz') self.assertTrue(isinstance(c, SSHGitClient)) self.assertEqual('foo.com', c.host) self.assertEqual(None, c.port) self.assertEqual(None, c.username) self.assertEqual('bar/baz', path) def test_ssh_user_host_relpath(self): c, path = get_transport_and_path('user@foo.com:bar/baz') self.assertTrue(isinstance(c, SSHGitClient)) self.assertEqual('foo.com', c.host) self.assertEqual(None, c.port) self.assertEqual('user', c.username) self.assertEqual('bar/baz', path) def test_local(self): c, path = get_transport_and_path('foo.bar/baz') self.assertTrue(isinstance(c, LocalGitClient)) self.assertEqual('foo.bar/baz', path) @skipIf(sys.platform != 'win32', 'Behaviour only happens on windows.') def test_local_abs_windows_path(self): c, path = get_transport_and_path('C:\\foo.bar\\baz') self.assertTrue(isinstance(c, LocalGitClient)) self.assertEqual('C:\\foo.bar\\baz', path) def test_error(self): # Need to use a known urlparse.uses_netloc URL scheme to get the # expected parsing of the URL on Python versions less than 2.6.5 c, path = get_transport_and_path('prospero://bar/baz') self.assertTrue(isinstance(c, SSHGitClient)) def test_http(self): url = 'https://github.com/jelmer/dulwich' c, path = get_transport_and_path(url) self.assertTrue(isinstance(c, HttpGitClient)) self.assertEqual('/jelmer/dulwich', path) def test_http_auth(self): url = 'https://user:passwd@github.com/jelmer/dulwich' c, path = get_transport_and_path(url) self.assertTrue(isinstance(c, HttpGitClient)) self.assertEqual('/jelmer/dulwich', path) self.assertEqual('user', c._username) self.assertEqual('passwd', c._password) def test_http_auth_with_username(self): url = 'https://github.com/jelmer/dulwich' c, path = get_transport_and_path( url, username='user2', password='blah') self.assertTrue(isinstance(c, HttpGitClient)) self.assertEqual('/jelmer/dulwich', path) self.assertEqual('user2', c._username) self.assertEqual('blah', c._password) def test_http_auth_with_username_and_in_url(self): url = 'https://user:passwd@github.com/jelmer/dulwich' c, path = get_transport_and_path( url, username='user2', password='blah') self.assertTrue(isinstance(c, HttpGitClient)) self.assertEqual('/jelmer/dulwich', path) self.assertEqual('user', c._username) self.assertEqual('passwd', c._password) def test_http_no_auth(self): url = 'https://github.com/jelmer/dulwich' c, path = get_transport_and_path(url) self.assertTrue(isinstance(c, HttpGitClient)) self.assertEqual('/jelmer/dulwich', path) self.assertIs(None, c._username) self.assertIs(None, c._password) class TestGetTransportAndPathFromUrl(TestCase): def test_tcp(self): c, path = get_transport_and_path_from_url('git://foo.com/bar/baz') self.assertTrue(isinstance(c, TCPGitClient)) self.assertEqual('foo.com', c._host) self.assertEqual(TCP_GIT_PORT, c._port) self.assertEqual('/bar/baz', path) def test_tcp_port(self): c, path = get_transport_and_path_from_url('git://foo.com:1234/bar/baz') self.assertTrue(isinstance(c, TCPGitClient)) self.assertEqual('foo.com', c._host) self.assertEqual(1234, c._port) self.assertEqual('/bar/baz', path) def test_ssh_explicit(self): c, path = get_transport_and_path_from_url('git+ssh://foo.com/bar/baz') self.assertTrue(isinstance(c, SSHGitClient)) self.assertEqual('foo.com', c.host) self.assertEqual(None, c.port) self.assertEqual(None, c.username) self.assertEqual('/bar/baz', path) def test_ssh_port_explicit(self): c, path = get_transport_and_path_from_url( 'git+ssh://foo.com:1234/bar/baz') self.assertTrue(isinstance(c, SSHGitClient)) self.assertEqual('foo.com', c.host) self.assertEqual(1234, c.port) self.assertEqual('/bar/baz', path) def test_ssh_homepath(self): c, path = get_transport_and_path_from_url( 'git+ssh://foo.com/~/bar/baz') self.assertTrue(isinstance(c, SSHGitClient)) self.assertEqual('foo.com', c.host) self.assertEqual(None, c.port) self.assertEqual(None, c.username) self.assertEqual('/~/bar/baz', path) def test_ssh_port_homepath(self): c, path = get_transport_and_path_from_url( 'git+ssh://foo.com:1234/~/bar/baz') self.assertTrue(isinstance(c, SSHGitClient)) self.assertEqual('foo.com', c.host) self.assertEqual(1234, c.port) self.assertEqual('/~/bar/baz', path) def test_ssh_host_relpath(self): self.assertRaises( ValueError, get_transport_and_path_from_url, 'foo.com:bar/baz') def test_ssh_user_host_relpath(self): self.assertRaises( ValueError, get_transport_and_path_from_url, 'user@foo.com:bar/baz') def test_local_path(self): self.assertRaises( ValueError, get_transport_and_path_from_url, 'foo.bar/baz') def test_error(self): # Need to use a known urlparse.uses_netloc URL scheme to get the # expected parsing of the URL on Python versions less than 2.6.5 self.assertRaises( ValueError, get_transport_and_path_from_url, 'prospero://bar/baz') def test_http(self): url = 'https://github.com/jelmer/dulwich' c, path = get_transport_and_path_from_url(url) self.assertTrue(isinstance(c, HttpGitClient)) self.assertEqual('https://github.com', c.get_url(b'/')) self.assertEqual('/jelmer/dulwich', path) def test_http_port(self): url = 'https://github.com:9090/jelmer/dulwich' c, path = get_transport_and_path_from_url(url) self.assertEqual('https://github.com:9090', c.get_url(b'/')) self.assertTrue(isinstance(c, HttpGitClient)) self.assertEqual('/jelmer/dulwich', path) def test_file(self): c, path = get_transport_and_path_from_url('file:///home/jelmer/foo') self.assertTrue(isinstance(c, LocalGitClient)) self.assertEqual('/home/jelmer/foo', path) class TestSSHVendor(object): def __init__(self): self.host = None self.command = "" self.username = None self.port = None self.password = None self.key_filename = None def run_command(self, host, command, username=None, port=None, password=None, key_filename=None): self.host = host self.command = command self.username = username self.port = port self.password = password self.key_filename = key_filename class Subprocess: pass setattr(Subprocess, 'read', lambda: None) setattr(Subprocess, 'write', lambda: None) setattr(Subprocess, 'close', lambda: None) setattr(Subprocess, 'can_read', lambda: None) return Subprocess() class SSHGitClientTests(TestCase): def setUp(self): super(SSHGitClientTests, self).setUp() self.server = TestSSHVendor() self.real_vendor = client.get_ssh_vendor client.get_ssh_vendor = lambda: self.server self.client = SSHGitClient('git.samba.org') def tearDown(self): super(SSHGitClientTests, self).tearDown() client.get_ssh_vendor = self.real_vendor def test_get_url(self): path = '/tmp/repo.git' c = SSHGitClient('git.samba.org') url = c.get_url(path) self.assertEqual('ssh://git.samba.org/tmp/repo.git', url) def test_get_url_with_username_and_port(self): path = '/tmp/repo.git' c = SSHGitClient('git.samba.org', port=2222, username='user') url = c.get_url(path) self.assertEqual('ssh://user@git.samba.org:2222/tmp/repo.git', url) def test_default_command(self): self.assertEqual( b'git-upload-pack', self.client._get_cmd_path(b'upload-pack')) def test_alternative_command_path(self): self.client.alternative_paths[b'upload-pack'] = ( b'/usr/lib/git/git-upload-pack') self.assertEqual( b'/usr/lib/git/git-upload-pack', self.client._get_cmd_path(b'upload-pack')) def test_alternative_command_path_spaces(self): self.client.alternative_paths[b'upload-pack'] = ( b'/usr/lib/git/git-upload-pack -ibla') self.assertEqual(b"/usr/lib/git/git-upload-pack -ibla", self.client._get_cmd_path(b'upload-pack')) def test_connect(self): server = self.server client = self.client client.username = b"username" client.port = 1337 client._connect(b"command", b"/path/to/repo") self.assertEqual(b"username", server.username) self.assertEqual(1337, server.port) self.assertEqual("git-command '/path/to/repo'", server.command) client._connect(b"relative-command", b"/~/path/to/repo") self.assertEqual("git-relative-command '~/path/to/repo'", server.command) class ReportStatusParserTests(TestCase): def test_invalid_pack(self): parser = ReportStatusParser() parser.handle_packet(b"unpack error - foo bar") parser.handle_packet(b"ok refs/foo/bar") parser.handle_packet(None) - self.assertRaises(SendPackError, parser.check) + self.assertRaises(SendPackError, list, parser.check()) def test_update_refs_error(self): parser = ReportStatusParser() parser.handle_packet(b"unpack ok") parser.handle_packet(b"ng refs/foo/bar need to pull") parser.handle_packet(None) - self.assertRaises(UpdateRefsError, parser.check) + self.assertEqual( + [(b'refs/foo/bar', 'need to pull')], list(parser.check())) def test_ok(self): parser = ReportStatusParser() parser.handle_packet(b"unpack ok") parser.handle_packet(b"ok refs/foo/bar") parser.handle_packet(None) - parser.check() + self.assertEqual([(b'refs/foo/bar', None)], list(parser.check())) class LocalGitClientTests(TestCase): def test_get_url(self): path = "/tmp/repo.git" c = LocalGitClient() url = c.get_url(path) self.assertEqual('file:///tmp/repo.git', url) def test_fetch_into_empty(self): c = LocalGitClient() t = MemoryRepo() s = open_repo('a.git') self.addCleanup(tear_down_repo, s) self.assertEqual(s.get_refs(), c.fetch(s.path, t).refs) def test_fetch_empty(self): c = LocalGitClient() s = open_repo('a.git') self.addCleanup(tear_down_repo, s) out = BytesIO() walker = {} ret = c.fetch_pack( s.path, lambda heads: [], graph_walker=walker, pack_data=out.write) self.assertEqual({ b'HEAD': b'a90fa2d900a17e99b433217e988c4eb4a2e9a097', b'refs/heads/master': b'a90fa2d900a17e99b433217e988c4eb4a2e9a097', b'refs/tags/mytag': b'28237f4dc30d0d462658d6b937b08a0f0b6ef55a', b'refs/tags/mytag-packed': b'b0931cadc54336e78a1d980420e3268903b57a50' }, ret.refs) self.assertEqual( {b'HEAD': b'refs/heads/master'}, ret.symrefs) self.assertEqual( b"PACK\x00\x00\x00\x02\x00\x00\x00\x00\x02\x9d\x08" b"\x82;\xd8\xa8\xea\xb5\x10\xadj\xc7\\\x82<\xfd>\xd3\x1e", out.getvalue()) def test_fetch_pack_none(self): c = LocalGitClient() s = open_repo('a.git') self.addCleanup(tear_down_repo, s) out = BytesIO() walker = MemoryRepo().get_graph_walker() ret = c.fetch_pack( s.path, lambda heads: [b"a90fa2d900a17e99b433217e988c4eb4a2e9a097"], graph_walker=walker, pack_data=out.write) self.assertEqual({b'HEAD': b'refs/heads/master'}, ret.symrefs) self.assertEqual({ b'HEAD': b'a90fa2d900a17e99b433217e988c4eb4a2e9a097', b'refs/heads/master': b'a90fa2d900a17e99b433217e988c4eb4a2e9a097', b'refs/tags/mytag': b'28237f4dc30d0d462658d6b937b08a0f0b6ef55a', b'refs/tags/mytag-packed': b'b0931cadc54336e78a1d980420e3268903b57a50' }, ret.refs) # Hardcoding is not ideal, but we'll fix that some other day.. self.assertTrue(out.getvalue().startswith( b'PACK\x00\x00\x00\x02\x00\x00\x00\x07')) def test_send_pack_without_changes(self): local = open_repo('a.git') self.addCleanup(tear_down_repo, local) target = open_repo('a.git') self.addCleanup(tear_down_repo, target) self.send_and_verify(b"master", local, target) def test_send_pack_with_changes(self): local = open_repo('a.git') self.addCleanup(tear_down_repo, local) target_path = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, target_path) with Repo.init_bare(target_path) as target: self.send_and_verify(b"master", local, target) def test_get_refs(self): local = open_repo('refs.git') self.addCleanup(tear_down_repo, local) client = LocalGitClient() refs = client.get_refs(local.path) self.assertDictEqual(local.refs.as_dict(), refs) def send_and_verify(self, branch, local, target): """Send branch from local to remote repository and verify it worked.""" client = LocalGitClient() ref_name = b"refs/heads/" + branch - new_refs = client.send_pack(target.path, - lambda _: {ref_name: local.refs[ref_name]}, - local.generate_pack_data) + result = client.send_pack(target.path, + lambda _: {ref_name: local.refs[ref_name]}, + local.generate_pack_data) - self.assertEqual(local.refs[ref_name], new_refs[ref_name]) + self.assertEqual(local.refs[ref_name], result.refs[ref_name]) + self.assertIs(None, result.agent) + self.assertEqual({}, result.ref_status) - obj_local = local.get_object(new_refs[ref_name]) - obj_target = target.get_object(new_refs[ref_name]) + obj_local = local.get_object(result.refs[ref_name]) + obj_target = target.get_object(result.refs[ref_name]) self.assertEqual(obj_local, obj_target) class HttpGitClientTests(TestCase): def test_get_url(self): base_url = 'https://github.com/jelmer/dulwich' path = '/jelmer/dulwich' c = HttpGitClient(base_url) url = c.get_url(path) self.assertEqual('https://github.com/jelmer/dulwich', url) def test_get_url_bytes_path(self): base_url = 'https://github.com/jelmer/dulwich' path_bytes = b'/jelmer/dulwich' c = HttpGitClient(base_url) url = c.get_url(path_bytes) self.assertEqual('https://github.com/jelmer/dulwich', url) def test_get_url_with_username_and_passwd(self): base_url = 'https://github.com/jelmer/dulwich' path = '/jelmer/dulwich' c = HttpGitClient(base_url, username='USERNAME', password='PASSWD') url = c.get_url(path) self.assertEqual('https://github.com/jelmer/dulwich', url) def test_init_username_passwd_set(self): url = 'https://github.com/jelmer/dulwich' c = HttpGitClient(url, config=None, username='user', password='passwd') self.assertEqual('user', c._username) self.assertEqual('passwd', c._password) basic_auth = c.pool_manager.headers['authorization'] auth_string = '%s:%s' % ('user', 'passwd') b64_credentials = base64.b64encode(auth_string.encode('latin1')) expected_basic_auth = 'Basic %s' % b64_credentials.decode('latin1') self.assertEqual(basic_auth, expected_basic_auth) def test_init_no_username_passwd(self): url = 'https://github.com/jelmer/dulwich' c = HttpGitClient(url, config=None) self.assertIs(None, c._username) self.assertIs(None, c._password) self.assertNotIn('authorization', c.pool_manager.headers) def test_from_parsedurl_on_url_with_quoted_credentials(self): original_username = 'john|the|first' quoted_username = urlquote(original_username) original_password = 'Ya#1$2%3' quoted_password = urlquote(original_password) url = 'https://{username}:{password}@github.com/jelmer/dulwich'.format( username=quoted_username, password=quoted_password ) c = HttpGitClient.from_parsedurl(urlparse(url)) self.assertEqual(original_username, c._username) self.assertEqual(original_password, c._password) basic_auth = c.pool_manager.headers['authorization'] auth_string = '%s:%s' % (original_username, original_password) b64_credentials = base64.b64encode(auth_string.encode('latin1')) expected_basic_auth = 'Basic %s' % b64_credentials.decode('latin1') self.assertEqual(basic_auth, expected_basic_auth) def test_url_redirect_location(self): from urllib3.response import HTTPResponse test_data = { 'https://gitlab.com/inkscape/inkscape/': { 'redirect_url': 'https://gitlab.com/inkscape/inkscape.git/', 'refs_data': (b'001e# service=git-upload-pack\n00000032' b'fb2bebf4919a011f0fd7cec085443d0031228e76 ' b'HEAD\n0000') }, 'https://github.com/jelmer/dulwich/': { 'redirect_url': 'https://github.com/jelmer/dulwich/', 'refs_data': (b'001e# service=git-upload-pack\n00000032' b'3ff25e09724aa4d86ea5bca7d5dd0399a3c8bfcf ' b'HEAD\n0000') } } tail = 'info/refs?service=git-upload-pack' # we need to mock urllib3.PoolManager as this test will fail # otherwise without an active internet connection class PoolManagerMock(): def __init__(self): self.headers = {} def request(self, method, url, fields=None, headers=None, redirect=True): base_url = url[:-len(tail)] redirect_base_url = test_data[base_url]['redirect_url'] redirect_url = redirect_base_url + tail headers = { 'Content-Type': 'application/x-git-upload-pack-advertisement' } body = test_data[base_url]['refs_data'] # urllib3 handles automatic redirection by default status = 200 request_url = redirect_url # simulate urllib3 behavior when redirect parameter is False if redirect is False: request_url = url if redirect_base_url != base_url: body = '' headers['location'] = redirect_url status = 301 return HTTPResponse(body=body, headers=headers, request_method=method, request_url=request_url, status=status) pool_manager = PoolManagerMock() for base_url in test_data.keys(): # instantiate HttpGitClient with mocked pool manager c = HttpGitClient(base_url, pool_manager=pool_manager, config=None) # call method that detects url redirection _, _, processed_url = c._discover_references(b'git-upload-pack', base_url) # send the same request as the method above without redirection resp = c.pool_manager.request('GET', base_url + tail, redirect=False) # check expected behavior of urllib3 redirect_location = resp.get_redirect_location() if resp.status == 200: self.assertFalse(redirect_location) if redirect_location: # check that url redirection has been correctly detected self.assertEqual(processed_url, redirect_location[:-len(tail)]) else: # check also the no redirection case self.assertEqual(processed_url, base_url) class TCPGitClientTests(TestCase): def test_get_url(self): host = 'github.com' path = '/jelmer/dulwich' c = TCPGitClient(host) url = c.get_url(path) self.assertEqual('git://github.com/jelmer/dulwich', url) def test_get_url_with_port(self): host = 'github.com' path = '/jelmer/dulwich' port = 9090 c = TCPGitClient(host, port=port) url = c.get_url(path) self.assertEqual('git://github.com:9090/jelmer/dulwich', url) class DefaultUrllib3ManagerTest(TestCase): def test_no_config(self): manager = default_urllib3_manager(config=None) self.assertEqual(manager.connection_pool_kw['cert_reqs'], 'CERT_REQUIRED') def test_config_no_proxy(self): import urllib3 manager = default_urllib3_manager(config=ConfigDict()) self.assertNotIsInstance(manager, urllib3.ProxyManager) self.assertIsInstance(manager, urllib3.PoolManager) def test_config_no_proxy_custom_cls(self): import urllib3 class CustomPoolManager(urllib3.PoolManager): pass manager = default_urllib3_manager(config=ConfigDict(), pool_manager_cls=CustomPoolManager) self.assertIsInstance(manager, CustomPoolManager) def test_config_ssl(self): config = ConfigDict() config.set(b'http', b'sslVerify', b'true') manager = default_urllib3_manager(config=config) self.assertEqual(manager.connection_pool_kw['cert_reqs'], 'CERT_REQUIRED') def test_config_no_ssl(self): config = ConfigDict() config.set(b'http', b'sslVerify', b'false') manager = default_urllib3_manager(config=config) self.assertEqual(manager.connection_pool_kw['cert_reqs'], 'CERT_NONE') def test_config_proxy(self): import urllib3 config = ConfigDict() config.set(b'http', b'proxy', b'http://localhost:3128/') manager = default_urllib3_manager(config=config) self.assertIsInstance(manager, urllib3.ProxyManager) self.assertTrue(hasattr(manager, 'proxy')) self.assertEqual(manager.proxy.scheme, 'http') self.assertEqual(manager.proxy.host, 'localhost') self.assertEqual(manager.proxy.port, 3128) def test_config_proxy_custom_cls(self): import urllib3 class CustomProxyManager(urllib3.ProxyManager): pass config = ConfigDict() config.set(b'http', b'proxy', b'http://localhost:3128/') manager = default_urllib3_manager(config=config, proxy_manager_cls=CustomProxyManager) self.assertIsInstance(manager, CustomProxyManager) def test_config_no_verify_ssl(self): manager = default_urllib3_manager(config=None, cert_reqs="CERT_NONE") self.assertEqual(manager.connection_pool_kw['cert_reqs'], 'CERT_NONE') class SubprocessSSHVendorTests(TestCase): def setUp(self): # Monkey Patch client subprocess popen self._orig_popen = dulwich.client.subprocess.Popen dulwich.client.subprocess.Popen = DummyPopen def tearDown(self): dulwich.client.subprocess.Popen = self._orig_popen def test_run_command_dashes(self): vendor = SubprocessSSHVendor() self.assertRaises(StrangeHostname, vendor.run_command, '--weird-host', 'git-clone-url') def test_run_command_password(self): vendor = SubprocessSSHVendor() self.assertRaises(NotImplementedError, vendor.run_command, 'host', 'git-clone-url', password='12345') def test_run_command_password_and_privkey(self): vendor = SubprocessSSHVendor() self.assertRaises(NotImplementedError, vendor.run_command, 'host', 'git-clone-url', password='12345', key_filename='/tmp/id_rsa') def test_run_command_with_port_username_and_privkey(self): expected = ['ssh', '-x', '-p', '2200', '-i', '/tmp/id_rsa', 'user@host', 'git-clone-url'] vendor = SubprocessSSHVendor() command = vendor.run_command( 'host', 'git-clone-url', username='user', port='2200', key_filename='/tmp/id_rsa') args = command.proc.args self.assertListEqual(expected, args[0]) class PLinkSSHVendorTests(TestCase): def setUp(self): # Monkey Patch client subprocess popen self._orig_popen = dulwich.client.subprocess.Popen dulwich.client.subprocess.Popen = DummyPopen def tearDown(self): dulwich.client.subprocess.Popen = self._orig_popen def test_run_command_dashes(self): vendor = PLinkSSHVendor() self.assertRaises(StrangeHostname, vendor.run_command, '--weird-host', 'git-clone-url') def test_run_command_password_and_privkey(self): vendor = PLinkSSHVendor() warnings.simplefilter("always", UserWarning) self.addCleanup(warnings.resetwarnings) warnings_list, restore_warnings = setup_warning_catcher() self.addCleanup(restore_warnings) command = vendor.run_command( 'host', 'git-clone-url', password='12345', key_filename='/tmp/id_rsa') expected_warning = UserWarning( 'Invoking PLink with a password exposes the password in the ' 'process list.') 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)) args = command.proc.args if sys.platform == 'win32': binary = ['plink.exe', '-ssh'] else: binary = ['plink', '-ssh'] expected = binary + [ '-pw', '12345', '-i', '/tmp/id_rsa', 'host', 'git-clone-url'] self.assertListEqual(expected, args[0]) def test_run_command_password(self): if sys.platform == 'win32': binary = ['plink.exe', '-ssh'] else: binary = ['plink', '-ssh'] expected = binary + ['-pw', '12345', 'host', 'git-clone-url'] vendor = PLinkSSHVendor() warnings.simplefilter("always", UserWarning) self.addCleanup(warnings.resetwarnings) warnings_list, restore_warnings = setup_warning_catcher() self.addCleanup(restore_warnings) command = vendor.run_command('host', 'git-clone-url', password='12345') expected_warning = UserWarning( 'Invoking PLink with a password exposes the password in the ' 'process list.') 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)) args = command.proc.args self.assertListEqual(expected, args[0]) def test_run_command_with_port_username_and_privkey(self): if sys.platform == 'win32': binary = ['plink.exe', '-ssh'] else: binary = ['plink', '-ssh'] expected = binary + [ '-P', '2200', '-i', '/tmp/id_rsa', 'user@host', 'git-clone-url'] vendor = PLinkSSHVendor() command = vendor.run_command( 'host', 'git-clone-url', username='user', port='2200', key_filename='/tmp/id_rsa') args = command.proc.args self.assertListEqual(expected, args[0]) class RsyncUrlTests(TestCase): def test_simple(self): self.assertEqual( parse_rsync_url('foo:bar/path'), (None, 'foo', 'bar/path')) self.assertEqual( parse_rsync_url('user@foo:bar/path'), ('user', 'foo', 'bar/path')) def test_path(self): self.assertRaises(ValueError, parse_rsync_url, '/path') class CheckWantsTests(TestCase): def test_fine(self): check_wants( [b'2f3dc7a53fb752a6961d3a56683df46d4d3bf262'], {b'refs/heads/blah': b'2f3dc7a53fb752a6961d3a56683df46d4d3bf262'}) def test_missing(self): self.assertRaises( InvalidWants, check_wants, [b'2f3dc7a53fb752a6961d3a56683df46d4d3bf262'], {b'refs/heads/blah': b'3f3dc7a53fb752a6961d3a56683df46d4d3bf262'}) def test_annotated(self): self.assertRaises( InvalidWants, check_wants, [b'2f3dc7a53fb752a6961d3a56683df46d4d3bf262'], {b'refs/heads/blah': b'3f3dc7a53fb752a6961d3a56683df46d4d3bf262', b'refs/heads/blah^{}': b'2f3dc7a53fb752a6961d3a56683df46d4d3bf262'}) class FetchPackResultTests(TestCase): def test_eq(self): self.assertEqual( FetchPackResult( {b'refs/heads/master': b'2f3dc7a53fb752a6961d3a56683df46d4d3bf262'}, {}, b'user/agent'), FetchPackResult( {b'refs/heads/master': b'2f3dc7a53fb752a6961d3a56683df46d4d3bf262'}, {}, b'user/agent')) class GitCredentialStoreTests(TestCase): @classmethod def setUpClass(cls): with tempfile.NamedTemporaryFile(delete=False) as f: f.write(b'https://user:pass@example.org') cls.fname = f.name @classmethod def tearDownClass(cls): os.unlink(cls.fname) def test_nonmatching_scheme(self): self.assertEqual( get_credentials_from_store( b'http', b'example.org', fnames=[self.fname]), None) def test_nonmatching_hostname(self): self.assertEqual( get_credentials_from_store( b'https', b'noentry.org', fnames=[self.fname]), None) def test_match_without_username(self): self.assertEqual( get_credentials_from_store( b'https', b'example.org', fnames=[self.fname]), (b'user', b'pass')) def test_match_with_matching_username(self): self.assertEqual( get_credentials_from_store( b'https', b'example.org', b'user', fnames=[self.fname]), (b'user', b'pass')) def test_no_match_with_nonmatching_username(self): self.assertEqual( get_credentials_from_store( b'https', b'example.org', b'otheruser', fnames=[self.fname]), None) diff --git a/dulwich/tests/test_graph.py b/dulwich/tests/test_graph.py new file mode 100644 index 00000000..aed5bb61 --- /dev/null +++ b/dulwich/tests/test_graph.py @@ -0,0 +1,184 @@ +# -*- coding: utf-8 -*- +# test_index.py -- Tests for merge +# encoding: utf-8 +# Copyright (c) 2020 Kevin B. Hendricks, Stratford Ontario Canada +# +# 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.graph.""" + +from dulwich.tests import TestCase +from dulwich.tests.utils import make_commit +from dulwich.object_store import MemoryObjectStore + +from dulwich.graph import _find_lcas, can_fast_forward + + +class FindMergeBaseTests(TestCase): + + @staticmethod + def run_test(dag, inputs): + def lookup_parents(commit_id): + return dag[commit_id] + c1 = inputs[0] + c2s = inputs[1:] + return set(_find_lcas(lookup_parents, c1, c2s)) + + def test_multiple_lca(self): + # two lowest common ancestors + graph = { + '5': ['1', '2'], + '4': ['3', '1'], + '3': ['2'], + '2': ['0'], + '1': [], + '0': [] + } + self.assertEqual(self.run_test(graph, ['4', '5']), set(['1', '2'])) + + def test_no_common_ancestor(self): + # no common ancestor + graph = { + '4': ['2'], + '3': ['1'], + '2': [], + '1': ['0'], + '0': [], + } + self.assertEqual(self.run_test(graph, ['4', '3']), set([])) + + def test_ancestor(self): + # ancestor + graph = { + 'G': ['D', 'F'], + 'F': ['E'], + 'D': ['C'], + 'C': ['B'], + 'E': ['B'], + 'B': ['A'], + 'A': [] + } + self.assertEqual(self.run_test(graph, ['D', 'C']), set(['C'])) + + def test_direct_parent(self): + # parent + graph = { + 'G': ['D', 'F'], + 'F': ['E'], + 'D': ['C'], + 'C': ['B'], + 'E': ['B'], + 'B': ['A'], + 'A': [] + } + self.assertEqual(self.run_test(graph, ['G', 'D']), set(['D'])) + + def test_another_crossover(self): + # Another cross over + graph = { + 'G': ['D', 'F'], + 'F': ['E', 'C'], + 'D': ['C', 'E'], + 'C': ['B'], + 'E': ['B'], + 'B': ['A'], + 'A': [] + } + self.assertEqual(self.run_test(graph, ['D', 'F']), set(['E', 'C'])) + + def test_three_way_merge_lca(self): + # three way merge commit straight from git docs + graph = { + 'C': ['C1'], + 'C1': ['C2'], + 'C2': ['C3'], + 'C3': ['C4'], + 'C4': ['2'], + 'B': ['B1'], + 'B1': ['B2'], + 'B2': ['B3'], + 'B3': ['1'], + 'A': ['A1'], + 'A1': ['A2'], + 'A2': ['A3'], + 'A3': ['1'], + '1': ['2'], + '2': [], + } + # assumes a theoretical merge M exists that merges B and C first + # which actually means find the first LCA from either of B OR C with A + self.assertEqual(self.run_test(graph, ['A', 'B', 'C']), set(['1'])) + + def test_octopus(self): + # octopus algorithm test + # test straight from git docs of A, B, and C + # but this time use octopus to find lcas of A, B, and C simultaneously + graph = { + 'C': ['C1'], + 'C1': ['C2'], + 'C2': ['C3'], + 'C3': ['C4'], + 'C4': ['2'], + 'B': ['B1'], + 'B1': ['B2'], + 'B2': ['B3'], + 'B3': ['1'], + 'A': ['A1'], + 'A1': ['A2'], + 'A2': ['A3'], + 'A3': ['1'], + '1': ['2'], + '2': [], + } + + def lookup_parents(cid): + return graph[cid] + lcas = ['A'] + others = ['B', 'C'] + for cmt in others: + next_lcas = [] + for ca in lcas: + res = _find_lcas(lookup_parents, cmt, [ca]) + next_lcas.extend(res) + lcas = next_lcas[:] + self.assertEqual(set(lcas), set(['2'])) + + +class CanFastForwardTests(TestCase): + + def test_ff(self): + store = MemoryObjectStore() + base = make_commit() + c1 = make_commit(parents=[base.id]) + c2 = make_commit(parents=[c1.id]) + store.add_objects([(base, None), (c1, None), (c2, None)]) + self.assertTrue(can_fast_forward(store, c1.id, c1.id)) + self.assertTrue(can_fast_forward(store, base.id, c1.id)) + self.assertTrue(can_fast_forward(store, c1.id, c2.id)) + self.assertFalse(can_fast_forward(store, c2.id, c1.id)) + + def test_diverged(self): + store = MemoryObjectStore() + base = make_commit() + c1 = make_commit(parents=[base.id]) + c2a = make_commit(parents=[c1.id], message=b'2a') + c2b = make_commit(parents=[c1.id], message=b'2b') + store.add_objects([(base, None), (c1, None), (c2a, None), (c2b, None)]) + self.assertTrue(can_fast_forward(store, c1.id, c2a.id)) + self.assertTrue(can_fast_forward(store, c1.id, c2b.id)) + self.assertFalse(can_fast_forward(store, c2a.id, c2b.id)) + self.assertFalse(can_fast_forward(store, c2b.id, c2a.id)) diff --git a/dulwich/tests/test_objectspec.py b/dulwich/tests/test_objectspec.py index 1ddb5789..37a20f76 100644 --- a/dulwich/tests/test_objectspec.py +++ b/dulwich/tests/test_objectspec.py @@ -1,233 +1,238 @@ # test_objectspec.py -- tests for objectspec.py # Copyright (C) 2014 Jelmer Vernooij # # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Tests for revision spec parsing.""" # TODO: Round-trip parse-serialize-parse and serialize-parse-serialize tests. from dulwich.objects import ( Blob, ) from dulwich.objectspec import ( parse_object, parse_commit, parse_commit_range, parse_ref, parse_refs, parse_reftuple, parse_reftuples, parse_tree, ) from dulwich.repo import MemoryRepo from dulwich.tests import ( TestCase, ) from dulwich.tests.utils import ( build_commit_graph, ) class ParseObjectTests(TestCase): """Test parse_object.""" def test_nonexistent(self): r = MemoryRepo() self.assertRaises(KeyError, parse_object, r, "thisdoesnotexist") def test_blob_by_sha(self): r = MemoryRepo() b = Blob.from_string(b"Blah") r.object_store.add_object(b) self.assertEqual(b, parse_object(r, b.id)) class ParseCommitRangeTests(TestCase): """Test parse_commit_range.""" def test_nonexistent(self): r = MemoryRepo() self.assertRaises(KeyError, parse_commit_range, r, "thisdoesnotexist") def test_commit_by_sha(self): r = MemoryRepo() c1, c2, c3 = build_commit_graph( r.object_store, [[1], [2, 1], [3, 1, 2]]) self.assertEqual([c1], list(parse_commit_range(r, c1.id))) class ParseCommitTests(TestCase): """Test parse_commit.""" def test_nonexistent(self): r = MemoryRepo() self.assertRaises(KeyError, parse_commit, r, "thisdoesnotexist") def test_commit_by_sha(self): r = MemoryRepo() [c1] = build_commit_graph(r.object_store, [[1]]) self.assertEqual(c1, parse_commit(r, c1.id)) def test_commit_by_short_sha(self): r = MemoryRepo() [c1] = build_commit_graph(r.object_store, [[1]]) self.assertEqual(c1, parse_commit(r, c1.id[:10])) class ParseRefTests(TestCase): def test_nonexistent(self): r = {} self.assertRaises(KeyError, parse_ref, r, b"thisdoesnotexist") def test_ambiguous_ref(self): r = {b"ambig1": 'bla', b"refs/ambig1": 'bla', b"refs/tags/ambig1": 'bla', b"refs/heads/ambig1": 'bla', b"refs/remotes/ambig1": 'bla', b"refs/remotes/ambig1/HEAD": "bla"} self.assertEqual(b"ambig1", parse_ref(r, b"ambig1")) def test_ambiguous_ref2(self): r = {b"refs/ambig2": 'bla', b"refs/tags/ambig2": 'bla', b"refs/heads/ambig2": 'bla', b"refs/remotes/ambig2": 'bla', b"refs/remotes/ambig2/HEAD": "bla"} self.assertEqual(b"refs/ambig2", parse_ref(r, b"ambig2")) def test_ambiguous_tag(self): r = {b"refs/tags/ambig3": 'bla', b"refs/heads/ambig3": 'bla', b"refs/remotes/ambig3": 'bla', b"refs/remotes/ambig3/HEAD": "bla"} self.assertEqual(b"refs/tags/ambig3", parse_ref(r, b"ambig3")) def test_ambiguous_head(self): r = {b"refs/heads/ambig4": 'bla', b"refs/remotes/ambig4": 'bla', b"refs/remotes/ambig4/HEAD": "bla"} self.assertEqual(b"refs/heads/ambig4", parse_ref(r, b"ambig4")) def test_ambiguous_remote(self): r = {b"refs/remotes/ambig5": 'bla', b"refs/remotes/ambig5/HEAD": "bla"} self.assertEqual(b"refs/remotes/ambig5", parse_ref(r, b"ambig5")) def test_ambiguous_remote_head(self): r = {b"refs/remotes/ambig6/HEAD": "bla"} self.assertEqual(b"refs/remotes/ambig6/HEAD", parse_ref(r, b"ambig6")) def test_heads_full(self): r = {b"refs/heads/foo": "bla"} self.assertEqual(b"refs/heads/foo", parse_ref(r, b"refs/heads/foo")) def test_heads_partial(self): r = {b"refs/heads/foo": "bla"} self.assertEqual(b"refs/heads/foo", parse_ref(r, b"heads/foo")) def test_tags_partial(self): r = {b"refs/tags/foo": "bla"} self.assertEqual(b"refs/tags/foo", parse_ref(r, b"tags/foo")) class ParseRefsTests(TestCase): def test_nonexistent(self): r = {} self.assertRaises(KeyError, parse_refs, r, [b"thisdoesnotexist"]) def test_head(self): r = {b"refs/heads/foo": "bla"} self.assertEqual([b"refs/heads/foo"], parse_refs(r, [b"foo"])) def test_full(self): r = {b"refs/heads/foo": "bla"} self.assertEqual([b"refs/heads/foo"], parse_refs(r, b"refs/heads/foo")) class ParseReftupleTests(TestCase): def test_nonexistent(self): r = {} self.assertRaises(KeyError, parse_reftuple, r, r, b"thisdoesnotexist") def test_head(self): r = {b"refs/heads/foo": "bla"} self.assertEqual((b"refs/heads/foo", b"refs/heads/foo", False), parse_reftuple(r, r, b"foo")) self.assertEqual((b"refs/heads/foo", b"refs/heads/foo", True), parse_reftuple(r, r, b"+foo")) self.assertEqual((b"refs/heads/foo", b"refs/heads/foo", True), parse_reftuple(r, {}, b"+foo")) + self.assertEqual((b"refs/heads/foo", b"refs/heads/foo", True), + parse_reftuple(r, {}, b"foo", True)) def test_full(self): r = {b"refs/heads/foo": "bla"} self.assertEqual((b"refs/heads/foo", b"refs/heads/foo", False), parse_reftuple(r, r, b"refs/heads/foo")) def test_no_left_ref(self): r = {b"refs/heads/foo": "bla"} self.assertEqual((None, b"refs/heads/foo", False), parse_reftuple(r, r, b":refs/heads/foo")) def test_no_right_ref(self): r = {b"refs/heads/foo": "bla"} self.assertEqual((b"refs/heads/foo", None, False), parse_reftuple(r, r, b"refs/heads/foo:")) def test_default_with_string(self): r = {b"refs/heads/foo": "bla"} self.assertEqual((b"refs/heads/foo", b"refs/heads/foo", False), parse_reftuple(r, r, "foo")) class ParseReftuplesTests(TestCase): def test_nonexistent(self): r = {} self.assertRaises(KeyError, parse_reftuples, r, r, [b"thisdoesnotexist"]) def test_head(self): r = {b"refs/heads/foo": "bla"} self.assertEqual([(b"refs/heads/foo", b"refs/heads/foo", False)], parse_reftuples(r, r, [b"foo"])) def test_full(self): r = {b"refs/heads/foo": "bla"} self.assertEqual([(b"refs/heads/foo", b"refs/heads/foo", False)], parse_reftuples(r, r, b"refs/heads/foo")) + r = {b"refs/heads/foo": "bla"} + self.assertEqual([(b"refs/heads/foo", b"refs/heads/foo", True)], + parse_reftuples(r, r, b"refs/heads/foo", True)) class ParseTreeTests(TestCase): """Test parse_tree.""" def test_nonexistent(self): r = MemoryRepo() self.assertRaises(KeyError, parse_tree, r, "thisdoesnotexist") def test_from_commit(self): r = MemoryRepo() c1, c2, c3 = build_commit_graph( r.object_store, [[1], [2, 1], [3, 1, 2]]) self.assertEqual(r[c1.tree], parse_tree(r, c1.id)) self.assertEqual(r[c1.tree], parse_tree(r, c1.tree)) diff --git a/dulwich/tests/test_porcelain.py b/dulwich/tests/test_porcelain.py index f68220a3..d41385fb 100644 --- a/dulwich/tests/test_porcelain.py +++ b/dulwich/tests/test_porcelain.py @@ -1,1858 +1,1941 @@ # 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, StringIO 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 FileExistsError: pass 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, + porcelain.Error, 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) self.assertEqual( set(['foo', 'blah', 'adir', '.git']), set(os.listdir('.'))) self.assertEqual( (['foo', os.path.join('adir', 'afile')], set()), 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, FileNotFoundError), 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') + self.assertRaises( + porcelain.Error, 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, 'origin', b"HEAD:" + refs_path, outstream=outstream, errstream=errstream) self.assertEqual( target_repo.refs[b'refs/remotes/origin/foo'], target_repo.refs[b'HEAD']) # 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()) + def test_diverged(self): + 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() + + remote_id = porcelain.commit( + repo=self.repo.path, message=b'remote change', + author=b'author ', + committer=b'committer ') + + local_id = porcelain.commit( + repo=clone_path, message=b'local change', + author=b'author ', + committer=b'committer ') + + # Push to the remote + self.assertRaises( + porcelain.DivergedBranches, + porcelain.push, clone_path, self.repo.path, b'refs/heads/master', + outstream=outstream, errstream=errstream) + + self.assertEqual({ + b'HEAD': remote_id, + b'refs/heads/master': remote_id, + }, self.repo.get_refs()) + + # Push to the remote with --force + porcelain.push( + clone_path, self.repo.path, b'refs/heads/master', + outstream=outstream, errstream=errstream, force=True) + + self.assertEqual({ + b'HEAD': local_id, + b'refs/heads/master': local_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) + self.assertIn(b'refs/heads/master', self.repo.refs) + self.assertIn(b'refs/heads/master', 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_diverged(self): + outstream = BytesIO() + errstream = BytesIO() + + c3a = porcelain.commit( + repo=self.target_path, message=b'test3a', + author=b'test2 ', + committer=b'test2 ') + + porcelain.commit( + repo=self.repo.path, message=b'test3b', + author=b'test2 ', + committer=b'test2 ') + + # Pull changes into the cloned repo + self.assertRaises( + porcelain.DivergedBranches, 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'refs/heads/master'].id, c3a) + + self.assertRaises( + NotImplementedError, porcelain.pull, + self.target_path, self.repo.path, + b'refs/heads/master', outstream=outstream, errstream=errstream, + fast_forward=False) + + # Check the target repo for pushed changes + with Repo(self.target_path) as r: + self.assertEqual(r[b'refs/heads/master'].id, c3a) + 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) def test_no_remote_location(self): outstream = BytesIO() errstream = BytesIO() # Pull changes into the cloned repo porcelain.pull(self.target_path, refspecs=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) 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") + self.assertRaises( + porcelain.Error, 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, 'origin', 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 = '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_config = target_repo.get_config() target_config.set( (b'remote', remote_name.encode()), b'url', self.repo.path.encode()) target_repo.close() # Fetch changes into the cloned repo porcelain.fetch(target_path, 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 PathToTreeTests(PorcelainTestCase): def setUp(self): super(PathToTreeTests, self).setUp() self.fp = os.path.join(self.test_dir, 'bar') with open(self.fp, 'w') as f: f.write('something') oldcwd = os.getcwd() self.addCleanup(os.chdir, oldcwd) os.chdir(self.test_dir) def test_path_to_tree_path_base(self): self.assertEqual( b'bar', porcelain.path_to_tree_path(self.test_dir, self.fp)) 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('.', './bar')) def test_path_to_tree_path_error(self): with self.assertRaises(ValueError): with tempfile.TemporaryDirectory() as od: porcelain.path_to_tree_path(od, self.fp) 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')) with open('baz', 'w') as f: f.write('contents') 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): 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/dulwich/tests/test_server.py b/dulwich/tests/test_server.py index c726d694..f26f52d0 100644 --- a/dulwich/tests/test_server.py +++ b/dulwich/tests/test_server.py @@ -1,1112 +1,1143 @@ # test_server.py -- Tests for the git server # 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. # """Tests for the smart protocol server.""" from io import BytesIO import os import shutil import tempfile import sys from dulwich.errors import ( GitProtocolError, NotGitRepository, UnexpectedCommandError, HangupException, ) +from dulwich.objects import Tree from dulwich.object_store import ( MemoryObjectStore, ) from dulwich.repo import ( MemoryRepo, Repo, ) from dulwich.server import ( Backend, DictBackend, FileSystemBackend, MultiAckGraphWalkerImpl, MultiAckDetailedGraphWalkerImpl, PackHandler, _split_proto_line, serve_command, _find_shallow, _ProtocolGraphWalker, ReceivePackHandler, SingleAckGraphWalkerImpl, UploadPackHandler, update_server_info, ) from dulwich.tests import TestCase from dulwich.tests.utils import ( make_commit, make_tag, ) from dulwich.protocol import ( ZERO_SHA, ) ONE = b'1' * 40 TWO = b'2' * 40 THREE = b'3' * 40 FOUR = b'4' * 40 FIVE = b'5' * 40 SIX = b'6' * 40 class TestProto(object): def __init__(self): self._output = [] self._received = {0: [], 1: [], 2: [], 3: []} def set_output(self, output_lines): self._output = output_lines def read_pkt_line(self): if self._output: data = self._output.pop(0) if data is not None: return data.rstrip() + b'\n' else: # flush-pkt ('0000'). return None else: raise HangupException() def write_sideband(self, band, data): self._received[band].append(data) def write_pkt_line(self, data): self._received[0].append(data) def get_received_line(self, band=0): lines = self._received[band] return lines.pop(0) class TestGenericPackHandler(PackHandler): def __init__(self): PackHandler.__init__(self, Backend(), None) @classmethod def capabilities(cls): return [b'cap1', b'cap2', b'cap3'] @classmethod def required_capabilities(cls): return [b'cap2'] class HandlerTestCase(TestCase): def setUp(self): super(HandlerTestCase, self).setUp() self._handler = TestGenericPackHandler() def assertSucceeds(self, func, *args, **kwargs): try: func(*args, **kwargs) except GitProtocolError as e: self.fail(e) def test_capability_line(self): self.assertEqual( b' cap1 cap2 cap3', self._handler.capability_line([b'cap1', b'cap2', b'cap3'])) def test_set_client_capabilities(self): set_caps = self._handler.set_client_capabilities self.assertSucceeds(set_caps, [b'cap2']) self.assertSucceeds(set_caps, [b'cap1', b'cap2']) # different order self.assertSucceeds(set_caps, [b'cap3', b'cap1', b'cap2']) # error cases self.assertRaises(GitProtocolError, set_caps, [b'capxxx', b'cap2']) self.assertRaises(GitProtocolError, set_caps, [b'cap1', b'cap3']) # ignore innocuous but unknown capabilities self.assertRaises(GitProtocolError, set_caps, [b'cap2', b'ignoreme']) self.assertFalse(b'ignoreme' in self._handler.capabilities()) self._handler.innocuous_capabilities = lambda: (b'ignoreme',) self.assertSucceeds(set_caps, [b'cap2', b'ignoreme']) def test_has_capability(self): self.assertRaises(GitProtocolError, self._handler.has_capability, b'cap') caps = self._handler.capabilities() self._handler.set_client_capabilities(caps) for cap in caps: self.assertTrue(self._handler.has_capability(cap)) self.assertFalse(self._handler.has_capability(b'capxxx')) class UploadPackHandlerTestCase(TestCase): def setUp(self): super(UploadPackHandlerTestCase, self).setUp() self._repo = MemoryRepo.init_bare([], {}) backend = DictBackend({b'/': self._repo}) self._handler = UploadPackHandler( backend, [b'/', b'host=lolcathost'], TestProto()) def test_progress(self): caps = self._handler.required_capabilities() self._handler.set_client_capabilities(caps) self._handler.progress(b'first message') self._handler.progress(b'second message') self.assertEqual(b'first message', self._handler.proto.get_received_line(2)) self.assertEqual(b'second message', self._handler.proto.get_received_line(2)) self.assertRaises(IndexError, self._handler.proto.get_received_line, 2) def test_no_progress(self): caps = list(self._handler.required_capabilities()) + [b'no-progress'] self._handler.set_client_capabilities(caps) self._handler.progress(b'first message') self._handler.progress(b'second message') self.assertRaises(IndexError, self._handler.proto.get_received_line, 2) def test_get_tagged(self): refs = { b'refs/tags/tag1': ONE, b'refs/tags/tag2': TWO, b'refs/heads/master': FOUR, # not a tag, no peeled value } # repo needs to peel this object self._repo.object_store.add_object(make_commit(id=FOUR)) self._repo.refs._update(refs) peeled = { b'refs/tags/tag1': b'1234' * 10, b'refs/tags/tag2': b'5678' * 10, } self._repo.refs._update_peeled(peeled) caps = list(self._handler.required_capabilities()) + [b'include-tag'] self._handler.set_client_capabilities(caps) self.assertEqual({b'1234' * 10: ONE, b'5678' * 10: TWO}, self._handler.get_tagged(refs, repo=self._repo)) # non-include-tag case caps = self._handler.required_capabilities() self._handler.set_client_capabilities(caps) self.assertEqual({}, self._handler.get_tagged(refs, repo=self._repo)) + def test_nothing_to_do_but_wants(self): + # Just the fact that the client claims to want an object is enough + # for sending a pack. Even if there turns out to be nothing. + refs = {b'refs/tags/tag1': ONE} + tree = Tree() + self._repo.object_store.add_object(tree) + self._repo.object_store.add_object(make_commit(id=ONE, tree=tree)) + self._repo.refs._update(refs) + self._handler.proto.set_output( + [b'want ' + ONE + b' side-band-64k thin-pack ofs-delta', + None, b'have ' + ONE, b'done', None]) + self._handler.handle() + # The server should always send a pack, even if it's empty. + self.assertTrue( + self._handler.proto.get_received_line(1).startswith(b'PACK')) + + def test_nothing_to_do_no_wants(self): + # Don't send a pack if the client didn't ask for anything. + refs = {b'refs/tags/tag1': ONE} + tree = Tree() + self._repo.object_store.add_object(tree) + self._repo.object_store.add_object(make_commit(id=ONE, tree=tree)) + self._repo.refs._update(refs) + self._handler.proto.set_output([None]) + self._handler.handle() + # The server should not send a pack, since the client didn't ask for + # anything. + self.assertEqual([], self._handler.proto._received[1]) + class FindShallowTests(TestCase): def setUp(self): super(FindShallowTests, self).setUp() self._store = MemoryObjectStore() def make_commit(self, **attrs): commit = make_commit(**attrs) self._store.add_object(commit) return commit def make_linear_commits(self, n, message=b''): commits = [] parents = [] for _ in range(n): commits.append(self.make_commit(parents=parents, message=message)) parents = [commits[-1].id] return commits def assertSameElements(self, expected, actual): self.assertEqual(set(expected), set(actual)) def test_linear(self): c1, c2, c3 = self.make_linear_commits(3) self.assertEqual((set([c3.id]), set([])), _find_shallow(self._store, [c3.id], 1)) self.assertEqual((set([c2.id]), set([c3.id])), _find_shallow(self._store, [c3.id], 2)) self.assertEqual((set([c1.id]), set([c2.id, c3.id])), _find_shallow(self._store, [c3.id], 3)) self.assertEqual((set([]), set([c1.id, c2.id, c3.id])), _find_shallow(self._store, [c3.id], 4)) def test_multiple_independent(self): a = self.make_linear_commits(2, message=b'a') b = self.make_linear_commits(2, message=b'b') c = self.make_linear_commits(2, message=b'c') heads = [a[1].id, b[1].id, c[1].id] self.assertEqual((set([a[0].id, b[0].id, c[0].id]), set(heads)), _find_shallow(self._store, heads, 2)) def test_multiple_overlapping(self): # Create the following commit tree: # 1--2 # \ # 3--4 c1, c2 = self.make_linear_commits(2) c3 = self.make_commit(parents=[c1.id]) c4 = self.make_commit(parents=[c3.id]) # 1 is shallow along the path from 4, but not along the path from 2. self.assertEqual((set([c1.id]), set([c1.id, c2.id, c3.id, c4.id])), _find_shallow(self._store, [c2.id, c4.id], 3)) def test_merge(self): c1 = self.make_commit() c2 = self.make_commit() c3 = self.make_commit(parents=[c1.id, c2.id]) self.assertEqual((set([c1.id, c2.id]), set([c3.id])), _find_shallow(self._store, [c3.id], 2)) def test_tag(self): c1, c2 = self.make_linear_commits(2) tag = make_tag(c2, name=b'tag') self._store.add_object(tag) self.assertEqual((set([c1.id]), set([c2.id])), _find_shallow(self._store, [tag.id], 2)) class TestUploadPackHandler(UploadPackHandler): @classmethod def required_capabilities(self): return [] class ReceivePackHandlerTestCase(TestCase): def setUp(self): super(ReceivePackHandlerTestCase, self).setUp() self._repo = MemoryRepo.init_bare([], {}) backend = DictBackend({b'/': self._repo}) self._handler = ReceivePackHandler( backend, [b'/', b'host=lolcathost'], TestProto()) def test_apply_pack_del_ref(self): refs = { b'refs/heads/master': TWO, b'refs/heads/fake-branch': ONE} self._repo.refs._update(refs) update_refs = [[ONE, ZERO_SHA, b'refs/heads/fake-branch'], ] self._handler.set_client_capabilities([b'delete-refs']) status = self._handler._apply_pack(update_refs) self.assertEqual(status[0][0], b'unpack') self.assertEqual(status[0][1], b'ok') self.assertEqual(status[1][0], b'refs/heads/fake-branch') self.assertEqual(status[1][1], b'ok') class ProtocolGraphWalkerEmptyTestCase(TestCase): + def setUp(self): super(ProtocolGraphWalkerEmptyTestCase, self).setUp() self._repo = MemoryRepo.init_bare([], {}) backend = DictBackend({b'/': self._repo}) self._walker = _ProtocolGraphWalker( TestUploadPackHandler(backend, [b'/', b'host=lolcats'], TestProto()), self._repo.object_store, self._repo.get_peeled, self._repo.refs.get_symrefs) def test_empty_repository(self): # The server should wait for a flush packet. self._walker.proto.set_output([]) self.assertRaises(HangupException, self._walker.determine_wants, {}) self.assertEqual(None, self._walker.proto.get_received_line()) self._walker.proto.set_output([None]) self.assertEqual([], self._walker.determine_wants({})) self.assertEqual(None, self._walker.proto.get_received_line()) class ProtocolGraphWalkerTestCase(TestCase): def setUp(self): super(ProtocolGraphWalkerTestCase, self).setUp() # Create the following commit tree: # 3---5 # / # 1---2---4 commits = [ make_commit(id=ONE, parents=[], commit_time=111), make_commit(id=TWO, parents=[ONE], commit_time=222), make_commit(id=THREE, parents=[ONE], commit_time=333), make_commit(id=FOUR, parents=[TWO], commit_time=444), make_commit(id=FIVE, parents=[THREE], commit_time=555), ] self._repo = MemoryRepo.init_bare(commits, {}) backend = DictBackend({b'/': self._repo}) self._walker = _ProtocolGraphWalker( TestUploadPackHandler(backend, [b'/', b'host=lolcats'], TestProto()), self._repo.object_store, self._repo.get_peeled, self._repo.refs.get_symrefs) def test_all_wants_satisfied_no_haves(self): self._walker.set_wants([ONE]) self.assertFalse(self._walker.all_wants_satisfied([])) self._walker.set_wants([TWO]) self.assertFalse(self._walker.all_wants_satisfied([])) self._walker.set_wants([THREE]) self.assertFalse(self._walker.all_wants_satisfied([])) def test_all_wants_satisfied_have_root(self): self._walker.set_wants([ONE]) self.assertTrue(self._walker.all_wants_satisfied([ONE])) self._walker.set_wants([TWO]) self.assertTrue(self._walker.all_wants_satisfied([ONE])) self._walker.set_wants([THREE]) self.assertTrue(self._walker.all_wants_satisfied([ONE])) def test_all_wants_satisfied_have_branch(self): self._walker.set_wants([TWO]) self.assertTrue(self._walker.all_wants_satisfied([TWO])) # wrong branch self._walker.set_wants([THREE]) self.assertFalse(self._walker.all_wants_satisfied([TWO])) def test_all_wants_satisfied(self): self._walker.set_wants([FOUR, FIVE]) # trivial case: wants == haves self.assertTrue(self._walker.all_wants_satisfied([FOUR, FIVE])) # cases that require walking the commit tree self.assertTrue(self._walker.all_wants_satisfied([ONE])) self.assertFalse(self._walker.all_wants_satisfied([TWO])) self.assertFalse(self._walker.all_wants_satisfied([THREE])) self.assertTrue(self._walker.all_wants_satisfied([TWO, THREE])) def test_split_proto_line(self): allowed = (b'want', b'done', None) self.assertEqual((b'want', ONE), _split_proto_line(b'want ' + ONE + b'\n', allowed)) self.assertEqual((b'want', TWO), _split_proto_line(b'want ' + TWO + b'\n', allowed)) self.assertRaises(GitProtocolError, _split_proto_line, b'want xxxx\n', allowed) self.assertRaises(UnexpectedCommandError, _split_proto_line, b'have ' + THREE + b'\n', allowed) self.assertRaises(GitProtocolError, _split_proto_line, b'foo ' + FOUR + b'\n', allowed) self.assertRaises(GitProtocolError, _split_proto_line, b'bar', allowed) self.assertEqual((b'done', None), _split_proto_line(b'done\n', allowed)) self.assertEqual((None, None), _split_proto_line(b'', allowed)) def test_determine_wants(self): self._walker.proto.set_output([None]) self.assertEqual([], self._walker.determine_wants({})) self.assertEqual(None, self._walker.proto.get_received_line()) self._walker.proto.set_output([ b'want ' + ONE + b' multi_ack', b'want ' + TWO, None, ]) heads = { b'refs/heads/ref1': ONE, b'refs/heads/ref2': TWO, b'refs/heads/ref3': THREE, } self._repo.refs._update(heads) self.assertEqual([ONE, TWO], self._walker.determine_wants(heads)) self._walker.advertise_refs = True self.assertEqual([], self._walker.determine_wants(heads)) self._walker.advertise_refs = False self._walker.proto.set_output([b'want ' + FOUR + b' multi_ack', None]) self.assertRaises(GitProtocolError, self._walker.determine_wants, heads) self._walker.proto.set_output([None]) self.assertEqual([], self._walker.determine_wants(heads)) self._walker.proto.set_output( [b'want ' + ONE + b' multi_ack', b'foo', None]) self.assertRaises(GitProtocolError, self._walker.determine_wants, heads) self._walker.proto.set_output([b'want ' + FOUR + b' multi_ack', None]) self.assertRaises(GitProtocolError, self._walker.determine_wants, heads) def test_determine_wants_advertisement(self): self._walker.proto.set_output([None]) # advertise branch tips plus tag heads = { b'refs/heads/ref4': FOUR, b'refs/heads/ref5': FIVE, b'refs/heads/tag6': SIX, } self._repo.refs._update(heads) self._repo.refs._update_peeled(heads) self._repo.refs._update_peeled({b'refs/heads/tag6': FIVE}) self._walker.determine_wants(heads) lines = [] while True: line = self._walker.proto.get_received_line() if line is None: break # strip capabilities list if present if b'\x00' in line: line = line[:line.index(b'\x00')] lines.append(line.rstrip()) self.assertEqual([ FOUR + b' refs/heads/ref4', FIVE + b' refs/heads/ref5', FIVE + b' refs/heads/tag6^{}', SIX + b' refs/heads/tag6', ], sorted(lines)) # ensure peeled tag was advertised immediately following tag for i, line in enumerate(lines): if line.endswith(b' refs/heads/tag6'): self.assertEqual(FIVE + b' refs/heads/tag6^{}', lines[i+1]) # TODO: test commit time cutoff def _handle_shallow_request(self, lines, heads): self._walker.proto.set_output(lines + [None]) self._walker._handle_shallow_request(heads) def assertReceived(self, expected): self.assertEqual( expected, list(iter(self._walker.proto.get_received_line, None))) def test_handle_shallow_request_no_client_shallows(self): self._handle_shallow_request([b'deepen 2\n'], [FOUR, FIVE]) self.assertEqual(set([TWO, THREE]), self._walker.shallow) self.assertReceived([ b'shallow ' + TWO, b'shallow ' + THREE, ]) def test_handle_shallow_request_no_new_shallows(self): lines = [ b'shallow ' + TWO + b'\n', b'shallow ' + THREE + b'\n', b'deepen 2\n', ] self._handle_shallow_request(lines, [FOUR, FIVE]) self.assertEqual(set([TWO, THREE]), self._walker.shallow) self.assertReceived([]) def test_handle_shallow_request_unshallows(self): lines = [ b'shallow ' + TWO + b'\n', b'deepen 3\n', ] self._handle_shallow_request(lines, [FOUR, FIVE]) self.assertEqual(set([ONE]), self._walker.shallow) self.assertReceived([ b'shallow ' + ONE, b'unshallow ' + TWO, # THREE is unshallow but was is not shallow in the client ]) class TestProtocolGraphWalker(object): def __init__(self): self.acks = [] self.lines = [] self.wants_satisified = False - self.http_req = None + self.stateless_rpc = None self.advertise_refs = False self._impl = None self.done_required = True self.done_received = False self._empty = False self.pack_sent = False def read_proto_line(self, allowed): command, sha = self.lines.pop(0) if allowed is not None: assert command in allowed return command, sha def send_ack(self, sha, ack_type=b''): self.acks.append((sha, ack_type)) def send_nak(self): self.acks.append((None, b'nak')) def all_wants_satisfied(self, haves): if haves: return self.wants_satisified def pop_ack(self): if not self.acks: return None return self.acks.pop(0) def handle_done(self): if not self._impl: return # Whether or not PACK is sent after is determined by this, so # record this value. self.pack_sent = self._impl.handle_done( self.done_required, self.done_received) return self.pack_sent def notify_done(self): self.done_received = True class AckGraphWalkerImplTestCase(TestCase): """Base setup and asserts for AckGraphWalker tests.""" def setUp(self): super(AckGraphWalkerImplTestCase, self).setUp() self._walker = TestProtocolGraphWalker() self._walker.lines = [ (b'have', TWO), (b'have', ONE), (b'have', THREE), (b'done', None), ] self._impl = self.impl_cls(self._walker) self._walker._impl = self._impl def assertNoAck(self): self.assertEqual(None, self._walker.pop_ack()) def assertAcks(self, acks): for sha, ack_type in acks: self.assertEqual((sha, ack_type), self._walker.pop_ack()) self.assertNoAck() def assertAck(self, sha, ack_type=b''): self.assertAcks([(sha, ack_type)]) def assertNak(self): self.assertAck(None, b'nak') def assertNextEquals(self, sha): self.assertEqual(sha, next(self._impl)) def assertNextEmpty(self): # This is necessary because of no-done - the assumption that it # it safe to immediately send out the final ACK is no longer # true but the test is still needed for it. TestProtocolWalker # does implement the handle_done which will determine whether # the final confirmation can be sent. self.assertRaises(IndexError, next, self._impl) self._walker.handle_done() class SingleAckGraphWalkerImplTestCase(AckGraphWalkerImplTestCase): impl_cls = SingleAckGraphWalkerImpl def test_single_ack(self): self.assertNextEquals(TWO) self.assertNoAck() self.assertNextEquals(ONE) self._impl.ack(ONE) self.assertAck(ONE) self.assertNextEquals(THREE) self._impl.ack(THREE) self.assertNoAck() self.assertNextEquals(None) self.assertNoAck() def test_single_ack_flush(self): # same as ack test but ends with a flush-pkt instead of done self._walker.lines[-1] = (None, None) self.assertNextEquals(TWO) self.assertNoAck() self.assertNextEquals(ONE) self._impl.ack(ONE) self.assertAck(ONE) self.assertNextEquals(THREE) self.assertNoAck() self.assertNextEquals(None) self.assertNoAck() def test_single_ack_nak(self): self.assertNextEquals(TWO) self.assertNoAck() self.assertNextEquals(ONE) self.assertNoAck() self.assertNextEquals(THREE) self.assertNoAck() self.assertNextEquals(None) self.assertNextEmpty() self.assertNak() def test_single_ack_nak_flush(self): # same as nak test but ends with a flush-pkt instead of done self._walker.lines[-1] = (None, None) self.assertNextEquals(TWO) self.assertNoAck() self.assertNextEquals(ONE) self.assertNoAck() self.assertNextEquals(THREE) self.assertNoAck() self.assertNextEquals(None) self.assertNextEmpty() self.assertNak() class MultiAckGraphWalkerImplTestCase(AckGraphWalkerImplTestCase): impl_cls = MultiAckGraphWalkerImpl def test_multi_ack(self): self.assertNextEquals(TWO) self.assertNoAck() self.assertNextEquals(ONE) self._impl.ack(ONE) self.assertAck(ONE, b'continue') self.assertNextEquals(THREE) self._impl.ack(THREE) self.assertAck(THREE, b'continue') self.assertNextEquals(None) self.assertNextEmpty() self.assertAck(THREE) def test_multi_ack_partial(self): self.assertNextEquals(TWO) self.assertNoAck() self.assertNextEquals(ONE) self._impl.ack(ONE) self.assertAck(ONE, b'continue') self.assertNextEquals(THREE) self.assertNoAck() self.assertNextEquals(None) self.assertNextEmpty() self.assertAck(ONE) def test_multi_ack_flush(self): self._walker.lines = [ (b'have', TWO), (None, None), (b'have', ONE), (b'have', THREE), (b'done', None), ] self.assertNextEquals(TWO) self.assertNoAck() self.assertNextEquals(ONE) self.assertNak() # nak the flush-pkt self._impl.ack(ONE) self.assertAck(ONE, b'continue') self.assertNextEquals(THREE) self._impl.ack(THREE) self.assertAck(THREE, b'continue') self.assertNextEquals(None) self.assertNextEmpty() self.assertAck(THREE) def test_multi_ack_nak(self): self.assertNextEquals(TWO) self.assertNoAck() self.assertNextEquals(ONE) self.assertNoAck() self.assertNextEquals(THREE) self.assertNoAck() self.assertNextEquals(None) self.assertNextEmpty() self.assertNak() class MultiAckDetailedGraphWalkerImplTestCase(AckGraphWalkerImplTestCase): impl_cls = MultiAckDetailedGraphWalkerImpl def test_multi_ack(self): self.assertNextEquals(TWO) self.assertNoAck() self.assertNextEquals(ONE) self._impl.ack(ONE) self.assertAck(ONE, b'common') self.assertNextEquals(THREE) self._impl.ack(THREE) self.assertAck(THREE, b'common') # done is read. self._walker.wants_satisified = True self.assertNextEquals(None) self._walker.lines.append((None, None)) self.assertNextEmpty() self.assertAcks([(THREE, b'ready'), (None, b'nak'), (THREE, b'')]) # PACK is sent self.assertTrue(self._walker.pack_sent) def test_multi_ack_nodone(self): self._walker.done_required = False self.assertNextEquals(TWO) self.assertNoAck() self.assertNextEquals(ONE) self._impl.ack(ONE) self.assertAck(ONE, b'common') self.assertNextEquals(THREE) self._impl.ack(THREE) self.assertAck(THREE, b'common') # done is read. self._walker.wants_satisified = True self.assertNextEquals(None) self._walker.lines.append((None, None)) self.assertNextEmpty() self.assertAcks([(THREE, b'ready'), (None, b'nak'), (THREE, b'')]) # PACK is sent self.assertTrue(self._walker.pack_sent) def test_multi_ack_flush_end(self): # transmission ends with a flush-pkt without a done but no-done is # assumed. self._walker.lines[-1] = (None, None) self.assertNextEquals(TWO) self.assertNoAck() self.assertNextEquals(ONE) self._impl.ack(ONE) self.assertAck(ONE, b'common') self.assertNextEquals(THREE) self._impl.ack(THREE) self.assertAck(THREE, b'common') # no done is read self._walker.wants_satisified = True self.assertNextEmpty() self.assertAcks([(THREE, b'ready'), (None, b'nak')]) # PACK is NOT sent self.assertFalse(self._walker.pack_sent) def test_multi_ack_flush_end_nodone(self): # transmission ends with a flush-pkt without a done but no-done is # assumed. self._walker.lines[-1] = (None, None) self._walker.done_required = False self.assertNextEquals(TWO) self.assertNoAck() self.assertNextEquals(ONE) self._impl.ack(ONE) self.assertAck(ONE, b'common') self.assertNextEquals(THREE) self._impl.ack(THREE) self.assertAck(THREE, b'common') # no done is read, but pretend it is (last 'ACK 'commit_id' '') self._walker.wants_satisified = True self.assertNextEmpty() self.assertAcks([(THREE, b'ready'), (None, b'nak'), (THREE, b'')]) # PACK is sent self.assertTrue(self._walker.pack_sent) def test_multi_ack_partial(self): self.assertNextEquals(TWO) self.assertNoAck() self.assertNextEquals(ONE) self._impl.ack(ONE) self.assertAck(ONE, b'common') self.assertNextEquals(THREE) self.assertNoAck() self.assertNextEquals(None) self.assertNextEmpty() self.assertAck(ONE) def test_multi_ack_flush(self): # same as ack test but contains a flush-pkt in the middle self._walker.lines = [ (b'have', TWO), (None, None), (b'have', ONE), (b'have', THREE), (b'done', None), (None, None), ] self.assertNextEquals(TWO) self.assertNoAck() self.assertNextEquals(ONE) self.assertNak() # nak the flush-pkt self._impl.ack(ONE) self.assertAck(ONE, b'common') self.assertNextEquals(THREE) self._impl.ack(THREE) self.assertAck(THREE, b'common') self._walker.wants_satisified = True self.assertNextEquals(None) self.assertNextEmpty() self.assertAcks([(THREE, b'ready'), (None, b'nak'), (THREE, b'')]) def test_multi_ack_nak(self): self.assertNextEquals(TWO) self.assertNoAck() self.assertNextEquals(ONE) self.assertNoAck() self.assertNextEquals(THREE) self.assertNoAck() # Done is sent here. self.assertNextEquals(None) self.assertNextEmpty() self.assertNak() self.assertNextEmpty() self.assertTrue(self._walker.pack_sent) def test_multi_ack_nak_nodone(self): self._walker.done_required = False self.assertNextEquals(TWO) self.assertNoAck() self.assertNextEquals(ONE) self.assertNoAck() self.assertNextEquals(THREE) self.assertNoAck() # Done is sent here. self.assertFalse(self._walker.pack_sent) self.assertNextEquals(None) self.assertNextEmpty() self.assertTrue(self._walker.pack_sent) self.assertNak() self.assertNextEmpty() def test_multi_ack_nak_flush(self): # same as nak test but contains a flush-pkt in the middle self._walker.lines = [ (b'have', TWO), (None, None), (b'have', ONE), (b'have', THREE), (b'done', None), ] self.assertNextEquals(TWO) self.assertNoAck() self.assertNextEquals(ONE) self.assertNak() self.assertNextEquals(THREE) self.assertNoAck() self.assertNextEquals(None) self.assertNextEmpty() self.assertNak() def test_multi_ack_stateless(self): # transmission ends with a flush-pkt self._walker.lines[-1] = (None, None) - self._walker.http_req = True + self._walker.stateless_rpc = True self.assertNextEquals(TWO) self.assertNoAck() self.assertNextEquals(ONE) self.assertNoAck() self.assertNextEquals(THREE) self.assertNoAck() self.assertFalse(self._walker.pack_sent) self.assertNextEquals(None) self.assertNak() self.assertNextEmpty() self.assertNoAck() self.assertFalse(self._walker.pack_sent) def test_multi_ack_stateless_nodone(self): self._walker.done_required = False # transmission ends with a flush-pkt self._walker.lines[-1] = (None, None) - self._walker.http_req = True + self._walker.stateless_rpc = True self.assertNextEquals(TWO) self.assertNoAck() self.assertNextEquals(ONE) self.assertNoAck() self.assertNextEquals(THREE) self.assertNoAck() self.assertFalse(self._walker.pack_sent) self.assertNextEquals(None) self.assertNak() self.assertNextEmpty() self.assertNoAck() # PACK will still not be sent. self.assertFalse(self._walker.pack_sent) class FileSystemBackendTests(TestCase): """Tests for FileSystemBackend.""" def setUp(self): super(FileSystemBackendTests, self).setUp() self.path = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, self.path) self.repo = Repo.init(self.path) if sys.platform == 'win32': self.backend = FileSystemBackend(self.path[0] + ':' + os.sep) else: self.backend = FileSystemBackend() def test_nonexistant(self): self.assertRaises(NotGitRepository, self.backend.open_repository, "/does/not/exist/unless/foo") def test_absolute(self): repo = self.backend.open_repository(self.path) self.assertTrue(os.path.samefile( os.path.abspath(repo.path), os.path.abspath(self.repo.path))) def test_child(self): self.assertRaises( NotGitRepository, self.backend.open_repository, os.path.join(self.path, "foo")) def test_bad_repo_path(self): backend = FileSystemBackend() self.assertRaises(NotGitRepository, lambda: backend.open_repository('/ups')) class DictBackendTests(TestCase): """Tests for DictBackend.""" def test_nonexistant(self): repo = MemoryRepo.init_bare([], {}) backend = DictBackend({b'/': repo}) self.assertRaises( NotGitRepository, backend.open_repository, "/does/not/exist/unless/foo") def test_bad_repo_path(self): repo = MemoryRepo.init_bare([], {}) backend = DictBackend({b'/': repo}) self.assertRaises(NotGitRepository, lambda: backend.open_repository('/ups')) class ServeCommandTests(TestCase): """Tests for serve_command.""" def setUp(self): super(ServeCommandTests, self).setUp() self.backend = DictBackend({}) def serve_command(self, handler_cls, args, inf, outf): return serve_command( handler_cls, [b"test"] + args, backend=self.backend, inf=inf, outf=outf) def test_receive_pack(self): commit = make_commit(id=ONE, parents=[], commit_time=111) self.backend.repos[b"/"] = MemoryRepo.init_bare( [commit], {b"refs/heads/master": commit.id}) outf = BytesIO() exitcode = self.serve_command(ReceivePackHandler, [b"/"], BytesIO(b"0000"), outf) outlines = outf.getvalue().splitlines() self.assertEqual(2, len(outlines)) self.assertEqual( b"1111111111111111111111111111111111111111 refs/heads/master", outlines[0][4:].split(b"\x00")[0]) self.assertEqual(b"0000", outlines[-1]) self.assertEqual(0, exitcode) class UpdateServerInfoTests(TestCase): """Tests for update_server_info.""" def setUp(self): super(UpdateServerInfoTests, self).setUp() self.path = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, self.path) self.repo = Repo.init(self.path) def test_empty(self): update_server_info(self.repo) with open(os.path.join(self.path, ".git", "info", "refs"), 'rb') as f: self.assertEqual(b'', f.read()) p = os.path.join(self.path, ".git", "objects", "info", "packs") with open(p, 'rb') as f: self.assertEqual(b'', f.read()) def test_simple(self): commit_id = self.repo.do_commit( message=b"foo", committer=b"Joe Example ", ref=b"refs/heads/foo") update_server_info(self.repo) with open(os.path.join(self.path, ".git", "info", "refs"), 'rb') as f: self.assertEqual(f.read(), commit_id + b'\trefs/heads/foo\n') p = os.path.join(self.path, ".git", "objects", "info", "packs") with open(p, 'rb') as f: self.assertEqual(f.read(), b'') diff --git a/dulwich/tests/test_web.py b/dulwich/tests/test_web.py index deff10cc..7d332439 100644 --- a/dulwich/tests/test_web.py +++ b/dulwich/tests/test_web.py @@ -1,573 +1,573 @@ # test_web.py -- Tests for the git HTTP server # 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. # """Tests for the Git HTTP server.""" from io import BytesIO import gzip import re import os from typing import Type from dulwich.object_store import ( MemoryObjectStore, ) from dulwich.objects import ( Blob, ) from dulwich.repo import ( BaseRepo, MemoryRepo, ) from dulwich.server import ( DictBackend, ) from dulwich.tests import ( TestCase, ) from dulwich.web import ( HTTP_OK, HTTP_NOT_FOUND, HTTP_FORBIDDEN, HTTP_ERROR, GunzipFilter, send_file, get_text_file, get_loose_object, get_pack_file, get_idx_file, get_info_refs, get_info_packs, handle_service_request, _LengthLimitedFile, HTTPGitRequest, HTTPGitApplication, ) from dulwich.tests.utils import ( make_object, make_tag, ) class MinimalistWSGIInputStream(object): """WSGI input stream with no 'seek()' and 'tell()' methods.""" def __init__(self, data): self.data = data self.pos = 0 def read(self, howmuch): start = self.pos end = self.pos + howmuch if start >= len(self.data): return '' self.pos = end return self.data[start:end] class MinimalistWSGIInputStream2(MinimalistWSGIInputStream): """WSGI input stream with no *working* 'seek()' and 'tell()' methods.""" def seek(self, pos): raise NotImplementedError def tell(self): raise NotImplementedError class TestHTTPGitRequest(HTTPGitRequest): """HTTPGitRequest with overridden methods to help test caching.""" def __init__(self, *args, **kwargs): HTTPGitRequest.__init__(self, *args, **kwargs) self.cached = None def nocache(self): self.cached = False def cache_forever(self): self.cached = True class WebTestCase(TestCase): """Base TestCase with useful instance vars and utility functions.""" _req_class = TestHTTPGitRequest # type: Type[HTTPGitRequest] def setUp(self): super(WebTestCase, self).setUp() self._environ = {} self._req = self._req_class(self._environ, self._start_response, handlers=self._handlers()) self._status = None self._headers = [] self._output = BytesIO() def _start_response(self, status, headers): self._status = status self._headers = list(headers) return self._output.write def _handlers(self): return None def assertContentTypeEquals(self, expected): self.assertTrue(('Content-Type', expected) in self._headers) def _test_backend(objects, refs=None, named_files=None): if not refs: refs = {} if not named_files: named_files = {} repo = MemoryRepo.init_bare(objects, refs) for path, contents in named_files.items(): repo._put_named_file(path, contents) return DictBackend({'/': repo}) class DumbHandlersTestCase(WebTestCase): def test_send_file_not_found(self): list(send_file(self._req, None, 'text/plain')) self.assertEqual(HTTP_NOT_FOUND, self._status) def test_send_file(self): f = BytesIO(b'foobar') output = b''.join(send_file(self._req, f, 'some/thing')) self.assertEqual(b'foobar', output) self.assertEqual(HTTP_OK, self._status) self.assertContentTypeEquals('some/thing') self.assertTrue(f.closed) def test_send_file_buffered(self): bufsize = 10240 xs = b'x' * bufsize f = BytesIO(2 * xs) self.assertEqual([xs, xs], list(send_file(self._req, f, 'some/thing'))) self.assertEqual(HTTP_OK, self._status) self.assertContentTypeEquals('some/thing') self.assertTrue(f.closed) def test_send_file_error(self): class TestFile(object): def __init__(self, exc_class): self.closed = False self._exc_class = exc_class def read(self, size=-1): raise self._exc_class() def close(self): self.closed = True f = TestFile(IOError) list(send_file(self._req, f, 'some/thing')) self.assertEqual(HTTP_ERROR, self._status) self.assertTrue(f.closed) self.assertFalse(self._req.cached) # non-IOErrors are reraised f = TestFile(AttributeError) self.assertRaises(AttributeError, list, send_file(self._req, f, 'some/thing')) self.assertTrue(f.closed) self.assertFalse(self._req.cached) def test_get_text_file(self): backend = _test_backend([], named_files={'description': b'foo'}) mat = re.search('.*', 'description') output = b''.join(get_text_file(self._req, backend, mat)) self.assertEqual(b'foo', output) self.assertEqual(HTTP_OK, self._status) self.assertContentTypeEquals('text/plain') self.assertFalse(self._req.cached) def test_get_loose_object(self): blob = make_object(Blob, data=b'foo') backend = _test_backend([blob]) mat = re.search('^(..)(.{38})$', blob.id.decode('ascii')) output = b''.join(get_loose_object(self._req, backend, mat)) self.assertEqual(blob.as_legacy_object(), output) self.assertEqual(HTTP_OK, self._status) self.assertContentTypeEquals('application/x-git-loose-object') self.assertTrue(self._req.cached) def test_get_loose_object_missing(self): mat = re.search('^(..)(.{38})$', '1' * 40) list(get_loose_object(self._req, _test_backend([]), mat)) self.assertEqual(HTTP_NOT_FOUND, self._status) def test_get_loose_object_error(self): blob = make_object(Blob, data=b'foo') backend = _test_backend([blob]) mat = re.search('^(..)(.{38})$', blob.id.decode('ascii')) def as_legacy_object_error(self): raise IOError self.addCleanup( setattr, Blob, 'as_legacy_object', Blob.as_legacy_object) Blob.as_legacy_object = as_legacy_object_error list(get_loose_object(self._req, backend, mat)) self.assertEqual(HTTP_ERROR, self._status) def test_get_pack_file(self): pack_name = os.path.join( 'objects', 'pack', 'pack-%s.pack' % ('1' * 40)) backend = _test_backend([], named_files={pack_name: b'pack contents'}) mat = re.search('.*', pack_name) output = b''.join(get_pack_file(self._req, backend, mat)) self.assertEqual(b'pack contents', output) self.assertEqual(HTTP_OK, self._status) self.assertContentTypeEquals('application/x-git-packed-objects') self.assertTrue(self._req.cached) def test_get_idx_file(self): idx_name = os.path.join('objects', 'pack', 'pack-%s.idx' % ('1' * 40)) backend = _test_backend([], named_files={idx_name: b'idx contents'}) mat = re.search('.*', idx_name) output = b''.join(get_idx_file(self._req, backend, mat)) self.assertEqual(b'idx contents', output) self.assertEqual(HTTP_OK, self._status) self.assertContentTypeEquals('application/x-git-packed-objects-toc') self.assertTrue(self._req.cached) def test_get_info_refs(self): self._environ['QUERY_STRING'] = '' blob1 = make_object(Blob, data=b'1') blob2 = make_object(Blob, data=b'2') blob3 = make_object(Blob, data=b'3') tag1 = make_tag(blob2, name=b'tag-tag') objects = [blob1, blob2, blob3, tag1] refs = { b'HEAD': b'000', b'refs/heads/master': blob1.id, b'refs/tags/tag-tag': tag1.id, b'refs/tags/blob-tag': blob3.id, } backend = _test_backend(objects, refs=refs) mat = re.search('.*', '//info/refs') self.assertEqual([blob1.id + b'\trefs/heads/master\n', blob3.id + b'\trefs/tags/blob-tag\n', tag1.id + b'\trefs/tags/tag-tag\n', blob2.id + b'\trefs/tags/tag-tag^{}\n'], list(get_info_refs(self._req, backend, mat))) self.assertEqual(HTTP_OK, self._status) self.assertContentTypeEquals('text/plain') self.assertFalse(self._req.cached) def test_get_info_refs_not_found(self): self._environ['QUERY_STRING'] = '' objects = [] refs = {} backend = _test_backend(objects, refs=refs) mat = re.search('info/refs', '/foo/info/refs') self.assertEqual( [b'No git repository was found at /foo'], list(get_info_refs(self._req, backend, mat))) self.assertEqual(HTTP_NOT_FOUND, self._status) self.assertContentTypeEquals('text/plain') def test_get_info_packs(self): class TestPackData(object): def __init__(self, sha): self.filename = "pack-%s.pack" % sha class TestPack(object): def __init__(self, sha): self.data = TestPackData(sha) packs = [TestPack(str(i) * 40) for i in range(1, 4)] class TestObjectStore(MemoryObjectStore): # property must be overridden, can't be assigned @property def packs(self): return packs store = TestObjectStore() repo = BaseRepo(store, None) backend = DictBackend({'/': repo}) mat = re.search('.*', '//info/packs') output = b''.join(get_info_packs(self._req, backend, mat)) expected = b''.join( [(b'P pack-' + s + b'.pack\n') for s in [b'1' * 40, b'2' * 40, b'3' * 40]]) self.assertEqual(expected, output) self.assertEqual(HTTP_OK, self._status) self.assertContentTypeEquals('text/plain') self.assertFalse(self._req.cached) class SmartHandlersTestCase(WebTestCase): class _TestUploadPackHandler(object): - def __init__(self, backend, args, proto, http_req=None, + def __init__(self, backend, args, proto, stateless_rpc=None, advertise_refs=False): self.args = args self.proto = proto - self.http_req = http_req + self.stateless_rpc = stateless_rpc self.advertise_refs = advertise_refs def handle(self): self.proto.write(b'handled input: ' + self.proto.recv(1024)) def _make_handler(self, *args, **kwargs): self._handler = self._TestUploadPackHandler(*args, **kwargs) return self._handler def _handlers(self): return {b'git-upload-pack': self._make_handler} def test_handle_service_request_unknown(self): mat = re.search('.*', '/git-evil-handler') content = list(handle_service_request(self._req, 'backend', mat)) self.assertEqual(HTTP_FORBIDDEN, self._status) self.assertFalse(b'git-evil-handler' in b"".join(content)) self.assertFalse(self._req.cached) def _run_handle_service_request(self, content_length=None): self._environ['wsgi.input'] = BytesIO(b'foo') if content_length is not None: self._environ['CONTENT_LENGTH'] = content_length mat = re.search('.*', '/git-upload-pack') class Backend(object): def open_repository(self, path): return None handler_output = b''.join( handle_service_request(self._req, Backend(), mat)) write_output = self._output.getvalue() # Ensure all output was written via the write callback. self.assertEqual(b'', handler_output) self.assertEqual(b'handled input: foo', write_output) self.assertContentTypeEquals('application/x-git-upload-pack-result') self.assertFalse(self._handler.advertise_refs) - self.assertTrue(self._handler.http_req) + self.assertTrue(self._handler.stateless_rpc) self.assertFalse(self._req.cached) def test_handle_service_request(self): self._run_handle_service_request() def test_handle_service_request_with_length(self): self._run_handle_service_request(content_length='3') def test_handle_service_request_empty_length(self): self._run_handle_service_request(content_length='') def test_get_info_refs_unknown(self): self._environ['QUERY_STRING'] = 'service=git-evil-handler' class Backend(object): def open_repository(self, url): return None mat = re.search('.*', '/git-evil-pack') content = list(get_info_refs(self._req, Backend(), mat)) self.assertFalse(b'git-evil-handler' in b"".join(content)) self.assertEqual(HTTP_FORBIDDEN, self._status) self.assertFalse(self._req.cached) def test_get_info_refs(self): self._environ['wsgi.input'] = BytesIO(b'foo') self._environ['QUERY_STRING'] = 'service=git-upload-pack' class Backend(object): def open_repository(self, url): return None mat = re.search('.*', '/git-upload-pack') handler_output = b''.join(get_info_refs(self._req, Backend(), mat)) write_output = self._output.getvalue() self.assertEqual((b'001e# service=git-upload-pack\n' b'0000' # input is ignored by the handler b'handled input: '), write_output) # Ensure all output was written via the write callback. self.assertEqual(b'', handler_output) self.assertTrue(self._handler.advertise_refs) - self.assertTrue(self._handler.http_req) + self.assertTrue(self._handler.stateless_rpc) self.assertFalse(self._req.cached) class LengthLimitedFileTestCase(TestCase): def test_no_cutoff(self): f = _LengthLimitedFile(BytesIO(b'foobar'), 1024) self.assertEqual(b'foobar', f.read()) def test_cutoff(self): f = _LengthLimitedFile(BytesIO(b'foobar'), 3) self.assertEqual(b'foo', f.read()) self.assertEqual(b'', f.read()) def test_multiple_reads(self): f = _LengthLimitedFile(BytesIO(b'foobar'), 3) self.assertEqual(b'fo', f.read(2)) self.assertEqual(b'o', f.read(2)) self.assertEqual(b'', f.read()) class HTTPGitRequestTestCase(WebTestCase): # This class tests the contents of the actual cache headers _req_class = HTTPGitRequest def test_not_found(self): self._req.cache_forever() # cache headers should be discarded message = 'Something not found' self.assertEqual(message.encode('ascii'), self._req.not_found(message)) self.assertEqual(HTTP_NOT_FOUND, self._status) self.assertEqual(set([('Content-Type', 'text/plain')]), set(self._headers)) def test_forbidden(self): self._req.cache_forever() # cache headers should be discarded message = 'Something not found' self.assertEqual(message.encode('ascii'), self._req.forbidden(message)) self.assertEqual(HTTP_FORBIDDEN, self._status) self.assertEqual(set([('Content-Type', 'text/plain')]), set(self._headers)) def test_respond_ok(self): self._req.respond() self.assertEqual([], self._headers) self.assertEqual(HTTP_OK, self._status) def test_respond(self): self._req.nocache() self._req.respond(status=402, content_type='some/type', headers=[('X-Foo', 'foo'), ('X-Bar', 'bar')]) self.assertEqual(set([ ('X-Foo', 'foo'), ('X-Bar', 'bar'), ('Content-Type', 'some/type'), ('Expires', 'Fri, 01 Jan 1980 00:00:00 GMT'), ('Pragma', 'no-cache'), ('Cache-Control', 'no-cache, max-age=0, must-revalidate'), ]), set(self._headers)) self.assertEqual(402, self._status) class HTTPGitApplicationTestCase(TestCase): def setUp(self): super(HTTPGitApplicationTestCase, self).setUp() self._app = HTTPGitApplication('backend') self._environ = { 'PATH_INFO': '/foo', 'REQUEST_METHOD': 'GET', } def _test_handler(self, req, backend, mat): # tests interface used by all handlers self.assertEqual(self._environ, req.environ) self.assertEqual('backend', backend) self.assertEqual('/foo', mat.group(0)) return 'output' def _add_handler(self, app): req = self._environ['REQUEST_METHOD'] app.services = { (req, re.compile('/foo$')): self._test_handler, } def test_call(self): self._add_handler(self._app) self.assertEqual('output', self._app(self._environ, None)) def test_fallback_app(self): def test_app(environ, start_response): return 'output' app = HTTPGitApplication('backend', fallback_app=test_app) self.assertEqual('output', app(self._environ, None)) class GunzipTestCase(HTTPGitApplicationTestCase): __doc__ = """TestCase for testing the GunzipFilter, ensuring the wsgi.input is correctly decompressed and headers are corrected. """ example_text = __doc__.encode('ascii') def setUp(self): super(GunzipTestCase, self).setUp() self._app = GunzipFilter(self._app) self._environ['HTTP_CONTENT_ENCODING'] = 'gzip' self._environ['REQUEST_METHOD'] = 'POST' def _get_zstream(self, text): zstream = BytesIO() zfile = gzip.GzipFile(fileobj=zstream, mode='w') zfile.write(text) zfile.close() zlength = zstream.tell() zstream.seek(0) return zstream, zlength def _test_call(self, orig, zstream, zlength): self._add_handler(self._app.app) self.assertLess(zlength, len(orig)) self.assertEqual(self._environ['HTTP_CONTENT_ENCODING'], 'gzip') self._environ['CONTENT_LENGTH'] = zlength self._environ['wsgi.input'] = zstream self._app(self._environ, None) buf = self._environ['wsgi.input'] self.assertIsNot(buf, zstream) buf.seek(0) self.assertEqual(orig, buf.read()) self.assertIs(None, self._environ.get('CONTENT_LENGTH')) self.assertNotIn('HTTP_CONTENT_ENCODING', self._environ) def test_call(self): self._test_call( self.example_text, *self._get_zstream(self.example_text) ) def test_call_no_seek(self): """ This ensures that the gunzipping code doesn't require any methods on 'wsgi.input' except for '.read()'. (In particular, it shouldn't require '.seek()'. See https://github.com/jelmer/dulwich/issues/140.) """ zstream, zlength = self._get_zstream(self.example_text) self._test_call( self.example_text, MinimalistWSGIInputStream(zstream.read()), zlength) def test_call_no_working_seek(self): """ Similar to 'test_call_no_seek', but this time the methods are available (but defunct). See https://github.com/jonashaag/klaus/issues/154. """ zstream, zlength = self._get_zstream(self.example_text) self._test_call( self.example_text, MinimalistWSGIInputStream2(zstream.read()), zlength) diff --git a/dulwich/web.py b/dulwich/web.py index 89816cef..d4d6aa6b 100644 --- a/dulwich/web.py +++ b/dulwich/web.py @@ -1,526 +1,526 @@ # web.py -- WSGI smart-http server # Copyright (C) 2010 Google, Inc. # Copyright (C) 2012 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. # """HTTP server for dulwich that implements the git smart HTTP protocol.""" from io import BytesIO import shutil import tempfile import gzip import os import re import sys import time from typing import List, Tuple, Optional from wsgiref.simple_server import ( WSGIRequestHandler, ServerHandler, WSGIServer, make_server, ) from urllib.parse import parse_qs from dulwich import log_utils from dulwich.protocol import ( ReceivableProtocol, ) from dulwich.repo import ( BaseRepo, NotGitRepository, Repo, ) from dulwich.server import ( DictBackend, DEFAULT_HANDLERS, generate_info_refs, generate_objects_info_packs, ) logger = log_utils.getLogger(__name__) # HTTP error strings HTTP_OK = '200 OK' HTTP_NOT_FOUND = '404 Not Found' HTTP_FORBIDDEN = '403 Forbidden' HTTP_ERROR = '500 Internal Server Error' def date_time_string(timestamp: Optional[float] = None) -> str: # From BaseHTTPRequestHandler.date_time_string in BaseHTTPServer.py in the # Python 2.6.5 standard library, following modifications: # - Made a global rather than an instance method. # - weekdayname and monthname are renamed and locals rather than class # variables. # Copyright (c) 2001-2010 Python Software Foundation; All Rights Reserved weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] months = [None, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] if timestamp is None: timestamp = time.time() year, month, day, hh, mm, ss, wd = time.gmtime(timestamp)[:7] return '%s, %02d %3s %4d %02d:%02d:%02d GMD' % ( weekdays[wd], day, months[month], year, hh, mm, ss) def url_prefix(mat) -> str: """Extract the URL prefix from a regex match. Args: mat: A regex match object. Returns: The URL prefix, defined as the text before the match in the original string. Normalized to start with one leading slash and end with zero. """ return '/' + mat.string[:mat.start()].strip('/') def get_repo(backend, mat) -> BaseRepo: """Get a Repo instance for the given backend and URL regex match.""" return backend.open_repository(url_prefix(mat)) def send_file(req, f, content_type): """Send a file-like object to the request output. Args: req: The HTTPGitRequest object to send output to. f: An open file-like object to send; will be closed. content_type: The MIME type for the file. Returns: Iterator over the contents of the file, as chunks. """ if f is None: yield req.not_found('File not found') return try: req.respond(HTTP_OK, content_type) while True: data = f.read(10240) if not data: break yield data except IOError: yield req.error('Error reading file') finally: f.close() def _url_to_path(url): return url.replace('/', os.path.sep) def get_text_file(req, backend, mat): req.nocache() path = _url_to_path(mat.group()) logger.info('Sending plain text file %s', path) return send_file(req, get_repo(backend, mat).get_named_file(path), 'text/plain') def get_loose_object(req, backend, mat): sha = (mat.group(1) + mat.group(2)).encode('ascii') logger.info('Sending loose object %s', sha) object_store = get_repo(backend, mat).object_store if not object_store.contains_loose(sha): yield req.not_found('Object not found') return try: data = object_store[sha].as_legacy_object() except IOError: yield req.error('Error reading object') return req.cache_forever() req.respond(HTTP_OK, 'application/x-git-loose-object') yield data def get_pack_file(req, backend, mat): req.cache_forever() path = _url_to_path(mat.group()) logger.info('Sending pack file %s', path) return send_file(req, get_repo(backend, mat).get_named_file(path), 'application/x-git-packed-objects') def get_idx_file(req, backend, mat): req.cache_forever() path = _url_to_path(mat.group()) logger.info('Sending pack file %s', path) return send_file(req, get_repo(backend, mat).get_named_file(path), 'application/x-git-packed-objects-toc') def get_info_refs(req, backend, mat): params = parse_qs(req.environ['QUERY_STRING']) service = params.get('service', [None])[0] try: repo = get_repo(backend, mat) except NotGitRepository as e: yield req.not_found(str(e)) return if service and not req.dumb: handler_cls = req.handlers.get(service.encode('ascii'), None) if handler_cls is None: yield req.forbidden('Unsupported service') return req.nocache() write = req.respond( HTTP_OK, 'application/x-%s-advertisement' % service) proto = ReceivableProtocol(BytesIO().read, write) handler = handler_cls(backend, [url_prefix(mat)], proto, - http_req=req, advertise_refs=True) + stateless_rpc=req, advertise_refs=True) handler.proto.write_pkt_line( b'# service=' + service.encode('ascii') + b'\n') handler.proto.write_pkt_line(None) handler.handle() else: # non-smart fallback # TODO: select_getanyfile() (see http-backend.c) req.nocache() req.respond(HTTP_OK, 'text/plain') logger.info('Emulating dumb info/refs') for text in generate_info_refs(repo): yield text def get_info_packs(req, backend, mat): req.nocache() req.respond(HTTP_OK, 'text/plain') logger.info('Emulating dumb info/packs') return generate_objects_info_packs(get_repo(backend, mat)) class _LengthLimitedFile(object): """Wrapper class to limit the length of reads from a file-like object. This is used to ensure EOF is read from the wsgi.input object once Content-Length bytes are read. This behavior is required by the WSGI spec but not implemented in wsgiref as of 2.5. """ def __init__(self, input, max_bytes): self._input = input self._bytes_avail = max_bytes def read(self, size=-1): if self._bytes_avail <= 0: return b'' if size == -1 or size > self._bytes_avail: size = self._bytes_avail self._bytes_avail -= size return self._input.read(size) # TODO: support more methods as necessary def handle_service_request(req, backend, mat): service = mat.group().lstrip('/') logger.info('Handling service request for %s', service) handler_cls = req.handlers.get(service.encode('ascii'), None) if handler_cls is None: yield req.forbidden('Unsupported service') return try: get_repo(backend, mat) except NotGitRepository as e: yield req.not_found(str(e)) return req.nocache() write = req.respond(HTTP_OK, 'application/x-%s-result' % service) proto = ReceivableProtocol(req.environ['wsgi.input'].read, write) # TODO(jelmer): Find a way to pass in repo, rather than having handler_cls # reopen. - handler = handler_cls(backend, [url_prefix(mat)], proto, http_req=req) + handler = handler_cls(backend, [url_prefix(mat)], proto, stateless_rpc=req) handler.handle() class HTTPGitRequest(object): """Class encapsulating the state of a single git HTTP request. :ivar environ: the WSGI environment for the request. """ def __init__( self, environ, start_response, dumb: bool = False, handlers=None): self.environ = environ self.dumb = dumb self.handlers = handlers self._start_response = start_response self._cache_headers = [] # type: List[Tuple[str, str]] self._headers = [] # type: List[Tuple[str, str]] def add_header(self, name, value): """Add a header to the response.""" self._headers.append((name, value)) def respond( self, status: str = HTTP_OK, content_type: Optional[str] = None, headers: Optional[List[Tuple[str, str]]] = None): """Begin a response with the given status and other headers.""" if headers: self._headers.extend(headers) if content_type: self._headers.append(('Content-Type', content_type)) self._headers.extend(self._cache_headers) return self._start_response(status, self._headers) def not_found(self, message: str) -> bytes: """Begin a HTTP 404 response and return the text of a message.""" self._cache_headers = [] logger.info('Not found: %s', message) self.respond(HTTP_NOT_FOUND, 'text/plain') return message.encode('ascii') def forbidden(self, message: str) -> bytes: """Begin a HTTP 403 response and return the text of a message.""" self._cache_headers = [] logger.info('Forbidden: %s', message) self.respond(HTTP_FORBIDDEN, 'text/plain') return message.encode('ascii') def error(self, message: str) -> bytes: """Begin a HTTP 500 response and return the text of a message.""" self._cache_headers = [] logger.error('Error: %s', message) self.respond(HTTP_ERROR, 'text/plain') return message.encode('ascii') def nocache(self) -> None: """Set the response to never be cached by the client.""" self._cache_headers = [ ('Expires', 'Fri, 01 Jan 1980 00:00:00 GMT'), ('Pragma', 'no-cache'), ('Cache-Control', 'no-cache, max-age=0, must-revalidate'), ] def cache_forever(self) -> None: """Set the response to be cached forever by the client.""" now = time.time() self._cache_headers = [ ('Date', date_time_string(now)), ('Expires', date_time_string(now + 31536000)), ('Cache-Control', 'public, max-age=31536000'), ] class HTTPGitApplication(object): """Class encapsulating the state of a git WSGI application. :ivar backend: the Backend object backing this application """ services = { ('GET', re.compile('/HEAD$')): get_text_file, ('GET', re.compile('/info/refs$')): get_info_refs, ('GET', re.compile('/objects/info/alternates$')): get_text_file, ('GET', re.compile('/objects/info/http-alternates$')): get_text_file, ('GET', re.compile('/objects/info/packs$')): get_info_packs, ('GET', re.compile('/objects/([0-9a-f]{2})/([0-9a-f]{38})$')): get_loose_object, ('GET', re.compile('/objects/pack/pack-([0-9a-f]{40})\\.pack$')): get_pack_file, ('GET', re.compile('/objects/pack/pack-([0-9a-f]{40})\\.idx$')): get_idx_file, ('POST', re.compile('/git-upload-pack$')): handle_service_request, ('POST', re.compile('/git-receive-pack$')): handle_service_request, } def __init__( self, backend, dumb: bool = False, handlers=None, fallback_app=None): self.backend = backend self.dumb = dumb self.handlers = dict(DEFAULT_HANDLERS) self.fallback_app = fallback_app if handlers is not None: self.handlers.update(handlers) def __call__(self, environ, start_response): path = environ['PATH_INFO'] method = environ['REQUEST_METHOD'] req = HTTPGitRequest(environ, start_response, dumb=self.dumb, handlers=self.handlers) # environ['QUERY_STRING'] has qs args handler = None for smethod, spath in self.services.keys(): if smethod != method: continue mat = spath.search(path) if mat: handler = self.services[smethod, spath] break if handler is None: if self.fallback_app is not None: return self.fallback_app(environ, start_response) else: return [req.not_found('Sorry, that method is not supported')] return handler(req, self.backend, mat) class GunzipFilter(object): """WSGI middleware that unzips gzip-encoded requests before passing on to the underlying application. """ def __init__(self, application): self.app = application def __call__(self, environ, start_response): if environ.get('HTTP_CONTENT_ENCODING', '') == 'gzip': try: environ['wsgi.input'].tell() wsgi_input = environ['wsgi.input'] except (AttributeError, IOError, NotImplementedError): # The gzip implementation in the standard library of Python 2.x # requires working '.seek()' and '.tell()' methods on the input # stream. Read the data into a temporary file to work around # this limitation. wsgi_input = tempfile.SpooledTemporaryFile(16 * 1024 * 1024) shutil.copyfileobj(environ['wsgi.input'], wsgi_input) wsgi_input.seek(0) environ['wsgi.input'] = gzip.GzipFile( filename=None, fileobj=wsgi_input, mode='r') del environ['HTTP_CONTENT_ENCODING'] if 'CONTENT_LENGTH' in environ: del environ['CONTENT_LENGTH'] return self.app(environ, start_response) class LimitedInputFilter(object): """WSGI middleware that limits the input length of a request to that specified in Content-Length. """ def __init__(self, application): self.app = application def __call__(self, environ, start_response): # This is not necessary if this app is run from a conforming WSGI # server. Unfortunately, there's no way to tell that at this point. # TODO: git may used HTTP/1.1 chunked encoding instead of specifying # content-length content_length = environ.get('CONTENT_LENGTH', '') if content_length: environ['wsgi.input'] = _LengthLimitedFile( environ['wsgi.input'], int(content_length)) return self.app(environ, start_response) def make_wsgi_chain(*args, **kwargs): """Factory function to create an instance of HTTPGitApplication, correctly wrapped with needed middleware. """ app = HTTPGitApplication(*args, **kwargs) wrapped_app = LimitedInputFilter(GunzipFilter(app)) return wrapped_app class ServerHandlerLogger(ServerHandler): """ServerHandler that uses dulwich's logger for logging exceptions.""" def log_exception(self, exc_info): logger.exception('Exception happened during processing of request', exc_info=exc_info) def log_message(self, format, *args): logger.info(format, *args) def log_error(self, *args): logger.error(*args) class WSGIRequestHandlerLogger(WSGIRequestHandler): """WSGIRequestHandler that uses dulwich's logger for logging exceptions.""" def log_exception(self, exc_info): logger.exception('Exception happened during processing of request', exc_info=exc_info) def log_message(self, format, *args): logger.info(format, *args) def log_error(self, *args): logger.error(*args) def handle(self): """Handle a single HTTP request""" self.raw_requestline = self.rfile.readline() if not self.parse_request(): # An error code has been sent, just exit return handler = ServerHandlerLogger( self.rfile, self.wfile, self.get_stderr(), self.get_environ() ) handler.request_handler = self # backpointer for logging handler.run(self.server.get_app()) class WSGIServerLogger(WSGIServer): def handle_error(self, request, client_address): """Handle an error. """ logger.exception( 'Exception happened during processing of request from %s' % str(client_address)) def main(argv=sys.argv): """Entry point for starting an HTTP git server.""" import optparse parser = optparse.OptionParser() parser.add_option("-l", "--listen_address", dest="listen_address", default="localhost", help="Binding IP address.") parser.add_option("-p", "--port", dest="port", type=int, default=8000, help="Port to listen on.") options, args = parser.parse_args(argv) if len(args) > 1: gitdir = args[1] else: gitdir = os.getcwd() log_utils.default_logging_config() backend = DictBackend({'/': Repo(gitdir)}) app = make_wsgi_chain(backend) server = make_server(options.listen_address, options.port, app, handler_class=WSGIRequestHandlerLogger, server_class=WSGIServerLogger) logger.info('Listening for HTTP connections on %s:%d', options.listen_address, options.port) server.serve_forever() if __name__ == '__main__': main() diff --git a/setup.py b/setup.py index b92e06ad..8de4f742 100755 --- a/setup.py +++ b/setup.py @@ -1,125 +1,132 @@ -#!/usr/bin/python +#!/usr/bin/python3 # 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.20.3' + +if sys.version_info < (3, 5): + raise Exception( + 'Dulwich only supports Python 3.5 and later. ' + 'For 2.7 support, please install a version prior to 0.20') + + +dulwich_version_string = '0.20.5' 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']), Extension('dulwich._pack', ['dulwich/_pack.c']), Extension('dulwich._diff_tree', ['dulwich/_diff_tree.c']), ] setup_kwargs = {} scripts = ['bin/dul-receive-pack', 'bin/dul-upload-pack'] 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 setup_kwargs['entry_points'] = { "console_scripts": [ "dulwich=dulwich.cli:main", ]} setup_kwargs['python_requires'] = '>=3.5' else: scripts.append('bin/dulwich') 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=scripts, ext_modules=ext_modules, distclass=DulwichDistribution, classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Operating System :: POSIX', 'Operating System :: Microsoft :: Windows', 'Topic :: Software Development :: Version Control', ], **setup_kwargs )