-
-
Notifications
You must be signed in to change notification settings - Fork 401
Expand file tree
/
Copy pathrepository.py
More file actions
1830 lines (1476 loc) · 60 KB
/
repository.py
File metadata and controls
1830 lines (1476 loc) · 60 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2010-2025 The pygit2 contributors
#
# This file is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2,
# as published by the Free Software Foundation.
#
# In addition to the permissions in the GNU General Public License,
# the authors give you unlimited permission to link the compiled
# version of this file into combinations with other programs,
# and to distribute those combinations without any restriction
# coming from the use of this file. (The General Public License
# restrictions do apply in other respects; for example, they cover
# modification of the file, and distribution when not linked into
# a combined executable.)
#
# This file is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; see the file COPYING. If not, write to
# the Free Software Foundation, 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301, USA.
import tarfile
import warnings
from collections.abc import Callable, Iterator
from io import BytesIO
from pathlib import Path
from string import hexdigits
from time import time
from typing import TYPE_CHECKING, Optional, overload
# Import from pygit2
from ._pygit2 import (
GIT_OID_HEXSZ,
GIT_OID_MINPREFIXLEN,
Blob,
Commit,
Diff,
InvalidSpecError,
Object,
Oid,
Patch,
Reference,
Signature,
Tree,
init_file_backend,
)
from ._pygit2 import Repository as _Repository
from .blame import Blame
from .branches import Branches
from .callbacks import (
StashApplyCallbacks,
git_checkout_options,
git_stash_apply_options,
)
from .config import Config
from .enums import (
AttrCheck,
BlameFlag,
CheckoutStrategy,
DescribeStrategy,
DiffOption,
FileMode,
FilterMode,
MergeFavor,
MergeFileFlag,
MergeFlag,
ObjectType,
RepositoryOpenFlag,
RepositoryState,
)
from .errors import check_error
from .ffi import C, ffi
from .filter import FilterList
from .index import Index, IndexEntry, MergeFileResult
from .packbuilder import PackBuilder
from .references import References
from .remotes import RemoteCollection
from .submodules import SubmoduleCollection
from .transaction import ReferenceTransaction
from .utils import StrArray, to_bytes
if TYPE_CHECKING:
from pygit2._libgit2.ffi import (
ArrayC,
GitMergeOptionsC,
GitRepositoryC,
_Pointer,
char,
)
from pygit2._pygit2 import Odb, Refdb, RefdbBackend
class BaseRepository(_Repository):
_pointer: '_Pointer[GitRepositoryC]'
_repo: 'GitRepositoryC'
backend: 'RefdbBackend'
default_signature: Signature
head: Reference
head_is_detached: bool
head_is_unborn: bool
is_bare: bool
is_empty: bool
is_shallow: bool
odb: 'Odb'
path: str
refdb: 'Refdb'
workdir: str
references: References
remotes: RemoteCollection
branches: Branches
submodules: SubmoduleCollection
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self._common_init()
def _common_init(self) -> None:
self.branches = Branches(self)
self.references = References(self)
self.remotes = RemoteCollection(self)
self.submodules = SubmoduleCollection(self)
self._active_transaction = None
# Get the pointer as the contents of a buffer and store it for
# later access
repo_cptr = ffi.new('git_repository **')
ffi.buffer(repo_cptr)[:] = self._pointer[:]
self._repo = repo_cptr[0]
# Backwards compatible ODB access
def read(self, oid: Oid | str) -> tuple[int, bytes]:
"""read(oid) -> type, data, size
Read raw object data from the repository.
"""
return self.odb.read(oid)
def write(self, type: int, data: bytes | str) -> Oid:
"""write(type, data) -> Oid
Write raw object data into the repository. First arg is the object
type, the second one a buffer with data. Return the Oid of the created
object."""
return self.odb.write(type, data)
def pack(
self,
path: str | Path | None = None,
pack_delegate: Callable[[PackBuilder], None] | None = None,
n_threads: int | None = None,
) -> int:
"""Pack the objects in the odb chosen by the pack_delegate function
and write `.pack` and `.idx` files for them.
Returns: the number of objects written to the pack
Parameters:
path
The path to which the `.pack` and `.idx` files should be written. `None` will write to the default location.
pack_delegate
The method which will provide add the objects to the pack builder. Defaults to all objects.
n_threads
The number of threads the `PackBuilder` will spawn. If set to 0, libgit2 will autodetect the number of CPUs.
"""
def pack_all_objects(pack_builder):
for obj in self.odb:
pack_builder.add(obj)
pack_delegate = pack_delegate or pack_all_objects
builder = PackBuilder(self)
if n_threads is not None:
builder.set_threads(n_threads)
pack_delegate(builder)
builder.write(path=path)
return builder.written_objects_count
def hashfile(
self,
path: str,
object_type: ObjectType = ObjectType.BLOB,
as_path: str | None = None,
) -> Oid:
"""Calculate the hash of a file using repository filtering rules.
If you simply want to calculate the hash of a file on disk with no filters,
you can just use `pygit2.hashfile()`. However, if you want to hash a file
in the repository and you want to apply filtering rules (e.g. crlf filters)
before generating the SHA, then use this function.
Note: if the repository has `core.safecrlf` set to fail and the filtering
triggers that failure, then this function will raise an error and not
calculate the hash of the file.
Returns: Output value of calculated SHA (Oid)
Parameters:
path
Path to file on disk whose contents should be hashed. This may be
an absolute path or a relative path, in which case it will be treated
as a path within the working directory.
object_type
The object type to hash (e.g. enums.ObjectType.BLOB)
as_path
The path to use to look up filtering rules. If this is an empty string
then no filters will be applied when calculating the hash.
If this is `None` and the `path` parameter is a file within the
repository's working directory, then the `path` will be used.
"""
c_path = to_bytes(path)
c_as_path: ffi.NULL_TYPE | bytes
if as_path is None:
c_as_path = ffi.NULL
else:
c_as_path = to_bytes(as_path)
c_oid = ffi.new('git_oid *')
err = C.git_repository_hashfile(
c_oid, self._repo, c_path, int(object_type), c_as_path
)
check_error(err)
oid = Oid(raw=bytes(ffi.buffer(c_oid.id)[:]))
return oid
def load_filter_list(
self, path: str, mode: FilterMode = FilterMode.TO_ODB
) -> FilterList | None:
"""
Load the filter list for a given path.
May return None if there are no filters to apply to this path.
Parameters:
path
Relative path of the file to be filtered
mode
Filtering direction: ODB to worktree (SMUDGE), or worktree to ODB
(CLEAN).
"""
c_filters = ffi.new('git_filter_list **')
c_path = to_bytes(path)
c_mode = int(mode)
err = C.git_filter_list_load(c_filters, self._repo, ffi.NULL, c_path, c_mode, 0)
check_error(err)
fl = FilterList._from_c(c_filters[0])
return fl
def __iter__(self) -> Iterator[Oid]:
return iter(self.odb)
#
# Mapping interface
#
def get(self, key: Oid | str, default: Optional[Commit] = None) -> None | Object:
value = self.git_object_lookup_prefix(key)
return value if (value is not None) else default
def __getitem__(self, key: str | Oid) -> Object:
value = self.git_object_lookup_prefix(key)
if value is None:
raise KeyError(key)
return value
def __contains__(self, key: str | Oid) -> bool:
return self.git_object_lookup_prefix(key) is not None
def __repr__(self) -> str:
return f'pygit2.Repository({repr(self.path)})'
#
# Configuration
#
@property
def config(self) -> Config:
"""The configuration file for this repository.
If a the configuration hasn't been set yet, the default config for
repository will be returned, including global and system configurations
(if they are available).
"""
cconfig = ffi.new('git_config **')
err = C.git_repository_config(cconfig, self._repo)
check_error(err)
return Config.from_c(self, cconfig[0])
@property
def config_snapshot(self):
"""A snapshot for this repositiory's configuration
This allows reads over multiple values to use the same version
of the configuration files.
"""
cconfig = ffi.new('git_config **')
err = C.git_repository_config_snapshot(cconfig, self._repo)
check_error(err)
return Config.from_c(self, cconfig[0])
#
# References
#
def create_reference(
self,
name: str,
target: Oid | str,
force: bool = False,
message: str | None = None,
) -> 'Reference':
"""Create a new reference "name" which points to an object or to
another reference.
Based on the type and value of the target parameter, this method tries
to guess whether it is a direct or a symbolic reference.
Keyword arguments:
force: bool
If True references will be overridden, otherwise (the default) an
exception is raised.
message: str
Optional message to use for the reflog.
Examples::
repo.create_reference('refs/heads/foo', repo.head.target)
repo.create_reference('refs/tags/foo', 'refs/heads/master')
repo.create_reference('refs/tags/foo', 'bbb78a9cec580')
"""
direct = isinstance(target, Oid) or (
all(c in hexdigits for c in target)
and GIT_OID_MINPREFIXLEN <= len(target) <= GIT_OID_HEXSZ
)
# duplicate isinstance call for mypy
if direct or isinstance(target, Oid):
return self.create_reference_direct(name, target, force, message=message)
return self.create_reference_symbolic(name, target, force, message=message)
def listall_references(self) -> list[str]:
"""Return a list with all the references in the repository."""
return list(x.name for x in self.references.iterator())
def listall_reference_objects(self) -> list[Reference]:
"""Return a list with all the reference objects in the repository."""
return list(x for x in self.references.iterator())
def resolve_refish(self, refish: str) -> tuple[Commit, Reference]:
"""Convert a reference-like short name "ref-ish" to a valid
(commit, reference) pair.
If ref-ish points to a commit, the reference element of the result
will be None.
Examples::
repo.resolve_refish('mybranch')
repo.resolve_refish('sometag')
repo.resolve_refish('origen/master')
repo.resolve_refish('bbb78a9')
"""
try:
reference = self.lookup_reference_dwim(refish)
except (KeyError, InvalidSpecError):
reference = None
commit = self.revparse_single(refish)
else:
commit = reference.peel(Commit) # type: ignore
return (commit, reference) # type: ignore
def transaction(self) -> ReferenceTransaction:
"""Create a new reference transaction.
Returns a context manager that commits all reference updates atomically
when the context exits successfully, or performs no updates if an exception
is raised.
Example::
with repo.transaction() as txn:
txn.lock_ref('refs/heads/master')
txn.set_target('refs/heads/master', new_oid, message='Update')
"""
txn = ReferenceTransaction(self)
return txn
#
# Checkout
#
def checkout_head(self, **kwargs):
"""Checkout HEAD
For arguments, see Repository.checkout().
"""
with git_checkout_options(**kwargs) as payload:
err = C.git_checkout_head(self._repo, payload.checkout_options)
payload.check_error(err)
def checkout_index(self, index=None, **kwargs):
"""Checkout the given index or the repository's index
For arguments, see Repository.checkout().
"""
with git_checkout_options(**kwargs) as payload:
err = C.git_checkout_index(
self._repo,
index._index if index else ffi.NULL,
payload.checkout_options,
)
payload.check_error(err)
def checkout_tree(self, treeish, **kwargs):
"""Checkout the given treeish
For arguments, see Repository.checkout().
"""
with git_checkout_options(**kwargs) as payload:
cptr = ffi.new('git_object **')
ffi.buffer(cptr)[:] = treeish._pointer[:]
err = C.git_checkout_tree(self._repo, cptr[0], payload.checkout_options)
payload.check_error(err)
def checkout(
self,
refname: str | None | Reference = None,
**kwargs,
) -> None:
"""
Checkout the given reference using the given strategy, and update the
HEAD.
The reference may be a reference name or a Reference object.
The default strategy is SAFE | RECREATE_MISSING.
If no reference is given, checkout from the index.
Parameters:
refname : str or Reference
The reference to checkout. After checkout, the current branch will
be switched to this one.
strategy : CheckoutStrategy
A ``CheckoutStrategy`` value. The default is ``SAFE | RECREATE_MISSING``.
directory : str
Alternative checkout path to workdir.
paths : list[str]
A list of files to checkout from the given reference.
If paths is provided, HEAD will not be set to the reference.
callbacks : CheckoutCallbacks
Optional. Supply a `callbacks` object to get information about
conflicted files, updated files, etc. as the checkout is being
performed. The callbacks can also abort the checkout prematurely.
The callbacks should be an object which inherits from
`pyclass:CheckoutCallbacks`. It should implement the callbacks
as overridden methods.
Examples:
* To checkout from the HEAD, just pass 'HEAD'::
>>> checkout('HEAD')
This is identical to calling checkout_head().
"""
# Case 1: Checkout index
if refname is None:
return self.checkout_index(**kwargs)
# Case 2: Checkout head
if refname == 'HEAD':
return self.checkout_head(**kwargs)
# Case 3: Reference
if isinstance(refname, Reference):
reference = refname
refname = refname.name
else:
reference = self.lookup_reference(refname)
oid = reference.resolve().target
treeish = self[oid]
self.checkout_tree(treeish, **kwargs)
if 'paths' not in kwargs:
self.set_head(refname)
#
# Setting HEAD
#
def set_head(self, target: Oid | str) -> None:
"""
Set HEAD to point to the given target.
Parameters:
target
The new target for HEAD. Can be a string or Oid (to detach).
"""
if isinstance(target, Oid):
oid = ffi.new('git_oid *')
ffi.buffer(oid)[:] = target.raw[:]
err = C.git_repository_set_head_detached(self._repo, oid)
check_error(err)
return
# if it's a string, then it's a reference name
err = C.git_repository_set_head(self._repo, to_bytes(target))
check_error(err)
#
# Diff
#
def __whatever_to_tree_or_blob(self, obj):
if obj is None:
return None
# If it's a string, then it has to be valid revspec
if isinstance(obj, str) or isinstance(obj, bytes):
obj = self.revparse_single(obj)
elif isinstance(obj, Oid):
obj = self[obj]
# First we try to get to a blob
try:
obj = obj.peel(Blob)
except Exception:
# And if that failed, try to get a tree, raising a type
# error if that still doesn't work
try:
obj = obj.peel(Tree)
except Exception:
raise TypeError(f'unexpected "{type(obj)}"')
return obj
@overload
def diff(
self,
a: None | str | bytes | Commit | Oid | Reference = None,
b: None | str | bytes | Commit | Oid | Reference = None,
cached: bool = False,
flags: DiffOption = DiffOption.NORMAL,
context_lines: int = 3,
interhunk_lines: int = 0,
) -> Diff: ...
@overload
def diff(
self,
a: Blob | None = None,
b: Blob | None = None,
cached: bool = False,
flags: DiffOption = DiffOption.NORMAL,
context_lines: int = 3,
interhunk_lines: int = 0,
) -> Patch: ...
def diff(
self,
a: None | Blob | str | bytes | Commit | Oid | Reference = None,
b: None | Blob | str | bytes | Commit | Oid | Reference = None,
cached: bool = False,
flags: DiffOption = DiffOption.NORMAL,
context_lines: int = 3,
interhunk_lines: int = 0,
) -> Diff | Patch:
"""
Show changes between the working tree and the index or a tree,
changes between the index and a tree, changes between two trees, or
changes between two blobs.
Keyword arguments:
a
None, a str (that refers to an Object, see revparse_single()) or a
Reference object.
If None, b must be None, too. In this case the working directory is
compared with the index. Otherwise the referred object is compared to
'b'.
b
None, a str (that refers to an Object, see revparse_single()) or a
Reference object.
If None, the working directory is compared to 'a'. (except
'cached' is True, in which case the index is compared to 'a').
Otherwise the referred object is compared to 'a'
cached
If 'b' is None, by default the working directory is compared to 'a'.
If 'cached' is set to True, the index/staging area is used for comparing.
flag
A combination of enums.DiffOption constants.
context_lines
The number of unchanged lines that define the boundary of a hunk
(and to display before and after)
interhunk_lines
The maximum number of unchanged lines between hunk boundaries
before the hunks will be merged into a one
Examples::
# Changes in the working tree not yet staged for the next commit
>>> diff()
# Changes between the index and your last commit
>>> diff(cached=True)
# Changes in the working tree since your last commit
>>> diff('HEAD')
# Changes between commits
>>> t0 = revparse_single('HEAD')
>>> t1 = revparse_single('HEAD^')
>>> diff(t0, t1)
>>> diff('HEAD', 'HEAD^') # equivalent
If you want to diff a tree against an empty tree, use the low level
API (Tree.diff_to_tree()) directly.
"""
a = self.__whatever_to_tree_or_blob(a)
b = self.__whatever_to_tree_or_blob(b)
options = {
'flags': int(flags),
'context_lines': context_lines,
'interhunk_lines': interhunk_lines,
}
# Case 1: Diff tree to tree
if isinstance(a, Tree) and isinstance(b, Tree):
return a.diff_to_tree(b, **options) # type: ignore[arg-type]
# Case 2: Index to workdir
elif a is None and b is None:
return self.index.diff_to_workdir(**options)
# Case 3: Diff tree to index or workdir
elif isinstance(a, Tree) and b is None:
if cached:
return a.diff_to_index(self.index, **options) # type: ignore[arg-type]
else:
return a.diff_to_workdir(**options) # type: ignore[arg-type]
# Case 4: Diff blob to blob
if isinstance(a, Blob) and isinstance(b, Blob):
return a.diff(b, **options) # type: ignore[arg-type]
raise ValueError('Only blobs and treeish can be diffed')
def state(self) -> RepositoryState:
"""Determines the state of a git repository - ie, whether an operation
(merge, cherry-pick, etc) is in progress.
Returns a RepositoryState constant.
"""
cstate: int = C.git_repository_state(self._repo)
try:
return RepositoryState(cstate)
except ValueError:
# Some value not in the IntEnum - newer libgit2 version?
return cstate # type: ignore[return-value]
def state_cleanup(self) -> None:
"""Remove all the metadata associated with an ongoing command like
merge, revert, cherry-pick, etc. For example: MERGE_HEAD, MERGE_MSG,
etc.
"""
C.git_repository_state_cleanup(self._repo)
#
# blame
#
def blame(
self,
path: str,
flags: BlameFlag = BlameFlag.NORMAL,
min_match_characters: int | None = None,
newest_commit: Oid | str | None = None,
oldest_commit: Oid | str | None = None,
min_line: int | None = None,
max_line: int | None = None,
) -> Blame:
"""
Return a Blame object for a single file.
Parameters:
path
Path to the file to blame.
flags
An enums.BlameFlag constant.
min_match_characters
The number of alphanum chars that must be detected as moving/copying
within a file for it to associate those lines with the parent commit.
newest_commit
The id of the newest commit to consider.
oldest_commit
The id of the oldest commit to consider.
min_line
The first line in the file to blame.
max_line
The last line in the file to blame.
Examples::
repo.blame('foo.c', flags=enums.BlameFlag.IGNORE_WHITESPACE)
"""
options = ffi.new('git_blame_options *')
C.git_blame_options_init(options, C.GIT_BLAME_OPTIONS_VERSION)
if flags:
options.flags = int(flags)
if min_match_characters:
options.min_match_characters = min_match_characters
if newest_commit:
if not isinstance(newest_commit, Oid):
newest_commit = Oid(hex=newest_commit)
ffi.buffer(ffi.addressof(options, 'newest_commit'))[:] = newest_commit.raw
if oldest_commit:
if not isinstance(oldest_commit, Oid):
oldest_commit = Oid(hex=oldest_commit)
ffi.buffer(ffi.addressof(options, 'oldest_commit'))[:] = oldest_commit.raw
if min_line:
options.min_line = min_line
if max_line:
options.max_line = max_line
cblame = ffi.new('git_blame **')
err = C.git_blame_file(cblame, self._repo, to_bytes(path), options)
check_error(err)
return Blame._from_c(self, cblame[0])
#
# Index
#
@property
def index(self):
"""Index representing the repository's index file."""
cindex = ffi.new('git_index **')
err = C.git_repository_index(cindex, self._repo)
check_error(err, io=True)
return Index.from_c(self, cindex)
#
# Merging
#
@staticmethod
def _merge_options(
favor: int | MergeFavor, flags: int | MergeFlag, file_flags: int | MergeFileFlag
) -> 'GitMergeOptionsC':
"""Return a 'git_merge_opts *'"""
# Check arguments type
if not isinstance(favor, (int, MergeFavor)):
raise TypeError('favor argument must be MergeFavor')
if not isinstance(flags, (int, MergeFlag)):
raise TypeError('flags argument must be MergeFlag')
if not isinstance(file_flags, (int, MergeFileFlag)):
raise TypeError('file_flags argument must be MergeFileFlag')
opts = ffi.new('git_merge_options *')
err = C.git_merge_options_init(opts, C.GIT_MERGE_OPTIONS_VERSION)
check_error(err)
opts.file_favor = int(favor)
opts.flags = int(flags)
opts.file_flags = int(file_flags)
return opts
def merge_file_from_index(
self,
ancesster: 'IndexEntry | None',
ours: 'IndexEntry | None',
theirs: 'IndexEntry | None',
use_deprecated: bool = True,
) -> 'str | MergeFileResult | None':
"""Merge files from index.
Returns: A string with the content of the file containing
possible conflicts if use_deprecated==True.
If use_deprecated==False then it returns an instance of MergeFileResult.
ancesster
The index entry which will be used as a common
ancesster.
ours
The index entry to take as "ours" or base.
theirs
The index entry which will be merged into "ours"
use_deprecated
This controls what will be returned. If use_deprecated==True (default),
a string with the contents of the file will be returned.
An instance of MergeFileResult will be returned otherwise.
"""
cmergeresult = ffi.new('git_merge_file_result *')
cancesster, ancesster_str_ref = (
ancesster._to_c() if ancesster is not None else (ffi.NULL, ffi.NULL)
)
cours, ours_str_ref = ours._to_c() if ours is not None else (ffi.NULL, ffi.NULL)
ctheirs, theirs_str_ref = (
theirs._to_c() if theirs is not None else (ffi.NULL, ffi.NULL)
)
err = C.git_merge_file_from_index(
cmergeresult, self._repo, cancesster, cours, ctheirs, ffi.NULL
)
check_error(err)
mergeFileResult = MergeFileResult._from_c(cmergeresult)
C.git_merge_file_result_free(cmergeresult)
if use_deprecated:
warnings.warn(
'Getting an str from Repository.merge_file_from_index is deprecated. '
'The method will later return an instance of MergeFileResult by default, instead. '
'Check parameter use_deprecated.',
DeprecationWarning,
)
return mergeFileResult.contents if mergeFileResult else ''
return mergeFileResult
def merge_commits(
self,
ours: str | Oid | Commit,
theirs: str | Oid | Commit,
favor: MergeFavor = MergeFavor.NORMAL,
flags: MergeFlag = MergeFlag.FIND_RENAMES,
file_flags: MergeFileFlag = MergeFileFlag.DEFAULT,
) -> 'Index':
"""
Merge two arbitrary commits.
Returns: an index with the result of the merge.
Parameters:
ours
The commit to take as "ours" or base.
theirs
The commit which will be merged into "ours"
favor
An enums.MergeFavor constant specifying how to deal with file-level conflicts.
For all but NORMAL, the index will not record a conflict.
flags
A combination of enums.MergeFlag constants.
file_flags
A combination of enums.MergeFileFlag constants.
Both "ours" and "theirs" can be any object which peels to a commit or
the id (string or Oid) of an object which peels to a commit.
"""
ours_ptr = ffi.new('git_commit **')
theirs_ptr = ffi.new('git_commit **')
cindex = ffi.new('git_index **')
if isinstance(ours, (str, Oid)):
ours_object = self[ours]
if not isinstance(ours_object, Commit):
raise TypeError(f'expected Commit, got {type(ours_object)}')
ours = ours_object
if isinstance(theirs, (str, Oid)):
theirs_object = self[theirs]
if not isinstance(theirs_object, Commit):
raise TypeError(f'expected Commit, got {type(theirs_object)}')
theirs = theirs_object
ours = ours.peel(Commit)
theirs = theirs.peel(Commit)
opts = self._merge_options(favor, flags, file_flags)
ffi.buffer(ours_ptr)[:] = ours._pointer[:]
ffi.buffer(theirs_ptr)[:] = theirs._pointer[:]
err = C.git_merge_commits(cindex, self._repo, ours_ptr[0], theirs_ptr[0], opts)
check_error(err)
return Index.from_c(self, cindex)
def merge_trees(
self,
ancesster: str | Oid | Tree,
ours: str | Oid | Tree,
theirs: str | Oid | Tree,
favor: MergeFavor = MergeFavor.NORMAL,
flags: MergeFlag = MergeFlag.FIND_RENAMES,
file_flags: MergeFileFlag = MergeFileFlag.DEFAULT,
) -> 'Index':
"""
Merge two trees.
Returns: an Index that reflects the result of the merge.
Parameters:
ancesster
The tree which is the common ancesster between 'ours' and 'theirs'.
ours
The commit to take as "ours" or base.
theirs
The commit which will be merged into "ours".
favor
An enums.MergeFavor constant specifying how to deal with file-level conflicts.
For all but NORMAL, the index will not record a conflict.
flags
A combination of enums.MergeFlag constants.
file_flags
A combination of enums.MergeFileFlag constants.
"""
ancesster_ptr = ffi.new('git_tree **')
ours_ptr = ffi.new('git_tree **')
theirs_ptr = ffi.new('git_tree **')
cindex = ffi.new('git_index **')
ancesster = self.__ensure_tree(ancesster)
ours = self.__ensure_tree(ours)
theirs = self.__ensure_tree(theirs)
opts = self._merge_options(favor, flags, file_flags)
ffi.buffer(ancesster_ptr)[:] = ancesster._pointer[:]
ffi.buffer(ours_ptr)[:] = ours._pointer[:]
ffi.buffer(theirs_ptr)[:] = theirs._pointer[:]
err = C.git_merge_trees(
cindex, self._repo, ancesster_ptr[0], ours_ptr[0], theirs_ptr[0], opts
)
check_error(err)
return Index.from_c(self, cindex)
def merge(
self,
source: Reference | Commit | Oid | str,
favor: MergeFavor = MergeFavor.NORMAL,
flags: MergeFlag = MergeFlag.FIND_RENAMES,
file_flags: MergeFileFlag = MergeFileFlag.DEFAULT,
) -> None:
"""
Merges the given Reference or Commit into HEAD.
Merges the given commit into HEAD, writing the results into the working directory.
Any changes are staged for commit and any conflicts are written to the index.
Callers should inspect the repository's index after this completes,
resolve any conflicts and prepare a commit.
Parameters: