GitPython is a Python library used to interact with Git repositories
npx @tessl/cli install tessl/pypi-gitpython@3.1.00
# GitPython
1
2
GitPython is a comprehensive Python library for interacting with Git repositories, providing both high-level porcelain and low-level plumbing interfaces. It offers abstractions for Git objects (commits, trees, blobs, tags), repository management, branch and remote operations, and supports complex Git workflows including merging, rebasing, and conflict resolution.
3
4
## Package Information
5
6
- **Package Name**: GitPython
7
- **Language**: Python
8
- **Installation**: `pip install GitPython`
9
- **Requirements**: Git 1.7.x or newer, Python >= 3.7
10
11
## Core Imports
12
13
```python
14
import git
15
```
16
17
Common import patterns:
18
19
```python
20
from git import Repo
21
from git import Repo, Actor, RemoteProgress
22
from git.exc import GitCommandError, InvalidGitRepositoryError
23
```
24
25
## Basic Usage
26
27
```python
28
from git import Repo
29
30
# Initialize a new repository
31
repo = Repo.init("/path/to/repo")
32
33
# Open an existing repository
34
repo = Repo("/path/to/existing/repo")
35
36
# Clone a repository
37
repo = Repo.clone_from("https://github.com/user/repo.git", "/local/path")
38
39
# Basic repository operations
40
print(f"Current branch: {repo.active_branch}")
41
print(f"Is dirty: {repo.is_dirty()}")
42
print(f"Untracked files: {repo.untracked_files}")
43
44
# Access commits
45
for commit in repo.iter_commits('main', max_count=10):
46
print(f"{commit.hexsha[:7]} - {commit.message.strip()}")
47
48
# Stage and commit changes
49
repo.index.add(['file1.txt', 'file2.txt'])
50
repo.index.commit("Added files")
51
52
# Work with remotes
53
origin = repo.remotes.origin
54
origin.fetch()
55
origin.push()
56
```
57
58
## Architecture
59
60
GitPython provides a comprehensive object model that mirrors Git's internal structure:
61
62
- **Repository (`Repo`)**: Central interface providing access to all repository data and operations
63
- **Git Objects**: Complete object model including commits, trees, blobs, and tags with full metadata access
64
- **References**: Management of branches, tags, HEAD, and remote references with symbolic reference support
65
- **Index**: Full staging area control with fine-grained file operation support
66
- **Remotes**: Complete remote repository interaction including fetch, push, and progress reporting
67
- **Command Interface**: Direct access to Git command-line operations with comprehensive error handling
68
69
This design enables both high-level Git workflows and low-level repository manipulation, making it suitable for automation tools, CI/CD systems, code analysis tools, and any application requiring Git repository interaction.
70
71
## Capabilities
72
73
### Repository Management
74
75
Core repository operations including initialization, cloning, configuration, and state inspection. Provides the foundation for all Git operations through the central Repo interface.
76
77
```python { .api }
78
class Repo:
79
def __init__(self, path: PathLike, odbt: Type[GitCmdObjectDB] = GitCmdObjectDB, search_parent_directories: bool = False, expand_vars: bool = True): ...
80
@classmethod
81
def init(cls, path: PathLike, mkdir: bool = True, odbt: Type[GitCmdObjectDB] = GitCmdObjectDB, expand_vars: bool = True, **kwargs) -> "Repo": ...
82
@classmethod
83
def clone_from(cls, url: str, to_path: PathLike, progress: RemoteProgress = None, env: dict = None, multi_options: list = None, **kwargs) -> "Repo": ...
84
85
def is_dirty(self, index: bool = True, working_tree: bool = True, untracked_files: bool = False, submodules: bool = True, path: PathLike = None) -> bool: ...
86
def iter_commits(self, rev: str = None, paths: str | list = None, **kwargs) -> Iterator["Commit"]: ...
87
```
88
89
[Repository Management](./repository.md)
90
91
### Git Objects
92
93
Access to Git's core object model including commits, trees, blobs, and tags. Provides complete metadata access and object traversal capabilities for repository analysis and manipulation.
94
95
```python { .api }
96
class Object:
97
def __init__(self, repo: "Repo", binsha: bytes, mode: int = None, path: str = None): ...
98
99
class Commit(Object):
100
def __init__(self, repo: "Repo", binsha: bytes, tree: "Tree" = None, author: Actor = None, authored_date: int = None, author_tz_offset: int = None, committer: Actor = None, committed_date: int = None, committer_tz_offset: int = None, message: str = None, parents: list = None, encoding: str = None): ...
101
102
class Tree(Object):
103
def __init__(self, repo: "Repo", binsha: bytes, mode: int = None, path: str = None): ...
104
105
class Blob(Object):
106
def __init__(self, repo: "Repo", binsha: bytes, mode: int = None, path: str = None): ...
107
```
108
109
[Git Objects](./objects.md)
110
111
### References and Branches
112
113
Management of Git references including branches, tags, HEAD, and remote references. Supports creation, deletion, and manipulation of all reference types with symbolic reference handling.
114
115
```python { .api }
116
class Reference:
117
def __init__(self, repo: "Repo", path: str, check_path: bool = True): ...
118
def set_commit(self, commit: "Commit", logmsg: str = None) -> "Reference": ...
119
def delete(self, repo: "Repo", *refs: "Reference") -> None: ...
120
121
class Head(Reference):
122
def checkout(self, force: bool = False, **kwargs) -> "HEAD": ...
123
def reset(self, commit: "Commit" = None, index: bool = True, working_tree: bool = False, paths: list = None, **kwargs) -> "Head": ...
124
125
class Tag(Reference):
126
def delete(self, repo: "Repo", *tags: "Tag") -> None: ...
127
```
128
129
[References and Branches](./references.md)
130
131
### Index and Staging
132
133
Complete control over Git's staging area with support for adding, removing, and committing changes. Includes advanced staging operations and conflict resolution capabilities.
134
135
```python { .api }
136
class IndexFile:
137
def __init__(self, repo: "Repo", file_path: PathLike = None): ...
138
def add(self, items: list, force: bool = True, fprogress: Callable = None, path_rewriter: Callable = None, write: bool = True, write_extension_data: bool = False) -> "IndexFile": ...
139
def remove(self, items: list, working_tree: bool = False, **kwargs) -> "IndexFile": ...
140
def commit(self, message: str, parent_commits: list = None, head: bool = True, author: Actor = None, committer: Actor = None, author_date: str = None, commit_date: str = None, skip_hooks: bool = False) -> "Commit": ...
141
```
142
143
[Index and Staging](./index-staging.md)
144
145
### Remote Operations
146
147
Remote repository interaction including fetch, push, pull operations with comprehensive progress reporting and authentication support. Handles multiple remotes and protocol support.
148
149
```python { .api }
150
class Remote:
151
def __init__(self, repo: "Repo", name: str): ...
152
def fetch(self, refspec: str = None, progress: RemoteProgress = None, **kwargs) -> list["FetchInfo"]: ...
153
def push(self, refspec: str = None, progress: RemoteProgress = None, **kwargs) -> list["PushInfo"]: ...
154
def pull(self, refspec: str = None, progress: RemoteProgress = None, **kwargs) -> list["FetchInfo"]: ...
155
156
class RemoteProgress:
157
def update(self, op_code: int, cur_count: str | float, max_count: str | float = None, message: str = "") -> None: ...
158
```
159
160
[Remote Operations](./remote.md)
161
162
### Diff Operations
163
164
Comprehensive diff functionality for comparing commits, trees, and working directory state. Supports unified diff generation, patch creation, and change detection with file-level granularity.
165
166
```python { .api }
167
class Diff:
168
def __init__(self, repo: "Repo", a_rawpath: bytes, b_rawpath: bytes, a_blob_id: str, b_blob_id: str, a_mode: int, b_mode: int, new_file: bool, deleted_file: bool, copied_file: bool, raw_rename_from: str, raw_rename_to: str, diff: str, change_type: str): ...
169
170
class DiffIndex(list):
171
def __init__(self, repo: "Repo", *args): ...
172
def iter_change_type(self, change_type: str) -> Iterator["Diff"]: ...
173
174
class Diffable:
175
def diff(self, other: Union["Diffable", str, None] = None, paths: Union[str, list] = None, create_patch: bool = False, **kwargs) -> "DiffIndex": ...
176
```
177
178
[Diff Operations](./diff.md)
179
180
### Configuration Management
181
182
Access to Git configuration at repository, user, and system levels. Supports reading and writing configuration values with proper scope management and type conversion.
183
184
```python { .api }
185
class GitConfigParser:
186
def __init__(self, file_or_files: Union[str, list, None] = None, read_only: bool = True, merge_includes: bool = True, config_level: str = None): ...
187
def get_value(self, section: str, option: str, default: Any = None) -> Any: ...
188
def set_value(self, section: str, option: str, value: Any) -> "GitConfigParser": ...
189
def write(self) -> None: ...
190
```
191
192
[Configuration](./configuration.md)
193
194
### Command Interface
195
196
Direct access to Git command-line operations with comprehensive error handling, output parsing, and environment control. Enables custom Git operations not covered by high-level interfaces.
197
198
```python { .api }
199
class Git:
200
def __init__(self, working_dir: PathLike = None): ...
201
def execute(self, command: list, istream: BinaryIO = None, with_extended_output: bool = False, with_exceptions: bool = True, as_process: bool = False, output_stream: BinaryIO = None, stdout_as_string: bool = True, kill_after_timeout: int = None, with_stdout: bool = True, universal_newlines: bool = False, shell: bool = None, env: dict = None, max_chunk_size: int = io.DEFAULT_BUFFER_SIZE, **subprocess_kwargs) -> Union[str, tuple]: ...
202
```
203
204
[Command Interface](./command.md)
205
206
### Exception Handling
207
208
Comprehensive exception hierarchy for robust error handling across all Git operations. Includes specific exceptions for common Git scenarios and command failures.
209
210
```python { .api }
211
class GitError(Exception): ...
212
class InvalidGitRepositoryError(GitError): ...
213
class GitCommandError(GitError): ...
214
class GitCommandNotFound(GitError): ...
215
class CheckoutError(GitError): ...
216
class RepositoryDirtyError(GitError): ...
217
```
218
219
[Exception Handling](./exceptions.md)
220
221
### Database and Utilities
222
223
Infrastructure components for object database access and file locking mechanisms. Provides low-level access to Git's object storage and concurrent access control.
224
225
```python { .api }
226
class GitDB:
227
"""Git object database interface."""
228
229
class GitCmdObjectDB:
230
"""Git object database using command-line interface."""
231
def __init__(self, root_path: PathLike, git: "Git") -> None: ...
232
233
class LockFile:
234
"""File-based locking mechanism for concurrent access control."""
235
236
class BlockingLockFile(LockFile):
237
"""Blocking file lock that waits until lock can be obtained."""
238
```
239
240
[Database and Utilities](./database.md)
241
242
## Types
243
244
```python { .api }
245
from typing import Union, Optional, List, Iterator, Callable, Any, BinaryIO
246
from pathlib import Path
247
248
PathLike = Union[str, Path]
249
250
class Actor:
251
def __init__(self, name: str, email: str): ...
252
253
class Stats:
254
def __init__(self, repo: "Repo", total: dict, files: dict): ...
255
256
@property
257
def total(self) -> dict:
258
"""Total statistics (files, insertions, deletions)."""
259
260
@property
261
def files(self) -> dict:
262
"""Per-file statistics."""
263
264
265
StageType = int # 0=base, 1=ours, 2=theirs, 3=merge
266
267
# Utility functions
268
def refresh(path: Optional[PathLike] = None) -> None:
269
"""Refresh git executable path and global configuration."""
270
271
def remove_password_if_present(url: str) -> str:
272
"""Remove password from URL for safe logging."""
273
274
def safe_decode(data: bytes) -> str:
275
"""Safe decoding of bytes to string."""
276
277
def to_hex_sha(binsha: bytes) -> str:
278
"""Convert binary SHA to hexadecimal string."""
279
280
def rmtree(path: PathLike, ignore_errors: bool = False) -> None:
281
"""Remove directory tree with proper cleanup."""
282
```