/
repository.py
1552 lines (1262 loc) · 55.4 KB
/
repository.py
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
# -*- coding: utf-8 -*-
#
# Copyright 2018-2022- Swiss Data Science Center (SDSC)
# A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and
# Eidgenössische Technische Hochschule Zürich (ETHZ).
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""An abstraction layer for the underlying VCS."""
import configparser
import math
import os
import subprocess
import tempfile
from collections import defaultdict
from datetime import datetime
from functools import lru_cache
from itertools import zip_longest
from pathlib import Path
from typing import (
Any,
BinaryIO,
Callable,
Dict,
Generator,
List,
NamedTuple,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
cast,
)
import git
from renku.core import errors
from renku.core.util.os import delete_file, get_absolute_path
NULL_TREE = git.NULL_TREE
_MARKER = object()
def git_unicode_unescape(s: Optional[str], encoding: str = "utf-8") -> str:
"""Undoes git/GitPython unicode encoding."""
if s is None:
return ""
if s.startswith('"'):
return s.strip('"').encode("latin1").decode("unicode-escape").encode("latin1").decode(encoding)
return s
def split_paths(*paths):
"""Return a generator with split list of paths."""
argument_batch_size = 100
batch_count = math.ceil(len(paths) / argument_batch_size)
batch_count = max(batch_count, 1)
for index in range(batch_count):
yield paths[index * argument_batch_size : (index + 1) * argument_batch_size]
class BaseRepository:
"""Abstract Base repository."""
def __init__(self, path: Union[Path, str] = ".", repository: Optional[git.Repo] = None):
super().__init__()
self._repository: Optional[git.Repo] = repository
self._path = Path(path).resolve()
def __repr__(self) -> str:
return f"<{self.__class__.__name__} {self.path}>"
@property
def path(self) -> Path:
"""Absolute path to the repository's root."""
return self._path
@property
def head(self) -> "SymbolicReference":
"""HEAD of the repository."""
if self._repository is None:
raise errors.ParameterError("Repository not set.")
return SymbolicReference(self._repository, "HEAD")
@property
def active_branch(self) -> Optional["Branch"]:
"""Return current checked out branch."""
if self.head.reference is None:
return None
if self._repository is None:
raise errors.ParameterError("Repository not set.")
return Branch(self._repository, self.head.reference.path)
@property
def branches(self) -> "BranchManager":
"""Return all branches."""
if self._repository is None:
raise errors.ParameterError("Repository not set.")
return BranchManager(self._repository)
@property
def remotes(self) -> "RemoteManager":
"""Return all remotes."""
if self._repository is None:
raise errors.ParameterError("Repository not set.")
return RemoteManager(self._repository)
@property # type: ignore
@lru_cache()
def submodules(self) -> "SubmoduleManager":
"""Return a list of submodules."""
if self._repository is None:
raise errors.ParameterError("Repository not set.")
return SubmoduleManager(self._repository)
@property
def staged_changes(self) -> List["Diff"]:
"""Return a list of staged changes.
NOTE: This can be implemented by ``git diff --cached --name-status -z``.
"""
if self._repository is None:
raise errors.ParameterError("Repository not set.")
try:
diff = self._repository.index.diff("HEAD", ignore_submodules=True)
return [Diff.from_diff(d) for d in diff]
except (git.BadName, git.BadObject, git.GitError) as e: # type: ignore
raise errors.GitError("Cannot get staged changes") from e
@property
def tags(self) -> "TagManager":
"""Return all available tags."""
if self._repository is None:
raise errors.ParameterError("Repository not set.")
return TagManager(self._repository)
@property
def unstaged_changes(self) -> List["Diff"]:
"""Return a list of changes that are not staged."""
if self._repository is None:
raise errors.ParameterError("Repository not set.")
try:
diff = self._repository.index.diff(None, ignore_submodules=True)
return [Diff.from_diff(d) for d in diff]
except (git.BadName, git.BadObject, git.GitError) as e: # type: ignore
raise errors.GitError("Cannot get modified changes") from e
@property
def unmerged_blobs(self) -> Dict[str, List[Tuple[int, "Object"]]]:
"""Return a map of path to stage and blob for unmerged blobs in the current index."""
if self._repository is None:
raise errors.ParameterError("Repository not set.")
return {
str(path): [(e[0], Object.from_object(e[1])) for e in values]
for path, values in self._repository.index.unmerged_blobs().items()
}
@property
def untracked_files(self) -> List[str]:
"""Return the list of untracked files."""
if self._repository is None:
raise errors.ParameterError("Repository not set.")
return self._repository.untracked_files
@property
def files(self) -> List[str]:
"""Return a list of all files in the current version of the repository."""
if self._repository is None:
raise errors.ParameterError("Repository not set.")
return [str(e[0]) for e in self._repository.index.entries]
def is_valid(self) -> bool:
"""Return True if a valid repository exists."""
return self._repository is not None
def add(self, *paths: Union[Path, str], force: bool = False, all: bool = False) -> None:
"""Add a list of files to be committed to the VCS."""
if all:
assert len(paths) == 0, "Cannot pass both ``all`` and ``paths``."
self.run_git_command("add", all=True, force=force)
else:
for batch in split_paths(*paths):
self.run_git_command("add", *batch, force=force)
def commit(
self,
message: str,
*,
amend: bool = False,
author: "Actor" = None,
committer: "Actor" = None,
no_verify: bool = False,
no_edit: bool = False,
) -> "Commit":
"""Commit added files to the VCS."""
if self._repository is None:
raise errors.ParameterError("Repository not set.")
env = {}
if author:
env.update({"GIT_AUTHOR_NAME": author.name, "GIT_AUTHOR_EMAIL": author.email})
if committer:
env.update({"GIT_COMMITTER_NAME": committer.name, "GIT_COMMITTER_EMAIL": committer.email})
self.run_git_command("commit", message=message, no_verify=no_verify, amend=amend, no_edit=no_edit, env=env)
return Commit.from_commit(self._repository, self._repository.head.commit)
def checkout(self, reference: Union["Branch", "Tag", str]):
"""Check-out a specific reference."""
self.run_git_command("checkout", reference)
def clean(self, paths: List[Union[Path, str]] = None):
"""Remove untracked files."""
self.run_git_command("clean", "-xdff", paths)
def fetch(
self,
remote: Union["Remote", str] = None,
refspec: Union["Branch", str] = None,
all: bool = False,
tags: bool = False,
unshallow: bool = False,
depth: int = None,
):
"""Update a remote branches."""
if all:
assert remote is None and refspec is None, "Cannot fetch all while a reference is passed"
self.run_git_command(
"fetch", _to_string(remote), _to_string(refspec), all=all, unshallow=unshallow, depth=depth, tags=tags
)
def contains(self, path: Union[Path, str]) -> bool:
"""Return True if path is tracked in the repository."""
try:
self.run_git_command("ls-files", "--error-unmatch", str(path))
except errors.GitCommandError:
return False
else:
return True
def move(self, *sources: Union[Path, str], destination: Union[Path, str], force: bool = False):
"""Move source files to the destination."""
self.run_git_command("mv", *sources, destination, force=force)
def pull(self, remote: Union["Remote", str] = None, refspec: Union["Branch", str] = None):
"""Update changes from remotes."""
self.run_git_command("pull", _to_string(remote), _to_string(refspec))
def push(
self,
remote: Union["Remote", str] = None,
refspec: Union["Branch", str] = None,
*,
no_verify: bool = False,
set_upstream: bool = False,
delete: bool = False,
force: bool = False,
):
"""Push local changes to a remote repository."""
self.run_git_command(
"push",
_to_string(remote),
_to_string(refspec),
no_verify=no_verify,
set_upstream=set_upstream,
delete=delete,
force=force,
)
def remove(
self,
*paths: Union[Path, str],
index: bool = False,
not_exists_ok: bool = False,
recursive: bool = False,
force: bool = False,
):
"""Remove paths from repository or index."""
self.run_git_command("rm", "--", *paths, cached=index, ignore_unmatch=not_exists_ok, r=recursive, force=force)
def reset(self, reference: Union["Branch", "Commit", "Reference", str] = None, hard: bool = False):
"""Reset a git repository to a given reference."""
self.run_git_command("reset", _to_string(reference), hard=hard)
def status(self) -> str:
"""Return status of a repository."""
return self.run_git_command("status")
def is_dirty(self, untracked_files: bool = False) -> bool:
"""Return True if the repository has modified or untracked files ignoring submodules."""
if self._repository is None:
raise errors.ParameterError("Repository not set.")
return self._repository.is_dirty(untracked_files=untracked_files, submodules=False)
def run_git_command(self, command: str, *args, **kwargs) -> str:
"""Run a git command in this repository."""
if self._repository is None:
raise errors.ParameterError("Repository not set.")
return _run_git_command(self._repository, command, *args, **kwargs)
def get_attributes(self, *paths: Union[Path, str]) -> Dict[str, Dict[str, str]]:
"""Return a map from paths to its attributes.
NOTE: Dict keys are the same relative or absolute path as inputs.
"""
if len(paths) == 0:
return {}
attributes: Dict[str, Dict[str, str]] = defaultdict(dict)
for batch in split_paths(*paths):
data = self.run_git_command("check-attr", "-z", "--all", "--", *batch)
for path, name, value in zip_longest(*[iter(data.strip("\0").split("\0"))] * 3):
if path:
attributes[path][name] = value
return attributes
def get_previous_commit(
self,
path: Union[Path, str],
revision: Optional[Union["Commit", str]] = None,
first: bool = False,
full_history: bool = True,
submodule: bool = False,
) -> Optional["Commit"]:
"""Return a previous commit for a given path starting from ``revision``."""
revision = revision or "HEAD"
assert isinstance(revision, (Commit, str)), f"'revision' must be Commit/str not '{type(revision)}'"
commit = _find_previous_commit_helper(
repository=self,
path=path,
revision=str(revision),
first=first,
full_history=full_history,
submodules=submodule,
)
if not commit:
raise errors.GitCommitNotFoundError(f"Cannot find previous commit for '{path}' from '{revision}'")
return commit
def iterate_commits(
self,
*paths: Union[Path, str],
revision: Optional[str] = None,
reverse: bool = False,
full_history: bool = False,
max_count: int = -1,
) -> Generator["Commit", None, None]:
"""Return a list of commits."""
if self._repository is None:
raise errors.ParameterError("Repository not set.")
revision = revision or "HEAD"
assert isinstance(revision, str), f"'revision' must be string not '{type(revision)}'"
try:
for c in self._repository.iter_commits(
rev=revision, paths=paths, reverse=reverse, full_history=full_history, max_count=max_count
):
yield Commit.from_commit(self._repository, c)
except git.GitCommandError:
return
def get_commit(self, revision: str) -> "Commit":
"""Return Commit with the provided sha."""
if self._repository is None:
raise errors.ParameterError("Repository not set.")
try:
commit = self._repository.commit(revision)
except (ValueError, IndexError, git.BadName, git.BadObject) as e: # type: ignore
raise errors.GitCommitNotFoundError(f"Cannot find a commit with revision '{revision}'") from e
else:
wrapped_commit = Commit.from_commit(self._repository, commit)
if not wrapped_commit:
raise errors.GitCommitNotFoundError(f"Cannot find a commit with revision '{revision}'")
return wrapped_commit
def get_ignored_paths(self, *paths: Union[Path, str]) -> List[str]:
"""Return ignored paths matching ``.gitignore`` file."""
ignored = []
for batch in split_paths(*paths):
try:
ignored.extend(self.run_git_command("check-ignore", *batch).split(os.linesep))
except errors.GitCommandError:
pass
return ignored
def get_content(
self,
path: Union[Path, str],
*,
revision: Optional[Union["Reference", str]] = None,
checksum: Optional[str] = None,
binary: bool = False,
) -> Union[bytes, str]:
"""Get content of a file in a given revision as text or binary."""
output = self.copy_content_to_file(path=path, checksum=checksum, revision=revision)
output_path = Path(output)
content: Union[bytes, str] = output_path.read_bytes() if binary else output_path.read_text()
delete_file(output)
return content
def get_raw_content(
self, *, path: Union[Path, str], revision: Optional[str] = None, checksum: Optional[str] = None
) -> str:
"""Get raw content of a file in a given revision as text without applying any filter on it."""
output = self.copy_content_to_file(path=path, checksum=checksum, revision=revision, apply_filters=False)
return Path(output).read_text()
def copy_content_to_file(
self,
path: Union[Path, str],
revision: Optional[Union["Reference", str]] = None,
checksum: Optional[str] = None,
output_file: Optional[BinaryIO] = None,
apply_filters: bool = True,
) -> str:
"""Get content of an object using its checksum, write it to a file, and return the file's path."""
absolute_path = get_absolute_path(path, self.path)
def get_content_helper(output_file) -> bool:
command = ["git", "cat-file"]
if checksum is None:
assert revision is not None, "Either ``revision`` or ``checksum`` must be passed."
relative_path = os.path.relpath(absolute_path, self.path)
prefix = "--filters" if apply_filters else "-p"
object = [prefix, f"{revision}:{relative_path}"]
else:
assert revision is None, "Cannot pass both ``revision`` and ``checksum``."
object = ["--filters", "--path", absolute_path] if apply_filters else ["-p"]
object.append(checksum)
command.extend(object)
try:
subprocess.run(
command,
check=True,
stdout=output_file,
stderr=subprocess.DEVNULL,
cwd=self.path,
)
except subprocess.CalledProcessError:
return False
else:
# NOTE: No need to check the exit code since ``check=True`` takes care of non-zero exit codes
return True
def get_content_from_submodules():
for submodule in self.submodules:
try:
Path(absolute_path).relative_to(submodule.path)
except ValueError:
continue
else:
return submodule.copy_content_to_file(
path=absolute_path, checksum=checksum, revision=revision, apply_filters=apply_filters
)
if output_file is None:
with tempfile.NamedTemporaryFile(mode="w+b", delete=False) as temp_output_file:
if get_content_helper(output_file=temp_output_file):
return temp_output_file.name
else:
if get_content_helper(output_file):
return output_file.name
from_submodules = get_content_from_submodules()
if from_submodules:
return from_submodules
# TODO: Return FileNotFound
raise errors.ExportError(f"File not found in the repository: '{revision}/{checksum}:{path}'")
def get_object_hashes(
self, paths: List[Union[Path, str]], revision: Optional[str] = None
) -> Dict[Union[Path, str], Optional[str]]:
"""Return git hash of an object in a Repo or its submodule.
NOTE: path must be relative to the repo's root regardless if this function is called from a subdirectory or not.
"""
def _get_uncommitted_file_hashes(paths: Set[Union[Path, str]]) -> Dict[str, str]:
"""Get hashes for all modified/uncommitted/staged files."""
staged_files = [d.a_path for d in self.staged_changes] if self.head.is_valid() else []
modified_files = [item.b_path for item in self.unstaged_changes if not item.deleted]
dirty_files = {os.path.join(self.path, p) for p in self.untracked_files + modified_files + staged_files}
dirty_files = {p for p in dirty_files if p in paths and not os.path.isdir(p)}
dirty_files_list = list(dirty_files)
dirty_files_hashes = Repository.hash_objects(cast(List[Union[Path, str]], dirty_files_list))
return dict(zip(dirty_files_list, dirty_files_hashes))
def _get_hashes_from_revision(
paths: Set[Union[Path, str]], revision: str, repository: BaseRepository
) -> Dict[Union[Path, str], Optional[str]]:
"""Get hashes for paths in a specific revision."""
existing_paths = repository.get_existing_paths_in_revision(paths, revision=revision)
result: Dict[Union[Path, str], Optional[str]] = {}
for batch in split_paths(*existing_paths):
hashes = self.run_git_command("rev-parse", *[f"{revision}:{relative_path}" for relative_path in batch])
result.update(zip(batch, hashes.splitlines()))
for path in paths:
if path not in result:
result[path] = None
return result
path_mapping = {get_absolute_path(path, self.path): path for path in paths}
absolute_paths = set(path_mapping.keys())
hashes: Dict[Union[Path, str], Optional[str]] = {}
# NOTE: If revision is not specified, we use hash-object to hash the (possibly) modified object
if not revision:
uncommitted_hashes = _get_uncommitted_file_hashes(cast(Set[Union[Path, str]], absolute_paths))
hashes.update({path_mapping.get(p, p): h for p, h in uncommitted_hashes.items()})
if len(hashes) == len(absolute_paths):
# NOTE: there were only uncommitted files
return hashes
revision = "HEAD"
absolute_paths = {p for p in absolute_paths if p not in uncommitted_hashes}
submodule_paths = defaultdict(list)
main_repo_paths = []
if len(self.submodules) > 0: # type: ignore
# NOTE: filter paths belonging to main repo from those belonging to submodules
for absolute_path in absolute_paths:
found = False
for submodule in self.submodules: # type: ignore
try:
Path(absolute_path).relative_to(submodule.path)
submodule_paths[submodule].append(absolute_path)
found = True
break
except ValueError:
continue
if not found:
main_repo_paths.append(os.path.relpath(absolute_path, start=self.path))
else:
main_repo_paths = list(map(lambda p: os.path.relpath(p, start=self.path), absolute_paths))
if main_repo_paths:
# NOTE: Get hashes for paths in the main repository
revision_hashes = _get_hashes_from_revision(set(main_repo_paths), revision, self)
hashes.update({path_mapping.get(get_absolute_path(p, self.path), p): h for p, h in revision_hashes.items()})
if not submodule_paths:
return hashes
# NOTE: Get hashes for paths in submodules
for submodule, submodule_path in submodule_paths.items():
submodule_hashes = submodule.get_object_hashes(paths=submodule_path, revision="HEAD")
hashes.update(
{path_mapping.get(get_absolute_path(p, self.path), p): h for p, h in submodule_hashes.items()}
)
return hashes
def get_object_hash(self, path: Union[Path, str], revision: Optional[Union["Commit", str]] = None) -> Optional[str]:
"""Return git hash of an object in a Repo or its submodule.
NOTE: path must be relative to the repo's root regardless if this function is called from a subdirectory or not.
"""
absolute_path = get_absolute_path(path, self.path)
# NOTE: If revision is not specified, we use hash-object to hash the (possibly) modified object
if not revision:
try:
return Repository.hash_object(absolute_path)
except errors.GitCommandError:
# NOTE: If object does not exist anymore, hash-object doesn't work, fall back to rev-parse
revision = "HEAD"
def get_staged_directory_hash() -> Optional[str]:
if not os.path.isdir(absolute_path):
return None
stashed_revision = self.run_git_command("stash", "create")
if not stashed_revision:
return None
try:
return self.run_git_command("rev-parse", f"{stashed_revision}:{relative_path}")
except errors.GitCommandError:
return None
def get_object_hash_from_submodules() -> Optional[str]:
for submodule in self.submodules: # type: ignore
try:
Path(absolute_path).relative_to(submodule.path)
except ValueError:
continue
else:
return submodule.get_object_hash(path=absolute_path, revision="HEAD")
return None
relative_path = os.path.relpath(absolute_path, start=self.path)
try:
return self.run_git_command("rev-parse", f"{revision}:{relative_path}")
except errors.GitCommandError:
# NOTE: The file can be in a submodule or it can be a directory which is staged but not committed yet.
# It's also possible that the file was not there when the command ran but was there when workflows were
# migrated (this can happen only for Usage); the project might be broken too.
staged_directory_hash = get_staged_directory_hash()
if staged_directory_hash:
return staged_directory_hash
return get_object_hash_from_submodules()
def get_user(self) -> "Actor":
"""Return the local/global git user."""
configuration = self.get_configuration()
return Repository._get_user_from_configuration(configuration)
@staticmethod
def get_global_user() -> "Actor":
"""Return the global git user."""
configuration = Repository.get_global_configuration()
return Repository._get_user_from_configuration(configuration)
@staticmethod
def _get_user_from_configuration(configuration: "Configuration") -> "Actor":
try:
name = configuration.get_value("user", "name", None)
email = configuration.get_value("user", "email", None)
except errors.GitConfigurationError: # pragma: no cover
raise errors.GitConfigurationError(
'The user name and email are not configured. Please use the "git config" command to configure them.\n\n'
'\tgit config --global --add user.name "John Doe"\n'
'\tgit config --global --add user.email "john.doe@example.com"\n'
)
# Check the git configuration.
if not name: # pragma: no cover
raise errors.GitMissingUsername
if not email: # pragma: no cover
raise errors.GitMissingEmail
name = _sanitize_git_config_value(name)
email = _sanitize_git_config_value(email)
return Actor(name=name, email=email)
def get_configuration(self, writable=False, scope: str = None) -> "Configuration":
"""Return git configuration.
NOTE: Scope can be "global" or "local".
"""
return Configuration(repository=self._repository, scope=scope, writable=writable)
@staticmethod
def get_global_configuration(writable: bool = False) -> "Configuration":
"""Return global git configuration."""
return Configuration(repository=None, writable=writable)
def get_existing_paths_in_revision(
self, paths: Union[List[Union[Path, str]], Set[Union[Path, str]]] = None, revision: str = "HEAD"
) -> List[str]:
"""List all paths that exist in a revision."""
try:
if paths:
dirs = []
files = []
for path in paths:
if os.path.isdir(path):
dirs.append(path)
else:
files.append(path)
result = []
if files:
# NOTE: check existing files
for batch in split_paths(*files):
existing_paths = git.Git(working_dir=self.path).ls_tree(*batch, r=revision, name_only=True)
result.extend(existing_paths.splitlines())
if dirs:
# NOTE: check existing dirs
for batch in split_paths(*dirs):
existing_paths = git.Git(working_dir=self.path).ls_tree(
*batch, d=True, r=revision, name_only=True
)
result.extend(existing_paths.splitlines())
return result
else:
existing_files = git.Git().ls_tree(r=revision, name_only=True).splitlines()
existing_dirs = git.Git().ls_tree(r=revision, name_only=True, d=True).splitlines()
return existing_dirs + existing_files
except git.GitCommandError as e:
raise errors.GitCommandError(
message=f"Git command failed: {str(e)}",
command=e.command,
stdout=e.stdout,
stderr=e.stderr,
status=e.status,
) from e
@staticmethod
def hash_objects(paths: List[Union[Path, str]]) -> List[str]:
"""Create a git hash for a list of paths. The paths don't need to be in a repository."""
hashes = []
try:
for batch in split_paths(*paths):
calculated_hashes = git.Git().hash_object(*batch)
hashes.extend(calculated_hashes.splitlines())
return hashes
except git.GitCommandError as e:
raise errors.GitCommandError(
message=f"Git command failed: {str(e)}",
command=e.command,
stdout=e.stdout,
stderr=e.stderr,
status=e.status,
) from e
@staticmethod
def hash_object(path: Union[Path, str]) -> Optional[str]:
"""Create a git hash for a a path. The path doesn't need to be in a repository."""
result = BaseRepository.hash_objects([path])
if result and len(result) > 0:
return result[0]
return None
class Repository(BaseRepository):
"""Abstract Base repository."""
def __init__(
self, path: Union[Path, str] = ".", search_parent_directories: bool = False, repository: git.Repo = None
):
repo = repository or _create_repository(path, search_parent_directories)
super().__init__(path=Path(repo.working_dir).resolve(), repository=repo) # type: ignore
@classmethod
def clone_from(
cls,
url: Union[Path, str],
path: Union[Path, str],
*,
branch: str = None,
recursive: bool = False,
depth: int = None,
progress: Optional[Callable] = None,
no_checkout: bool = False,
env: dict = None,
clone_options: List[str] = None,
) -> "Repository":
"""Clone a remote repository and create an instance."""
try:
repository = git.Repo.clone_from(
url=url,
to_path=path,
branch=branch,
recursive=recursive,
depth=depth,
progress=progress,
no_checkout=no_checkout,
env=env,
multi_options=clone_options,
)
except git.GitCommandError as e:
raise errors.GitCommandError(
message=f"Git command failed: {str(e)}",
command=e.command,
stdout=e.stdout,
stderr=e.stderr,
status=e.status,
) from e
else:
return cls(path=path, repository=repository)
@classmethod
def initialize(cls, path: Union[Path, str], *, bare: bool = False, branch: str = None) -> "Repository":
"""Initialize a git repository."""
try:
Path(path).mkdir(parents=True, exist_ok=True)
repository = git.Repo.init(path=str(path), bare=bare, initial_branch=branch)
except git.GitCommandError as e:
raise errors.GitCommandError(
message=f"Git command failed: {str(e)}",
command=e.command,
stdout=e.stdout,
stderr=e.stderr,
status=e.status,
) from e
except git.GitError as e:
raise errors.GitError(f"Git command failed: {str(e)}") from e
else:
return cls(path=path, repository=repository)
class Submodule(BaseRepository):
"""A git submodule."""
def __init__(self, parent: git.Repo, name: str, path: Union[Path, str], url: str):
super().__init__(path=path, repository=None)
self._parent: git.Repo = parent or _create_repository(path=path, search_parent_directories=True)
self._name: str = name
self._url: str = url
try:
self._repository: git.Repo = _create_repository(path, search_parent_directories=False)
except errors.GitError:
# NOTE: Submodule directory doesn't exist yet, so, we ignore the error
pass
@classmethod
def from_submodule(cls, parent: git.Repo, submodule: git.Submodule) -> "Submodule": # type: ignore
"""Create an instance from a git submodule."""
path = Path(parent.working_dir) / submodule.path # type: ignore
return cls(parent=parent, name=submodule.name, path=path, url=submodule.url)
def __str__(self) -> str:
return self.name
def __repr__(self) -> str:
return f"<Submodule {self.relative_path}>"
@property
def name(self) -> str:
"""Return submodule's name."""
return self._name
@property
def relative_path(self) -> Path:
"""Relative submodule's path to its parent repository."""
return self._path.relative_to(self._parent.working_dir) # type: ignore
@property
def url(self) -> str:
"""Return submodule's url."""
return self._url
class SubmoduleManager:
"""Manage submodules of a Repository."""
def __init__(self, repository: git.Repo):
self._repository = repository
try:
self.update()
except errors.GitError:
# NOTE: Update fails if submodule repo cannot be cloned. Repository still works but submodules are broken.
pass
def __getitem__(self, name: str) -> Submodule:
try:
submodule = self._repository.submodules[name]
except IndexError:
raise errors.GitError(f"Submodule '{name}' not found")
else:
return Submodule.from_submodule(self._repository, submodule)
def __iter__(self):
return (Submodule.from_submodule(self._repository, s) for s in self._repository.submodules)
def __len__(self) -> int:
return len(self._repository.submodules)
def __repr__(self) -> str:
return str(list(self))
def remove(self, submodule: Union[Submodule, str], force: bool = False):
"""Remove an existing submodule."""
name = submodule if isinstance(submodule, str) else submodule.name
try:
submodule = self._repository.submodules[name]
submodule.remove(force=force)
except git.GitError as e:
raise errors.GitError(f"Cannot delete submodule '{submodule}'") from e
def update(self, initialize: bool = True):
"""Update all submodule."""
# NOTE: Git complains if ``--init`` comes before ``update``
args = ("update", "--init") if initialize else ("update",)
_run_git_command(self._repository, "submodule", *args)
class Object(NamedTuple):
"""Represent a git object."""
path: str
type: str
size: int
hexsha: str
@classmethod
def from_object(cls, object: git.Object): # type: ignore
"""Create an instance from a git object."""
return cls(path=object.path, type=object.type, size=object.size, hexsha=object.hexsha)
class Actor(NamedTuple):
"""Author/creator of a commit."""
name: str
email: str
def __eq__(self, other: Any) -> bool:
return self.name == other.name and self.email == other.email
def __hash__(self) -> int:
return hash((self.name, self.email))
class Diff(NamedTuple):
"""A single diff object between two trees."""
# NOTE: In case a rename, a_path and b_path have different values. Make sure to use the correct one.
a_path: str
b_path: str
"""
Possible values:
A = Added
D = Deleted
R = Renamed
M = Modified
T = Changed in the type
"""
change_type: str
@classmethod
def from_diff(cls, diff: git.Diff):
"""Create an instance from a git object."""
a_path = git_unicode_unescape(diff.a_path)
b_path = git_unicode_unescape(diff.b_path)
# NOTE: Make sure a_path or b_path are the same in case of addition or deletion
a_path = a_path or b_path
b_path = b_path or a_path
return cls(a_path=a_path, b_path=b_path, change_type=cast(str, diff.change_type))
@property
def deleted(self) -> bool:
"""True if file was deleted."""
return self.change_type == "D"
@property
def added(self) -> bool:
"""True if file was added."""
return self.change_type == "A"
class Commit:
"""A VCS commit."""
def __init__(self, repository: git.Repo, commit: git.Commit): # type: ignore
self._repository: git.Repo = repository
self._commit: git.Commit = commit # type: ignore
self._hexsha: str = commit.hexsha
self._author: Actor = Actor(name=commit.author.name, email=commit.author.email)
self._committer: Actor = Actor(name=commit.committer.name, email=commit.committer.email)
@classmethod
def from_commit(
cls, repository: git.Repo, commit: Union[git.Commit, git.types.Commit_ish] # type: ignore
) -> "Commit":
"""Create an instance from a git Commit object."""
return Commit(repository, commit)
def __eq__(self, other: Any) -> bool:
return self._hexsha == getattr(other, "_hexsha", _MARKER)