pax_global_header00006660000000000000000000000064125644431610014520gustar00rootroot0000000000000052 comment=c8b837923d506e265ff8bb79af61c0d86e7d5b2e python-git-1.0.1+git137-gc8b8379/000077500000000000000000000000001256444316100160075ustar00rootroot00000000000000python-git-1.0.1+git137-gc8b8379/.coveragerc000066400000000000000000000001341256444316100201260ustar00rootroot00000000000000[run] source = git ; to make nosetests happy [report] include = */git/* omit = */git/ext/* python-git-1.0.1+git137-gc8b8379/.gitignore000066400000000000000000000002311256444316100177730ustar00rootroot00000000000000*.py[co] *.swp *~ /*.egg-info /lib/GitPython.egg-info cover/ .coverage /build /dist /doc/_build nbproject *.sublime-workspace .DS_Store /*egg-info /.tox python-git-1.0.1+git137-gc8b8379/.gitmodules000066400000000000000000000001431256444316100201620ustar00rootroot00000000000000[submodule "gitdb"] url = https://github.com/gitpython-developers/gitdb.git path = git/ext/gitdb python-git-1.0.1+git137-gc8b8379/.travis.private-ssh-key-for-issue-301000066400000000000000000000032131256444316100245640ustar00rootroot00000000000000-----BEGIN RSA PRIVATE KEY----- MIIEogIBAAKCAQEAu5awaLHx+F7O9gE1ac3gKztAi3OYzCS75XsUmQkjIZ+6je/3 L+uVmtFyQ8t0PXaSF8rPBs+E35Vl1t9uz+vry7Q6bI5ClvlzaXCYHAuOqnDwrpdo jykjKN4U0r0leDBO3rXpvjluKCGiE4pj0KgTe+xtoU4r64z7/DPQcaAmHbOFabxs b8YZ/gHvA3vA8RA81eHWw83cw1U12dqjcE/gj6UZ0f4qj+PKQG6nfZEg6MzV71rS wdHtCMljd4pz/3vzrCYCdl34jrzlm0lxuDbX/oMVe2OhoJAgilUQ6ieMhG0MKTr4 Cf5LBRQGNKkuwNgj70fmsYphm3xKeehjvwxB/wIDAQABAoIBACKZkMA+0hq1ogbO AkQZrRdMPoN6Ntywidex9AKmJMy24Xn8oOM92MJNj33hsPcFP70Ts0vWSvPSYo5X d+Dx6vQPshcDxlSCfj8cfXHuz8mwOzR4yNhfBhUroTudl6OrhWCevRZREXhle7eO 9wotdiqNWUs/V+qCfpfuFqxelak0erSSdR4rh35uZYNBdopPiMlo8klYEDRGrH2R LCjeOiC9pkkj7f1ylyDCjkI8hdjOnWO/QYYD7g8ZDKFwRRBm0os6d3Nj20ED7N8y eBRBjDv6k5165MAtFmjHrO9olUh1o+2rwrYK+hVckg5uE/cv6VanRs9tRgF6TyIw 97tSeQECgYEA3yuy0aINAW+T7+3oOPuo9c6ZrBMrPTOlRJufrLS4WvV3laL/AVNt DmKkQOjKbQI8cknlqV9CovteRT2Dj9lTZwSGmecVPijslAUmwz9s4Ucu1BR8Qckl i470z5Fge6fdPsAYhjhqjbLUE2Lml2A/YyNnpTFSP4wXpyy6HLkT1pECgYEA1y8E 0zVlnoeHKDgpGDpmXV9YhcqtQ6Q2HC/g9oUn+jAfeYkVX8L5brUX2S4L03hYAljH j0RJZnOZoXpN6WMRnWJkOP80Fkq5Jv6vJkghNPJ7vWtXJan4wkNr/nGQ65DvxeLJ qIEmSe+sZHCB/W26y9bgI+ELHt4VgPuEIoGad48CgYBNza5J53UhSwUIYKjVNOdy ytRIaWZpr9euU5MXYunizDEkue6tR6h9m2YoOwBXgLASKDEpG0zgBUKYYRm8zMeG 4s0KWsXNJfdUo3cgGryazXZF+d5YEQhF31D6DHTWp286sT3bjU+Ylv/YwmIh5Cw1 I+K+dLN39B9K6Qz5doy0AQKBgFHlzFFSflWiwVcWYNWezHz3H+rz45Pd+NYrhtRs g3WeQSxxdxgWTfbLp8L52nhm0iA6h+FIHSOIFc22jdao5PhgjUKAJuPhFqz3u9O3 GiRbsaq7ItTr5wiQvpZ9xKlTZV6MXTHrzZXQSW2EwISi8bhJFM+zBBeAcPDBSV4U s6STAoGANTuc66z/2wtZYINA2+JN1kSELL22ka8yKYWBmi0NJ7Hp+7MPKj9v71mM Oq4zuNIYEJfQaf53xhi6BhZVWMERDKMGWqJet88BATbBIqBahHxFTiCmsP6fBH7e AipTene7xg9mqG8qoluFdHRvzGqZFu0lZSGxtZYeU/y+U2b7lzI= -----END RSA PRIVATE KEY----- python-git-1.0.1+git137-gc8b8379/.travis.yml000066400000000000000000000031421256444316100201200ustar00rootroot00000000000000language: python python: - "2.6" - "2.7" - "3.3" - "3.4" # - "pypy" - won't work as smmap doesn't work (see gitdb/.travis.yml for details) git: # a higher depth is needed for most of the tests - must be high enough to not actually be shallow # as we clone our own repository in the process depth: 99999 install: - git submodule update --init --recursive - git fetch --tags - pip install coveralls flake8 sphinx # generate some reflog as git-python tests need it (in master) - git tag __testing_point__ - git checkout master - git reset --hard HEAD~1 - git reset --hard HEAD~1 - git reset --hard HEAD~1 - git reset --hard __testing_point__ # as commits are performed with the default user, it needs to be set for travis too - git config --global user.email "travis@ci.com" - git config --global user.name "Travis Runner" # If we rewrite the user's config by accident, we will mess it up # and cause subsequent tests to fail - cat git/test/fixtures/.gitconfig >> ~/.gitconfig # used later when testing for specific issue # copy the configured key into place so clone can work # The key just has read-only access to the test-repository - cp .travis.private-ssh-key-for-issue-301 ~/.ssh/id_rsa - chmod 0400 ~/.ssh/id_rsa - git clone git@github.com:gitpython-developers/gitpython_issue_301.git issue-301-repo script: # Make sure we limit open handles to see if we are leaking them - ulimit -n 96 - ulimit -n - nosetests -v --with-coverage - '( cd issue-301-repo && PYTHONPATH=$PWD/.. ./reproduce.py )' - flake8 - cd doc && make html after_success: - coveralls python-git-1.0.1+git137-gc8b8379/AUTHORS000066400000000000000000000011101256444316100170500ustar00rootroot00000000000000GitPython was originally written by Michael Trier. GitPython 0.2 was partially (re)written by Sebastian Thiel, based on 0.1.6 and git-dulwich. Contributors are: -Michael Trier -Alan Briolat -Florian Apolloner -David Aguilar -Jelmer Vernooij -Steve Frécinaux -Kai Lautaportti -Paul Sowden -Sebastian Thiel Portions derived from other open source works and are clearly marked. python-git-1.0.1+git137-gc8b8379/CHANGES000066400000000000000000000002201256444316100167740ustar00rootroot00000000000000Please see the online documentation for the latest changelog: https://github.com/gitpython-developers/GitPython/blob/0.3/doc/source/changes.rst python-git-1.0.1+git137-gc8b8379/LICENSE000066400000000000000000000027611256444316100170220ustar00rootroot00000000000000Copyright (C) 2008, 2009 Michael Trier and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the GitPython project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. python-git-1.0.1+git137-gc8b8379/MANIFEST.in000066400000000000000000000002341256444316100175440ustar00rootroot00000000000000include VERSION include LICENSE include CHANGES include AUTHORS include README include requirements.txt graft git/test/fixtures graft git/test/performance python-git-1.0.1+git137-gc8b8379/README.md000066400000000000000000000104441256444316100172710ustar00rootroot00000000000000## GitPython GitPython is a python library used to interact with git repositories, high-level like git-porcelain, or low-level like git-plumbing. It provides abstractions of git objects for easy access of repository data, and additionally allows you to access the git repository more directly using either a pure python implementation, or the faster, but more resource intensive git command implementation. The object database implementation is optimized for handling large quantities of objects and large datasets, which is achieved by using low-level structures and data streaming. ### REQUIREMENTS GitPython needs the `git` executable to be installed on the system and available in your `PATH` for most operations. If it is not in your `PATH`, you can help GitPython find it by setting the `GIT_PYTHON_GIT_EXECUTABLE=` environment variable. * Git (1.7.x or newer) The list of dependencies are listed in `./requirements.txt` and `./test-requirements.txt`. The installer takes care of installing them for you. ### INSTALL [![Latest Version](https://pypip.in/version/GitPython/badge.svg)](https://pypi.python.org/pypi/GitPython/) [![Supported Python Versions](https://pypip.in/py_versions/GitPython/badge.svg)](https://pypi.python.org/pypi/GitPython/) If you have downloaded the source code: python setup.py install or if you want to obtain a copy from the Pypi repository: pip install gitpython Both commands will install the required package dependencies. A distribution package can be obtained for manual installation at: http://pypi.python.org/pypi/GitPython ### RUNNING TESTS The easiest way to run test is by using [tox](https://pypi.python.org/pypi/tox) a wrapper around virtualenv. It will take care of setting up environnements with the proper dependencies installed and execute test commands. To install it simply: pip install tox Then run: tox ### SOURCE GitPython's git repo is available on GitHub, which can be browsed at [github](https://github.com/gitpython-developers/GitPython) and cloned like that: git clone https://github.com/gitpython-developers/GitPython ### Live Coding You can watch me fix issues or implement new features [live on Twitch][twitch-channel], or have a look at [past recordings on youtube][youtube-playlist] * [Live on Twitch][twitch-channel] (just follow the channel to be notified when a session starts) * [Archive on Youtube][youtube-playlist] ### INFRASTRUCTURE * [User Documentation](http://gitpython.readthedocs.org) * [Questions and Answers](http://stackexchange.com/filters/167317/gitpython) * Please post on stackoverflow and use the `gitpython` tag * [Mailing List](http://groups.google.com/group/git-python) * Please use it for everything that doesn't fit Stackoverflow. * [Issue Tracker](https://github.com/gitpython-developers/GitPython/issues) * Post reproducible bugs and feature requests as a new issue. Please be sure to provide the following information if posting bugs: * GitPython version (e.g. `import git; git.__version__`) * Python version (e.g. `python --version`) * The encountered stack-trace, if applicable * Enough information to allow reproducing the issue ### LICENSE New BSD License. See the LICENSE file. ### DEVELOPMENT STATUS [![Build Status](https://travis-ci.org/gitpython-developers/GitPython.svg)](https://travis-ci.org/gitpython-developers/GitPython) [![Code Climate](https://codeclimate.com/github/gitpython-developers/GitPython/badges/gpa.svg)](https://codeclimate.com/github/gitpython-developers/GitPython) [![Documentation Status](https://readthedocs.org/projects/gitpython/badge/?version=stable)](https://readthedocs.org/projects/gitpython/?badge=stable) [![Issue Stats](http://www.issuestats.com/github/gitpython-developers/GitPython/badge/pr)](http://www.issuestats.com/github/gitpython-developers/GitPython) [![Issue Stats](http://www.issuestats.com/github/gitpython-developers/GitPython/badge/issue)](http://www.issuestats.com/github/gitpython-developers/GitPython) Now that there seems to be a massive user base, this should be motivation enough to let git-python return to a proper state, which means * no open pull requests * no open issues describing bugs [twitch-channel]: http://www.twitch.tv/byronimo/profile [youtube-playlist]: https://www.youtube.com/playlist?list=PLMHbQxe1e9MnoEcLhn6Yhv5KAvpWkJbL0python-git-1.0.1+git137-gc8b8379/TODO000066400000000000000000000001621256444316100164760ustar00rootroot00000000000000For a list of tickets, please visit http://byronimo.lighthouseapp.com/projects/51787-gitpython/overview python-git-1.0.1+git137-gc8b8379/VERSION000066400000000000000000000000061256444316100170530ustar00rootroot000000000000001.0.1 python-git-1.0.1+git137-gc8b8379/doc/000077500000000000000000000000001256444316100165545ustar00rootroot00000000000000python-git-1.0.1+git137-gc8b8379/doc/.gitignore000066400000000000000000000000071256444316100205410ustar00rootroot00000000000000build/ python-git-1.0.1+git137-gc8b8379/doc/Makefile000066400000000000000000000044501256444316100202170ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d build/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source .PHONY: help clean html web pickle htmlhelp latex changes linkcheck help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " changes to make an overview over all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" clean: -rm -rf build/* html: mkdir -p build/html build/doctrees $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) build/html @echo @echo "Build finished. The HTML pages are in build/html." pickle: mkdir -p build/pickle build/doctrees $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) build/pickle @echo @echo "Build finished; now you can process the pickle files." web: pickle json: mkdir -p build/json build/doctrees $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) build/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: mkdir -p build/htmlhelp build/doctrees $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) build/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in build/htmlhelp." latex: mkdir -p build/latex build/doctrees $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) build/latex @echo @echo "Build finished; the LaTeX files are in build/latex." @echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \ "run these through (pdf)latex." changes: mkdir -p build/changes build/doctrees $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) build/changes @echo @echo "The overview file is in build/changes." linkcheck: mkdir -p build/linkcheck build/doctrees $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) build/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in build/linkcheck/output.txt." python-git-1.0.1+git137-gc8b8379/doc/source/000077500000000000000000000000001256444316100200545ustar00rootroot00000000000000python-git-1.0.1+git137-gc8b8379/doc/source/changes.rst000066400000000000000000000534201256444316100222220ustar00rootroot00000000000000========= Changelog ========= 1.0.2 - Fixes ============= * CRITICAL: fixed incorrect `Commit` object serialization when authored or commit date had timezones which were not divisable by 3600 seconds. This would happen if the timezone was something like `+0530` for instance. * A list of all additional fixes can be found `on github `_ 1.0.1 - Fixes ============= * A list of all issues can be found `on github `_ 1.0.0 - Notes ============= This version is equivalent to v0.3.7, but finally acknowledges that GitPython is stable and production ready. It follows the `semantic version scheme `_, and thus will not break its existing API unless it goes 2.0. 0.3.7 - Fixes ============= * `IndexFile.add()` will now write the index without any extension data by default. However, you may override this behaviour with the new `write_extension_data` keyword argument. - Renamed `ignore_tree_extension_data` keyword argument in `IndexFile.write(...)` to `ignore_extension_data` * If the git command executed during `Remote.push(...)|fetch(...)` returns with an non-zero exit code and GitPython didn't obtain any head-information, the corresponding `GitCommandError` will be raised. This may break previous code which expected these operations to never raise. However, that behavious is undesirable as it would effectively hide the fact that there was an error. See `this issue `_ for more information. * If the git executable can't be found in the PATH or at the path provided by `GIT_PYTHON_GIT_EXECUTABLE`, this is made obvious by throwing `GitCommandNotFound`, both on unix and on windows. - Those who support **GUI on windows** will now have to set `git.Git.USE_SHELL = True` to get the previous behaviour. * A list of all issues can be found `on github `_ 0.3.6 - Features ================ * **DOCS** * special members like `__init__` are now listed in the API documentation * tutorial section was revised entirely, more advanced examples were added. * **POSSIBLY BREAKING CHANGES** * As `rev_parse` will now throw `BadName` as well as `BadObject`, client code will have to catch both exception types. * Repo.working_tree_dir now returns None if it is bare. Previously it raised AssertionError. * IndexFile.add() previously raised AssertionError when paths where used with bare repository, now it raises InvalidGitRepositoryError * Added `Repo.merge_base()` implementation. See the `respective issue on github `_ * `[include]` sections in git configuration files are now respected * Added `GitConfigParser.rename_section()` * Added `Submodule.rename()` * A list of all issues can be found `on github `_ 0.3.5 - Bugfixes ================ * push/pull/fetch operations will not block anymore * diff() can now properly detect renames, both in patch and raw format. Previously it only worked when create_patch was True. * repo.odb.update_cache() is now called automatically after fetch and pull operations. In case you did that in your own code, you might want to remove your line to prevent a double-update that causes unnecessary IO. * `Repo(path)` will not automatically search upstream anymore and find any git directory on its way up. If you need that behaviour, you can turn it back on using the new `search_parent_directories=True` flag when constructing a `Repo` object. * IndexFile.commit() now runs the `pre-commit` and `post-commit` hooks. Verified to be working on posix systems only. * A list of all fixed issues can be found here: https://github.com/gitpython-developers/GitPython/issues?q=milestone%3A%22v0.3.5+-+bugfixes%22+ 0.3.4 - Python 3 Support ======================== * Internally, hexadecimal SHA1 are treated as ascii encoded strings. Binary SHA1 are treated as bytes. * Id attribute of Commit objects is now `hexsha`, instead of `binsha`. The latter makes no sense in python 3 and I see no application of it anyway besides its artificial usage in test cases. * **IMPORTANT**: If you were using the config_writer(), you implicitly relied on __del__ to work as expected to flush changes. To be sure changes are flushed under PY3, you will have to call the new `release()` method to trigger a flush. For some reason, __del__ is not called necessarily anymore when a symbol goes out of scope. * The `Tree` now has a `.join('name')` method which is equivalent to `tree / 'name'` 0.3.3 ===== * When fetching, pulling or pushing, and an error occours, it will not be reported on stdout anymore. However, if there is a fatal error, it will still result in a GitCommandError to be thrown. This goes hand in hand with improved fetch result parsing. * Code Cleanup (in preparation for python 3 support) * Applied autopep8 and cleaned up code * Using python logging module instead of print statments to signal certain kinds of errors 0.3.2.1 ======= * `Fix for #207 `_ 0.3.2 ===== * Release of most recent version as non-RC build, just to allow pip to install the latest version right away. * Have a look at the milestones (https://github.com/gitpython-developers/GitPython/milestones) to see what's next. 0.3.2 RC1 ========= * **git** command wrapper * Added ``version_info`` property which returns a tuple of integers representing the installed git version. * Added GIT_PYTHON_GIT_EXECUTABLE environment variable, which can be used to set the desired git executable to be used. despite of what would be found in the path. * **Blob** Type * Added mode constants to ease the manual creation of blobs * **IterableList** * Added __contains__ and __delitem__ methods * **More Changes** * Configuration file parsing is more robust. It should now be able to handle everything that the git command can parse as well. * The progress parsing was updated to support git 1.7.0.3 and newer. Previously progress was not enabled for the git command or only worked with ssh in case of older git versions. * Parsing of tags was improved. Previously some parts of the name could not be parsed properly. * The rev-parse pure python implementation now handles branches correctly if they look like hexadecimal sha's. * GIT_PYTHON_TRACE is now set on class level of the Git type, previously it was a module level global variable. * GIT_PYTHON_GIT_EXECUTABLE is a class level variable as well. 0.3.1 Beta 2 ============ * Added **reflog support** ( reading and writing ) * New types: ``RefLog`` and ``RefLogEntry`` * Reflog is maintained automatically when creating references and deleting them * Non-intrusive changes to ``SymbolicReference``, these don't require your code to change. They allow to append messages to the reflog. * ``abspath`` property added, similar to ``abspath`` of Object instances * ``log()`` method added * ``log_append(...)`` method added * ``set_reference(...)`` method added (reflog support) * ``set_commit(...)`` method added (reflog support) * ``set_object(...)`` method added (reflog support) * **Intrusive Changes** to ``Head`` type * ``create(...)`` method now supports the reflog, but will not raise ``GitCommandError`` anymore as it is a pure python implementation now. Instead, it raises ``OSError``. * **Intrusive Changes** to ``Repo`` type * ``create_head(...)`` method does not support kwargs anymore, instead it supports a logmsg parameter * Repo.rev_parse now supports the [ref]@{n} syntax, where *n* is the number of steps to look into the reference's past * **BugFixes** * Removed incorrect ORIG_HEAD handling * **Flattened directory** structure to make development more convenient. * .. note:: This alters the way projects using git-python as a submodule have to adjust their sys.path to be able to import git-python successfully. * Misc smaller changes and bugfixes 0.3.1 Beta 1 ============ * Full Submodule-Support * Added unicode support for author names. Commit.author.name is now unicode instead of string. * Head Type changes * config_reader() & config_writer() methods added for access to head specific options. * tracking_branch() & set_tracking_branch() methods addded for easy configuration of tracking branches. 0.3.0 Beta 2 ============ * Added python 2.4 support 0.3.0 Beta 1 ============ Renamed Modules --------------- * For consistency with naming conventions used in sub-modules like gitdb, the following modules have been renamed * git.utils -> git.util * git.errors -> git.exc * git.objects.utils -> git.objects.util General ------- * Object instances, and everything derived from it, now use binary sha's internally. The 'sha' member was removed, in favor of the 'binsha' member. An 'hexsha' property is available for convenient conversions. They may only be initialized using their binary shas, reference names or revision specs are not allowed anymore. * IndexEntry instances contained in IndexFile.entries now use binary sha's. Use the .hexsha property to obtain the hexadecimal version. The .sha property was removed to make the use of the respective sha more explicit. * If objects are instantiated explicitly, a binary sha is required to identify the object, where previously any rev-spec could be used. The ref-spec compatible version still exists as Object.new or Repo.commit|Repo.tree respectively. * The .data attribute was removed from the Object type, to obtain plain data, use the data_stream property instead. * ConcurrentWriteOperation was removed, and replaced by LockedFD * IndexFile.get_entries_key was renamed to entry_key * IndexFile.write_tree: removed missing_ok keyword, its always True now. Instead of raising GitCommandError it raises UnmergedEntriesError. This is required as the pure-python implementation doesn't support the missing_ok keyword yet. * diff.Diff.null_hex_sha renamed to NULL_HEX_SHA, to be conforming with the naming in the Object base class 0.2 Beta 2 =========== * Commit objects now carry the 'encoding' information of their message. It wasn't parsed previously, and defaults to UTF-8 * Commit.create_from_tree now uses a pure-python implementation, mimicing git-commit-tree 0.2 ===== General ------- * file mode in Tree, Blob and Diff objects now is an int compatible to definintiions in the stat module, allowing you to query whether individual user, group and other read, write and execute bits are set. * Adjusted class hierarchy to generally allow comparison and hash for Objects and Refs * Improved Tag object which now is a Ref that may contain a tag object with additional Information * id_abbrev method has been removed as it could not assure the returned short SHA's where unique * removed basename method from Objects with path's as it replicated features of os.path * from_string and list_from_string methods are now private and were renamed to _from_string and _list_from_string respectively. As part of the private API, they may change without prior notice. * Renamed all find_all methods to list_items - this method is part of the Iterable interface that also provides a more efficients and more responsive iter_items method * All dates, like authored_date and committer_date, are stored as seconds since epoc to consume less memory - they can be converted using time.gmtime in a more suitable presentation format if needed. * Named method parameters changed on a wide scale to unify their use. Now git specific terms are used everywhere, such as "Reference" ( ref ) and "Revision" ( rev ). Prevously multiple terms where used making it harder to know which type was allowed or not. * Unified diff interface to allow easy diffing between trees, trees and index, trees and working tree, index and working tree, trees and index. This closely follows the git-diff capabilities. * Git.execute does not take the with_raw_output option anymore. It was not used by anyone within the project and False by default. Item Iteration -------------- * Previously one would return and process multiple items as list only which can hurt performance and memory consumption and reduce response times. iter_items method provide an iterator that will return items on demand as parsed from a stream. This way any amount of objects can be handled. * list_items method returns IterableList allowing to access list members by name objects Package ---------------- * blob, tree, tag and commit module have been moved to new objects package. This should not affect you though unless you explicitly imported individual objects. If you just used the git package, names did not change. Blob ---- * former 'name' member renamed to path as it suits the actual data better GitCommand ----------- * git.subcommand call scheme now prunes out None from the argument list, allowing to be called more confortably as None can never be a valid to the git command if converted to a string. * Renamed 'git_dir' attribute to 'working_dir' which is exactly how it is used Commit ------ * 'count' method is not an instance method to increase its ease of use * 'name_rev' property returns a nice name for the commit's sha Config ------ * The git configuration can now be read and manipulated directly from within python using the GitConfigParser * Repo.config_reader() returns a read-only parser * Repo.config_writer() returns a read-write parser Diff ---- * Members a a_commit and b_commit renamed to a_blob and b_blob - they are populated with Blob objects if possible * Members a_path and b_path removed as this information is kept in the blobs * Diffs are now returned as DiffIndex allowing to more quickly find the kind of diffs you are interested in Diffing ------- * Commit and Tree objects now support diffing natively with a common interface to compare agains other Commits or Trees, against the working tree or against the index. Index ----- * A new Index class allows to read and write index files directly, and to perform simple two and three way merges based on an arbitrary index. Referernces ------------ * References are object that point to a Commit * SymbolicReference are a pointer to a Reference Object, which itself points to a specific Commit * They will dynmically retrieve their object at the time of query to assure the information is actual. Recently objects would be cached, hence ref object not be safely kept persistent. Repo ---- * Moved blame method from Blob to repo as it appeared to belong there much more. * active_branch method now returns a Head object instead of a string with the name of the active branch. * tree method now requires a Ref instance as input and defaults to the active_branche instead of master * is_dirty now takes additional arguments allowing fine-grained control about what is considered dirty * Removed the following methods: - 'log' method as it as effectively the same as the 'commits' method - 'commits_since' as it is just a flag given to rev-list in Commit.iter_items - 'commit_count' as it was just a redirection to the respective commit method - 'commits_between', replaced by a note on the iter_commits method as it can achieve the same thing - 'commit_delta_from' as it was a very special case by comparing two different repjrelated repositories, i.e. clones, git-rev-list would be sufficient to find commits that would need to be transferred for example. - 'create' method which equals the 'init' method's functionality - 'diff' - it returned a mere string which still had to be parsed - 'commit_diff' - moved to Commit, Tree and Diff types respectively * Renamed the following methods: - commits to iter_commits to improve the performance, adjusted signature - init_bare to init, implying less about the options to be used - fork_bare to clone, as it was to represent general clone functionality, but implied a bare clone to be more versatile - archive_tar_gz and archive_tar and replaced by archive method with different signature * 'commits' method has no max-count of returned commits anymore, it now behaves like git-rev-list * The following methods and properties were added - 'untracked_files' property, returning all currently untracked files - 'head', creates a head object - 'tag', creates a tag object - 'iter_trees' method - 'config_reader' method - 'config_writer' method - 'bare' property, previously it was a simple attribute that could be written * Renamed the following attributes - 'path' is now 'git_dir' - 'wd' is now 'working_dir' * Added attribute - 'working_tree_dir' which may be None in case of bare repositories Remote ------ * Added Remote object allowing easy access to remotes * Repo.remotes lists all remotes * Repo.remote returns a remote of the specified name if it exists Test Framework -------------- * Added support for common TestCase base class that provides additional functionality to receive repositories tests can also write to. This way, more aspects can be tested under real-world ( un-mocked ) conditions. Tree ---- * former 'name' member renamed to path as it suits the actual data better * added traverse method allowing to recursively traverse tree items * deleted blob method * added blobs and trees properties allowing to query the respective items in the tree * now mimics behaviour of a read-only list instead of a dict to maintain order. * content_from_string method is now private and not part of the public API anymore 0.1.6 ===== General ------- * Added in Sphinx documentation. * Removed ambiguity between paths and treeishs. When calling commands that accept treeish and path arguments and there is a path with the same name as a treeish git cowardly refuses to pick one and asks for the command to use the unambiguous syntax where '--' seperates the treeish from the paths. * ``Repo.commits``, ``Repo.commits_between``, ``Repo.commits_since``, ``Repo.commit_count``, ``Repo.commit``, ``Commit.count`` and ``Commit.find_all`` all now optionally take a path argument which constrains the lookup by path. This changes the order of the positional arguments in ``Repo.commits`` and ``Repo.commits_since``. Commit ------ * ``Commit.message`` now contains the full commit message (rather than just the first line) and a new property ``Commit.summary`` contains the first line of the commit message. * Fixed a failure when trying to lookup the stats of a parentless commit from a bare repo. Diff ---- * The diff parser is now far faster and also addresses a bug where sometimes b_mode was not set. * Added support for parsing rename info to the diff parser. Addition of new properties ``Diff.renamed``, ``Diff.rename_from``, and ``Diff.rename_to``. Head ---- * Corrected problem where branches was only returning the last path component instead of the entire path component following refs/heads/. Repo ---- * Modified the gzip archive creation to use the python gzip module. * Corrected ``commits_between`` always returning None instead of the reversed list. 0.1.5 ===== General ------- * upgraded to Mock 0.4 dependency. * Replace GitPython with git in repr() outputs. * Fixed packaging issue caused by ez_setup.py. Blob ---- * No longer strip newlines from Blob data. Commit ------ * Corrected problem with git-rev-list --bisect-all. See http://groups.google.com/group/git-python/browse_thread/thread/aed1d5c4b31d5027 Repo ---- * Corrected problems with creating bare repositories. * Repo.tree no longer accepts a path argument. Use: >>> dict(k, o for k, o in tree.items() if k in paths) * Made daemon export a property of Repo. Now you can do this: >>> exported = repo.daemon_export >>> repo.daemon_export = True * Allows modifying the project description. Do this: >>> repo.description = "Foo Bar" >>> repo.description 'Foo Bar' * Added a read-only property Repo.is_dirty which reflects the status of the working directory. * Added a read-only Repo.active_branch property which returns the name of the currently active branch. Tree ---- * Switched to using a dictionary for Tree contents since you will usually want to access them by name and order is unimportant. * Implemented a dictionary protocol for Tree objects. The following: child = tree.contents['grit'] becomes: child = tree['grit'] * Made Tree.content_from_string a static method. 0.1.4.1 ======= * removed ``method_missing`` stuff and replaced with a ``__getattr__`` override in ``Git``. 0.1.4 ===== * renamed ``git_python`` to ``git``. Be sure to delete all pyc files before testing. Commit ------ * Fixed problem with commit stats not working under all conditions. Git --- * Renamed module to cmd. * Removed shell escaping completely. * Added support for ``stderr``, ``stdin``, and ``with_status``. * ``git_dir`` is now optional in the constructor for ``git.Git``. Git now falls back to ``os.getcwd()`` when git_dir is not specified. * add a ``with_exceptions`` keyword argument to git commands. ``GitCommandError`` is raised when the exit status is non-zero. * add support for a ``GIT_PYTHON_TRACE`` environment variable. ``GIT_PYTHON_TRACE`` allows us to debug GitPython's usage of git through the use of an environment variable. Tree ---- * Fixed up problem where ``name`` doesn't exist on root of tree. Repo ---- * Corrected problem with creating bare repo. Added ``Repo.create`` alias. 0.1.2 ===== Tree ---- * Corrected problem with ``Tree.__div__`` not working with zero length files. Removed ``__len__`` override and replaced with size instead. Also made size cach properly. This is a breaking change. 0.1.1 ===== Fixed up some urls because I'm a moron 0.1.0 ===== initial release python-git-1.0.1+git137-gc8b8379/doc/source/conf.py000066400000000000000000000142231256444316100213550ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # GitPython documentation build configuration file, created by # sphinx-quickstart on Sat Jan 24 11:51:01 2009. # # This file is execfile()d with the current directory set to its containing dir. # # The contents of this file are pickled, so don't put values in the namespace # that aren't pickleable (module imports are okay, they're removed automatically). # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If your extensions are in another directory, add it here. If the directory # is relative to the documentation root, use os.path.abspath to make it # absolute, like shown here. #sys.path.append(os.path.abspath('.')) sys.path.insert(0, os.path.abspath('../..')) # General configuration # --------------------- # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest'] # Add any paths that contain templates here, relative to this directory. templates_path = ['.templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8' # The master toctree document. master_doc = 'index' # General information about the project. project = u'GitPython' copyright = u'Copyright (C) 2008, 2009 Michael Trier and contributors, 2010-2015 Sebastian Thiel' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. VERSION = open(os.path.join(os.path.dirname(__file__),"..", "..", 'VERSION')).readline().strip() version = VERSION # The full version, including alpha/beta/rc tags. release = VERSION # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of documents that shouldn't be included in the build. #unused_docs = [] # List of directories, relative to source directory, that shouldn't be searched # for source files. exclude_trees = ['build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # Options for HTML output # ----------------------- html_theme_options = { } # The style sheet to use for HTML and HTML Help pages. A file of that name # must exist either in Sphinx' static/ path, or in one of the custom paths # given in html_static_path. html_style = 'default.css' # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['.static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_use_modindex = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, the reST sources are included in the HTML build as _sources/. #html_copy_source = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = '' # Output file base name for HTML help builder. htmlhelp_basename = 'gitpythondoc' # Options for LaTeX output # ------------------------ # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, document class [howto/manual]). latex_documents = [ ('index', 'GitPython.tex', ur'GitPython Documentation', ur'Michael Trier', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # Additional stuff for the LaTeX preamble. #latex_preamble = '' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_use_modindex = True python-git-1.0.1+git137-gc8b8379/doc/source/index.rst000066400000000000000000000007111256444316100217140ustar00rootroot00000000000000.. GitPython documentation master file, created by sphinx-quickstart on Sat Jan 24 11:51:01 2009. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. GitPython Documentation ======================= .. toctree:: :maxdepth: 2 intro whatsnew tutorial reference roadmap changes Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` python-git-1.0.1+git137-gc8b8379/doc/source/intro.rst000066400000000000000000000067731256444316100217560ustar00rootroot00000000000000.. _intro_toplevel: ================== Overview / Install ================== GitPython is a python library used to interact with git repositories, high-level like git-porcelain, or low-level like git-plumbing. It provides abstractions of git objects for easy access of repository data, and additionally allows you to access the git repository more directly using either a pure python implementation, or the faster, but more resource intensive git command implementation. The object database implementation is optimized for handling large quantities of objects and large datasets, which is achieved by using low-level structures and data streaming. Requirements ============ * `Git`_ 1.7.0 or newer It should also work with older versions, but it may be that some operations involving remotes will not work as expected. * `GitDB`_ - a pure python git database implementation * `Python Nose`_ - used for running the tests * `Mock by Michael Foord`_ used for tests. Requires version 0.5 .. _Git: http://git-scm.com/ .. _Python Nose: http://code.google.com/p/python-nose/ .. _Mock by Michael Foord: http://www.voidspace.org.uk/python/mock.html .. _GitDB: http://pypi.python.org/pypi/gitdb Installing GitPython ==================== Installing GitPython is easily done using `pip`_. Assuming it is installed, just run the following from the command-line: .. sourcecode:: none # pip install gitpython This command will download the latest version of GitPython from the `Python Package Index `_ and install it to your system. More information about ``pip`` and pypi can be found here: * `install pip `_ * `pypi `_ .. _pip: https://pip.pypa.io/en/latest/installing.html Alternatively, you can install from the distribution using the ``setup.py`` script: .. sourcecode:: none # python setup.py install .. note:: In this case, you have to manually install `GitDB`_ as well. It would be recommended to use the :ref:`git source repository ` in that case. Getting Started =============== * :ref:`tutorial-label` - This tutorial provides a walk-through of some of the basic functionality and concepts used in GitPython. It, however, is not exhaustive so you are encouraged to spend some time in the :ref:`api_reference_toplevel`. API Reference ============= An organized section of the GitPthon API is at :ref:`api_reference_toplevel`. .. _source-code-label: Source Code =========== GitPython's git repo is available on GitHub, which can be browsed at: * https://github.com/gitpython-developers/GitPython and cloned using:: $ git clone https://github.com/gitpython-developers/GitPython git-python Initialize all submodules to obtain the required dependencies with:: $ cd git-python $ git submodule update --init --recursive Finally verify the installation by running the `nose powered `_ unit tests:: $ nosetests Questions and Answers ===================== Please use stackoverflow for questions, and don't forget to tag it with `gitpython` to assure the right people see the question in a timely manner. http://stackoverflow.com/questions/tagged/gitpython Issue Tracker ============= The issue tracker is hosted by github: https://github.com/gitpython-developers/GitPython/issues License Information =================== GitPython is licensed under the New BSD License. See the LICENSE file for more information. python-git-1.0.1+git137-gc8b8379/doc/source/reference.rst000066400000000000000000000062511256444316100225500ustar00rootroot00000000000000.. _api_reference_toplevel: API Reference ============= Objects.Base ------------ .. automodule:: git.objects.base :members: :undoc-members: :special-members: Objects.Blob ------------ .. automodule:: git.objects.blob :members: :undoc-members: :special-members: Objects.Commit -------------- .. automodule:: git.objects.commit :members: :undoc-members: :special-members: Objects.Tag ----------- .. automodule:: git.objects.tag :members: :undoc-members: :special-members: Objects.Tree ------------ .. automodule:: git.objects.tree :members: :undoc-members: :special-members: Objects.Functions ----------------- .. automodule:: git.objects.fun :members: :undoc-members: :special-members: Objects.Submodule.base ---------------------- .. automodule:: git.objects.submodule.base :members: :undoc-members: :special-members: Objects.Submodule.root ---------------------- .. automodule:: git.objects.submodule.root :members: :undoc-members: :special-members: Objects.Submodule.util ---------------------- .. automodule:: git.objects.submodule.util :members: :undoc-members: :special-members: Objects.Util ------------- .. automodule:: git.objects.util :members: :undoc-members: :special-members: Index.Base ---------- .. automodule:: git.index.base :members: :undoc-members: :special-members: Index.Functions --------------- .. automodule:: git.index.fun :members: :undoc-members: :special-members: Index.Types ----------- .. automodule:: git.index.typ :members: :undoc-members: :special-members: Index.Util ------------- .. automodule:: git.index.util :members: :undoc-members: :special-members: GitCmd ------ .. automodule:: git.cmd :members: :undoc-members: :special-members: Config ------ .. automodule:: git.config :members: :undoc-members: :special-members: Diff ---- .. automodule:: git.diff :members: :undoc-members: :special-members: Exceptions ---------- .. automodule:: git.exc :members: :undoc-members: :special-members: Refs.symbolic ------------- .. automodule:: git.refs.symbolic :members: :undoc-members: :special-members: Refs.reference -------------- .. automodule:: git.refs.reference :members: :undoc-members: :special-members: Refs.head --------- .. automodule:: git.refs.head :members: :undoc-members: :special-members: Refs.tag ------------ .. automodule:: git.refs.tag :members: :undoc-members: :special-members: Refs.remote ------------ .. automodule:: git.refs.remote :members: :undoc-members: :special-members: Refs.log ------------ .. automodule:: git.refs.log :members: :undoc-members: :special-members: Remote ------ .. automodule:: git.remote :members: :undoc-members: :special-members: Repo.Base --------- .. automodule:: git.repo.base :members: :undoc-members: :special-members: Repo.Functions -------------- .. automodule:: git.repo.fun :members: :undoc-members: :special-members: Util ---- .. automodule:: git.util :members: :undoc-members: :special-members: python-git-1.0.1+git137-gc8b8379/doc/source/roadmap.rst000066400000000000000000000003561256444316100222350ustar00rootroot00000000000000 ####### Roadmap ####### The full list of milestones including associated tasks can be found on github: https://github.com/gitpython-developers/GitPython/issues Select the respective milestone to filter the list of issues accordingly. python-git-1.0.1+git137-gc8b8379/doc/source/tutorial.rst000066400000000000000000000571101256444316100224550ustar00rootroot00000000000000.. _tutorial_toplevel: .. highlight:: python .. _tutorial-label: ================== GitPython Tutorial ================== GitPython provides object model access to your git repository. This tutorial is composed of multiple sections, most of which explains a real-life usecase. All code presented here originated from `test_docs.py `_ to assure correctness. Knowing this should also allow you to more easily run the code for your own testing purposes, all you need is a developer installation of git-python. Meet the Repo type ****************** The first step is to create a :class:`git.Repo ` object to represent your repository. .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [1-test_init_repo_object] :end-before: # ![1-test_init_repo_object] In the above example, the directory ``self.rorepo.working_tree_dir`` equals ``/Users/mtrier/Development/git-python`` and is my working repository which contains the ``.git`` directory. You can also initialize GitPython with a *bare* repository. .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [2-test_init_repo_object] :end-before: # ![2-test_init_repo_object] A repo object provides high-level access to your data, it allows you to create and delete heads, tags and remotes and access the configuration of the repository. .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [3-test_init_repo_object] :end-before: # ![3-test_init_repo_object] Query the active branch, query untracked files or whether the repository data has been modified. .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [4-test_init_repo_object] :end-before: # ![4-test_init_repo_object] Clone from existing repositories or initialize new empty ones. .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [5-test_init_repo_object] :end-before: # ![5-test_init_repo_object] Archive the repository contents to a tar file. .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [6-test_init_repo_object] :end-before: # ![6-test_init_repo_object] Advanced Repo Usage =================== And of course, there is much more you can do with this type, most of the following will be explained in greater detail in specific tutorials. Don't worry if you don't understand some of these examples right away, as they may require a thorough understanding of gits inner workings. Query relevant repository paths ... .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [7-test_init_repo_object] :end-before: # ![7-test_init_repo_object] :class:`Heads ` Heads are branches in git-speak. :class:`References ` are pointers to a specific commit or to other references. Heads and :class:`Tags ` are a kind of references. GitPython allows you to query them rather intuitively. .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [8-test_init_repo_object] :end-before: # ![8-test_init_repo_object] You can also create new heads ... .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [9-test_init_repo_object] :end-before: # ![9-test_init_repo_object] ... and tags ... .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [10-test_init_repo_object] :end-before: # ![10-test_init_repo_object] You can traverse down to :class:`git objects ` through references and other objects. Some objects like :class:`commits ` have additional meta-data to query. .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [11-test_init_repo_object] :end-before: # ![11-test_init_repo_object] :class:`Remotes ` allow to handle fetch, pull and push operations, while providing optional real-time progress information to :class:`progress delegates `. .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [12-test_init_repo_object] :end-before: # ![12-test_init_repo_object] The :class:`index ` is also called stage in git-speak. It is used to prepare new commits, and can be used to keep results of merge operations. Our index implementation allows to stream date into the index, which is useful for bare repositories that do not have a working tree. .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [13-test_init_repo_object] :end-before: # ![13-test_init_repo_object] :class:`Submodules ` represent all aspects of git submodules, which allows you query all of their related information, and manipulate in various ways. .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [14-test_init_repo_object] :end-before: # ![14-test_init_repo_object] Examining References ******************** :class:`References ` are the tips of your commit graph from which you can easily examine the history of your project. .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [1-test_references_and_objects] :end-before: # ![1-test_references_and_objects] :class:`Tags ` are (usually immutable) references to a commit and/or a tag object. .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [2-test_references_and_objects] :end-before: # ![2-test_references_and_objects] A :class:`symbolic reference ` is a special case of a reference as it points to another reference instead of a commit. .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [3-test_references_and_objects] :end-before: # ![3-test_references_and_objects] Access the :class:`reflog ` easily. .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [4-test_references_and_objects] :end-before: # ![4-test_references_and_objects] Modifying References ******************** You can easily create and delete :class:`reference types ` or modify where they point to. .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [5-test_references_and_objects] :end-before: # ![5-test_references_and_objects] Create or delete :class:`tags ` the same way except you may not change them afterwards. .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [6-test_references_and_objects] :end-before: # ![6-test_references_and_objects] Change the :class:`symbolic reference ` to switch branches cheaply (without adjusting the index or the working tree). .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [7-test_references_and_objects] :end-before: # ![7-test_references_and_objects] Understanding Objects ********************* An Object is anything storable in git's object database. Objects contain information about their type, their uncompressed size as well as the actual data. Each object is uniquely identified by a binary SHA1 hash, being 20 bytes in size, or 40 bytes in hexadecimal notation. Git only knows 4 distinct object types being :class:`Blobs `, :class:`Trees `, :class:`Commits ` and :class:`Tags `. In GitPython, all objects can be accessed through their common base, can be compared and hashed. They are usually not instantiated directly, but through references or specialized repository functions. .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [8-test_references_and_objects] :end-before: # ![8-test_references_and_objects] Common fields are ... .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [9-test_references_and_objects] :end-before: # ![9-test_references_and_objects] :class:`Index objects ` are objects that can be put into git's index. These objects are trees, blobs and submodules which additionally know about their path in the file system as well as their mode. .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [10-test_references_and_objects] :end-before: # ![10-test_references_and_objects] Access :class:`blob ` data (or any object data) using streams. .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [11-test_references_and_objects] :end-before: # ![11-test_references_and_objects] The Commit object ***************** :class:`Commit ` objects contain information about a specific commit. Obtain commits using references as done in `Examining References`_ or as follows. Obtain commits at the specified revision .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [12-test_references_and_objects] :end-before: # ![12-test_references_and_objects] Iterate 50 commits, and if you need paging, you can specify a number of commits to skip. .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [13-test_references_and_objects] :end-before: # ![13-test_references_and_objects] A commit object carries all sorts of meta-data .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [14-test_references_and_objects] :end-before: # ![14-test_references_and_objects] Note: date time is represented in a ``seconds since epoch`` format. Conversion to human readable form can be accomplished with the various `time module `_ methods. .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [15-test_references_and_objects] :end-before: # ![15-test_references_and_objects] You can traverse a commit's ancestry by chaining calls to ``parents`` .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [16-test_references_and_objects] :end-before: # ![16-test_references_and_objects] The above corresponds to ``master^^^`` or ``master~3`` in git parlance. The Tree object *************** A :class:`tree ` records pointers to the contents of a directory. Let's say you want the root tree of the latest commit on the master branch .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [17-test_references_and_objects] :end-before: # ![17-test_references_and_objects] Once you have a tree, you can get it's contents .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [18-test_references_and_objects] :end-before: # ![18-test_references_and_objects] It is useful to know that a tree behaves like a list with the ability to query entries by name .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [19-test_references_and_objects] :end-before: # ![19-test_references_and_objects] There is a convenience method that allows you to get a named sub-object from a tree with a syntax similar to how paths are written in a posix system .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [20-test_references_and_objects] :end-before: # ![20-test_references_and_objects] You can also get a commit's root tree directly from the repository .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [21-test_references_and_objects] :end-before: # ![21-test_references_and_objects] As trees allow direct access to their intermediate child entries only, use the traverse method to obtain an iterator to retrieve entries recursively .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [22-test_references_and_objects] :end-before: # ![22-test_references_and_objects] .. note:: If trees return Submodule objects, they will assume that they exist at the current head's commit. The tree it originated from may be rooted at another commit though, that it doesn't know. That is why the caller would have to set the submodule's owning or parent commit using the ``set_parent_commit(my_commit)`` method. The Index Object **************** The git index is the stage containing changes to be written with the next commit or where merges finally have to take place. You may freely access and manipulate this information using the :class:`IndexFile ` object. Modify the index with ease .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [23-test_references_and_objects] :end-before: # ![23-test_references_and_objects] Create new indices from other trees or as result of a merge. Write that result to a new index file for later inspection. .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [24-test_references_and_objects] :end-before: # ![24-test_references_and_objects] Handling Remotes **************** :class:`Remotes ` are used as alias for a foreign repository to ease pushing to and fetching from them .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [25-test_references_and_objects] :end-before: # ![25-test_references_and_objects] You can easily access configuration information for a remote by accessing options as if they where attributes. The modification of remote configuration is more explicit though. .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [26-test_references_and_objects] :end-before: # ![26-test_references_and_objects] You can also specify per-call custom environments using a new context manager on the Git command, e.g. for using a specific SSH key. The following example works with `git` starting at *v2.3*:: ssh_cmd = 'ssh -i id_deployment_key' with repo.git.custom_environment(GIT_SSH_COMMAND=ssh_cmd): repo.remotes.origin.fetch() This one sets a custom script to be executed in place of `ssh`, and can be used in `git` prior to *v2.3*:: ssh_executable = os.path.join(rw_dir, 'my_ssh_executable.sh') with repo.git.custom_environment(GIT_SSH=ssh_executable): repo.remotes.origin.fetch() Here's an example executable that can be used in place of the `ssh_executable` above:: #!/bin/sh ID_RSA=/var/lib/openshift/5562b947ecdd5ce939000038/app-deployments/id_rsa exec /usr/bin/ssh -o StrictHostKeyChecking=no -i $ID_RSA "$@" Please note that the script must be executable (i.e. `chomd +x script.sh`). `StrictHostKeyChecking=no` is used to avoid prompts asking to save the hosts key to `~/.ssh/known_hosts`, which happens in case you run this as daemon. You might also have a look at `Git.update_environment(...)` in case you want to setup a changed environment more permanently. Submodule Handling ****************** :class:`Submodules ` can be conveniently handled using the methods provided by GitPython, and as an added benefit, GitPython provides functionality which behave smarter and less error prone than its original c-git implementation, that is GitPython tries hard to keep your repository consistent when updating submodules recursively or adjusting the existing configuration. .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [1-test_submodules] :end-before: # ![1-test_submodules] In addition to the query functionality, you can move the submodule's repository to a different path <``move(...)``>, write its configuration <``config_writer().set_value(...).release()``>, update its working tree <``update(...)``>, and remove or add them <``remove(...)``, ``add(...)``>. If you obtained your submodule object by traversing a tree object which is not rooted at the head's commit, you have to inform the submodule about its actual commit to retrieve the data from by using the ``set_parent_commit(...)`` method. The special :class:`RootModule ` type allows you to treat your master repository as root of a hierarchy of submodules, which allows very convenient submodule handling. Its ``update(...)`` method is reimplemented to provide an advanced way of updating submodules as they change their values over time. The update method will track changes and make sure your working tree and submodule checkouts stay consistent, which is very useful in case submodules get deleted or added to name just two of the handled cases. Additionally, GitPython adds functionality to track a specific branch, instead of just a commit. Supported by customized update methods, you are able to automatically update submodules to the latest revision available in the remote repository, as well as to keep track of changes and movements of these submodules. To use it, set the name of the branch you want to track to the ``submodule.$name.branch`` option of the *.gitmodules* file, and use GitPython update methods on the resulting repository with the ``to_latest_revision`` parameter turned on. In the latter case, the sha of your submodule will be ignored, instead a local tracking branch will be updated to the respective remote branch automatically, provided there are no local changes. The resulting behaviour is much like the one of svn::externals, which can be useful in times. Obtaining Diff Information ************************** Diffs can generally be obtained by subclasses of :class:`Diffable ` as they provide the ``diff`` method. This operation yields a :class:`DiffIndex ` allowing you to easily access diff information about paths. Diffs can be made between the Index and Trees, Index and the working tree, trees and trees as well as trees and the working copy. If commits are involved, their tree will be used implicitly. .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [27-test_references_and_objects] :end-before: # ![27-test_references_and_objects] The item returned is a DiffIndex which is essentially a list of Diff objects. It provides additional filtering to ease finding what you might be looking for. .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [28-test_references_and_objects] :end-before: # ![28-test_references_and_objects] Use the diff framework if you want to implement git-status like functionality. * A diff between the index and the commit's tree your HEAD points to * use ``repo.index.diff(repo.head.commit)`` * A diff between the index and the working tree * use ``repo.index.diff(None)`` * A list of untracked files * use ``repo.untracked_files`` Switching Branches ****************** To switch between branches similar to ``git checkout``, you effectively need to point your HEAD symbolic reference to the new branch and reset your index and working copy to match. A simple manual way to do it is the following one .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [29-test_references_and_objects] :end-before: # ![29-test_references_and_objects] The previous approach would brutally overwrite the user's changes in the working copy and index though and is less sophisticated than a ``git-checkout``. The latter will generally prevent you from destroying your work. Use the safer approach as follows. .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [30-test_references_and_objects] :end-before: # ![30-test_references_and_objects] Initializing a repository ************************* In this example, we will initialize an empty repository, add an empty file to the index, and commit the change. .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: def test_add_file_and_commit :end-before: # ![test_add_file_and_commit] Please have a look at the individual methods as they usually support a vast amount of arguments to customize their behavior. Using git directly ****************** In case you are missing functionality as it has not been wrapped, you may conveniently use the :class:`git ` command directly. It is owned by each repository instance. .. literalinclude:: ../../git/test/test_docs.py :language: python :start-after: # [31-test_references_and_objects] :end-before: # ![31-test_references_and_objects] The return value will by default be a string of the standard output channel produced by the command. Keyword arguments translate to short and long keyword arguments on the command-line. The special notion ``git.command(flag=True)`` will create a flag without value like ``command --flag``. If ``None`` is found in the arguments, it will be dropped silently. Lists and tuples passed as arguments will be unpacked recursively to individual arguments. Objects are converted to strings using the ``str(...)`` function. Object Databases **************** :class:`git.Repo ` instances are powered by its object database instance which will be used when extracting any data, or when writing new objects. The type of the database determines certain performance characteristics, such as the quantity of objects that can be read per second, the resource usage when reading large data files, as well as the average memory footprint of your application. GitDB ===== The GitDB is a pure-python implementation of the git object database. It is the default database to use in GitPython 0.3. Its uses less memory when handling huge files, but will be 2 to 5 times slower when extracting large quantities small of objects from densely packed repositories:: repo = Repo("path/to/repo", odbt=GitDB) GitCmdObjectDB ============== The git command database uses persistent git-cat-file instances to read repository information. These operate very fast under all conditions, but will consume additional memory for the process itself. When extracting large files, memory usage will be much higher than the one of the ``GitDB``:: repo = Repo("path/to/repo", odbt=GitCmdObjectDB) Git Command Debugging and Customization *************************************** Using environment variables, you can further adjust the behaviour of the git command. * **GIT_PYTHON_TRACE** * If set to non-0, all executed git commands will be logged using a python logger. * if set to *full*, the executed git command and its output on stdout and stderr will be logged using a python logger. * **GIT_PYTHON_GIT_EXECUTABLE** * If set, it should contain the full path to the git executable, e.g. *c:\\Program Files (x86)\\Git\\bin\\git.exe* on windows or */usr/bin/git* on linux. And even more ... ***************** There is more functionality in there, like the ability to archive repositories, get stats and logs, blame, and probably a few other things that were not mentioned here. Check the unit tests for an in-depth introduction on how each function is supposed to be used. python-git-1.0.1+git137-gc8b8379/doc/source/whatsnew.rst000066400000000000000000000043331256444316100224510ustar00rootroot00000000000000 ################ Whats New in 0.3 ################ GitPython 0.3 is the first step in creating a hybrid which uses a pure python implementations for all simple git features which can be implemented without significant performance penalties. Everything else is still performed using the git command, which is nicely integrated and easy to use. Its biggest strength, being the support for all git features through the git command itself, is a weakness as well considering the possibly vast amount of times the git command is being started up. Depending on the actual command being performed, the git repository will be initialized on many of these invocations, causing additional overhead for possibly tiny operations. Keeping as many major operations in the python world will result in improved caching benefits as certain data structures just have to be initialized once and can be reused multiple times. This mode of operation may improve performance when altering the git database on a low level, and is clearly beneficial on operating systems where command invocations are very slow. **************** Object Databases **************** An object database provides a simple interface to query object information or to write new object data. Objects are generally identified by their 20 byte binary sha1 value during query. GitPython uses the ``gitdb`` project to provide a pure-python implementation of the git database, which includes reading and writing loose objects, reading pack files and handling alternate repositories. The great thing about this is that ``Repo`` objects can use any object database, hence it easily supports different implementations with different performance characteristics. If you are thinking in extremes, you can implement your own database representation, which may be more efficient for what you want to do specifically, like handling big files more efficiently. ************************ Reduced Memory Footprint ************************ Objects, such as commits, tags, trees and blobs now use 20 byte sha1 signatures internally, reducing their memory demands by 20 bytes per object, allowing you to keep more objects in memory at the same time. The internal caches of tree objects were improved to use less memory as well. python-git-1.0.1+git137-gc8b8379/etc/000077500000000000000000000000001256444316100165625ustar00rootroot00000000000000python-git-1.0.1+git137-gc8b8379/etc/sublime-text/000077500000000000000000000000001256444316100212045ustar00rootroot00000000000000python-git-1.0.1+git137-gc8b8379/etc/sublime-text/git-python.sublime-project000066400000000000000000000017031256444316100263350ustar00rootroot00000000000000{ "folders": [ // GIT-PYTHON ///////////// { "follow_symlinks": true, "path": "../..", "file_exclude_patterns" : [ "*.sublime-workspace", ".git", ".noseids", ".coverage" ], "folder_exclude_patterns" : [ ".git", "cover", "git/ext", "dist", ".tox", "doc/build", "*.egg-info" ] }, // GITDB //////// { "follow_symlinks": true, "path": "../../git/ext/gitdb", "file_exclude_patterns" : [ "*.sublime-workspace", ".git", ".noseids", ".coverage" ], "folder_exclude_patterns" : [ ".git", "cover", "gitdb/ext", "dist", "doc/build", ".tox", ] }, // // SMMAP // //////// { "follow_symlinks": true, "path": "../../git/ext/gitdb/gitdb/ext/smmap", "file_exclude_patterns" : [ "*.sublime-workspace", ".git", ".noseids", ".coverage" ], "folder_exclude_patterns" : [ ".git", "cover", ] }, ] } python-git-1.0.1+git137-gc8b8379/git/000077500000000000000000000000001256444316100165725ustar00rootroot00000000000000python-git-1.0.1+git137-gc8b8379/git/__init__.py000066400000000000000000000023201256444316100207000ustar00rootroot00000000000000# __init__.py # Copyright (C) 2008, 2009 Michael Trier (mtrier@gmail.com) and contributors # # This module is part of GitPython and is released under # the BSD License: http://www.opensource.org/licenses/bsd-license.php # flake8: noqa import os import sys import inspect __version__ = 'git' #{ Initialization def _init_externals(): """Initialize external projects by putting them into the path""" if __version__ == 'git': sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'ext', 'gitdb')) try: import gitdb except ImportError: raise ImportError("'gitdb' could not be found in your PYTHONPATH") # END verify import #} END initialization ################# _init_externals() ################# #{ Imports from git.config import GitConfigParser from git.objects import * from git.refs import * from git.diff import * from git.exc import * from git.db import * from git.cmd import Git from git.repo import Repo from git.remote import * from git.index import * from git.util import ( LockFile, BlockingLockFile, Stats, Actor ) #} END imports __all__ = [name for name, obj in locals().items() if not (name.startswith('_') or inspect.ismodule(obj))] python-git-1.0.1+git137-gc8b8379/git/cmd.py000066400000000000000000001035701256444316100177150ustar00rootroot00000000000000# cmd.py # Copyright (C) 2008, 2009 Michael Trier (mtrier@gmail.com) and contributors # # This module is part of GitPython and is released under # the BSD License: http://www.opensource.org/licenses/bsd-license.php import os import os.path import sys import select import logging import threading import errno import mmap from contextlib import contextmanager from subprocess import ( call, Popen, PIPE ) from .util import ( LazyMixin, stream_copy, WaitGroup ) from .exc import ( GitCommandError, GitCommandNotFound ) from git.compat import ( string_types, defenc, PY3, bchr, # just to satisfy flake8 on py3 unicode ) execute_kwargs = ('istream', 'with_keep_cwd', 'with_extended_output', 'with_exceptions', 'as_process', 'stdout_as_string', 'output_stream', 'with_stdout') log = logging.getLogger('git.cmd') log.addHandler(logging.NullHandler()) __all__ = ('Git', ) if sys.platform != 'win32': WindowsError = OSError if PY3: _bchr = bchr else: def _bchr(c): return c # get custom byte character handling # ============================================================================== ## @name Utilities # ------------------------------------------------------------------------------ # Documentation ## @{ def handle_process_output(process, stdout_handler, stderr_handler, finalizer): """Registers for notifications to lean that process output is ready to read, and dispatches lines to the respective line handlers. We are able to handle carriage returns in case progress is sent by that mean. For performance reasons, we only apply this to stderr. This function returns once the finalizer returns :return: result of finalizer :param process: subprocess.Popen instance :param stdout_handler: f(stdout_line_string), or None :param stderr_hanlder: f(stderr_line_string), or None :param finalizer: f(proc) - wait for proc to finish""" fdmap = {process.stdout.fileno(): (stdout_handler, [b'']), process.stderr.fileno(): (stderr_handler, [b''])} def _parse_lines_from_buffer(buf): line = b'' bi = 0 lb = len(buf) while bi < lb: char = _bchr(buf[bi]) bi += 1 if char in (b'\r', b'\n') and line: yield bi, line line = b'' else: line += char # END process parsed line # END while file is not done reading # end def _read_lines_from_fno(fno, last_buf_list): buf = os.read(fno, mmap.PAGESIZE) buf = last_buf_list[0] + buf bi = 0 for bi, line in _parse_lines_from_buffer(buf): yield line # for each line to parse from the buffer # keep remainder last_buf_list[0] = buf[bi:] def _dispatch_single_line(line, handler): line = line.decode(defenc) if line and handler: try: handler(line) except Exception: # Keep reading, have to pump the lines empty nontheless log.error("Line handler exception on line: %s", line, exc_info=True) # end # end dispatch helper # end single line helper def _dispatch_lines(fno, handler, buf_list): lc = 0 for line in _read_lines_from_fno(fno, buf_list): _dispatch_single_line(line, handler) lc += 1 # for each line return lc # end def _deplete_buffer(fno, handler, buf_list, wg=None): lc = 0 while True: line_count = _dispatch_lines(fno, handler, buf_list) lc += line_count if line_count == 0: break # end deplete buffer if buf_list[0]: _dispatch_single_line(buf_list[0], handler) lc += 1 # end if wg: wg.done() return lc # end if hasattr(select, 'poll'): # poll is preferred, as select is limited to file handles up to 1024 ... . This could otherwise be # an issue for us, as it matters how many handles our own process has poll = select.poll() READ_ONLY = select.POLLIN | select.POLLPRI | select.POLLHUP | select.POLLERR CLOSED = select.POLLHUP | select.POLLERR poll.register(process.stdout, READ_ONLY) poll.register(process.stderr, READ_ONLY) closed_streams = set() while True: # no timeout try: poll_result = poll.poll() except select.error as e: if e.args[0] == errno.EINTR: continue raise # end handle poll exception for fd, result in poll_result: if result & CLOSED: closed_streams.add(fd) else: _dispatch_lines(fd, *fdmap[fd]) # end handle closed stream # end for each poll-result tuple if len(closed_streams) == len(fdmap): break # end its all done # end endless loop # Depelete all remaining buffers for fno, (handler, buf_list) in fdmap.items(): _deplete_buffer(fno, handler, buf_list) # end for each file handle for fno in fdmap.keys(): poll.unregister(fno) # end don't forget to unregister ! else: # Oh ... probably we are on windows. select.select() can only handle sockets, we have files # The only reliable way to do this now is to use threads and wait for both to finish # Since the finalizer is expected to wait, we don't have to introduce our own wait primitive # NO: It's not enough unfortunately, and we will have to sync the threads wg = WaitGroup() for fno, (handler, buf_list) in fdmap.items(): wg.add(1) t = threading.Thread(target=lambda: _deplete_buffer(fno, handler, buf_list, wg)) t.start() # end # NOTE: Just joining threads can possibly fail as there is a gap between .start() and when it's # actually started, which could make the wait() call to just return because the thread is not yet # active wg.wait() # end return finalizer(process) def dashify(string): return string.replace('_', '-') ## -- End Utilities -- @} class Git(LazyMixin): """ The Git class manages communication with the Git binary. It provides a convenient interface to calling the Git binary, such as in:: g = Git( git_dir ) g.init() # calls 'git init' program rval = g.ls_files() # calls 'git ls-files' program ``Debugging`` Set the GIT_PYTHON_TRACE environment variable print each invocation of the command to stdout. Set its value to 'full' to see details about the returned values. """ __slots__ = ("_working_dir", "cat_file_all", "cat_file_header", "_version_info", "_git_options", "_environment") # CONFIGURATION # The size in bytes read from stdout when copying git's output to another stream max_chunk_size = 1024 * 64 git_exec_name = "git" # default that should work on linux and windows git_exec_name_win = "git.cmd" # alternate command name, windows only # Enables debugging of GitPython's git commands GIT_PYTHON_TRACE = os.environ.get("GIT_PYTHON_TRACE", False) # Provide the full path to the git executable. Otherwise it assumes git is in the path _git_exec_env_var = "GIT_PYTHON_GIT_EXECUTABLE" GIT_PYTHON_GIT_EXECUTABLE = os.environ.get(_git_exec_env_var, git_exec_name) # If True, a shell will be used when executing git commands. # This should only be desirable on windows, see https://github.com/gitpython-developers/GitPython/pull/126 # for more information # Override this value using `Git.USE_SHELL = True` USE_SHELL = False class AutoInterrupt(object): """Kill/Interrupt the stored process instance once this instance goes out of scope. It is used to prevent processes piling up in case iterators stop reading. Besides all attributes are wired through to the contained process object. The wait method was overridden to perform automatic status code checking and possibly raise.""" __slots__ = ("proc", "args") def __init__(self, proc, args): self.proc = proc self.args = args def __del__(self): if self.proc is None: return proc = self.proc self.proc = None if proc.stdin: proc.stdin.close() proc.stdout.close() proc.stderr.close() # did the process finish already so we have a return code ? if proc.poll() is not None: return # can be that nothing really exists anymore ... if os is None: return # try to kill it try: os.kill(proc.pid, 2) # interrupt signal proc.wait() # ensure process goes away except (OSError, WindowsError): pass # ignore error when process already died except AttributeError: # try windows # for some reason, providing None for stdout/stderr still prints something. This is why # we simply use the shell and redirect to nul. Its slower than CreateProcess, question # is whether we really want to see all these messages. Its annoying no matter what. call(("TASKKILL /F /T /PID %s 2>nul 1>nul" % str(proc.pid)), shell=True) # END exception handling def __getattr__(self, attr): return getattr(self.proc, attr) def wait(self): """Wait for the process and return its status code. :raise GitCommandError: if the return status is not 0""" status = self.proc.wait() if status != 0: raise GitCommandError(self.args, status, self.proc.stderr.read()) # END status handling return status # END auto interrupt class CatFileContentStream(object): """Object representing a sized read-only stream returning the contents of an object. It behaves like a stream, but counts the data read and simulates an empty stream once our sized content region is empty. If not all data is read to the end of the objects's lifetime, we read the rest to assure the underlying stream continues to work""" __slots__ = ('_stream', '_nbr', '_size') def __init__(self, size, stream): self._stream = stream self._size = size self._nbr = 0 # num bytes read # special case: if the object is empty, has null bytes, get the # final newline right away. if size == 0: stream.read(1) # END handle empty streams def read(self, size=-1): bytes_left = self._size - self._nbr if bytes_left == 0: return '' if size > -1: # assure we don't try to read past our limit size = min(bytes_left, size) else: # they try to read all, make sure its not more than what remains size = bytes_left # END check early depletion data = self._stream.read(size) self._nbr += len(data) # check for depletion, read our final byte to make the stream usable by others if self._size - self._nbr == 0: self._stream.read(1) # final newline # END finish reading return data def readline(self, size=-1): if self._nbr == self._size: return '' # clamp size to lowest allowed value bytes_left = self._size - self._nbr if size > -1: size = min(bytes_left, size) else: size = bytes_left # END handle size data = self._stream.readline(size) self._nbr += len(data) # handle final byte if self._size - self._nbr == 0: self._stream.read(1) # END finish reading return data def readlines(self, size=-1): if self._nbr == self._size: return list() # leave all additional logic to our readline method, we just check the size out = list() nbr = 0 while True: line = self.readline() if not line: break out.append(line) if size > -1: nbr += len(line) if nbr > size: break # END handle size constraint # END readline loop return out def __iter__(self): return self def next(self): line = self.readline() if not line: raise StopIteration return line def __del__(self): bytes_left = self._size - self._nbr if bytes_left: # read and discard - seeking is impossible within a stream # includes terminating newline self._stream.read(bytes_left + 1) # END handle incomplete read def __init__(self, working_dir=None): """Initialize this instance with: :param working_dir: Git directory we should work in. If None, we always work in the current directory as returned by os.getcwd(). It is meant to be the working tree directory if available, or the .git directory in case of bare repositories.""" super(Git, self).__init__() self._working_dir = working_dir self._git_options = () # Extra environment variables to pass to git commands self._environment = {} # cached command slots self.cat_file_header = None self.cat_file_all = None def __getattr__(self, name): """A convenience method as it allows to call the command as if it was an object. :return: Callable object that will execute call _call_process with your arguments.""" if name[0] == '_': return LazyMixin.__getattr__(self, name) return lambda *args, **kwargs: self._call_process(name, *args, **kwargs) def _set_cache_(self, attr): if attr == '_version_info': # We only use the first 4 numbers, as everthing else could be strings in fact (on windows) version_numbers = self._call_process('version').split(' ')[2] self._version_info = tuple(int(n) for n in version_numbers.split('.')[:4] if n.isdigit()) else: super(Git, self)._set_cache_(attr) # END handle version info @property def working_dir(self): """:return: Git directory we are working on""" return self._working_dir @property def version_info(self): """ :return: tuple(int, int, int, int) tuple with integers representing the major, minor and additional version numbers as parsed from git version. This value is generated on demand and is cached""" return self._version_info def execute(self, command, istream=None, with_keep_cwd=False, with_extended_output=False, with_exceptions=True, as_process=False, output_stream=None, stdout_as_string=True, with_stdout=True, **subprocess_kwargs ): """Handles executing the command on the shell and consumes and returns the returned information (stdout) :param command: The command argument list to execute. It should be a string, or a sequence of program arguments. The program to execute is the first item in the args sequence or string. :param istream: Standard input filehandle passed to subprocess.Popen. :param with_keep_cwd: Whether to use the current working directory from os.getcwd(). The cmd otherwise uses its own working_dir that it has been initialized with if possible. :param with_extended_output: Whether to return a (status, stdout, stderr) tuple. :param with_exceptions: Whether to raise an exception when git returns a non-zero status. :param as_process: Whether to return the created process instance directly from which streams can be read on demand. This will render with_extended_output and with_exceptions ineffective - the caller will have to deal with the details himself. It is important to note that the process will be placed into an AutoInterrupt wrapper that will interrupt the process once it goes out of scope. If you use the command in iterators, you should pass the whole process instance instead of a single stream. :param output_stream: If set to a file-like object, data produced by the git command will be output to the given stream directly. This feature only has any effect if as_process is False. Processes will always be created with a pipe due to issues with subprocess. This merely is a workaround as data will be copied from the output pipe to the given output stream directly. Judging from the implementation, you shouldn't use this flag ! :param stdout_as_string: if False, the commands standard output will be bytes. Otherwise, it will be decoded into a string using the default encoding (usually utf-8). The latter can fail, if the output contains binary data. :param subprocess_kwargs: Keyword arguments to be passed to subprocess.Popen. Please note that some of the valid kwargs are already set by this method, the ones you specify may not be the same ones. :param with_stdout: If True, default True, we open stdout on the created process :return: * str(output) if extended_output = False (Default) * tuple(int(status), str(stdout), str(stderr)) if extended_output = True if ouput_stream is True, the stdout value will be your output stream: * output_stream if extended_output = False * tuple(int(status), output_stream, str(stderr)) if extended_output = True Note git is executed with LC_MESSAGES="C" to ensure consistent output regardless of system language. :raise GitCommandError: :note: If you add additional keyword arguments to the signature of this method, you must update the execute_kwargs tuple housed in this module.""" if self.GIT_PYTHON_TRACE and (self.GIT_PYTHON_TRACE != 'full' or as_process): log.info(' '.join(command)) # Allow the user to have the command executed in their working dir. if with_keep_cwd or self._working_dir is None: cwd = os.getcwd() else: cwd = self._working_dir # Start the process env = os.environ.copy() # Attempt to force all output to plain ascii english, which is what some parsing code # may expect. # According to stackoverflow (http://goo.gl/l74GC8), we are setting LANGUAGE as well # just to be sure. env["LANGUAGE"] = "C" env["LC_ALL"] = "C" env.update(self._environment) if sys.platform == 'win32': cmd_not_found_exception = WindowsError else: if sys.version_info[0] > 2: cmd_not_found_exception = FileNotFoundError # NOQA # this is defined, but flake8 doesn't know else: cmd_not_found_exception = OSError # end handle try: proc = Popen(command, env=env, cwd=cwd, stdin=istream, stderr=PIPE, stdout=with_stdout and PIPE or None, shell=self.USE_SHELL, close_fds=(os.name == 'posix'), # unsupported on windows **subprocess_kwargs ) except cmd_not_found_exception as err: raise GitCommandNotFound(str(err)) if as_process: return self.AutoInterrupt(proc, command) # Wait for the process to return status = 0 stdout_value = b'' stderr_value = b'' try: if output_stream is None: stdout_value, stderr_value = proc.communicate() # strip trailing "\n" if stdout_value.endswith(b"\n"): stdout_value = stdout_value[:-1] if stderr_value.endswith(b"\n"): stderr_value = stderr_value[:-1] status = proc.returncode else: stream_copy(proc.stdout, output_stream, self.max_chunk_size) stdout_value = output_stream stderr_value = proc.stderr.read() # strip trailing "\n" if stderr_value.endswith(b"\n"): stderr_value = stderr_value[:-1] status = proc.wait() # END stdout handling finally: proc.stdout.close() proc.stderr.close() if self.GIT_PYTHON_TRACE == 'full': cmdstr = " ".join(command) def as_text(stdout_value): return not output_stream and stdout_value.decode(defenc) or '' # end if stderr_value: log.info("%s -> %d; stdout: '%s'; stderr: '%s'", cmdstr, status, as_text(stdout_value), stderr_value.decode(defenc)) elif stdout_value: log.info("%s -> %d; stdout: '%s'", cmdstr, status, as_text(stdout_value)) else: log.info("%s -> %d", cmdstr, status) # END handle debug printing if with_exceptions and status != 0: if with_extended_output: raise GitCommandError(command, status, stderr_value, stdout_value) else: raise GitCommandError(command, status, stderr_value) if isinstance(stdout_value, bytes) and stdout_as_string: # could also be output_stream stdout_value = stdout_value.decode(defenc) # Allow access to the command's status code if with_extended_output: return (status, stdout_value, stderr_value.decode(defenc)) else: return stdout_value def environment(self): return self._environment def update_environment(self, **kwargs): """ Set environment variables for future git invocations. Return all changed values in a format that can be passed back into this function to revert the changes: ``Examples``:: old_env = self.update_environment(PWD='/tmp') self.update_environment(**old_env) :param kwargs: environment variables to use for git processes :return: dict that maps environment variables to their old values """ old_env = {} for key, value in kwargs.items(): # set value if it is None if value is not None: if key in self._environment: old_env[key] = self._environment[key] else: old_env[key] = None self._environment[key] = value # remove key from environment if its value is None elif key in self._environment: old_env[key] = self._environment[key] del self._environment[key] return old_env @contextmanager def custom_environment(self, **kwargs): """ A context manager around the above ``update_environment`` method to restore the environment back to its previous state after operation. ``Examples``:: with self.custom_environment(GIT_SSH='/bin/ssh_wrapper'): repo.remotes.origin.fetch() :param kwargs: see update_environment """ old_env = self.update_environment(**kwargs) try: yield finally: self.update_environment(**old_env) def transform_kwargs(self, split_single_char_options=False, **kwargs): """Transforms Python style kwargs into git command line options.""" args = list() for k, v in kwargs.items(): if len(k) == 1: if v is True: args.append("-%s" % k) elif type(v) is not bool: if split_single_char_options: args.extend(["-%s" % k, "%s" % v]) else: args.append("-%s%s" % (k, v)) else: if v is True: args.append("--%s" % dashify(k)) elif type(v) is not bool: args.append("--%s=%s" % (dashify(k), v)) return args @classmethod def __unpack_args(cls, arg_list): if not isinstance(arg_list, (list, tuple)): # This is just required for unicode conversion, as subprocess can't handle it # However, in any other case, passing strings (usually utf-8 encoded) is totally fine if not PY3 and isinstance(arg_list, unicode): return [arg_list.encode(defenc)] return [str(arg_list)] outlist = list() for arg in arg_list: if isinstance(arg_list, (list, tuple)): outlist.extend(cls.__unpack_args(arg)) elif not PY3 and isinstance(arg_list, unicode): outlist.append(arg_list.encode(defenc)) # END recursion else: outlist.append(str(arg)) # END for each arg return outlist def __call__(self, **kwargs): """Specify command line options to the git executable for a subcommand call :param kwargs: is a dict of keyword arguments. these arguments are passed as in _call_process but will be passed to the git command rather than the subcommand. ``Examples``:: git(work_tree='/tmp').difftool()""" self._git_options = self.transform_kwargs( split_single_char_options=True, **kwargs) return self def _call_process(self, method, *args, **kwargs): """Run the given git command with the specified arguments and return the result as a String :param method: is the command. Contained "_" characters will be converted to dashes, such as in 'ls_files' to call 'ls-files'. :param args: is the list of arguments. If None is included, it will be pruned. This allows your commands to call git more conveniently as None is realized as non-existent :param kwargs: is a dict of keyword arguments. This function accepts the same optional keyword arguments as execute(). ``Examples``:: git.rev_list('master', max_count=10, header=True) :return: Same as ``execute``""" # Handle optional arguments prior to calling transform_kwargs # otherwise these'll end up in args, which is bad. _kwargs = dict() for kwarg in execute_kwargs: try: _kwargs[kwarg] = kwargs.pop(kwarg) except KeyError: pass insert_after_this_arg = kwargs.pop('insert_kwargs_after', None) # Prepare the argument list opt_args = self.transform_kwargs(**kwargs) ext_args = self.__unpack_args([a for a in args if a is not None]) if insert_after_this_arg is None: args = opt_args + ext_args else: try: index = ext_args.index(insert_after_this_arg) except ValueError: raise ValueError("Couldn't find argument '%s' in args %s to insert kwargs after" % (insert_after_this_arg, str(ext_args))) # end handle error args = ext_args[:index + 1] + opt_args + ext_args[index + 1:] # end handle kwargs def make_call(): call = [self.GIT_PYTHON_GIT_EXECUTABLE] # add the git options, the reset to empty # to avoid side_effects call.extend(self._git_options) self._git_options = () call.extend([dashify(method)]) call.extend(args) return call # END utility to recreate call after changes if sys.platform == 'win32': try: try: return self.execute(make_call(), **_kwargs) except WindowsError: # did we switch to git.cmd already, or was it changed from default ? permanently fail if self.GIT_PYTHON_GIT_EXECUTABLE != self.git_exec_name: raise # END handle overridden variable type(self).GIT_PYTHON_GIT_EXECUTABLE = self.git_exec_name_win try: return self.execute(make_call(), **_kwargs) finally: import warnings msg = "WARNING: Automatically switched to use git.cmd as git executable" msg += ", which reduces performance by ~70%." msg += "It is recommended to put git.exe into the PATH or to " msg += "set the %s " % self._git_exec_env_var msg += "environment variable to the executable's location" warnings.warn(msg) # END print of warning # END catch first failure except WindowsError: raise WindowsError("The system cannot find or execute the file at %r" % self.GIT_PYTHON_GIT_EXECUTABLE) # END provide better error message else: return self.execute(make_call(), **_kwargs) # END handle windows default installation def _parse_object_header(self, header_line): """ :param header_line: type_string size_as_int :return: (hex_sha, type_string, size_as_int) :raise ValueError: if the header contains indication for an error due to incorrect input sha""" tokens = header_line.split() if len(tokens) != 3: if not tokens: raise ValueError("SHA could not be resolved, git returned: %r" % (header_line.strip())) else: raise ValueError("SHA %s could not be resolved, git returned: %r" % (tokens[0], header_line.strip())) # END handle actual return value # END error handling if len(tokens[0]) != 40: raise ValueError("Failed to parse header: %r" % header_line) return (tokens[0], tokens[1], int(tokens[2])) def _prepare_ref(self, ref): # required for command to separate refs on stdin, as bytes refstr = ref if isinstance(ref, bytes): # Assume 40 bytes hexsha - bin-to-ascii for some reason returns bytes, not text refstr = ref.decode('ascii') elif not isinstance(ref, string_types): refstr = str(ref) # could be ref-object if not refstr.endswith("\n"): refstr += "\n" return refstr.encode(defenc) def _get_persistent_cmd(self, attr_name, cmd_name, *args, **kwargs): cur_val = getattr(self, attr_name) if cur_val is not None: return cur_val options = {"istream": PIPE, "as_process": True} options.update(kwargs) cmd = self._call_process(cmd_name, *args, **options) setattr(self, attr_name, cmd) return cmd def __get_object_header(self, cmd, ref): cmd.stdin.write(self._prepare_ref(ref)) cmd.stdin.flush() return self._parse_object_header(cmd.stdout.readline()) def get_object_header(self, ref): """ Use this method to quickly examine the type and size of the object behind the given ref. :note: The method will only suffer from the costs of command invocation once and reuses the command in subsequent calls. :return: (hexsha, type_string, size_as_int)""" cmd = self._get_persistent_cmd("cat_file_header", "cat_file", batch_check=True) return self.__get_object_header(cmd, ref) def get_object_data(self, ref): """ As get_object_header, but returns object data as well :return: (hexsha, type_string, size_as_int,data_string) :note: not threadsafe""" hexsha, typename, size, stream = self.stream_object_data(ref) data = stream.read(size) del(stream) return (hexsha, typename, size, data) def stream_object_data(self, ref): """ As get_object_header, but returns the data as a stream :return: (hexsha, type_string, size_as_int, stream) :note: This method is not threadsafe, you need one independent Command instance per thread to be safe !""" cmd = self._get_persistent_cmd("cat_file_all", "cat_file", batch=True) hexsha, typename, size = self.__get_object_header(cmd, ref) return (hexsha, typename, size, self.CatFileContentStream(size, cmd.stdout)) def clear_cache(self): """Clear all kinds of internal caches to release resources. Currently persistent commands will be interrupted. :return: self""" self.cat_file_all = None self.cat_file_header = None return self python-git-1.0.1+git137-gc8b8379/git/compat.py000066400000000000000000000034731256444316100204360ustar00rootroot00000000000000#-*-coding:utf-8-*- # config.py # Copyright (C) 2008, 2009 Michael Trier (mtrier@gmail.com) and contributors # # This module is part of GitPython and is released under # the BSD License: http://www.opensource.org/licenses/bsd-license.php """utilities to help provide compatibility with python 3""" # flake8: noqa import sys from gitdb.utils.compat import ( PY3, xrange, MAXSIZE, izip, ) from gitdb.utils.encoding import ( string_types, text_type, force_bytes, force_text ) defenc = sys.getdefaultencoding() if PY3: import io FileType = io.IOBase def byte_ord(b): return b def bchr(n): return bytes([n]) def mviter(d): return d.values() unicode = str else: FileType = file # usually, this is just ascii, which might not enough for our encoding needs # Unless it's set specifically, we override it to be utf-8 if defenc == 'ascii': defenc = 'utf-8' byte_ord = ord bchr = chr unicode = unicode def mviter(d): return d.itervalues() def with_metaclass(meta, *bases): """copied from https://github.com/Byron/bcore/blob/master/src/python/butility/future.py#L15""" class metaclass(meta): __call__ = type.__call__ __init__ = type.__init__ def __new__(cls, name, nbases, d): if nbases is None: return type.__new__(cls, name, (), d) # There may be clients who rely on this attribute to be set to a reasonable value, which is why # we set the __metaclass__ attribute explicitly if not PY3 and '___metaclass__' not in d: d['__metaclass__'] = meta # end return meta(name, bases, d) # end # end metaclass return metaclass(meta.__name__ + 'Helper', None, {}) # end handle py2 python-git-1.0.1+git137-gc8b8379/git/config.py000066400000000000000000000543671256444316100204300ustar00rootroot00000000000000# config.py # Copyright (C) 2008, 2009 Michael Trier (mtrier@gmail.com) and contributors # # This module is part of GitPython and is released under # the BSD License: http://www.opensource.org/licenses/bsd-license.php """Module containing module parser implementation able to properly read and write configuration files""" import re try: import ConfigParser as cp except ImportError: # PY3 import configparser as cp import inspect import logging import abc import os from git.odict import OrderedDict from git.util import LockFile from git.compat import ( string_types, FileType, defenc, force_text, with_metaclass, PY3 ) __all__ = ('GitConfigParser', 'SectionConstraint') log = logging.getLogger('git.config') log.addHandler(logging.NullHandler()) class MetaParserBuilder(abc.ABCMeta): """Utlity class wrapping base-class methods into decorators that assure read-only properties""" def __new__(metacls, name, bases, clsdict): """ Equip all base-class methods with a needs_values decorator, and all non-const methods with a set_dirty_and_flush_changes decorator in addition to that.""" kmm = '_mutating_methods_' if kmm in clsdict: mutating_methods = clsdict[kmm] for base in bases: methods = (t for t in inspect.getmembers(base, inspect.isroutine) if not t[0].startswith("_")) for name, method in methods: if name in clsdict: continue method_with_values = needs_values(method) if name in mutating_methods: method_with_values = set_dirty_and_flush_changes(method_with_values) # END mutating methods handling clsdict[name] = method_with_values # END for each name/method pair # END for each base # END if mutating methods configuration is set new_type = super(MetaParserBuilder, metacls).__new__(metacls, name, bases, clsdict) return new_type def needs_values(func): """Returns method assuring we read values (on demand) before we try to access them""" def assure_data_present(self, *args, **kwargs): self.read() return func(self, *args, **kwargs) # END wrapper method assure_data_present.__name__ = func.__name__ return assure_data_present def set_dirty_and_flush_changes(non_const_func): """Return method that checks whether given non constant function may be called. If so, the instance will be set dirty. Additionally, we flush the changes right to disk""" def flush_changes(self, *args, **kwargs): rval = non_const_func(self, *args, **kwargs) self._dirty = True self.write() return rval # END wrapper method flush_changes.__name__ = non_const_func.__name__ return flush_changes class SectionConstraint(object): """Constrains a ConfigParser to only option commands which are constrained to always use the section we have been initialized with. It supports all ConfigParser methods that operate on an option""" __slots__ = ("_config", "_section_name") _valid_attrs_ = ("get_value", "set_value", "get", "set", "getint", "getfloat", "getboolean", "has_option", "remove_section", "remove_option", "options") def __init__(self, config, section): self._config = config self._section_name = section def __del__(self): # Yes, for some reason, we have to call it explicitly for it to work in PY3 ! # Apparently __del__ doesn't get call anymore if refcount becomes 0 # Ridiculous ... . self._config.release() def __getattr__(self, attr): if attr in self._valid_attrs_: return lambda *args, **kwargs: self._call_config(attr, *args, **kwargs) return super(SectionConstraint, self).__getattribute__(attr) def _call_config(self, method, *args, **kwargs): """Call the configuration at the given method which must take a section name as first argument""" return getattr(self._config, method)(self._section_name, *args, **kwargs) @property def config(self): """return: Configparser instance we constrain""" return self._config def release(self): """Equivalent to GitConfigParser.release(), which is called on our underlying parser instance""" return self._config.release() class GitConfigParser(with_metaclass(MetaParserBuilder, cp.RawConfigParser, object)): """Implements specifics required to read git style configuration files. This variation behaves much like the git.config command such that the configuration will be read on demand based on the filepath given during initialization. The changes will automatically be written once the instance goes out of scope, but can be triggered manually as well. The configuration file will be locked if you intend to change values preventing other instances to write concurrently. :note: The config is case-sensitive even when queried, hence section and option names must match perfectly.""" #{ Configuration # The lock type determines the type of lock to use in new configuration readers. # They must be compatible to the LockFile interface. # A suitable alternative would be the BlockingLockFile t_lock = LockFile re_comment = re.compile('^\s*[#;]') #} END configuration OPTCRE = re.compile( r'\s*(?P