or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/pypi-pygit2

Python bindings for libgit2 providing comprehensive Git repository operations and version control functionality.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/pygit2@1.18.x

To install, run

npx @tessl/cli install tessl/pypi-pygit2@1.18.0

0

# pygit2

1

2

Python bindings for libgit2 providing comprehensive Git repository operations and version control functionality. pygit2 enables programmatic Git operations including repository management, object manipulation, branching, merging, remote operations, and configuration management through both high-level Python APIs and low-level libgit2 bindings.

3

4

## Package Information

5

6

- **Package Name**: pygit2

7

- **Language**: Python

8

- **Installation**: `pip install pygit2`

9

- **Documentation**: https://www.pygit2.org/

10

- **Version**: 1.18.2

11

- **libgit2 Version**: Available via `pygit2.LIBGIT2_VERSION`

12

- **Features**: Thread safety, HTTPS, SSH support - check via `pygit2.features`

13

14

## Core Imports

15

16

```python

17

import pygit2

18

```

19

20

Common specific imports:

21

22

```python

23

from pygit2 import Repository, init_repository, clone_repository, discover_repository

24

from pygit2 import Commit, Tree, Blob, Tag, Reference, Branch, Walker

25

from pygit2 import Signature, Oid, Note, RevSpec, TreeBuilder

26

from pygit2 import Config, Index, Remote, Diff, settings

27

```

28

29

## Basic Usage

30

31

```python

32

import pygit2

33

34

# Initialize a new repository

35

repo = pygit2.init_repository('/path/to/repo')

36

37

# Open an existing repository

38

repo = pygit2.Repository('/path/to/existing/repo')

39

40

# Clone a repository

41

repo = pygit2.clone_repository('https://github.com/user/repo.git', '/local/path')

42

43

# Create a signature for commits

44

signature = pygit2.Signature('Author Name', 'author@example.com')

45

46

# Get repository status

47

status = repo.status()

48

for filepath, flags in status.items():

49

print(f"{filepath}: {flags}")

50

51

# Stage files and create commit

52

repo.index.add_all()

53

repo.index.write()

54

tree = repo.index.write_tree()

55

commit = repo.create_commit(

56

'HEAD',

57

signature,

58

signature,

59

'Commit message',

60

tree,

61

[repo.head.target]

62

)

63

```

64

65

## Architecture

66

67

pygit2 provides a layered architecture:

68

69

- **High-level Python API**: Pythonic wrappers for common Git operations

70

- **Low-level libgit2 bindings**: Direct access to libgit2 C library functions via CFFI

71

- **Git Objects**: Object-oriented representation of Git entities (Repository, Commit, Tree, Blob, etc.)

72

- **Collections**: Iterator-based access to branches, references, remotes, and other collections

73

- **Callbacks**: Event handling for remote operations, checkout, and other interactive processes

74

75

This design enables both simple high-level operations and fine-grained control over Git repository manipulation.

76

77

## Capabilities

78

79

### Repository Management

80

81

Core repository operations including initialization, opening, cloning, and basic repository information access. Provides the foundation for all Git operations.

82

83

```python { .api }

84

def init_repository(path: str, bare: bool = False, **kwargs) -> Repository: ...

85

def clone_repository(url: str, path: str, **kwargs) -> Repository: ...

86

def discover_repository(path: str) -> str: ...

87

88

class Repository:

89

def __init__(self, path: str): ...

90

@property

91

def workdir(self) -> str: ...

92

@property

93

def path(self) -> str: ...

94

@property

95

def is_bare(self) -> bool: ...

96

@property

97

def is_empty(self) -> bool: ...

98

@property

99

def head(self) -> Reference: ...

100

```

101

102

[Repository Management](./repository.md)

103

104

### Git Objects

105

106

Core Git object types including commits, trees, blobs, and tags. These represent the fundamental data structures in Git repositories.

107

108

```python { .api }

109

class Object:

110

@property

111

def oid(self) -> Oid: ...

112

@property

113

def type(self) -> int: ...

114

115

class Commit(Object):

116

@property

117

def message(self) -> str: ...

118

@property

119

def author(self) -> Signature: ...

120

@property

121

def committer(self) -> Signature: ...

122

@property

123

def tree(self) -> Tree: ...

124

@property

125

def parents(self) -> list[Commit]: ...

126

127

class Tree(Object):

128

def __getitem__(self, key: str) -> Object: ...

129

def __iter__(self): ...

130

131

class Blob(Object):

132

@property

133

def data(self) -> bytes: ...

134

@property

135

def size(self) -> int: ...

136

```

137

138

[Git Objects](./objects.md)

139

140

### History and Navigation

141

142

Git history traversal and revision parsing operations.

143

144

```python { .api }

145

class Walker:

146

"""Commit history walker"""

147

def push(self, oid: Oid): ...

148

def hide(self, oid: Oid): ...

149

def sort(self, sort_mode: int): ...

150

def __iter__(self): ...

151

152

class RevSpec:

153

"""Revision specification parsing result"""

154

@property

155

def from_object(self) -> Object: ...

156

@property

157

def to_object(self) -> Object: ...

158

@property

159

def flags(self) -> int: ...

160

```

161

162

### Git Notes

163

164

Git notes operations for attaching metadata to objects.

165

166

```python { .api }

167

class Note:

168

"""Git note object"""

169

@property

170

def oid(self) -> Oid: ...

171

@property

172

def annotated_id(self) -> Oid: ...

173

@property

174

def message(self) -> str: ...

175

```

176

177

### Working Directory and Worktrees

178

179

Extended working directory and worktree management.

180

181

```python { .api }

182

class Worktree:

183

"""Git worktree management"""

184

@property

185

def name(self) -> str: ...

186

@property

187

def path(self) -> str: ...

188

@property

189

def is_prunable(self) -> bool: ...

190

def prune(self, **kwargs): ...

191

```

192

193

### References and Branches

194

195

Git reference and branch management including creation, deletion, and iteration. Handles both local and remote references.

196

197

```python { .api }

198

class Reference:

199

@property

200

def name(self) -> str: ...

201

@property

202

def target(self) -> Oid | str: ...

203

@property

204

def type(self) -> int: ...

205

206

class Branch(Reference):

207

@property

208

def branch_name(self) -> str: ...

209

@property

210

def upstream(self) -> Branch | None: ...

211

@property

212

def is_head(self) -> bool: ...

213

214

class References:

215

def create(self, name: str, target: Oid | str) -> Reference: ...

216

def delete(self, name: str): ...

217

def __iter__(self): ...

218

```

219

220

[References and Branches](./references.md)

221

222

### Index and Staging

223

224

Git index (staging area) operations for preparing commits. Handles file staging, unstaging, and conflict resolution.

225

226

```python { .api }

227

class Index:

228

def add(self, path: str): ...

229

def add_all(self, pathspecs: list[str] = None): ...

230

def remove(self, path: str): ...

231

def write(self): ...

232

def write_tree(self) -> Oid: ...

233

@property

234

def conflicts(self) -> ConflictCollection: ...

235

236

class IndexEntry:

237

@property

238

def path(self) -> str: ...

239

@property

240

def oid(self) -> Oid: ...

241

@property

242

def mode(self) -> int: ...

243

```

244

245

[Index and Staging](./staging.md)

246

247

### Diff and Patches

248

249

Difference analysis between Git objects, working directory, and index. Provides detailed change information and patch generation.

250

251

```python { .api }

252

class Diff:

253

@property

254

def deltas(self) -> list[DiffDelta]: ...

255

@property

256

def stats(self) -> DiffStats: ...

257

def patch(self) -> str: ...

258

def find_similar(self, **kwargs): ...

259

260

class DiffDelta:

261

@property

262

def old_file(self) -> DiffFile: ...

263

@property

264

def new_file(self) -> DiffFile: ...

265

@property

266

def status(self) -> int: ...

267

268

class Patch:

269

@property

270

def delta(self) -> DiffDelta: ...

271

@property

272

def hunks(self) -> list[DiffHunk]: ...

273

```

274

275

[Diff and Patches](./diff.md)

276

277

### Remote Operations

278

279

Git remote repository operations including fetching, pushing, and remote management. Handles authentication and transfer progress.

280

281

```python { .api }

282

class Remote:

283

@property

284

def name(self) -> str: ...

285

@property

286

def url(self) -> str: ...

287

def fetch(self, refspecs: list[str] = None, **kwargs): ...

288

def push(self, refspecs: list[str], **kwargs): ...

289

def ls_remotes(self) -> list[RemoteHead]: ...

290

291

class RemoteCallbacks:

292

def credentials(self, url: str, username_from_url: str, allowed_types: int): ...

293

def progress(self, stats: TransferProgress): ...

294

def push_update_reference(self, refname: str, message: str): ...

295

```

296

297

[Remote Operations](./remotes.md)

298

299

### Configuration

300

301

Git configuration management for repository, global, and system settings. Provides type-safe access to Git configuration values.

302

303

```python { .api }

304

class Config:

305

def __getitem__(self, key: str): ...

306

def __setitem__(self, key: str, value): ...

307

def __delitem__(self, key: str): ...

308

def get_bool(self, key: str) -> bool: ...

309

def get_int(self, key: str) -> int: ...

310

def get_multivar(self, key: str) -> list[str]: ...

311

312

class ConfigEntry:

313

@property

314

def name(self) -> str: ...

315

@property

316

def value(self) -> str: ...

317

@property

318

def level(self) -> int: ...

319

```

320

321

[Configuration](./config.md)

322

323

### Authentication

324

325

Credential management for Git operations supporting various authentication methods including SSH keys, username/password, and SSH agent.

326

327

```python { .api }

328

class Username:

329

def __init__(self, username: str): ...

330

331

class UserPass:

332

def __init__(self, username: str, password: str): ...

333

334

class Keypair:

335

def __init__(self, username: str, pubkey_path: str, privkey_path: str, passphrase: str = ''): ...

336

337

class KeypairFromAgent:

338

def __init__(self, username: str): ...

339

340

class KeypairFromMemory:

341

def __init__(self, username: str, pubkey_data: str, privkey_data: str, passphrase: str = ''): ...

342

```

343

344

[Authentication](./auth.md)

345

346

### Advanced Operations

347

348

Advanced Git operations including blame, stashing, submodules, filtering, and object database access.

349

350

```python { .api }

351

class Blame:

352

@property

353

def hunks(self) -> list[BlameHunk]: ...

354

355

class Stash:

356

def save(self, message: str, **kwargs) -> Oid: ...

357

def apply(self, index: int, **kwargs): ...

358

def drop(self, index: int): ...

359

360

class Submodule:

361

@property

362

def name(self) -> str: ...

363

@property

364

def path(self) -> str: ...

365

@property

366

def url(self) -> str: ...

367

def update(self, **kwargs): ...

368

```

369

370

[Advanced Operations](./advanced.md)

371

372

### Utility Functions

373

374

Core utility functions for repository discovery, hashing, and data conversion operations.

375

376

```python { .api }

377

def discover_repository(path: str) -> str:

378

"""Find repository path containing the given path"""

379

380

def hash(data: bytes) -> Oid:

381

"""Calculate SHA-1 hash of data"""

382

383

def hashfile(path: str) -> Oid:

384

"""Calculate SHA-1 hash of file"""

385

386

def reference_is_valid_name(name: str) -> bool:

387

"""Check if reference name is valid"""

388

389

def to_bytes(text: str) -> bytes:

390

"""Convert string to bytes"""

391

392

def to_str(data: bytes) -> str:

393

"""Convert bytes to string"""

394

```

395

396

### Version and Feature Information

397

398

Access to library version information and feature flags.

399

400

```python { .api }

401

__version__: str # pygit2 version

402

LIBGIT2_VERSION: str # libgit2 version string

403

LIBGIT2_VER: tuple[int, int, int] # libgit2 version tuple

404

LIBGIT2_VER_MAJOR: int

405

LIBGIT2_VER_MINOR: int

406

LIBGIT2_VER_REVISION: int

407

408

class Features:

409

"""Feature flags for compiled capabilities"""

410

THREADS: int

411

HTTPS: int

412

SSH: int

413

NSEC: int

414

415

features: Features # Global features instance

416

```

417

418

### Global Settings

419

420

Global library configuration and settings management.

421

422

```python { .api }

423

class Settings:

424

def __getitem__(self, key: str): ...

425

def __setitem__(self, key: str, value): ...

426

427

settings: Settings # Global settings instance

428

```

429

430

### Modern Enums API

431

432

Type-safe enumeration values for Git operations (preferred over legacy constants).

433

434

```python { .api }

435

from pygit2 import enums

436

437

# Repository operations

438

enums.RepositoryInitFlag

439

enums.RepositoryOpenFlag

440

enums.RepositoryState

441

442

# Object types

443

enums.ObjectType

444

enums.FileMode

445

446

# Diff operations

447

enums.DiffOption

448

enums.DiffFind

449

enums.DeltaStatus

450

451

# Merge operations

452

enums.MergeAnalysis

453

enums.MergePreference

454

455

# Branch operations

456

enums.BranchType

457

enums.ReferenceType

458

459

# And many more...

460

```

461

462

## Error Handling

463

464

pygit2 operations can raise various exceptions for error conditions. All Git-related errors inherit from GitError.

465

466

```python { .api }

467

class GitError(Exception):

468

"""Base class for all Git-related errors"""

469

470

class AlreadyExistsError(GitError):

471

"""Raised when trying to create an object that already exists"""

472

473

class InvalidSpecError(GitError):

474

"""Raised when a revision specification is invalid"""

475

```

476

477

## Types

478

479

```python { .api }

480

class Oid:

481

def __init__(self, raw_bytes: bytes | str): ...

482

@property

483

def hex(self) -> str: ...

484

@property

485

def raw(self) -> bytes: ...

486

487

class Signature:

488

def __init__(self, name: str, email: str, time: int = None, offset: int = None): ...

489

@property

490

def name(self) -> str: ...

491

@property

492

def email(self) -> str: ...

493

@property

494

def time(self) -> int: ...

495

@property

496

def offset(self) -> int: ...

497

498

class Settings:

499

def __getitem__(self, key: str): ...

500

def __setitem__(self, key: str, value): ...

501

```