### Install GitPython using setup.py Source: https://gitpython.readthedocs.io/en/stable/intro.html Alternatively, install GitPython using its setup.py script. Ensure GitDB is installed manually if using this method. ```bash # python setup.py install ``` -------------------------------- ### Verify GitPython Installation Source: https://gitpython.readthedocs.io/en/stable/intro.html Run the unit tests to verify that GitPython has been installed correctly. ```bash $ python -m unittest ``` -------------------------------- ### Install GitPython using pip Source: https://gitpython.readthedocs.io/en/stable/intro.html Use this command to install the latest version of GitPython from the Python Package Index. ```bash # pip install GitPython ``` -------------------------------- ### git.compat.__getattr__ Source: https://gitpython.readthedocs.io/en/stable/reference.html Gets an attribute from the compat module. ```APIDOC ## git.compat.__getattr__ ### Description Gets an attribute from the compat module. ### Parameters * **_name** (str) - The name of the attribute to get. ### Returns Any ``` -------------------------------- ### Git Command Interface Example Source: https://gitpython.readthedocs.io/en/stable/reference.html Demonstrates how to initialize the Git class and call Git commands like 'init' and 'ls-files'. The GIT_PYTHON_TRACE environment variable can be used for debugging. ```python from git import Git g = Git( git_dir ) g.init() # calls 'git init' program rval = g.ls_files() # calls 'git ls-files' program ``` -------------------------------- ### Submodule Handling Example Source: https://gitpython.readthedocs.io/en/stable/_sources/tutorial.rst.txt Demonstrates basic submodule handling operations in GitPython, including moving, configuring, updating, and removing submodules. ```python # [1-test_submodules] # Submodule handling # ... (rest of the code from the literalinclude) ``` -------------------------------- ### New File Diff Example Source: https://gitpython.readthedocs.io/en/stable/reference.html Illustrates the expected state of diff members when a file is newly created. Members like a_mode, a_blob, and a_path will be None. ```python a_mode is None a_blob is None a_path is None ``` -------------------------------- ### Examine Git References Source: https://gitpython.readthedocs.io/en/stable/_sources/tutorial.rst.txt Provides examples for examining Git references, which represent the tips of your commit graph. ```python from git import Repo repo = Repo.init(".") # Examine references references = repo.references ``` -------------------------------- ### Diff Information Example Source: https://gitpython.readthedocs.io/en/stable/_sources/tutorial.rst.txt Obtain diff information between various Git states like Index and Trees, Index and working tree, or between commits. ```python # [27-test_references_and_objects] # Diff information # ... (rest of the code from the literalinclude) ``` -------------------------------- ### Deleted File Diff Example Source: https://gitpython.readthedocs.io/en/stable/reference.html Shows the expected state of diff members when a file has been deleted. Members like b_mode, b_blob, and b_path will be None. ```python b_mode is None b_blob is None b_path is None ``` -------------------------------- ### Repo Context Management Source: https://gitpython.readthedocs.io/en/stable/reference.html The Repo class supports context management, allowing for proper setup and teardown of repository resources using `with` statements. ```APIDOC ## Repo Context Management ### Description Supports context management for proper resource handling. ### Methods #### __enter__ ```python __enter__() -> Repo ``` Enters the runtime context related to this object. The most common use of this is with the `with` statement to ensure that clean-up operations are performed. #### __exit__ ```python __exit__(_* args: Any_) ``` Exits the runtime context and performs necessary cleanup operations. ``` -------------------------------- ### Index Operations for Commits and Merges Source: https://gitpython.readthedocs.io/en/stable/tutorial.html Utilize the index (staging area) to prepare new commits and manage merge results, including streaming data for bare repositories. This example shows adding a file, committing, performing a three-way merge, and updating branches without touching the working tree. ```python self.assertEqual(new_branch.checkout(), cloned_repo.active_branch) # Checking out branch adjusts the wtree. self.assertEqual(new_branch.commit, past.commit) # Now the past is checked out. new_file_path = os.path.join(cloned_repo.working_tree_dir, "my-new-file") open(new_file_path, "wb").close() # Create new file in working tree. cloned_repo.index.add([new_file_path]) # Add it to the index. # Commit the changes to deviate masters history. cloned_repo.index.commit("Added a new file in the past - for later merge") # Prepare a merge. master = cloned_repo.heads.master # Right-hand side is ahead of us, in the future. merge_base = cloned_repo.merge_base(new_branch, master) # Allows for a three-way merge. cloned_repo.index.merge_tree(master, base=merge_base) # Write the merge result into index. cloned_repo.index.commit( "Merged past and now into future ;)", parent_commits=(new_branch.commit, master.commit), ) # Now new_branch is ahead of master, which probably should be checked out and reset softly. # Note that all these operations didn't touch the working tree, as we managed it ourselves. # This definitely requires you to know what you are doing! :) assert os.path.basename(new_file_path) in new_branch.commit.tree # New file is now in tree. master.commit = new_branch.commit # Let master point to most recent commit. cloned_repo.head.reference = master # We adjusted just the reference, not the working tree or index. ``` -------------------------------- ### Working Tree Diff Example Source: https://gitpython.readthedocs.io/en/stable/reference.html Explains how working tree differences are represented. The working tree blob will have a null hexsha and null mode, but the path will be available. This indicates a modification compared to the index or tree. ```python When comparing to working trees, the working tree blob will have a null hexsha as a corresponding object does not yet exist. The mode will be null as well. The path will be available, though. If it is listed in a diff, the working tree version of the file must differ from the version in the index or tree, and hence has been modified. ``` -------------------------------- ### Get a Previous Commit Tree Source: https://gitpython.readthedocs.io/en/stable/quickstart.html Retrieve the tree object for a specific previous commit. This example gets the tree from the most recent commit among the last 10. ```python prev_commits = list(repo.iter_commits(all=True, max_count=10)) # Last 10 commits from all branches. tree = prev_commits[0].tree ``` -------------------------------- ### Initializing Repo with Different Path Formats Source: https://gitpython.readthedocs.io/en/stable/reference.html Demonstrates various valid path formats for initializing a Repo object. Supports absolute paths, relative paths with '~', environment variables, and Windows-style raw strings. ```python repo = Repo("/Users/mtrier/Development/git-python") ``` ```python repo = Repo("/Users/mtrier/Development/git-python.git") ``` ```python repo = Repo("~/Development/git-python.git") ``` ```python repo = Repo("$REPOSITORIES/Development/git-python.git") ``` ```python repo = Repo(R"C:\Users\mtrier\Development\git-python\.git") ``` -------------------------------- ### Initialize Repository, Add File, and Commit Source: https://gitpython.readthedocs.io/en/stable/_sources/tutorial.rst.txt Initializes an empty repository, adds an empty file to the index, and commits the change. ```python repo = Repo.init("path/to/repo") repo.index.add(["new_file.txt"]) repo.index.commit("Initial commit") ``` -------------------------------- ### Initialize Repo Object with Bare Repository Source: https://gitpython.readthedocs.io/en/stable/_sources/tutorial.rst.txt Initialize a Repo object for a bare repository. Bare repositories do not have a working tree. ```python from git import Repo # Assuming self.bare_repo is a valid path to a bare repository repo = Repo(self.bare_repo.working_tree_dir) ``` -------------------------------- ### Get Diff Between Index and Commit Source: https://gitpython.readthedocs.io/en/stable/_sources/tutorial.rst.txt Use repo.index.diff(repo.head.commit) to get a diff between the index and the commit your HEAD points to. ```python repo.index.diff(repo.head.commit) ``` -------------------------------- ### Get named sub-object from tree Source: https://gitpython.readthedocs.io/en/stable/_sources/tutorial.rst.txt Convenience method to get a named sub-object from a tree using path-like syntax. ```python tree.get_tree('subdir/another_subdir').blobs ``` -------------------------------- ### Initialize a new Git Repository with Bare Option Source: https://gitpython.readthedocs.io/en/stable/_sources/quickstart.rst.txt Creates a new, empty bare Git repository. Bare repositories do not have a working directory. ```python repo = git.Repo.init("/tmp/test_bare_repo", bare=True) ``` -------------------------------- ### Cloning a Repository with Multiple Options Source: https://gitpython.readthedocs.io/en/stable/reference.html Demonstrates how to use the `clone` method with multiple configuration options, such as setting core file mode and ignore case, and recursively cloning submodules. ```python repo.clone( "/path/to/new/repo.git", multi_options=[ "--config core.filemode=false", "--config core.ignorecase", "--recurse-submodule=repo1_path", "--recurse-submodule=repo2_path", ] ) ``` -------------------------------- ### Remote.name Source: https://gitpython.readthedocs.io/en/stable/reference.html Gets the name of the remote. ```APIDOC ## name ### Description Gets the name of the remote. ### Method name ### Parameters None ### Returns str - The name of the remote. ``` -------------------------------- ### Initialize Git Repository and Commit Source: https://gitpython.readthedocs.io/en/stable/tutorial.html Initializes an empty Git repository, adds a new file, and creates the initial commit. Ensure the directory exists before running. ```python import git import os repo_dir = os.path.join(rw_dir, "my-new-repo") file_name = os.path.join(repo_dir, "new-file") r = git.Repo.init(repo_dir) # This function just creates an empty file. open(file_name, "wb").close() r.index.add([file_name]) r.index.commit("initial commit") ``` -------------------------------- ### Repo.init Source: https://gitpython.readthedocs.io/en/stable/reference.html Initializes a new Git repository at the specified path. It can create the directory if it doesn't exist and configure object database types. ```APIDOC ## Repo.init ### Description Initializes a git repository at the given path if specified. ### Method Class method (Python) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **path** (str | ~os.PathLike[str] | None) - Optional - The full path to the repo. If None, the repository will be created in the current working directory. * **mkdir** (bool) - Optional - If True, will create the repository directory if it doesn’t already exist. Defaults to True. * **odbt** (~typing.Type[~git.db.GitCmdObjectDB]) - Optional - Object DataBase type. Defaults to `git.db.GitCmdObjectDB`. * **expand_vars** (bool) - Optional - If True, environment variables will not be escaped. Defaults to True. * **kwargs** (~typing.Any) - Optional - Keyword arguments serving as additional options to the `git-init(1)` command. ### Returns * **Repo** - The newly created repo object. ``` -------------------------------- ### Remote.refs Source: https://gitpython.readthedocs.io/en/stable/reference.html Gets the list of references for the remote. ```APIDOC ## refs ### Description Gets the list of references for the remote. ### Method refs ### Returns IterableList[RemoteReference] - A list of `RemoteReference` objects. ``` -------------------------------- ### SymbolicReference.abspath Source: https://gitpython.readthedocs.io/en/stable/reference.html Gets the absolute path of the symbolic reference. ```APIDOC ## SymbolicReference.abspath ### Description Gets the absolute path of the symbolic reference. ### Returns The absolute path of the symbolic reference. ``` -------------------------------- ### GitDB.__init__() Source: https://gitpython.readthedocs.io/en/stable/reference.html Initializes a GitDB instance. ```APIDOC ## GitDB.__init__() ### Description Initializes a GitDB instance. ### Method Constructor ### Endpoint N/A (Class constructor) ### Parameters * **path** (string) - Required - The path to the Git repository. ### Request Example ```python git_db = GitDB('/path/to/repository') ``` ### Response #### Success Response Initializes the GitDB object. #### Response Example No specific return value, object is created. ``` -------------------------------- ### git.compat.__dir__ Source: https://gitpython.readthedocs.io/en/stable/reference.html Returns a list of attributes for the compat module. ```APIDOC ## git.compat.__dir__ ### Description Returns a list of attributes for the compat module. ### Returns List[str] ``` -------------------------------- ### Remote.url Source: https://gitpython.readthedocs.io/en/stable/reference.html Gets the primary configured URL for the remote repository. ```APIDOC ## Remote.url ### Description Provides the primary configured URL for the remote repository. ### Returns - `str`: The URL of the remote. ``` -------------------------------- ### Get Remote URL Source: https://gitpython.readthedocs.io/en/stable/reference.html Retrieves the primary URL configured for the remote repository. ```python remote.url ``` -------------------------------- ### Initialize a new Git Repository Source: https://gitpython.readthedocs.io/en/stable/_sources/quickstart.rst.txt Creates a new, empty Git repository in the specified directory. ```python repo = git.Repo.init("/tmp/test_repo") ``` -------------------------------- ### Get repository's root tree Source: https://gitpython.readthedocs.io/en/stable/_sources/tutorial.rst.txt Retrieves the root tree of the repository directly. ```python repo.index.tree ``` -------------------------------- ### Clone and Initialize Repositories Source: https://gitpython.readthedocs.io/en/stable/tutorial.html Clone an existing Git repository to a new location or initialize a new empty repository. ```python cloned_repo = repo.clone(os.path.join(rw_dir, "to/this/path")) assert cloned_repo.__class__ is Repo # Clone an existing repository. assert Repo.init(os.path.join(rw_dir, "path/for/new/repo")).__class__ is Repo ``` -------------------------------- ### Get a Specific Commit Tree Source: https://gitpython.readthedocs.io/en/stable/_sources/quickstart.rst.txt Retrieves the tree object for a commit specified by its SHA. ```python commit = repo.commit("HEAD~") tree = commit.tree ``` -------------------------------- ### Create and Manage a Remote Repository Source: https://gitpython.readthedocs.io/en/stable/tutorial.html Initializes an empty repository, creates a remote alias, and performs basic operations like fetch, push, and pull. It also demonstrates setting up local tracking branches and renaming remotes. ```python empty_repo = git.Repo.init(os.path.join(rw_dir, "empty")) origin = empty_repo.create_remote("origin", repo.remotes.origin.url) assert origin.exists() assert origin == empty_repo.remotes.origin == empty_repo.remotes["origin"] origin.fetch() # Ensure we actually have data. fetch() returns useful information. # Set up a local tracking branch of a remote branch. empty_repo.create_head("master", origin.refs.master) # Create local branch "master" from remote "master". empty_repo.heads.master.set_tracking_branch(origin.refs.master) # Set local "master" to track remote "master. empty_repo.heads.master.checkout() # Check out local "master" to working tree. # Three above commands in one: empty_repo.create_head("master", origin.refs.master).set_tracking_branch(origin.refs.master).checkout() # Rename remotes. origin.rename("new_origin") # Push and pull behaves similarly to `git push|pull`. origin.pull() origin.push() # Attempt push, ignore errors. origin.push().raise_if_error() # Push and raise error if it fails. # assert not empty_repo.delete_remote(origin).exists() # Create and delete remotes. ``` -------------------------------- ### Modify Git References Source: https://gitpython.readthedocs.io/en/stable/_sources/tutorial.rst.txt Provides examples for creating, deleting, or modifying Git references. ```python from git import Repo repo = Repo.init(".") # Modify references # Example: create a new reference new_ref = repo.create_head('my_new_branch') # Example: delete a reference # repo.delete_head('my_old_branch') ``` -------------------------------- ### Get the Latest Commit Tree Source: https://gitpython.readthedocs.io/en/stable/_sources/quickstart.rst.txt Retrieves the tree object associated with the latest commit in the repository. ```python commit = repo.head.commit tree = commit.tree ``` -------------------------------- ### Recursively retrieve tree entries Source: https://gitpython.readthedocs.io/en/stable/_sources/tutorial.rst.txt Uses the traverse method to get an iterator for recursively retrieving entries. ```python repo.index.tree.traverse() ``` -------------------------------- ### Clone or Initialize Repository Source: https://gitpython.readthedocs.io/en/stable/_sources/tutorial.rst.txt Clone from existing repositories or initialize new empty ones using GitPython. ```python from git import Repo # Clone a repository repo = Repo.clone_from('git://github.com/user/repo.git', '/path/to/local/repo') # Initialize a new empty repository new_repo = Repo.init('/path/to/new/repo') ``` -------------------------------- ### Get Diff Objects for Modified Files Source: https://gitpython.readthedocs.io/en/stable/_sources/quickstart.rst.txt Retrieves a list of Diff objects representing modified files. ```python def test_get_diff_objects(self): repo = self.create_repo() repo.index.add([self.create_file("a.txt")]) repo.index.commit("commit a") with open("a.txt", "w") as f: f.write("new content") diffs = repo.index.diff("HEAD") self.assertEqual(len(diffs), 1) self.assertIsInstance(diffs[0], git.diff.Diff) ``` -------------------------------- ### Initialize a Repo Object Source: https://gitpython.readthedocs.io/en/stable/_sources/tutorial.rst.txt Create a Repo object to represent your local git repository. This is the first step to interacting with GitPython. ```python from git import Repo # Assuming self.rorepo is a valid path to a repository repo = Repo(self.rorepo.working_tree_dir) ``` -------------------------------- ### GitCmdObjectDB.__init__() Source: https://gitpython.readthedocs.io/en/stable/reference.html Initializes a GitCmdObjectDB instance. ```APIDOC ## GitCmdObjectDB.__init__() ### Description Initializes a GitCmdObjectDB instance. ### Method Constructor ### Endpoint N/A (Class constructor) ### Parameters * **path** (string) - Required - The path to the Git object database. * **git_cmd** (GitCommand) - Required - The Git command utility. ### Request Example ```python from git.cmd import Git git_cmd = Git(os.getcwd()) git_db = GitCmdObjectDB('/path/to/.git/objects', git_cmd) ``` ### Response #### Success Response Initializes the GitCmdObjectDB object. #### Response Example No specific return value, object is created. ``` -------------------------------- ### Initialize Index File Source: https://gitpython.readthedocs.io/en/stable/reference.html Initializes an IndexFile instance, optionally from a specified file path. If no path is given, it defaults to the current repository's index file. ```python IndexFile(_repo : Repo_, _file_path : str | os.PathLike[str] | None = None_) -> None ``` -------------------------------- ### Get Object Pointed to by Reference Source: https://gitpython.readthedocs.io/en/stable/reference.html Returns the object (Commit, Tree, TagObject, or Blob) that a reference currently points to. ```python ref._object ``` -------------------------------- ### Initialize GitPython Submodules Source: https://gitpython.readthedocs.io/en/stable/intro.html After cloning, initialize all submodules to obtain the necessary dependencies for GitPython. ```bash cd git-python $ git submodule update --init --recursive ``` -------------------------------- ### Get root tree of latest commit Source: https://gitpython.readthedocs.io/en/stable/_sources/tutorial.rst.txt Retrieves the root tree object of the latest commit on the master branch. ```python repo.tree('master') ``` -------------------------------- ### git.compat Source: https://gitpython.readthedocs.io/en/stable/_sources/reference.rst.txt Documentation for the compatibility module in GitPython. ```APIDOC ## git.compat ### Description Compatibility layer for different Python versions. ``` -------------------------------- ### Get Current User ID Source: https://gitpython.readthedocs.io/en/stable/reference.html Retrieves a string identifying the currently active system user in 'name@node' format. ```python git.util.get_user_id() ``` -------------------------------- ### Initialize Repository with GitCmdObjectDB Source: https://gitpython.readthedocs.io/en/stable/_sources/tutorial.rst.txt Initialize a repository using the GitCmdObjectDB, which uses persistent git-cat-file instances for faster reading under all conditions, but may consume more memory. ```python from git.db import GitCmdObjectDB repo = Repo("path/to/repo", odbt=GitCmdObjectDB) ``` -------------------------------- ### Get Tag Object for Tag Reference Source: https://gitpython.readthedocs.io/en/stable/reference.html Retrieves the TagObject associated with a tag reference. Returns None for lightweight tags. ```python tagref._tag ``` -------------------------------- ### Get Tracking Branch Source: https://gitpython.readthedocs.io/en/stable/reference.html Retrieves the remote reference that the current branch is tracking. Returns None if the branch is not a tracking branch. ```python tracking_branch() → RemoteReference | None ``` -------------------------------- ### Accessing and Modifying Repository Description Source: https://gitpython.readthedocs.io/en/stable/_sources/changes.rst.txt Demonstrates how to get and set the description attribute of a repository object. This is a read-only property that can be modified. ```python >>> repo.description = "Foo Bar" >>> repo.description 'Foo Bar' ``` -------------------------------- ### Initialize RefLog Source: https://gitpython.readthedocs.io/en/stable/reference.html Initializes a RefLog instance, optionally with a filepath to load and write reflog data. ```python RefLog(_filepath=None) ``` -------------------------------- ### Clone an Existing Git Repository Source: https://gitpython.readthedocs.io/en/stable/_sources/quickstart.rst.txt Clones a Git repository from a remote URL to a local directory. This is useful for starting with an existing project. ```python repo = git.Repo.clone_from("https://github.com/gitpython-developers/QuickStartTutorialFiles.git", "/tmp/test_repo") ``` -------------------------------- ### Get Commit Object for Tag Source: https://gitpython.readthedocs.io/en/stable/reference.html Retrieves the Commit object that a tag reference points to. Raises ValueError if the tag points to a tree or blob. ```python tagref._commit ``` -------------------------------- ### Create Untracked File Source: https://gitpython.readthedocs.io/en/stable/_sources/quickstart.rst.txt Demonstrates creating a new untracked file within a repository. ```python def test_untracked_files(self): repo = self.create_repo() repo.index.add([self.create_file("a.txt")]) repo.index.commit("commit a") self.create_file("b.txt") self.assertEqual(repo.untracked_files, ["b.txt"]) ``` -------------------------------- ### Repo Initialization Source: https://gitpython.readthedocs.io/en/stable/reference.html Initializes a new Repo instance, representing a Git repository. It can be initialized with a path to the repository, optionally specifying the object database type and whether to search parent directories. ```APIDOC ## Repo.__init__ ### Description Create a new `Repo` instance. ### Method __init__ ### Parameters #### Path Parameter - **_path** (str | ~os.PathLike[str] | None) - The path to the git repository. - **_odbt** (~typing.Type[~gitdb.db.loose.LooseObjectDB]) - The object database type to use. Defaults to `git.db.GitCmdObjectDB`. - **_search_parent_directories** (bool) - Whether to search parent directories for the repository. Defaults to `False`. - **_expand_vars** (bool) - Whether to expand environment variables in the path. Defaults to `True`. ``` -------------------------------- ### Tree Object Initialization and Access Source: https://gitpython.readthedocs.io/en/stable/reference.html Demonstrates how to initialize a Tree object and access its contents using various methods, including subscripting and the '/' operator. ```APIDOC ## Tree Object ### Description Represents an ordered list of `Blob`s and other `Tree`s in a Git repository. Supports list-like and dictionary-like access to its contents. ### Methods - **`__init__(_repo, _binsha, _mode=16384, _path=None)`** Initializes a `Tree` object. - **`repo`** (Repo): The repository this tree belongs to. - **`binsha`** (bytes): The 20-byte SHA1 hash of the tree. - **`mode`** (int): The file mode, compatible with `stat` module information. - **`path`** (str | os.PathLike[str] | None): The path to the tree relative to the repository root. May be unset if created directly. - **`__getitem__(_item: str | int | slice)`** Accesses a specific blob or tree within this tree using a filename, index, or slice. Returns: `Tree` | `Blob` | `Submodule` - **`__truediv__(_file: str | PathLike[str])`** The `/` operator provides an alternative syntax for joining paths, equivalent to `join()`. Returns: `Tree` | `Blob` | `Submodule` - **`join(_file: str | PathLike[str])`** Finds the named object within this tree's contents. Returns: `Blob`, `Tree`, or `Submodule` Raises: **KeyError** if the file or tree does not exist. ### Properties - **`blobs`** : List[Blob] A list of `Blob` objects directly contained within this tree. - **`trees`** : List[Tree] A list of `Tree` objects directly contained within this tree. - **`type`** : Literal['tree'] A string identifying the object type as 'tree'. ``` -------------------------------- ### Execute Git Commands Directly Source: https://gitpython.readthedocs.io/en/stable/tutorial.html Demonstrates how to use the GitPython library to execute raw git commands. Keyword arguments map to command-line flags, and '-' in command names becomes '_'. ```python git_cmd = repo.git git_cmd.checkout("HEAD", b="my_new_branch") # Create a new branch. git_cmd.branch("another-new-one") git_cmd.branch("-D", "another-new-one") # Pass strings for full control over argument order. git_cmd.for_each_ref() # '-' becomes '_' when calling it. ``` -------------------------------- ### Get Root Tree of Master Branch Source: https://gitpython.readthedocs.io/en/stable/tutorial.html Retrieves the root tree object for the latest commit on the master branch. Asserts the length of the hexadecimal SHA of the tree. ```python tree = repo.heads.master.commit.tree assert len(tree.hexsha) == 40 ``` -------------------------------- ### Initialize Repository with GitDB Source: https://gitpython.readthedocs.io/en/stable/_sources/tutorial.rst.txt Initialize a repository using the pure-python GitDB object database. This is the default in GitPython 0.3 and is suitable for handling huge files but may be slower for many small objects. ```python from git.db import GitDB repo = Repo("path/to/repo", odbt=GitDB) ``` -------------------------------- ### Access and Manage Tags Source: https://gitpython.readthedocs.io/en/stable/tutorial.html Demonstrates how to access existing tags, inspect the commit they point to, and how to create or delete tags using the repository object. ```python tags = repo.tags tagref = tags[0] tagref.tag # Tags may have tag objects carrying additional information tagref.commit # but they always point to commits. repo.delete_tag(tagref) # Delete or repo.create_tag("my_tag") # create tags using the repo for convenience. ``` -------------------------------- ### Managing Daemon Export Property Source: https://gitpython.readthedocs.io/en/stable/changes.html Illustrates how to get and set the daemon export status for a repository. This property controls whether the repository can be exported via the Git daemon. ```python exported = repo.daemon_export repo.daemon_export = True ``` -------------------------------- ### git.cmd Source: https://gitpython.readthedocs.io/en/stable/_sources/reference.rst.txt Documentation for the Git command execution module in GitPython. ```APIDOC ## git.cmd ### Description This module provides functionality to execute Git commands. ``` -------------------------------- ### Submodule Management Source: https://gitpython.readthedocs.io/en/stable/tutorial.html Manipulate Git submodules, including creation, removal, and updating. This example demonstrates creating a submodule, committing its addition, removing its working tree, and then updating it. ```python # Create a new submodule and check it out on the spot, setup to track master # branch of `bare_repo`. As our GitPython repository has submodules already that # point to GitHub, make sure we don't interact with them. for sm in cloned_repo.submodules: assert not sm.remove().exists() # after removal, the sm doesn't exist anymore sm = cloned_repo.create_submodule("mysubrepo", "path/to/subrepo", url=bare_repo.git_dir, branch="master") # .gitmodules was written and added to the index, which is now being committed. cloned_repo.index.commit("Added submodule") assert sm.exists() and sm.module_exists() # This submodule is definitely available. sm.remove(module=True, configuration=False) # Remove the working tree. assert sm.exists() and not sm.module_exists() # The submodule itself is still available. # Update all submodules, non-recursively to save time. This method is very powerful, go have a look. cloned_repo.submodule_update(recursive=False) assert sm.module_exists() # The submodule's working tree was checked out by update. ``` -------------------------------- ### Open an Existing Local Git Repository Source: https://gitpython.readthedocs.io/en/stable/quickstart.html Instantiate a Repo object for an existing local Git repository. ```python repo = Repo(path_to_dir) ``` -------------------------------- ### get Source: https://gitpython.readthedocs.io/en/stable/reference.html Retrieves an option's value from a given section. It searches in provided variables, the section, and default sections, with an optional fallback. Interpolations are expanded unless raw is True. ```APIDOC ## get ### Description Get an option value for a given section. Searches in vars, section, and DEFAULTSECT in order, with an optional fallback. Interpolations are expanded if raw is False. ### Method get ### Parameters - **_section_** (any) - Description of the section to retrieve the option from. - **_option_** (any) - Description of the option to retrieve. - **_raw** (bool) - Keyword-only. If True, interpolations are not expanded. - **_vars** (dict) - Keyword-only. A dictionary to search for the option. - **_fallback** (any) - Keyword-only. A fallback value if the option is not found. ``` -------------------------------- ### Example SSH Executable Script Source: https://gitpython.readthedocs.io/en/stable/_sources/tutorial.rst.txt A shell script that can be used as a custom SSH executable for Git operations, specifying an identity file and disabling strict host key checking. ```shell #!/bin/sh ID_RSA=/var/lib/openshift/5562b947ecdd5ce939000038/app-deployments/id_rsa exec /usr/bin/ssh -o StrictHostKeyChecking=no -i $ID_RSA "$@" ``` -------------------------------- ### Submodule Initialization Source: https://gitpython.readthedocs.io/en/stable/reference.html Initializes a Repo instance from the submodule's path. It can raise an InvalidGitRepositoryError if the repository is not available or not yet initialized. ```APIDOC ## Objects.Submodule.base ### Description Initializes a Repo instance from the submodule's path. ### Returns `Repo` instance initialized from the repository at our submodule path. ### Raises **git.exc.InvalidGitRepositoryError** – If a repository was not available. This could also mean that it was not yet initialized. ``` -------------------------------- ### GitConfigParser Initialization Parameters Source: https://gitpython.readthedocs.io/en/stable/reference.html Details the parameters for initializing the GitConfigParser, including file paths, read-only mode, include merging, configuration level, and repository reference. ```python __init__(_file_or_files : None | str | os.PathLike[str] | BytesIO | Sequence[str | os.PathLike[str] | BytesIO] = None_, _read_only : bool = True_, _merge_includes : bool = True_, _config_level : Literal['system', 'global', 'user', 'repository'] | None = None_, _repo : Repo | None = None_) -> None ``` -------------------------------- ### Iterate Commits with Pagination Source: https://gitpython.readthedocs.io/en/stable/tutorial.html Iterate through commits starting from a reference, with options to limit the number of commits and skip a certain number of initial commits. Useful for paginating commit history. ```python fifty_first_commits = list(repo.iter_commits("master", max_count=50)) assert len(fifty_first_commits) == 50 # This will return commits 21-30 from the commit list as traversed backwards master. ten_commits_past_twenty = list(repo.iter_commits("master", max_count=10, skip=20)) assert len(ten_commits_past_twenty) == 10 assert fifty_first_commits[20:30] == ten_commits_past_twenty ``` -------------------------------- ### Get Commit Trailers as List - GitPython Source: https://gitpython.readthedocs.io/en/stable/reference.html Use `trailers_list` to retrieve commit trailers as a list of raw key-value tuples. This method is useful for accessing all trailer instances, including duplicates. ```python [ ("key1", "value1.1"), ("key1", "value1.2"), ("key2", "value 2 with inner spaces"), ] ``` -------------------------------- ### Querying Submodule Information Source: https://gitpython.readthedocs.io/en/stable/tutorial.html Demonstrates how to access and verify information about submodules within a repository, such as their names, paths, and existence. This is useful for inspecting the submodule hierarchy and their states. ```python repo = self.rorepo sms = repo.submodules assert len(sms) == 1 sm = sms[0] self.assertEqual(sm.name, "gitdb") # GitPython has gitdb as its one and only (direct) submodule... self.assertEqual(sm.children()[0].name, "smmap") # ...which has smmap as its one and only submodule. # The module is the repository referenced by the submodule. assert sm.module_exists() # The module is available, which doesn't have to be the case. assert sm.module().working_tree_dir.endswith("gitdb") # The submodule's absolute path is the module's path. assert sm.abspath == sm.module().working_tree_dir self.assertEqual(len(sm.hexsha), 40) # Its sha defines the commit to check out. assert sm.exists() # Yes, this submodule is valid and exists. # Read its configuration conveniently. assert sm.config_reader().get_value("path") == sm.path self.assertEqual(len(sm.children()), 1) # Query the submodule hierarchy. ``` -------------------------------- ### Get Repository Root Tree from Repository Object Source: https://gitpython.readthedocs.io/en/stable/tutorial.html Shows how to obtain the root tree of a repository directly from the repository object using various ref-specs, including commit hashes and tags. ```python # This example shows the various types of allowed ref-specs. assert repo.tree() == repo.head.commit.tree past = repo.commit("HEAD~5") assert repo.tree(past) == repo.tree(past.hexsha) self.assertEqual(repo.tree("v0.8.1").type, "tree") # Yes, you can provide any refspec - works everywhere. ``` -------------------------------- ### Get Commit Trailers as Dictionary - GitPython Source: https://gitpython.readthedocs.io/en/stable/reference.html Use `trailers_dict` to retrieve commit trailers, mapping keys to a list of their values. This method parses trailer information similar to RFC 822 email headers. ```python { "key1": ["value1.1", "value1.2"], "key2": ["value 2 with inner spaces"], } ``` -------------------------------- ### Creating and Merging Indices Source: https://gitpython.readthedocs.io/en/stable/tutorial.html Shows how to create temporary in-memory indices from existing trees or by performing a three-way merge. The resulting index can be written to a file for later inspection. ```python from git import IndexFile # Load a tree into a temporary index, which exists just in memory. IndexFile.from_tree(repo, "HEAD~1") # Merge two trees three-way into memory... merge_index = IndexFile.from_tree(repo, "HEAD~10", "HEAD", repo.merge_base("HEAD~10", "HEAD")) # ...and persist it. merge_index.write(os.path.join(rw_dir, "merged_index")) ``` -------------------------------- ### read Source: https://gitpython.readthedocs.io/en/stable/reference.html Reads configuration data from the files initialized with the instance. Ignores unreadable files, potentially resulting in an empty configuration. Raises IOError if a file cannot be handled. ```APIDOC ## read ### Description Read the data stored in the files we have been initialized with. This will ignore files that cannot be read, possibly leaving an empty configuration. ### Method read ### Returns - None ### Raises - **IOError** - If a file cannot be handled. ``` -------------------------------- ### Index.Base.execute Source: https://gitpython.readthedocs.io/en/stable/reference.html Handles executing git commands, consuming, and returning the output. ```APIDOC ## Index.Base.execute ### Description Handles the execution of a git command, consuming and returning the relevant information, primarily stdout. ### Parameters #### Path Parameters * **command** (str | Sequence[Any]) - The command to execute. * **as_process** (Literal[True] | Literal[False]) - If True, returns AutoInterrupt. Defaults to False. * **stdout_as_string** (Literal[True] | Literal[False]) - If True, stdout is returned as a string. Defaults to False. * **with_extended_output** (Literal[False]) - If False, extended output is not included. ### Returns - AutoInterrupt: If `as_process` is True. - str: If `stdout_as_string` is True and `as_process` is False. - bytes: If `stdout_as_string` is False and `as_process` is False. - Tuple[int, str, str]: If `stdout_as_string` is True and `as_process` is False, returns (return code, stdout, stderr). - Tuple[int, bytes, str]: If `stdout_as_string` is False and `as_process` is False, returns (return code, stdout, stderr). ``` -------------------------------- ### Initialize Repository Object Source: https://gitpython.readthedocs.io/en/stable/_sources/tutorial.rst.txt Initializes a repository object for interacting with Git submodules. ```python from git import Repo # Initialize a Repo object repo = Repo.init(".") ``` -------------------------------- ### Accessing the Reflog Source: https://gitpython.readthedocs.io/en/stable/tutorial.html Demonstrates how to access the reflog for a reference, allowing inspection of its history of updates. Entries can be accessed by index. ```python log = master.log() log[0] # first (i.e. oldest) reflog entry log[-1] # last (i.e. most recent) reflog entry ``` -------------------------------- ### Convenience Path-like Access to Tree Objects Source: https://gitpython.readthedocs.io/en/stable/tutorial.html Illustrates using the '/' operator for accessing tree objects with a syntax similar to POSIX paths, comparing it with dictionary-style access. ```python assert tree / "smmap" == tree["smmap"] assert tree / blob.path == tree[blob.path] ``` -------------------------------- ### Using GitDB Object Database Source: https://gitpython.readthedocs.io/en/stable/tutorial.html Instantiate a GitPython repository using the pure-python GitDB implementation. This is suitable for handling huge files but can be slower for many small objects. ```python repo = Repo("path/to/repo", odbt=GitDB) ``` -------------------------------- ### Access RefLog Source: https://gitpython.readthedocs.io/en/stable/_sources/tutorial.rst.txt Demonstrates how to easily access the reflog of a Git repository. ```python from git import Repo repo = Repo.init(".") # Access the reflog reflog = repo.head.log() ```