forked from VedAstro/VedAstro
-
Notifications
You must be signed in to change notification settings - Fork 0
/
git-filter-repo
4005 lines (3523 loc) · 162 KB
/
git-filter-repo
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
#!/usr/bin/env python3
"""
git-filter-repo filters git repositories, similar to git filter-branch, BFG
repo cleaner, and others. The basic idea is that it works by running
git fast-export <options> | filter | git fast-import <options>
where this program not only launches the whole pipeline but also serves as
the 'filter' in the middle. It does a few additional things on top as well
in order to make it into a well-rounded filtering tool.
git-filter-repo can also be used as a library for more involved filtering
operations; however:
***** API BACKWARD COMPATIBILITY CAVEAT *****
Programs using git-filter-repo as a library can reach pretty far into its
internals, but I am not prepared to guarantee backward compatibility of
all APIs. I suspect changes will be rare, but I reserve the right to
change any API. Since it is assumed that repository filtering is
something one would do very rarely, and in particular that it's a
one-shot operation, this should not be a problem in practice for anyone.
However, if you want to re-use a program you have written that uses
git-filter-repo as a library (or makes use of one of its --*-callback
arguments), you should either make sure you are using the same version of
git and git-filter-repo, or make sure to re-test it.
If there are particular pieces of the API you are concerned about, and
there is not already a testcase for it in t9391-lib-usage.sh or
t9392-python-callback.sh, please contribute a testcase. That will not
prevent me from changing the API, but it will allow you to look at the
history of a testcase to see whether and how the API changed.
***** END API BACKWARD COMPATIBILITY CAVEAT *****
"""
import argparse
import collections
import fnmatch
import gettext
import io
import os
import platform
import re
import shutil
import subprocess
import sys
import time
import textwrap
from datetime import tzinfo, timedelta, datetime
__all__ = ["Blob", "Reset", "FileChange", "Commit", "Tag", "Progress",
"Checkpoint", "FastExportParser", "ProgressWriter",
"string_to_date", "date_to_string",
"record_id_rename", "GitUtils", "FilteringOptions", "RepoFilter"]
deleted_hash = b'0'*40
write_marks = True
date_format_permissive = True
def gettext_poison(msg):
if "GIT_TEST_GETTEXT_POISON" in os.environ: # pragma: no cover
return "# GETTEXT POISON #"
return gettext.gettext(msg)
_ = gettext_poison
def setup_gettext():
TEXTDOMAIN="git-filter-repo"
podir = os.environ.get("GIT_TEXTDOMAINDIR") or "@@LOCALEDIR@@"
if not os.path.isdir(podir): # pragma: no cover
podir = None # Python has its own fallback; use that
## This looks like the most straightforward translation of the relevant
## code in git.git:gettext.c and git.git:perl/Git/I18n.pm:
#import locale
#locale.setlocale(locale.LC_MESSAGES, "");
#locale.setlocale(locale.LC_TIME, "");
#locale.textdomain(TEXTDOMAIN);
#locale.bindtextdomain(TEXTDOMAIN, podir);
## but the python docs suggest using the gettext module (which doesn't
## have setlocale()) instead, so:
gettext.textdomain(TEXTDOMAIN);
gettext.bindtextdomain(TEXTDOMAIN, podir);
def _timedelta_to_seconds(delta):
"""
Converts timedelta to seconds
"""
offset = delta.days*86400 + delta.seconds + (delta.microseconds+0.0)/1000000
return round(offset)
class FixedTimeZone(tzinfo):
"""
Fixed offset in minutes east from UTC.
"""
tz_re = re.compile(br'^([-+]?)(\d\d)(\d\d)$')
def __init__(self, offset_string):
tzinfo.__init__(self)
sign, hh, mm = FixedTimeZone.tz_re.match(offset_string).groups()
factor = -1 if (sign and sign == b'-') else 1
self._offset = timedelta(minutes = factor*(60*int(hh) + int(mm)))
self._offset_string = offset_string
def utcoffset(self, dt):
return self._offset
def tzname(self, dt):
return self._offset_string
def dst(self, dt):
return timedelta(0)
def string_to_date(datestring):
(unix_timestamp, tz_offset) = datestring.split()
return datetime.fromtimestamp(int(unix_timestamp),
FixedTimeZone(tz_offset))
def date_to_string(dateobj):
epoch = datetime.fromtimestamp(0, dateobj.tzinfo)
return(b'%d %s' % (int(_timedelta_to_seconds(dateobj - epoch)),
dateobj.tzinfo.tzname(0)))
def decode(bytestr):
'Try to convert bytestr to utf-8 for outputting as an error message.'
return bytestr.decode('utf-8', 'backslashreplace')
def glob_to_regex(glob_bytestr):
'Translate glob_bytestr into a regex on bytestrings'
# fnmatch.translate is idiotic and won't accept bytestrings
if (decode(glob_bytestr).encode() != glob_bytestr): # pragma: no cover
raise SystemExit(_("Error: Cannot handle glob %s").format(glob_bytestr))
# Create regex operating on string
regex = fnmatch.translate(decode(glob_bytestr))
# FIXME: This is an ugly hack...
# fnmatch.translate tries to do multi-line matching and wants the glob to
# match up to the end of the input, which isn't relevant for us, so we
# have to modify the regex. fnmatch.translate has used different regex
# constructs to achieve this with different python versions, so we have
# to check for each of them and then fix it up. It would be much better
# if fnmatch.translate could just take some flags to allow us to specify
# what we want rather than employing this hackery, but since it
# doesn't...
if regex.endswith(r'\Z(?ms)'): # pragma: no cover
regex = regex[0:-7]
elif regex.startswith(r'(?s:') and regex.endswith(r')\Z'): # pragma: no cover
regex = regex[4:-3]
# Finally, convert back to regex operating on bytestr
return regex.encode()
class PathQuoting:
_unescape = {b'a': b'\a',
b'b': b'\b',
b'f': b'\f',
b'n': b'\n',
b'r': b'\r',
b't': b'\t',
b'v': b'\v',
b'"': b'"',
b'\\':b'\\'}
_unescape_re = re.compile(br'\\([a-z"\\]|[0-9]{3})')
_escape = [bytes([x]) for x in range(127)]+[
b'\\'+bytes(ord(c) for c in oct(x)[2:]) for x in range(127,256)]
_reverse = dict(map(reversed, _unescape.items()))
for x in _reverse:
_escape[ord(x)] = b'\\'+_reverse[x]
_special_chars = [len(x) > 1 for x in _escape]
@staticmethod
def unescape_sequence(orig):
seq = orig.group(1)
return PathQuoting._unescape[seq] if len(seq) == 1 else bytes([int(seq, 8)])
@staticmethod
def dequote(quoted_string):
if quoted_string.startswith(b'"'):
assert quoted_string.endswith(b'"')
return PathQuoting._unescape_re.sub(PathQuoting.unescape_sequence,
quoted_string[1:-1])
return quoted_string
@staticmethod
def enquote(unquoted_string):
# Option 1: Quoting when fast-export would:
# pqsc = PathQuoting._special_chars
# if any(pqsc[x] for x in set(unquoted_string)):
# Option 2, perf hack: do minimal amount of quoting required by fast-import
if unquoted_string.startswith(b'"') or b'\n' in unquoted_string:
pqe = PathQuoting._escape
return b'"' + b''.join(pqe[x] for x in unquoted_string) + b'"'
return unquoted_string
class AncestryGraph(object):
"""
A class that maintains a direct acycle graph of commits for the purpose of
determining if one commit is the ancestor of another.
"""
def __init__(self):
self.cur_value = 0
# A mapping from the external identifers given to us to the simple integers
# we use in self.graph
self.value = {}
# A tuple of (depth, list-of-ancestors). Values and keys in this graph are
# all integers from the self.value dict. The depth of a commit is one more
# than the max depth of any of its ancestors.
self.graph = {}
# Cached results from previous calls to is_ancestor().
self._cached_is_ancestor = {}
def record_external_commits(self, external_commits):
"""
Record in graph that each commit in external_commits exists, and is
treated as a root commit with no parents.
"""
for c in external_commits:
if c not in self.value:
self.cur_value += 1
self.value[c] = self.cur_value
self.graph[self.cur_value] = (1, [])
def add_commit_and_parents(self, commit, parents):
"""
Record in graph that commit has the given parents. parents _MUST_ have
been first recorded. commit _MUST_ not have been recorded yet.
"""
assert all(p in self.value for p in parents)
assert commit not in self.value
# Get values for commit and parents
self.cur_value += 1
self.value[commit] = self.cur_value
graph_parents = [self.value[x] for x in parents]
# Determine depth for commit, then insert the info into the graph
depth = 1
if parents:
depth += max(self.graph[p][0] for p in graph_parents)
self.graph[self.cur_value] = (depth, graph_parents)
def is_ancestor(self, possible_ancestor, check):
"""
Return whether possible_ancestor is an ancestor of check
"""
a, b = self.value[possible_ancestor], self.value[check]
original_pair = (a,b)
a_depth = self.graph[a][0]
ancestors = [b]
visited = set()
while ancestors:
ancestor = ancestors.pop()
prev_pair = (a, ancestor)
if prev_pair in self._cached_is_ancestor:
if not self._cached_is_ancestor[prev_pair]:
continue
self._cached_is_ancestor[original_pair] = True
return True
if ancestor in visited:
continue
visited.add(ancestor)
depth, more_ancestors = self.graph[ancestor]
if ancestor == a:
self._cached_is_ancestor[original_pair] = True
return True
elif depth <= a_depth:
continue
ancestors.extend(more_ancestors)
self._cached_is_ancestor[original_pair] = False
return False
class MailmapInfo(object):
def __init__(self, filename):
self.changes = {}
self._parse_file(filename)
def _parse_file(self, filename):
name_and_email_re = re.compile(br'(.*?)\s*<([^>]*)>\s*')
comment_re = re.compile(br'\s*#.*')
if not os.access(filename, os.R_OK):
raise SystemExit(_("Cannot read %s") % decode(filename))
with open(filename, 'br') as f:
count = 0
for line in f:
count += 1
err = "Unparseable mailmap file: line #{} is bad: {}".format(count, line)
# Remove comments
line = comment_re.sub(b'', line)
# Remove leading and trailing whitespace
line = line.strip()
if not line:
continue
m = name_and_email_re.match(line)
if not m:
raise SystemExit(err)
proper_name, proper_email = m.groups()
if len(line) == m.end():
self.changes[(None, proper_email)] = (proper_name, proper_email)
continue
rest = line[m.end():]
m = name_and_email_re.match(rest)
if m:
commit_name, commit_email = m.groups()
if len(rest) != m.end():
raise SystemExit(err)
else:
commit_name, commit_email = rest, None
self.changes[(commit_name, commit_email)] = (proper_name, proper_email)
def translate(self, name, email):
''' Given a name and email, return the expected new name and email from the
mailmap if there is a translation rule for it, otherwise just return
the given name and email.'''
for old, new in self.changes.items():
old_name, old_email = old
new_name, new_email = new
if (old_email is None or email.lower() == old_email.lower()) and (
name == old_name or not old_name):
return (new_name or name, new_email or email)
return (name, email)
class ProgressWriter(object):
def __init__(self):
self._last_progress_update = time.time()
self._last_message = None
def show(self, msg):
self._last_message = msg
now = time.time()
if now - self._last_progress_update > .1:
self._last_progress_update = now
sys.stdout.write("\r{}".format(msg))
sys.stdout.flush()
def finish(self):
self._last_progress_update = 0
if self._last_message:
self.show(self._last_message)
sys.stdout.write("\n")
class _IDs(object):
"""
A class that maintains the 'name domain' of all the 'marks' (short int
id for a blob/commit git object). The reason this mechanism is necessary
is because the text of fast-export may refer to an object using a different
mark than the mark that was assigned to that object using IDS.new(). This
class allows you to translate the fast-export marks (old) to the marks
assigned from IDS.new() (new).
Note that there are two reasons why the marks may differ: (1) The
user manually creates Blob or Commit objects (for insertion into the
stream) (2) We're reading the data from two different repositories
and trying to combine the data (git fast-export will number ids from
1...n, and having two 1's, two 2's, two 3's, causes issues).
"""
def __init__(self):
"""
Init
"""
# The id for the next created blob/commit object
self._next_id = 1
# A map of old-ids to new-ids (1:1 map)
self._translation = {}
# A map of new-ids to every old-id that points to the new-id (1:N map)
self._reverse_translation = {}
def has_renames(self):
"""
Return whether there have been ids remapped to new values
"""
return bool(self._translation)
def new(self):
"""
Should be called whenever a new blob or commit object is created. The
returned value should be used as the id/mark for that object.
"""
rv = self._next_id
self._next_id += 1
return rv
def record_rename(self, old_id, new_id, handle_transitivity = False):
"""
Record that old_id is being renamed to new_id.
"""
if old_id != new_id:
# old_id -> new_id
self._translation[old_id] = new_id
# Transitivity will be needed if new commits are being inserted mid-way
# through a branch.
if handle_transitivity:
# Anything that points to old_id should point to new_id
if old_id in self._reverse_translation:
for id_ in self._reverse_translation[old_id]:
self._translation[id_] = new_id
# Record that new_id is pointed to by old_id
if new_id not in self._reverse_translation:
self._reverse_translation[new_id] = []
self._reverse_translation[new_id].append(old_id)
def translate(self, old_id):
"""
If old_id has been mapped to an alternate id, return the alternate id.
"""
if old_id in self._translation:
return self._translation[old_id]
else:
return old_id
def __str__(self):
"""
Convert IDs to string; used for debugging
"""
rv = "Current count: %d\nTranslation:\n" % self._next_id
for k in sorted(self._translation):
rv += " %d -> %s\n" % (k, self._translation[k])
rv += "Reverse translation:\n"
for k in sorted(self._reverse_translation):
rv += " " + str(k) + " -> " + str(self._reverse_translation[k]) + "\n"
return rv
class _GitElement(object):
"""
The base class for all git elements that we create.
"""
def __init__(self):
# A string that describes what type of Git element this is
self.type = None
# A flag telling us if this Git element has been dumped
# (i.e. printed) or skipped. Typically elements that have been
# dumped or skipped will not be dumped again.
self.dumped = 0
def dump(self, file_):
"""
This version should never be called. Derived classes need to
override! We should note that subclasses should implement this
method such that the output would match the format produced by
fast-export.
"""
raise SystemExit(_("Unimplemented function: %s") % type(self).__name__
+".dump()") # pragma: no cover
def __bytes__(self):
"""
Convert GitElement to bytestring; used for debugging
"""
old_dumped = self.dumped
writeme = io.BytesIO()
self.dump(writeme)
output_lines = writeme.getvalue().splitlines()
writeme.close()
self.dumped = old_dumped
return b"%s:\n %s" % (type(self).__name__.encode(),
b"\n ".join(output_lines))
def skip(self, new_id=None):
"""
Ensures this element will not be written to output
"""
self.dumped = 2
class _GitElementWithId(_GitElement):
"""
The base class for Git elements that have IDs (commits and blobs)
"""
def __init__(self):
_GitElement.__init__(self)
# The mark (short, portable id) for this element
self.id = _IDS.new()
# The previous mark for this element
self.old_id = None
def skip(self, new_id=None):
"""
This element will no longer be automatically written to output. When a
commit gets skipped, it's ID will need to be translated to that of its
parent.
"""
self.dumped = 2
_IDS.record_rename(self.old_id or self.id, new_id)
class Blob(_GitElementWithId):
"""
This class defines our representation of git blob elements (i.e. our
way of representing file contents).
"""
def __init__(self, data, original_id = None):
_GitElementWithId.__init__(self)
# Denote that this is a blob
self.type = 'blob'
# Record original id
self.original_id = original_id
# Stores the blob's data
assert(type(data) == bytes)
self.data = data
def dump(self, file_):
"""
Write this blob element to a file.
"""
self.dumped = 1
HASH_TO_ID[self.original_id] = self.id
ID_TO_HASH[self.id] = self.original_id
file_.write(b'blob\n')
file_.write(b'mark :%d\n' % self.id)
file_.write(b'data %d\n%s' % (len(self.data), self.data))
file_.write(b'\n')
class Reset(_GitElement):
"""
This class defines our representation of git reset elements. A reset
event is the creation (or recreation) of a named branch, optionally
starting from a specific revision).
"""
def __init__(self, ref, from_ref = None):
_GitElement.__init__(self)
# Denote that this is a reset
self.type = 'reset'
# The name of the branch being (re)created
self.ref = ref
# Some reference to the branch/commit we are resetting from
self.from_ref = from_ref
def dump(self, file_):
"""
Write this reset element to a file
"""
self.dumped = 1
file_.write(b'reset %s\n' % self.ref)
if self.from_ref:
if isinstance(self.from_ref, int):
file_.write(b'from :%d\n' % self.from_ref)
else:
file_.write(b'from %s\n' % self.from_ref)
file_.write(b'\n')
class FileChange(_GitElement):
"""
This class defines our representation of file change elements. File change
elements are components within a Commit element.
"""
def __init__(self, type_, filename = None, id_ = None, mode = None):
_GitElement.__init__(self)
# Denote the type of file-change (b'M' for modify, b'D' for delete, etc)
# We could
# assert(type(type_) == bytes)
# here but I don't just due to worries about performance overhead...
self.type = type_
# Record the name of the file being changed
self.filename = filename
# Record the mode (mode describes type of file entry (non-executable,
# executable, or symlink)).
self.mode = mode
# blob_id is the id (mark) of the affected blob
self.blob_id = id_
if type_ == b'DELETEALL':
assert filename is None and id_ is None and mode is None
self.filename = b'' # Just so PathQuoting.enquote doesn't die
else:
assert filename is not None
if type_ == b'M':
assert id_ is not None and mode is not None
elif type_ == b'D':
assert id_ is None and mode is None
elif type_ == b'R': # pragma: no cover (now avoid fast-export renames)
assert mode is None
if id_ is None:
raise SystemExit(_("new name needed for rename of %s") % filename)
self.filename = (self.filename, id_)
self.blob_id = None
def dump(self, file_):
"""
Write this file-change element to a file
"""
skipped_blob = (self.type == b'M' and self.blob_id is None)
if skipped_blob: return
self.dumped = 1
quoted_filename = PathQuoting.enquote(self.filename)
if self.type == b'M' and isinstance(self.blob_id, int):
file_.write(b'M %s :%d %s\n' % (self.mode, self.blob_id, quoted_filename))
elif self.type == b'M':
file_.write(b'M %s %s %s\n' % (self.mode, self.blob_id, quoted_filename))
elif self.type == b'D':
file_.write(b'D %s\n' % quoted_filename)
elif self.type == b'DELETEALL':
file_.write(b'deleteall\n')
else:
raise SystemExit(_("Unhandled filechange type: %s") % self.type) # pragma: no cover
class Commit(_GitElementWithId):
"""
This class defines our representation of commit elements. Commit elements
contain all the information associated with a commit.
"""
def __init__(self, branch,
author_name, author_email, author_date,
committer_name, committer_email, committer_date,
message,
file_changes,
parents,
original_id = None,
encoding = None, # encoding for message; None implies UTF-8
**kwargs):
_GitElementWithId.__init__(self)
self.old_id = self.id
# Denote that this is a commit element
self.type = 'commit'
# Record the affected branch
self.branch = branch
# Record original id
self.original_id = original_id
# Record author's name
self.author_name = author_name
# Record author's email
self.author_email = author_email
# Record date of authoring
self.author_date = author_date
# Record committer's name
self.committer_name = committer_name
# Record committer's email
self.committer_email = committer_email
# Record date the commit was made
self.committer_date = committer_date
# Record commit message and its encoding
self.encoding = encoding
self.message = message
# List of file-changes associated with this commit. Note that file-changes
# are also represented as git elements
self.file_changes = file_changes
self.parents = parents
def dump(self, file_):
"""
Write this commit element to a file.
"""
self.dumped = 1
HASH_TO_ID[self.original_id] = self.id
ID_TO_HASH[self.id] = self.original_id
# Make output to fast-import slightly easier for humans to read if the
# message has no trailing newline of its own; cosmetic, but a nice touch...
extra_newline = b'\n'
if self.message.endswith(b'\n') or not (self.parents or self.file_changes):
extra_newline = b''
if not self.parents:
file_.write(b'reset %s\n' % self.branch)
file_.write((b'commit %s\n'
b'mark :%d\n'
b'author %s <%s> %s\n'
b'committer %s <%s> %s\n'
) % (
self.branch, self.id,
self.author_name, self.author_email, self.author_date,
self.committer_name, self.committer_email, self.committer_date
))
if self.encoding:
file_.write(b'encoding %s\n' % self.encoding)
file_.write(b'data %d\n%s%s' %
(len(self.message), self.message, extra_newline))
for i, parent in enumerate(self.parents):
file_.write(b'from ' if i==0 else b'merge ')
if isinstance(parent, int):
file_.write(b':%d\n' % parent)
else:
file_.write(b'%s\n' % parent)
for change in self.file_changes:
change.dump(file_)
if not self.parents and not self.file_changes:
# Workaround a bug in pre-git-2.22 versions of fast-import with
# the get-mark directive.
file_.write(b'\n')
file_.write(b'\n')
def first_parent(self):
"""
Return first parent commit
"""
if self.parents:
return self.parents[0]
return None
def skip(self, new_id=None):
_SKIPPED_COMMITS.add(self.old_id or self.id)
_GitElementWithId.skip(self, new_id)
class Tag(_GitElementWithId):
"""
This class defines our representation of annotated tag elements.
"""
def __init__(self, ref, from_ref,
tagger_name, tagger_email, tagger_date, tag_msg,
original_id = None):
_GitElementWithId.__init__(self)
self.old_id = self.id
# Denote that this is a tag element
self.type = 'tag'
# Store the name of the tag
self.ref = ref
# Store the entity being tagged (this should be a commit)
self.from_ref = from_ref
# Record original id
self.original_id = original_id
# Store the name of the tagger
self.tagger_name = tagger_name
# Store the email of the tagger
self.tagger_email = tagger_email
# Store the date
self.tagger_date = tagger_date
# Store the tag message
self.message = tag_msg
def dump(self, file_):
"""
Write this tag element to a file
"""
self.dumped = 1
HASH_TO_ID[self.original_id] = self.id
ID_TO_HASH[self.id] = self.original_id
file_.write(b'tag %s\n' % self.ref)
if (write_marks and self.id):
file_.write(b'mark :%d\n' % self.id)
markfmt = b'from :%d\n' if isinstance(self.from_ref, int) else b'from %s\n'
file_.write(markfmt % self.from_ref)
if self.tagger_name:
file_.write(b'tagger %s <%s> ' % (self.tagger_name, self.tagger_email))
file_.write(self.tagger_date)
file_.write(b'\n')
file_.write(b'data %d\n%s' % (len(self.message), self.message))
file_.write(b'\n')
class Progress(_GitElement):
"""
This class defines our representation of progress elements. The progress
element only contains a progress message, which is printed by fast-import
when it processes the progress output.
"""
def __init__(self, message):
_GitElement.__init__(self)
# Denote that this is a progress element
self.type = 'progress'
# Store the progress message
self.message = message
def dump(self, file_):
"""
Write this progress element to a file
"""
self.dumped = 1
file_.write(b'progress %s\n' % self.message)
file_.write(b'\n')
class Checkpoint(_GitElement):
"""
This class defines our representation of checkpoint elements. These
elements represent events which force fast-import to close the current
packfile, start a new one, and to save out all current branch refs, tags
and marks.
"""
def __init__(self):
_GitElement.__init__(self)
# Denote that this is a checkpoint element
self.type = 'checkpoint'
def dump(self, file_):
"""
Write this checkpoint element to a file
"""
self.dumped = 1
file_.write(b'checkpoint\n')
file_.write(b'\n')
class LiteralCommand(_GitElement):
"""
This class defines our representation of commands. The literal command
includes only a single line, and is not processed in any special way.
"""
def __init__(self, line):
_GitElement.__init__(self)
# Denote that this is a literal element
self.type = 'literal'
# Store the command
self.line = line
def dump(self, file_):
"""
Write this progress element to a file
"""
self.dumped = 1
file_.write(self.line)
class Alias(_GitElement):
"""
This class defines our representation of fast-import alias elements. An
alias element is the setting of one mark to the same sha1sum as another,
usually because the newer mark corresponded to a pruned commit.
"""
def __init__(self, ref, to_ref):
_GitElement.__init__(self)
# Denote that this is a reset
self.type = 'alias'
self.ref = ref
self.to_ref = to_ref
def dump(self, file_):
"""
Write this reset element to a file
"""
self.dumped = 1
file_.write(b'alias\nmark :%d\nto :%d\n\n' % (self.ref, self.to_ref))
class FastExportParser(object):
"""
A class for parsing and handling the output from fast-export. This
class allows the user to register callbacks when various types of
data are encountered in the fast-export output. The basic idea is that,
FastExportParser takes fast-export output, creates the various objects
as it encounters them, the user gets to use/modify these objects via
callbacks, and finally FastExportParser outputs the modified objects
in fast-import format (presumably so they can be used to create a new
repo).
"""
def __init__(self,
tag_callback = None, commit_callback = None,
blob_callback = None, progress_callback = None,
reset_callback = None, checkpoint_callback = None,
done_callback = None):
# Members below simply store callback functions for the various git
# elements
self._tag_callback = tag_callback
self._blob_callback = blob_callback
self._reset_callback = reset_callback
self._commit_callback = commit_callback
self._progress_callback = progress_callback
self._checkpoint_callback = checkpoint_callback
self._done_callback = done_callback
# Keep track of which refs appear from the export, and which make it to
# the import (pruning of empty commits, renaming of refs, and creating
# new manual objects and inserting them can cause these to differ).
self._exported_refs = set()
self._imported_refs = set()
# A list of the branches we've seen, plus the last known commit they
# pointed to. An entry in latest_*commit will be deleted if we get a
# reset for that branch. These are used because of fast-import's weird
# decision to allow having an implicit parent via naming the branch
# instead of requiring branches to be specified via 'from' directives.
self._latest_commit = {}
self._latest_orig_commit = {}
# A handle to the input source for the fast-export data
self._input = None
# A handle to the output file for the output we generate (we call dump
# on many of the git elements we create).
self._output = None
# Stores the contents of the current line of input being parsed
self._currentline = ''
# Compile some regexes and cache those
self._mark_re = re.compile(br'mark :(\d+)\n$')
self._parent_regexes = {}
parent_regex_rules = (br' :(\d+)\n$', br' ([0-9a-f]{40})\n')
for parent_refname in (b'from', b'merge'):
ans = [re.compile(parent_refname+x) for x in parent_regex_rules]
self._parent_regexes[parent_refname] = ans
self._quoted_string_re = re.compile(br'"(?:[^"\\]|\\.)*"')
self._refline_regexes = {}
for refline_name in (b'reset', b'commit', b'tag', b'progress'):
self._refline_regexes[refline_name] = re.compile(refline_name+b' (.*)\n$')
self._user_regexes = {}
for user in (b'author', b'committer', b'tagger'):
self._user_regexes[user] = re.compile(user + b' (.*?) <(.*?)> (.*)\n$')
def _advance_currentline(self):
"""
Grab the next line of input
"""
self._currentline = self._input.readline()
def _parse_optional_mark(self):
"""
If the current line contains a mark, parse it and advance to the
next line; return None otherwise
"""
mark = None
matches = self._mark_re.match(self._currentline)
if matches:
mark = int(matches.group(1))
self._advance_currentline()
return mark
def _parse_optional_parent_ref(self, refname):
"""
If the current line contains a reference to a parent commit, then
parse it and advance the current line; otherwise return None. Note
that the name of the reference ('from', 'merge') must match the
refname arg.
"""
orig_baseref, baseref = None, None
rule, altrule = self._parent_regexes[refname]
matches = rule.match(self._currentline)
if matches:
orig_baseref = int(matches.group(1))
# We translate the parent commit mark to what it needs to be in
# our mark namespace
baseref = _IDS.translate(orig_baseref)
self._advance_currentline()
else:
matches = altrule.match(self._currentline)
if matches:
orig_baseref = matches.group(1)
baseref = orig_baseref
self._advance_currentline()
return orig_baseref, baseref
def _parse_optional_filechange(self):
"""
If the current line contains a file-change object, then parse it