0
# Repository Management
1
2
Core repository operations providing the foundation for all Git interactions through the central `Repo` interface. Handles repository initialization, cloning, configuration access, and state inspection.
3
4
## Capabilities
5
6
### Repository Creation and Access
7
8
Create new repositories, clone from remotes, and open existing repositories with comprehensive path and configuration support.
9
10
```python { .api }
11
class Repo:
12
def __init__(
13
self,
14
path: PathLike = None,
15
odbt: Type[GitCmdObjectDB] = GitCmdObjectDB,
16
search_parent_directories: bool = False,
17
expand_vars: bool = True
18
):
19
"""
20
Initialize a repository object.
21
22
Args:
23
path: Path to repository root or .git directory
24
odbt: Object database type to use
25
search_parent_directories: Search parent dirs for .git directory
26
expand_vars: Expand environment variables in path
27
"""
28
29
@classmethod
30
def init(
31
cls,
32
path: PathLike,
33
mkdir: bool = True,
34
odbt: Type[GitCmdObjectDB] = GitCmdObjectDB,
35
expand_vars: bool = True,
36
**kwargs
37
) -> "Repo":
38
"""
39
Initialize a new git repository.
40
41
Args:
42
path: Path where repository should be created
43
mkdir: Create directory if it doesn't exist
44
odbt: Object database type
45
expand_vars: Expand environment variables
46
**kwargs: Additional git init options (bare, shared, etc.)
47
48
Returns:
49
New Repo instance
50
"""
51
52
@classmethod
53
def clone_from(
54
cls,
55
url: str,
56
to_path: PathLike,
57
progress: "RemoteProgress" = None,
58
env: dict = None,
59
multi_options: list = None,
60
**kwargs
61
) -> "Repo":
62
"""
63
Clone repository from URL.
64
65
Args:
66
url: Repository URL to clone from
67
to_path: Local path to clone to
68
progress: Progress reporter instance
69
env: Environment variables for git command
70
multi_options: Multiple option flags
71
**kwargs: Additional clone options (branch, depth, etc.)
72
73
Returns:
74
Cloned Repo instance
75
"""
76
```
77
78
### Repository State Inspection
79
80
Query repository state including dirty status, active branch, untracked files, and commit history with filtering support.
81
82
```python { .api }
83
def is_dirty(
84
self,
85
index: bool = True,
86
working_tree: bool = True,
87
untracked_files: bool = False,
88
submodules: bool = True,
89
path: PathLike = None
90
) -> bool:
91
"""
92
Check if repository has uncommitted changes.
93
94
Args:
95
index: Check staged changes
96
working_tree: Check working directory changes
97
untracked_files: Include untracked files
98
submodules: Check submodules for changes
99
path: Limit check to specific path
100
101
Returns:
102
True if repository has changes
103
"""
104
105
def iter_commits(
106
self,
107
rev: str = None,
108
paths: Union[str, list] = None,
109
**kwargs
110
) -> Iterator["Commit"]:
111
"""
112
Iterate over commits in repository.
113
114
Args:
115
rev: Starting revision (default: HEAD)
116
paths: Limit to commits affecting these paths
117
**kwargs: Additional options (max_count, skip, since, until, etc.)
118
119
Returns:
120
Iterator of Commit objects
121
"""
122
123
@property
124
def active_branch(self) -> "Head":
125
"""Current active branch."""
126
127
@property
128
def untracked_files(self) -> list[str]:
129
"""List of untracked file paths."""
130
131
@property
132
def heads(self) -> "IterableList[Head]":
133
"""All branch heads."""
134
135
@property
136
def tags(self) -> "IterableList[TagReference]":
137
"""All tags."""
138
139
@property
140
def remotes(self) -> "IterableList[Remote]":
141
"""All remotes."""
142
```
143
144
### Configuration Access
145
146
Access repository, user, and system Git configuration with read and write capabilities.
147
148
```python { .api }
149
def config_reader(self, config_level: str = "repository") -> "GitConfigParser":
150
"""
151
Get configuration reader.
152
153
Args:
154
config_level: Configuration level ('repository', 'user', 'system')
155
156
Returns:
157
Read-only configuration parser
158
"""
159
160
def config_writer(self, config_level: str = "repository") -> "GitConfigParser":
161
"""
162
Get configuration writer.
163
164
Args:
165
config_level: Configuration level to write to
166
167
Returns:
168
Configuration parser for writing
169
"""
170
```
171
172
### Repository Properties
173
174
Access to repository paths, state, and metadata.
175
176
```python { .api }
177
@property
178
def git_dir(self) -> str:
179
"""Path to .git directory."""
180
181
@property
182
def working_dir(self) -> Optional[str]:
183
"""Path to working directory (None for bare repos)."""
184
185
@property
186
def working_tree_dir(self) -> Optional[str]:
187
"""Alias for working_dir."""
188
189
@property
190
def bare(self) -> bool:
191
"""True if repository is bare."""
192
193
@property
194
def git(self) -> "Git":
195
"""Git command interface for this repository."""
196
197
@property
198
def index(self) -> "IndexFile":
199
"""Repository index/staging area."""
200
201
@property
202
def head(self) -> "HEAD":
203
"""HEAD reference."""
204
205
@property
206
def common_dir(self) -> str:
207
"""Path to common git directory."""
208
```
209
210
### Archive and Export
211
212
Create archives and export repository content.
213
214
```python { .api }
215
def archive(
216
self,
217
ostream: BinaryIO,
218
treeish: str = None,
219
prefix: str = None,
220
**kwargs
221
) -> "Repo":
222
"""
223
Create archive of repository content.
224
225
Args:
226
ostream: Output stream for archive
227
treeish: Tree-ish to archive (default: HEAD)
228
prefix: Prefix for archive entries
229
**kwargs: Additional archive options
230
231
Returns:
232
Self for chaining
233
"""
234
```
235
236
## Usage Examples
237
238
### Basic Repository Operations
239
240
```python
241
from git import Repo
242
243
# Create new repository
244
repo = Repo.init('/path/to/new/repo')
245
246
# Open existing repository
247
repo = Repo('/path/to/existing/repo')
248
249
# Clone repository
250
repo = Repo.clone_from(
251
'https://github.com/user/repo.git',
252
'/local/path',
253
branch='main'
254
)
255
256
# Check repository state
257
if repo.is_dirty():
258
print("Repository has uncommitted changes")
259
260
print(f"Active branch: {repo.active_branch}")
261
print(f"Untracked files: {repo.untracked_files}")
262
```
263
264
### Working with Commits
265
266
```python
267
# Get recent commits
268
for commit in repo.iter_commits('main', max_count=10):
269
print(f"{commit.hexsha[:7]} - {commit.message.strip()}")
270
271
# Get commits for specific file
272
file_commits = list(repo.iter_commits(paths='README.md', max_count=5))
273
274
# Get commits in date range
275
import datetime
276
since = datetime.datetime(2023, 1, 1)
277
recent_commits = list(repo.iter_commits(since=since))
278
```
279
280
### Configuration Management
281
282
```python
283
# Read configuration
284
config = repo.config_reader()
285
user_name = config.get_value('user', 'name')
286
user_email = config.get_value('user', 'email')
287
288
# Write configuration
289
with repo.config_writer() as config:
290
config.set_value('user', 'name', 'John Doe')
291
config.set_value('user', 'email', 'john@example.com')
292
```
293
294
### Repository Inspection
295
296
```python
297
# Check various repository properties
298
print(f"Git directory: {repo.git_dir}")
299
print(f"Working directory: {repo.working_dir}")
300
print(f"Is bare: {repo.bare}")
301
302
# List branches and tags
303
for branch in repo.heads:
304
print(f"Branch: {branch.name}")
305
306
for tag in repo.tags:
307
print(f"Tag: {tag.name}")
308
309
# List remotes
310
for remote in repo.remotes:
311
print(f"Remote: {remote.name} -> {remote.url}")
312
```