-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrit_lib.py
1448 lines (1198 loc) · 45.2 KB
/
rit_lib.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
from io import DEFAULT_BUFFER_SIZE
import subprocess
import shutil
import argparse
import datetime
import hashlib
import json
import logging
import os
import re
import sys
import time
from dataclasses import asdict, dataclass, field
from typing import Optional
from collections import defaultdict
''' GLOBALS '''
logger = logging.getLogger(__name__)
rit_dir_name = '.rit'
default_branch_name = 'main'
head_ref_name = 'HEAD'
short_hash_index = 7
fg = 30
bg = 40
black, red, green, yellow, blue, magenta, cyan, white = range(8)
''' STRUCTS '''
@dataclass
class RitPaths:
''' a class that represents the various directories used by rit '''
root: str
''' The directory to backup is stored here '''
rit_dir: str
''' All rit information is stored here '''
branches: str
'''
References are stored here. The filename is the ref name or head_ref_name.
head_ref_name lets us know what branch or commit the current working directory
is.
'''
commits: str
''' Commit info is stored here. The filename is commit_id. '''
backups: str
''' Backups are stored here, full and partial. '''
work: str
''' A place to temporarily store files '''
@staticmethod
def build_rit_paths(root: str, init: bool = False):
'''
Given a root rit directory, construct a rit paths object and ensure rit
subdirectories exist. If init is True, the root rit path will be created.
'''
root = os.path.realpath(root)
rit_dir = os.path.join(root, rit_dir_name)
if init:
os.makedirs(rit_dir)
branches = os.path.join(rit_dir, 'branches')
mkdir(branches, exists_ok=True)
commits = os.path.join(rit_dir, 'commits')
mkdir(commits, exists_ok=True)
backups = os.path.join(rit_dir, 'backups')
mkdir(backups, exists_ok=True)
work = os.path.join(rit_dir, 'work')
mkdir(work, exists_ok=True)
return RitPaths(
root = root,
rit_dir = rit_dir,
branches = branches,
commits = commits,
backups = backups,
work = work,
)
@dataclass
class Commit:
''' represents a single commit '''
parent_commit_id: Optional[str]
''' the commit id of parent, if any '''
commit_id: str
''' the current commit's commit id '''
create_time: float
''' the creation time of commit in seconds since posix '''
msg: str
''' the commit msg'''
def __post_init__(self):
check_obj_types(self, dict(
parent_commit_id = optional_t(exact_t(str)),
commit_id = exact_t(str),
create_time = exact_t(float),
msg = exact_t(str),
))
@dataclass
class Branch:
''' represents a branch '''
name: str
''' the branch name '''
commit_id: str
''' the commit id tied to the branch '''
def __post_init__(self):
check_obj_types(self, dict(
name = exact_t(str),
commit_id = exact_t(str),
))
@dataclass
class HeadNode:
'''
The rit directory's current location. This is a branch or a commit. It is
possible for a branch to be an orphan branch and have no commit, yet.
Since commit_id or branch_name must be non None, to have no commit, it must
have a branch. Like git, you cannot have head point to no commit without it
pointing to a branch.
'''
commit_id: Optional[str] = None
''' the current dir is based off of this commit id, if any '''
branch_name: Optional[str] = None
''' the current head is tied to this branch. new commits move the branch. '''
def __post_init__(self):
check_obj_types(self, dict(
commit_id = optional_t(exact_t(str)),
branch_name = optional_t(exact_t(str)),
))
if (self.commit_id is None) == (self.branch_name is None):
raise TypeError(head_ref_name + " must be a branch name or a commit id")
class RitError(Exception):
'''
an error raised by rit
how to render:
error_msg = exc.msg % exc.args
logger.error(exc.msg, *exc.args)
'''
def __init__(self, msg, *args):
super(RitError, self).__init__()
self.msg = msg
self.args = args
@dataclass
class RitResource:
'''
a resource to query the rit directory and cache results
All interactions with the rit directory should go through this object.
Any external changes to the rit directory invalidate's this object's cache and
in that case, _clear should be called. However, no user of this resource
should be calling _clear. Instead this class' api should be extended and that
new method should call _clear.
TODO: ensure all mutations of the rit directory are through this object, e.g.,
tar creation / deletion.
'''
root_rit_dir: str
''' the root rit directory '''
prevent_mutations: bool = False
'''
Set to True to prevent setter functions. Setting this to True makes it safe to
give to consumers of this api. It prevents them from changing the rit dir
directly.
'''
_paths: RitPaths = None
''' cache for paths property '''
_head: HeadNode = None
''' cache for head property '''
_commits: dict[str, Commit] = field(default_factory=dict)
''' cache for get_commit '''
_branches: dict[str, Branch] = field(default_factory=dict)
''' cache for get_branch '''
_branch_name_to_commit_ids: dict[str, str] = None
''' cache for get_branch_name_to_commit_ids '''
_commit_id_to_branch_names: dict[str, list[str]] = None
''' cache for get_commit_id_to_branch_names '''
_branch_names: list[str] = None
''' cache for get_branch_names '''
_commit_ids: list[str] = None
''' cache for get_commit_ids '''
_short_commit_tree: dict[str, list[str]] = None
''' cache for get_commit_tree '''
def __post_init__(self) -> None:
check_obj_types(self, dict(
root_rit_dir = exact_t(str),
))
def initialize(self):
'''
creates the rit directory
if already initialized, raise RitError
'''
try:
paths = RitPaths.build_rit_paths(self.root_rit_dir, init=True)
logger.info("Successfully created rit directory: %s", paths.rit_dir)
except FileExistsError:
raise RitError("The rit directory already exists: %s", self.paths.rit_dir)
def _clear(self):
''' If the rit directory is modified, then the cache must be cleared '''
cleared_rit = RitResource(self.root_rit_dir)
self._head = cleared_rit._head
self._commits = cleared_rit._commits
self._branches = cleared_rit._branches
self._branch_name_to_commit_ids = cleared_rit._branch_name_to_commit_ids
self._commit_id_to_branch_names = cleared_rit._commit_id_to_branch_names
self._branch_names = cleared_rit._branch_names
self._commit_ids = cleared_rit._commit_ids
self._short_commit_tree = cleared_rit._short_commit_tree
''' SET '''
def add_commit(self, commit: Commit):
''' add the commit to the rit dir '''
if self.prevent_mutations:
raise RitError("Doing this would mutate the rit directory, and that is disabled for this RitResource")
self._write_commit(commit)
self._clear()
def prune(self):
leaf_commits = set()
if self.head.commit_id is not None:
leaf_commits.add(self.head.commit_id)
for branch_name in self.get_branch_names():
leaf_commits.add(self.get_branch(branch_name, ensure=True).commit_id)
refed_commits = set(leaf_commits)
for leaf_commit in leaf_commits:
while True:
commit = self.get_commit(leaf_commit, ensure=True)
if commit.parent_commit_id is None or commit.parent_commit_id in refed_commits:
break
refed_commits.add(commit.parent_commit_id)
leaf_commit = commit.parent_commit_id
removed_commit_ids = []
for commit_id in self.get_commit_ids():
if commit_id in refed_commits:
continue
self._delete_commit(commit_id)
removed_commit_ids.append(commit_id)
return removed_commit_ids
def set_branch(self, branch: Branch):
''' add the branch to the rit dir '''
if self.prevent_mutations:
raise RitError("Doing this would mutate the rit directory, and that is disabled for this RitResource")
self._write_branch(branch)
self._clear()
def set_head(self, head: HeadNode):
''' set the new head point '''
if self.prevent_mutations:
raise RitError("Doing this would mutate the rit directory, and that is disabled for this RitResource")
self._write_head(head)
self._clear()
''' GET '''
@property
def paths(self):
''' returns a RitPaths object for this rit directory '''
if self._paths is None:
self._paths = self._read_paths()
return self._paths
@property
def head(self):
''' returns the HeadNode object for this rit directory '''
if self._head is None:
self._head = self._read_head()
return self._head
def get_head_commit_id(self):
''' get the commit id of the head, None if there isn't one '''
head = self.head
if head.commit_id is not None:
return head.commit_id
else:
branch = self.get_branch(head.branch_name)
if branch is not None:
return branch.commit_id
else:
return None
def get_commit_ids(self):
''' get all commit ids '''
if self._commit_ids is None:
self._commit_ids = self._read_commit_ids()
return self._commit_ids
def get_commit(self, commit_id: str, *, ensure=False):
'''
get commit object of a commit id
return a commit if found
otherwise return None, if ensure is set to True, the raise instead of return None.
'''
if commit_id not in self._commits:
try:
self._commits[commit_id] = self._read_commit(commit_id)
except FileNotFoundError:
if ensure:
raise RitError("Unable to load expected commit")
return None
return self._commits[commit_id]
def is_commit(self, commit_id: str):
''' return True if commit_id has a commit '''
return self.get_commit(commit_id) is not None
def get_branch_names(self):
''' return names of all branches '''
if self._branch_names is None:
self._branch_names = self._read_branch_names()
return self._branch_names
def get_branch(self, name: str, *, ensure=False):
'''
query for branch by name
returns None if not found. raises RitError instead if ensure is True
'''
if name not in self._branches:
try:
self._branches[name] = self._read_branch(name)
except FileNotFoundError:
if ensure:
raise RitError("Unable to load expected branch")
return None
return self._branches[name]
def is_branch(self, name: str):
''' return True if the branch name has a branch '''
return self.get_branch(name) is not None
def get_branch_name_to_commit_ids(self):
''' see _populate_commit_to_branch_map '''
if self._branch_name_to_commit_ids is None:
self._populate_commit_to_branch_map()
return self._branch_name_to_commit_ids
def get_commit_id_to_branch_names(self):
''' see _populate_commit_to_branch_map '''
if self._commit_id_to_branch_names is None:
self._populate_commit_to_branch_map()
return self._commit_id_to_branch_names
def get_commit_tree(self):
'''
returns a map of shortened commit prefixes to a list of all commit ids with
that prefix
the tree is used to find full commit ids given partial ones.
'''
if self._short_commit_tree is None:
self._short_commit_tree = defaultdict(list)
for commit_id in self.get_commit_ids():
self._short_commit_tree[commit_id[:short_hash_index]].append(commit_id)
return self._short_commit_tree
''' helpers '''
def _populate_commit_to_branch_map(self):
'''
populate the commit <-> branch maps
branches include the HEAD node
if a branch doesn't have a commit, the commit and branch will not have
entries in the maps
'''
branch_names = self.get_branch_names()
self._branch_name_to_commit_ids = {}
self._commit_id_to_branch_names = defaultdict(list)
for branch_name in branch_names:
branch = self.get_branch(branch_name, ensure=True)
commit_id = branch.commit_id
self._branch_name_to_commit_ids[branch_name] = commit_id
self._commit_id_to_branch_names[commit_id].append(branch_name)
head_commit_id = self.get_head_commit_id()
if head_commit_id is not None:
self._branch_name_to_commit_ids[head_ref_name] = head_commit_id
self._commit_id_to_branch_names[head_commit_id].append(head_ref_name)
''' IO '''
def _read_paths(self):
root_rit_dir = os.path.realpath(self.root_rit_dir)
rit_dir = os.path.join(root_rit_dir, rit_dir_name)
last_root_rit_dir = None
while not os.path.isdir(rit_dir):
last_root_rit_dir = root_rit_dir
root_rit_dir = os.path.dirname(root_rit_dir)
if last_root_rit_dir == root_rit_dir:
raise RitError("Unable to locate rit directory")
rit_dir = os.path.join(root_rit_dir, rit_dir_name)
return RitPaths.build_rit_paths(root_rit_dir)
def _read_head(self):
try:
with open(os.path.join(self.paths.rit_dir, head_ref_name)) as fin:
return HeadNode(**json.load(fin))
except FileNotFoundError:
return HeadNode(None, default_branch_name)
def _read_commit(self, commit_id: str):
logger.debug("Reading commit: %s", commit_id)
with open(os.path.join(self.paths.commits, commit_id)) as fin:
return Commit(**dict(**json.load(fin), commit_id=commit_id))
def _write_commit(self, commit: Commit):
logger.debug("Writing commit: %s", commit.commit_id)
with open(os.path.join(self.paths.commits, commit.commit_id), 'w') as fout:
data = asdict(commit)
del data['commit_id']
json.dump(data, fout)
def _delete_commit(self, commit_id: str):
try:
os.remove(os.path.join(self.paths.commits, commit_id))
except FileNotFoundError:
raise RitError("Failed to remove commit since it didn't exist: %s", commit_id)
try:
os.remove(get_tar_path(self, commit_id))
except FileNotFoundError:
raise RitError("Failed to remove commit's tar since it didn't exist: %s", commit_id)
try:
os.remove(get_snar_path(self, commit_id))
except FileNotFoundError:
raise RitError("Failed to remove commit's snar since it didn't exist: %s", commit_id)
def _read_branch(self, name: str):
logger.debug("Reading branch: %s", name)
with open(os.path.join(self.paths.branches, name)) as fin:
branch = json.load(fin)
return Branch(**dict(**branch, name=name))
def _write_branch(self, branch: Branch):
logger.debug("Writing branch %s to %s", branch.name, branch.commit_id)
if self.is_commit(branch.name):
raise RitError('Not creating a branch with the same name as a commit id: %s', branch.name)
data = asdict(branch)
del data['name']
with open(os.path.join(self.paths.branches, branch.name), 'w') as fout:
json.dump(data, fout)
def _read_branch_names(self):
for _, _, branch_names in os.walk(self.paths.branches):
return branch_names
return []
def _read_commit_ids(self):
for _, _, commit_ids in os.walk(self.paths.commits):
return commit_ids
return []
def _write_head(self, head: HeadNode):
with open(os.path.join(self.paths.rit_dir, head_ref_name), 'w') as fout:
json.dump(asdict(head), fout)
''' UTIL '''
def colorize(color: int, msg: str):
reset_seq = "\033[0m"
color_seq = "\033[1;{}m"
color_section = color_seq + "{}" + reset_seq
return color_section.format(color, msg)
def mkdir(*args, exists_ok=False, **kwargs):
try:
os.mkdir(*args, **kwargs)
except FileExistsError:
if not exists_ok:
raise
def none_t():
def none_type(obj):
return obj is None
return none_type
def exact_t(*types):
def exact_type(obj):
return isinstance(obj, types)
return exact_type
def optional_t(obj_t):
def optional_type(obj):
if obj is None:
return True
else:
return obj_t(obj)
return optional_type
def list_t(obj_t):
def list_type(obj):
if isinstance(obj, list):
return all(obj_t(val) for val in obj)
return False
return list_type
def check_types(**type_defs):
for name, (obj, type_def) in type_defs.items():
if not type_def(obj):
raise TypeError(f"Element had invalid type: {name}: {type(obj)}")
def check_obj_types(obj, type_defs):
objs = {}
for key, type_def in type_defs.items():
objs[key] = (getattr(obj, key), type_def)
def require(statement, msg, *args):
if not statement:
raise RitError(msg, *args)
''' RIT DIR HELPERS '''
def get_tar_path(rit: RitResource, commit_id: str):
''' get a commit's tar path, where the backup for that commit is '''
return os.path.join(rit.paths.backups, commit_id + '.tar')
def get_snar_path(rit: RitResource, commit_id: str):
''' get a commit's star path, where the backup's metadata for that commit is '''
return os.path.join(rit.paths.backups, commit_id + '.snar')
''' COMMIT HELPERS '''
def hash_commit(create_time: float, msg: str, snar: str, tar: str):
''' create a commit_id from '''
logger.debug("Calculating the hash of ref")
ref_hash = hashlib.sha1()
ref_hash.update(b'create_time')
ref_hash.update(str(create_time).encode('utf-8'))
ref_hash.update(b'msg')
ref_hash.update(msg.encode('utf-8'))
ref_hash.update(b'snar')
with open(snar, 'rb') as fin:
ref_hash.update(fin.read())
ref_hash.update(b'tar')
with open(tar, 'rb') as fin:
ref_hash.update(fin.read())
return ref_hash.hexdigest()
def check_tar():
''' verify tar is the correct version and GNU '''
logger.debug("Checking tar version")
process = subprocess.Popen(['tar', '--version'], stdout=subprocess.PIPE)
contents = process.stdout.read()
process.wait()
version = contents.decode('utf-8').split('\n', 1)[0]
logger.debug("Tar Version: %s", version)
assert 'GNU tar' in version, "You must have a GNU tar installed"
def status_tar(rit: RitResource, verbose: bool):
''' returns True if rit directory is dirty '''
parent_commit_id = rit.get_head_commit_id()
work_snar = os.path.join(rit.paths.work, 'ref.snar')
if parent_commit_id is not None:
head_snar = get_snar_path(rit, parent_commit_id)
# TODO: move into rit resource
shutil.copyfile(head_snar, work_snar)
check_tar()
tar_cmd = ['tar', '-cvg', work_snar, f'--exclude={rit_dir_name}', '-f', os.devnull, '.']
logger.debug("Running tar command: %s", tar_cmd)
# TODO: move into rit resource
process = subprocess.Popen(tar_cmd, cwd=rit.paths.root, stdout=subprocess.PIPE)
terminated = False
dirty = False
while True:
line = process.stdout.readline()
if not line:
break
if line == b'./\n':
continue
dirty = True
if verbose:
output = line.decode('utf-8').strip()
logger.info("\t- %s", colorize(fg + red, output))
else:
terminated = True
try:
process.terminate()
except Exception:
pass
break
# still need to read the stdout to prevent blocking and therefore deadlock
if terminated:
while process.stdout.read(DEFAULT_BUFFER_SIZE):
pass
exit_code = process.wait()
if not terminated and exit_code != 0:
raise RitError("Creating commit's tar failed with exit code: %d", exit_code)
os.remove(work_snar)
return dirty
def create_commit(rit: RitResource, create_time: float, msg: str):
''' create a commit with the current head as the parent commit (if any) '''
parent_commit_id = rit.get_head_commit_id()
logger.debug("Parent ref: %s", parent_commit_id)
work_tar = os.path.join(rit.paths.work, 'ref.tar')
logger.debug("Working tar: %s", work_tar)
work_snar = os.path.join(rit.paths.work, 'ref.snar')
logger.debug("Working snar: %s", work_snar)
if parent_commit_id is not None:
head_snar = get_snar_path(rit, parent_commit_id)
logger.debug("Copying previous snar: %s", head_snar)
# TODO: move into rit resource
shutil.copyfile(head_snar, work_snar)
else:
logger.debug("Using fresh snar file since no parent commit")
check_tar()
opts = '-cz'
if logger.getEffectiveLevel() <= logging.DEBUG:
opts += 'v'
opts += 'g'
tar_cmd = ['tar', opts, work_snar, f'--exclude={rit_dir_name}', '-f', work_tar, '.']
logger.debug("Running tar command: %s", tar_cmd)
# TODO: move into rit resource
process = subprocess.Popen(tar_cmd, cwd=rit.paths.root)
# TODO: doesn't forward SIGTERM, only SIGINT
exit_code = process.wait()
if exit_code != 0:
raise RitError("Creating commit's tar failed with exit code: %d", exit_code)
commit_id = hash_commit(create_time, msg, work_snar, work_tar)
logger.debug("Moving working snar into backups directory")
snar = get_snar_path(rit, commit_id)
os.rename(work_snar, snar)
logger.debug("Moving working tar into backups directory")
tar = get_tar_path(rit, commit_id)
os.rename(work_tar, tar)
commit = Commit(parent_commit_id, commit_id, create_time, msg)
rit.add_commit(commit)
if rit.head.commit_id is not None:
new_head = HeadNode(commit_id=commit_id, branch_name=None)
rit.set_head(new_head)
else:
rit.set_branch(Branch(rit.head.branch_name, commit_id))
return commit
''' RESET HELPERS '''
def apply_commit(rit: RitResource, commit: Commit):
'''
apply the commit to the rit directory
If the current rit directory isn't clean and isn't the parent of the commit
being applied, the results will not be the contents of commit.
See restore_to_commit.
'''
logger.info("Applying commit: %s", commit.commit_id)
tar_file = get_tar_path(rit, commit.commit_id)
tar_cmd = ['tar', '-xg', os.devnull, '-f', tar_file]
# rit resource thing?
process = subprocess.Popen(tar_cmd, cwd=rit.paths.root)
exit_code = process.wait()
if exit_code != 0:
raise RitError("Failed while trying to apply commit: %s", commit.commit_id)
def restore_to_commit(rit: RitResource, commit: Commit):
'''
This gets the chain of commits from commit to root and applies them. If there
are changes in the working directory relative to current head, then those will
be destroyed.
'''
logger.debug('resetting to %s', commit.commit_id)
commit_chain = [commit]
while commit.parent_commit_id is not None:
commit = rit.get_commit(commit.parent_commit_id, ensure=True)
commit_chain.append(commit)
commit_chain.reverse()
for commit in commit_chain:
apply_commit(rit, commit)
''' BRANCH HELPERS '''
@dataclass
class ResolvedRef:
'''
the user provides a ref, which can reference head, a branch or commit. this
object contains the HeadNode, Branch and Commit that the user's ref is
referring to. all 3 or None can be defined.
see resolve_ref
'''
commit: Optional[Commit] = None
'''
if None:
if head:
head points to a branch with no commit
else:
ref doesn't refer to a branch or commit
else:
ref ultimately refers to this commit
'''
branch: Optional[Branch] = None
'''
if head is None
if branch is None:
ref doesn't refer to a branch
else:
ref points to this branch
else:
if branch is None:
head points to a commit.
head points to a branch with no commit.
else:
head points to this branch
'''
head: Optional[HeadNode] = None
'''
if head is None:
ref was provided and not the head
else:
ref was omitted or explicitly set to the head
'''
def resolve_commit(rit: RitResource, partial_commit_id: str):
'''
resolve a user provided commit id to a commit. if no commit is found, then
return None. if the ref is an ambiguous shortened commit id, then this
function raises an exception.
'''
logger.debug("Resolving commit: %s", partial_commit_id)
commit = rit.get_commit(partial_commit_id)
if commit is not None:
return commit
if len(partial_commit_id) < short_hash_index:
return None
short_commit_id = partial_commit_id[:short_hash_index]
commit_tree = rit.get_commit_tree()
if short_commit_id not in commit_tree:
return None
commit = None
for commit_id in commit_tree[short_commit_id]:
size = len(partial_commit_id)
if partial_commit_id == commit_id[:size]:
if commit is not None:
raise RitError("Reference %s matched commits %s and %s", partial_commit_id, commit.commit_id, commit_id)
commit = rit.get_commit(commit_id, ensure=True)
return commit
def resolve_ref(rit: RitResource, ref: Optional[str]):
'''
resolve a user provided reference
if ref is None, then ref refers to the current head. ref can also explicitly
refer to the current head. ref otherwise refers to a branch. if the branch is
not found, then the ref refers to a commit. if no commit is found, all 3
fields of ResolvedRef will be None.
if the ref is an ambiguous shortened commit id, then this function raises an
exception.
see the def of ResolvedRef
'''
logger.debug("Resolving ref: %s", ref)
res = ResolvedRef()
if ref is None or ref == head_ref_name:
head = rit.head
res.head = head
if head.branch_name is not None:
res.branch = rit.get_branch(head.branch_name)
if res.branch is not None:
res.commit = rit.get_commit(res.branch.commit_id)
else:
res.commit = rit.get_commit(head.commit_id)
else:
res.branch = rit.get_branch(ref)
if res.branch is not None:
res.commit = rit.get_commit(res.branch.commit_id)
else:
res.commit = resolve_commit(rit, ref)
return res
def resolve_refs(rit: RitResource, refs: list[str], all: bool):
'''
Returns information regarding the provided refs
'''
resolved_refs: list[ResolvedRef] = []
if not refs:
refs.append(None)
if all:
refs.extend(rit.get_branch_names())
for ref in refs:
res = resolve_ref(rit, ref)
resolved_refs.append(res)
return resolved_refs
branch_name_re = re.compile('^\\w+$')
def validate_branch_name(name: str):
''' return whether this string is a valid branch name '''
if name == head_ref_name:
raise RitError("Branch can't be named the same as the head ref: %s", name)
elif branch_name_re.search(name) is None:
raise RitError("Invalid branch name: %s", name)
def _pprint_dur(dur: int, name: str):
return f"{dur} {name}{'s' if dur > 1 else ''}"
def pprint_time_duration(start: float, end: float):
''' pretty print a time duration '''
start_dt = datetime.datetime.fromtimestamp(start)
end_dt = datetime.datetime.fromtimestamp(end)
dur = end - start
dur_sec = dur
dur_min = dur / 60
dur_hour = dur_min / 60
dur_day = dur_hour / 24
dur_month = 12 * (end_dt.year - start_dt.year) + (end_dt.month - start_dt.month)
dur_year = dur_month // 12
parts = []
if dur_year >= 5:
parts.append(_pprint_dur(int(dur_year), 'year'))
elif dur_year >= 1:
parts.append(_pprint_dur(int(dur_year), 'year'))
parts.append(_pprint_dur(int(dur_month) % 12, 'month'))
elif dur_month >= 1:
parts.append(_pprint_dur(int(dur_month) % 12, 'month'))
elif dur_day >= 1:
parts.append(_pprint_dur(int(dur_day), 'day'))
elif dur_hour >= 1:
parts.append(_pprint_dur(int(dur_hour) % 60, 'hour'))
elif dur_min >= 1:
parts.append(_pprint_dur(int(dur_min) % 60, 'minute'))
elif dur_sec >= 20:
parts.append(_pprint_dur(int(dur_sec) % 60, 'second'))
else:
return 'Just now'
return ', '.join(parts) + ' ago'
''' SUB LOG COMMANDS '''
def log_commits(rit: RitResource, commits: list[Commit]):
'''
Returns tuple of the following:
- commit_graph: a tree containing all provided commits
- leafs: the set of leaf notes of the tree
- commit_id_to_commit: a map of each commit to a full Commit object
- commit_id_to_branch_names: a map of each commit_id to branch names, including the head_ref_name
'''
leafs: set[str] = set()
commit_graph: dict[str, str] = {}
for commit in commits:
if commit.commit_id not in commit_graph:
leafs.add(commit.commit_id)
while True:
commit_graph[commit.commit_id] = commit.parent_commit_id
if commit.parent_commit_id is None:
break
parent_commit = rit.get_commit(commit.parent_commit_id, ensure=True)
if parent_commit.commit_id in leafs:
leafs.remove(parent_commit.commit_id)
commit = parent_commit
now = time.time()
commit_id_to_branch_names = rit.get_commit_id_to_branch_names()
commit_id_to_commit: dict[str, Commit] = {}
for commit_id in leafs:
logger.info("Log branch from %s", commit_id[:short_hash_index])
while commit_id is not None:
if commit_id not in commit_id_to_commit:
commit_id_to_commit[commit_id] = rit.get_commit(commit_id, ensure=True)
commit = commit_id_to_commit[commit_id]
colored_commit_id = colorize(fg + yellow, commit.commit_id[:short_hash_index])
if commit.commit_id in commit_id_to_branch_names:
branch_names = commit_id_to_branch_names[commit.commit_id]
colored_branch_names = []
for branch_name in branch_names:
if branch_name == head_ref_name:
colored_branch_names.append(colorize(fg + blue, branch_name))
else:
colored_branch_names.append(colorize(fg + green, branch_name))
branch_details = f"({', '.join(colored_branch_names)}) "
else:
branch_details = ''
time_duration = pprint_time_duration(commit.create_time, now)
date_details = f'({time_duration}) '
logger.info("* %s %s%s%s", colored_commit_id, date_details, branch_details, commit.msg)
commit_id = commit_graph[commit_id]
return commit_graph, leafs, commit_id_to_commit, commit_id_to_branch_names
''' SUB BRANCH COMMANDS '''
def delete_branch(rit: RitResource, name: str):
''' removes a branch '''
try:
os.remove(os.path.join(rit.paths.branches, name))
except FileNotFoundError:
raise RitError("Failed to remove branch since it didn't exist.")
def list_branches(rit: RitResource):
''' logs branches to logger '''
head = rit.head
head_branch_name = head.branch_name
branch_names = rit.get_branch_names()
# TODO: this doesn't handle HEAD well if its commitless
for branch_name in branch_names:
this_sym = '*' if branch_name == head_branch_name else ' '
branch = rit.get_branch(branch_name, ensure=True)
commit = rit.get_commit(branch.commit_id, ensure=True)
colored_commit_id = colorize(fg + yellow, branch.commit_id[:short_hash_index])
colored_branch_name = colorize(fg + green, branch_name)
logger.info("%s %s\t%s %s", this_sym, colored_branch_name, colored_commit_id, commit.msg)
return head, branch_names
def create_branch(rit: RitResource, name: str, ref: Optional[str], force: bool):
'''
creates a branch with name name at ref ref. if the branch already exists,
force will move the branch to the new commit.
'''
if rit.is_branch(name) and not force:
raise RitError('Branch already exists: %s. Use -f to force the overwrite of it.', name)
res = resolve_ref(rit, ref)
if res.commit is None:
if res.head is not None:
raise RitError("Current head doesn't have a commit")
else:
raise RitError("Unable to resolve ref: %s", ref)