0
# References and Branches
1
2
Git reference and branch management including creation, deletion, and iteration. Handles both local and remote references, providing object-oriented access to Git's reference system.
3
4
## Capabilities
5
6
### Reference Management
7
8
References are named pointers to Git objects, forming the basis of branches, tags, and other named references.
9
10
```python { .api }
11
class Reference:
12
@property
13
def name(self) -> str:
14
"""Full reference name (e.g., 'refs/heads/main')"""
15
16
@property
17
def shorthand(self) -> str:
18
"""Short reference name (e.g., 'main')"""
19
20
@property
21
def target(self) -> Oid | str:
22
"""Reference target (OID for direct, name for symbolic)"""
23
24
@property
25
def type(self) -> int:
26
"""Reference type (GIT_REF_OID or GIT_REF_SYMBOLIC)"""
27
28
@property
29
def is_valid_name(self) -> bool:
30
"""True if reference name is valid"""
31
32
def resolve(self) -> Reference:
33
"""Resolve symbolic reference to direct reference"""
34
35
def delete(self):
36
"""Delete this reference"""
37
38
def rename(self, new_name: str) -> Reference:
39
"""Rename reference"""
40
41
def set_target(self, target: Oid | str, message: str = None) -> Reference:
42
"""Update reference target"""
43
44
def log(self) -> list[RefLogEntry]:
45
"""Get reference log entries"""
46
47
def peel(self, object_type: int = None) -> Object:
48
"""Peel reference to object"""
49
50
# Reference Type Constants
51
GIT_REF_INVALID: int # Invalid reference
52
GIT_REF_OID: int # Direct reference (points to OID)
53
GIT_REF_SYMBOLIC: int # Symbolic reference (points to name)
54
55
# Reference Filter Constants
56
GIT_REFERENCES_BRANCHES: int # Branch references only
57
GIT_REFERENCES_TAGS: int # Tag references only
58
GIT_REFERENCES_ALL: int # All references
59
```
60
61
### Reference Collection
62
63
The References collection provides access to all repository references with iteration and filtering capabilities.
64
65
```python { .api }
66
class References:
67
def create(
68
self,
69
name: str,
70
target: Oid | str,
71
force: bool = False,
72
message: str = None
73
) -> Reference:
74
"""
75
Create new reference.
76
77
Parameters:
78
- name: Reference name
79
- target: Target OID or symbolic name
80
- force: Overwrite existing reference
81
- message: Reflog message
82
83
Returns:
84
Reference object
85
"""
86
87
def delete(self, name: str):
88
"""Delete reference by name"""
89
90
def get(self, name: str) -> Reference:
91
"""Get reference by name"""
92
93
def __getitem__(self, name: str) -> Reference:
94
"""Get reference by name"""
95
96
def __contains__(self, name: str) -> bool:
97
"""Check if reference exists"""
98
99
def __iter__(self):
100
"""Iterate over all references"""
101
102
def __len__(self) -> int:
103
"""Number of references"""
104
105
def objects(self, flag: int = GIT_REFERENCES_ALL):
106
"""Iterate filtered references"""
107
108
def compress(self):
109
"""Compress loose references into packed-refs"""
110
```
111
112
### Branch Management
113
114
Branches are a special type of reference with additional metadata and operations.
115
116
```python { .api }
117
class Branch(Reference):
118
@property
119
def branch_name(self) -> str:
120
"""Branch name without refs/heads/ prefix"""
121
122
@property
123
def upstream(self) -> Branch | None:
124
"""Upstream tracking branch"""
125
126
@property
127
def upstream_name(self) -> str | None:
128
"""Name of upstream branch"""
129
130
@property
131
def is_head(self) -> bool:
132
"""True if this branch is current HEAD"""
133
134
@property
135
def is_checked_out(self) -> bool:
136
"""True if branch is checked out"""
137
138
def set_upstream(self, upstream: Branch | str):
139
"""Set upstream tracking branch"""
140
141
def unset_upstream(self):
142
"""Remove upstream tracking"""
143
144
class Branches:
145
def create(
146
self,
147
name: str,
148
commit: Commit | Oid,
149
force: bool = False
150
) -> Branch:
151
"""
152
Create new branch.
153
154
Parameters:
155
- name: Branch name
156
- commit: Target commit
157
- force: Overwrite existing branch
158
159
Returns:
160
Branch object
161
"""
162
163
def delete(self, name: str):
164
"""Delete branch"""
165
166
def get(self, name: str) -> Branch:
167
"""Get branch by name"""
168
169
def __getitem__(self, name: str) -> Branch:
170
"""Get branch by name"""
171
172
def __contains__(self, name: str) -> bool:
173
"""Check if branch exists"""
174
175
def __iter__(self):
176
"""Iterate over local branches"""
177
178
def local(self):
179
"""Iterate over local branches"""
180
181
def remote(self):
182
"""Iterate over remote branches"""
183
184
@property
185
def with_commit(self, commit: Oid):
186
"""Get branches containing commit"""
187
188
# Branch Type Constants
189
GIT_BRANCH_LOCAL: int # Local branches
190
GIT_BRANCH_REMOTE: int # Remote branches
191
GIT_BRANCH_ALL: int # All branches
192
```
193
194
### Reference Log
195
196
RefLog tracks changes to references over time.
197
198
```python { .api }
199
class RefLogEntry:
200
@property
201
def id_old(self) -> Oid:
202
"""Previous OID"""
203
204
@property
205
def id_new(self) -> Oid:
206
"""New OID"""
207
208
@property
209
def committer(self) -> Signature:
210
"""Committer who made change"""
211
212
@property
213
def message(self) -> str:
214
"""Reflog message"""
215
```
216
217
### Revision Parsing
218
219
Parse revision specifications into Git objects.
220
221
```python { .api }
222
def revparse_single(repo: Repository, spec: str) -> Object:
223
"""Parse revision spec to single object"""
224
225
def revparse(repo: Repository, spec: str) -> RevSpec:
226
"""Parse revision spec"""
227
228
class RevSpec:
229
@property
230
def from_object(self) -> Object:
231
"""Start object for range"""
232
233
@property
234
def to_object(self) -> Object:
235
"""End object for range"""
236
237
@property
238
def flags(self) -> int:
239
"""RevSpec flags"""
240
241
# RevSpec Flag Constants
242
GIT_REVSPEC_SINGLE: int # Single object
243
GIT_REVSPEC_RANGE: int # Range of objects
244
GIT_REVSPEC_MERGE_BASE: int # Merge base
245
```
246
247
### Usage Examples
248
249
#### Working with References
250
251
```python
252
import pygit2
253
254
repo = pygit2.Repository('/path/to/repo')
255
256
# List all references
257
for ref in repo.references:
258
print(f"{ref.name} -> {ref.target}")
259
260
# Create new reference
261
commit = repo[repo.head.target]
262
new_ref = repo.references.create('refs/heads/feature', commit.oid)
263
264
# Get specific reference
265
main_ref = repo.references['refs/heads/main']
266
print(f"Main branch points to: {main_ref.target}")
267
268
# Update reference
269
new_commit = repo.revparse_single('HEAD~1')
270
main_ref.set_target(new_commit.oid, "Reset to previous commit")
271
272
# Delete reference
273
repo.references.delete('refs/heads/old-feature')
274
```
275
276
#### Branch Operations
277
278
```python
279
# List branches
280
print("Local branches:")
281
for branch in repo.branches.local:
282
marker = " (HEAD)" if branch.is_head else ""
283
upstream = f" -> {branch.upstream_name}" if branch.upstream else ""
284
print(f" {branch.branch_name}{marker}{upstream}")
285
286
print("\nRemote branches:")
287
for branch in repo.branches.remote:
288
print(f" {branch.branch_name}")
289
290
# Create new branch
291
new_branch = repo.branches.create('feature-branch', repo.head.target)
292
293
# Set upstream tracking
294
origin_main = repo.branches['origin/main']
295
new_branch.set_upstream(origin_main)
296
297
# Switch to branch (checkout)
298
repo.checkout(new_branch)
299
300
# Delete branch
301
repo.branches.delete('old-feature')
302
```
303
304
#### Reference Logs
305
306
```python
307
# View reflog for HEAD
308
head_ref = repo.references['HEAD']
309
reflog = head_ref.log()
310
311
print("Recent HEAD changes:")
312
for entry in reflog[:5]: # Last 5 entries
313
print(f"{entry.id_old} -> {entry.id_new}")
314
print(f" {entry.committer.name}: {entry.message}")
315
print()
316
```
317
318
#### Revision Parsing
319
320
```python
321
# Parse various revision specifications
322
head_commit = repo.revparse_single('HEAD')
323
previous_commit = repo.revparse_single('HEAD~1')
324
tag_commit = repo.revparse_single('v1.0.0')
325
branch_commit = repo.revparse_single('feature-branch')
326
327
# Parse ranges
328
revspec = repo.revparse('HEAD~5..HEAD')
329
print(f"Range from {revspec.from_object.oid} to {revspec.to_object.oid}")
330
331
# Find merge base
332
base_commit = repo.revparse_single('main...feature')
333
print(f"Merge base: {base_commit.oid}")
334
```
335
336
#### Advanced Reference Operations
337
338
```python
339
# Find branches containing specific commit
340
commit_oid = repo.revparse_single('HEAD~3').oid
341
branches_with_commit = repo.branches.with_commit(commit_oid)
342
print(f"Branches containing {commit_oid}:")
343
for branch in branches_with_commit:
344
print(f" {branch.branch_name}")
345
346
# Compress loose references
347
repo.references.compress()
348
349
# Validate reference name
350
if pygit2.reference_is_valid_name('refs/heads/my-feature'):
351
print("Valid reference name")
352
353
# Resolve symbolic reference
354
head = repo.references['HEAD']
355
if head.type == pygit2.GIT_REF_SYMBOLIC:
356
resolved = head.resolve()
357
print(f"HEAD -> {resolved.name} -> {resolved.target}")
358
```