-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgit-sccsimport.py
1204 lines (1017 loc) · 33.8 KB
/
git-sccsimport.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
#!/usr/bin/env python
#
# git-sccsimport -- Import deltas collectively from SCCS files into git
#
#ident "%Z%%Y%:%M% %I% %E% %U% (%Q%)"
#
# Author: James Youngman <jay@gnu.org>
# Copyright: 2008 James Youngman <jay@gnu.org>
# License: GNU GPL version 2 or later <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>
#
# Additional Author: Greg A. Woods <woods@robohack.ca>
# Copyright: 2019 Greg A. Woods <woods@robohack.ca>
# License: GNU GPL version 2 or later <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>
#
# Import this from SCCS to Git with:
#
# if [ ! -d /work/woods/g-git-sccsimport/.git ]; then
# mkdir -p /work/woods/g-git-sccsimport
# cd /work/woods/g-git-sccsimport
# git init
# hub create robohack/git-sccsimport
# fi
# cd ~/src
# git-sccsimport --tz=-0800 --stdout --maildomain=robohack.ca SCCS/s.git-sccsimport.py | gsed '0,/^committer [^0-9]* \([0-9]*\) -0800/s//committer Jay Youngman <jay@gnu.org> 1200826930 +0100/' | (cd /work/woods/g-git-sccsimport && git fast-import && git checkout master -- . )
# cd /work/woods/g-git-sccsimport
# git push -u origin master
#
#
# ToDo:
#
# - add controls and defaults for timezones
#
# - fix the calling conventions (command-line API) to be more like:
#
# mkdir my-project-converted-to-git
# cd my-project-converted-to-git
# git init
# git-sccsimport $PROJECTDIR [...]
#
# - support branches? (CSRG did not really use branches [only a few somewhat
# scattered files in all of 4.4BSD-Alpha have branch numbers, and only a very
# few have branch numbers other than "R.L.1.S" (i.e. ".1"), mostly on a few
# release and version identifying files in Sendmail.
#
# - currently branch deltas just appear in chronological order in the git
# commit stream.
#
# - perhaps we could just commit branch deltas to "br-<filename>-R.L.B" refs
# (which are created with a "reset" section)?
#
# - fuzzy commit comparison would work better if delta sorting was smarter,
# e.g. if it could do some kind of "sliding window sort" on the comment text
# over a group of commits.
#
# - can the SCCS "descriptive text" be used and useful in Git?
#
# - what to do with the text from any 'm', 'q', and 't' flags?
#
# - consider incremental import support
#
# - it already essentially works by brute force (full re-import), but it could
# be optimized, and with new calling conventions it might work like:
#
# cd my-project-converted-to-git
# git-sccsimport --incr $PROJECTDIR [...]
#
# - might keep a rev list ala git-cvsimport (or just last rev?)
#
# - or does the last rev's timestamp suffice?
#
# - how does this interact with branches or does it matter?
#
# - this might help in situations where something happens to cause a diverging
# path, e.g. a tag is applied in a different place.
#
# - there probably should be a --quiet option to suppress progress info
#
"""A fast git importer for SCCS files.
It will import deltas collectively from groups of SCCS files into a fresh git
repository using "git fast-import".
How to use this program:
Let's assume you have some SCCS files in $PROJECTDIR and want to convert them to
a git repository in the directory $NEWGIT.
First, make sure the SCCS (or CSSC) binaries are on your $PATH. Then do this:
cd "$PROJECTDIR"
git-sccsimport --init --git-dir="$NEWGIT" --dirs .
Notice that git-sccsimport is being run with its working directory as the root
of the tree of SCCS files. This is because the relative path from your working
directory to the SCCS file is also used as the (path)name of the file in the
resulting git repository.
Since git-sccsimport always does a complete import, and because by default it
tries to merge commits with the same message text and author, it can create a
diverging tip if something weird happens between successive imports to the same
Git repository (e.g. a new matching commit is made, or new tag is implied).
When this happens git-fast-import will warn with a message like the following:
warning: Not updating refs/heads/master (new tip 6e7cd4a1aea270d27f588e3bed356a657bedd358 does not contain 82b901b23b94919807aef4ac65792ca2bd2f9512)
In this case if you must press on then you can reset your branch to the new tip
of the import with "git reset --hard <new-tip>". Note though that this will
cause other clones to see history being rewritten, but here this is intended and
any other clones just have to deal with it.
I tried this on a 32M code repository in SCCS and it produced a 36M git
repository.
"""
import datetime
import errno
import optparse
import os
import os.path
import pwd
import re
import resource
import stat
import string
import subprocess
import sys
import time
from distutils.version import LooseVersion
SCCS_ESCAPE = chr(1)
# this will normally not be used -- see the AuthorMap option....
#
MAIL_DOMAIN = None
DEFAULT_USER_TZ = "+0000"
UNIX_EPOCH = time.mktime(datetime.datetime(1970, 1, 1,
0, 0, 0, 0,
None).timetuple())
IMPORT_REF = None
# Two checkins separated by more than FUZZY_WINDOW will never be considered part
# of the same commit; N.B. even if they have the same non-empty comment,
# commiter, and MRs. (I.e. this can be a relatively large number, e.g. 1 day,
# or even potentially a much longer time, such as a week.)
FUZZY_WINDOW = 24.0 * 60.0 * 60.0 * 7.0
debug = False
verbose = False
DoTags = True
class ImportFailure(Exception):
pass
class CommandFailure(Exception):
pass
class UsageError(Exception):
pass
class AbstractClassError(Exception):
pass
def Usage(who, retval, f, e):
if e:
print >>f, e
print >>f, ("usage: %s sccs-file [sccs-file...]" % (who,))
if retval:
sys.exit(retval)
return retval
def NotImporting(file, sid, reason):
if sid:
msg = ("%s: not importing SID %s: %s"
% (file, sid, reason))
else:
msg = ("%s: not importing this file: %s"
% (file, reason))
print >>sys.stderr, msg
def ReportCommandFailure(command, returncode, errors):
if not errors:
errors = ""
if returncode < 0:
msg = ("%s: killed by signal %s" % (command, -(returncode),))
else:
msg = ("%s: returned exit status %d" % (command, returncode,))
raise CommandFailure, ("%s\n%s" % (errors, msg,))
def RunCommand(commandline):
try:
if debug:
msg = ("Running command: %s\n"
% (" ".join(commandline),))
sys.stderr.write(msg)
child = subprocess.Popen(commandline,
close_fds = True,
stdin =subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
output, errors = child.communicate(None)
# Some stderr output is normal (warnings, etc.)
if child.returncode != 0:
ReportCommandFailure(commandline[0], child.returncode, errors)
else:
if errors and debug:
print >>sys.stderr, ("%s stderr: %s" % (commandline[0], errors,))
return output
except OSError, oe:
msg = ("Failed to run '%s': %s (%s)"
% (commandline[0], oe,
errno.errorcode[oe.errno]))
if debug:
sys.stderr.write(msg + "\n")
raise OSError, msg
# for now we'll also just convert CommandFailure to ImportFailure
except CommandFailure, cmd_failure:
if verbose:
print >>sys.stderr, (cmd_failure)
raise ImportFailure, cmd_failure
def GetBody(sfile, seqno, expand_keywords):
commandline = GET.split(" ")
options = ["-p", "-s", ("-a%d" % (seqno,))]
if not expand_keywords:
options.append("-k")
options.append(sfile)
commandline.extend(options)
return RunCommand(commandline)
def FileMode(filename):
return stat.S_IMODE(os.stat(filename).st_mode)
class SccsFileQueryBase(object):
@staticmethod
def HeaderLines(filename):
header_end = "^%cT" % (SCCS_ESCAPE,)
result = []
try:
f = open(filename, "rb")
for line in f.readlines():
if line.startswith(header_end):
break
else:
result.append(line)
return result
finally:
f.close()
class SccsFileQuerySlow(SccsFileQueryBase):
"""Extract information from SCCS files by running prs."""
@staticmethod
def RunPrs(options):
commandline = PRS.split(" ")
commandline.extend(options)
return RunCommand(commandline)
@staticmethod
def RunVal(options):
commandline = VAL.split(" ")
commandline.extend(options)
return RunCommand(commandline)
@staticmethod
def FetchDeltaProperties(sid, filename):
fmt = (":Dy:/:Dm:/:Dd:%(esc)c" # 0 delta creation date
":Th:::Tm:::Ts:%(esc)c" # 1 delta creation time (24h)
":C:%(esc)c" # 2 checkin comments
":DS:%(esc)c" # 3 seqno
":DP:%(esc)c" # 4 parent seqno
":DT:%(esc)c" # 5 delta type (R or D)
":I:%(esc)c" # 6 SID
":MR:%(esc)c" # 7 MR numbers
":P:%(esc)c" # 8 Perpetrator (committer)
% { 'esc': SCCS_ESCAPE })
cmdline = [("-d%s" % (fmt,)), ("-r%s" % (sid,)), filename]
propdata = SccsFileQuerySlow.RunPrs(cmdline)
#print >>sys.stderr, ("PRS = ", propdata)
return propdata.split(SCCS_ESCAPE)
@staticmethod
def IsValidSccsFile(filename):
try:
output = SccsFileQuerySlow.RunVal([filename])
#print >>sys.stderr, ("%s: %s" % (VAL, output,))
return True
except ImportFailure:
return False
except OSError, oe:
print >>sys.stderr, ("\nVAL failed: %s" % (oe,))
sys.exit(1)
@staticmethod
def GetRevisionList(filename):
revisions = SccsFileQuerySlow.RunPrs(["-d:I: ", "-e", filename])
return revisions.split()
# XXX this is very incomplete! (see "props" array creation)
class SccsFileQueryFast(SccsFileQueryBase):
"""Extract information from SCCS files by parsing them directly."""
DELTA_RE = re.compile("^%cd D ([.0-9]*)" % (SCCS_ESCAPE,))
@staticmethod
def IsValidSccsFile(filename):
"""XXX A very incomplete validation of an SCCS file."""
try:
f = open(filename, "rb")
header = f.read(2)
return header[0] == SCCS_ESCAPE and header[1] == 'h'
finally:
f.close()
@staticmethod
def GetRevisionList(filename):
result = []
header_end = "^%cT" % (SCCS_ESCAPE,)
for line in SccsFileQueryBase.HeaderLines(filename):
m = SccsFileQueryFast.DELTA_RE.match(line)
if m:
result.append(m.group(1))
return result
@staticmethod
def FetchDeltaProperties(sid, filename):
found = False
props = []
comments = []
comment_leader = "%cc" % (SCCS_ESCAPE,)
for line in SccsFileQueryBase.HeaderLines(filename):
if not found:
m = SccsFileQueryFast.DELTA_RE.match(line)
if m and (sid == m.group(1)):
found = True
fields = line.split()
props = [ fields[3], # 0 creation date
fields[4], # 1 creation time
None, # XXX 2 checkin comment
fields[6], # 3 seqno
fields[7], # 4 parent seqno
'D', # XXX 5 delta type (R or D)
fields[2], # 6 SID
"", # XXX 7 MR list
fields[5], # 8 Perpetrator (committer)
"yodel" # XXX ???
]
continue
else:
if found:
if line.startswith(comment_leader):
comments.append(line[3:])
else:
break
if found:
props[2] = "\n".join(comments)
# print >>sys.stderr, "props: %s" % (props,)
return props
else:
return None
def SccsFileQuery():
"""Factory method for objects that query SccsFileQuery objects"""
return SccsFileQuerySlow()
class Delta(object):
"""Represents the properties of an SCCS delta that we
import into git."""
def __init__(self, sccsfile, sid, qif, *args, **kwargs):
super(Delta, self).__init__(*args, **kwargs)
self._sccsfile = sccsfile
self._sid = sid
self._qif = qif
self.FetchDeltaProperties()
def __repr__(self):
return 'Delta(%s, "%s")' % (repr(self._sccsfile), self._sid)
def FetchDeltaProperties(self):
"""Query the properties of this delta from the SCCS file."""
props = self._qif.FetchDeltaProperties(self._sid,
self._sccsfile._filename)
assert len(props)>1, "%s %s %s" % (self._sccsfile._filename, self._sid, props,)
#print >>sys.stderr, ("DeltaProperties: %s"
# % (props))
self.SetTimestamp(props[0], props[1])
(self._comment, self._seqno, self._parent_seqno, self._type,
sidcheck, mrlist, self._committer, _) = props[2:]
#print >>sys.stderr, ("DeltaProperties: %s"
# % (self))
#print >>sys.stderr, ("DeltaProperties: comment:%s"
# % (self._comment))
#print >>sys.stderr, ("DeltaProperties: committer:%s"
# % (self._committer))
self._seqno = int(self._seqno)
self._parent_seqno = int(self._parent_seqno)
if self._comment == "\n":
self._comment = None
assert sidcheck==self._sid
self._mrs = mrlist.split()
self._ui = GetUserInfo(self._committer, MAIL_DOMAIN, DEFAULT_USER_TZ)
def SameFuzzyCommit(self, other):
#print >>sys.stderr, ("SameFuzzyCommit: comparing\n1: %s with\n2: %s"
# % (self, other))
if self._comment != other._comment:
return False
elif self._committer != other._committer:
return False
elif self._mrs != other._mrs:
return False
else:
delta = abs(other._timestamp - self._timestamp)
if delta > FUZZY_WINDOW or self._comment == "":
return False
else:
return True
def SetTimestamp(self, checkin_date, checkin_time):
try:
year, month, monthday = [int(f) for f in checkin_date.split("/")]
except ValueError:
raise ImportFailure, ("Unexpected date format: %s"
% (checkin_date,))
try:
h,m,s = [int(f) for f in checkin_time.split(":")]
except ValueError:
raise ImportFailure, ("Unexpected time format: %s"
% (checkin_time,))
microsec = 0
if year < 100:
# Apply the y2k rule (see the "Year 2000 Issues" section
# of the CSSC documentation).
if year < 69:
year += 2000
else:
year += 1900
cdate = datetime.datetime(year, month, monthday,
h, m, s,
microsec, None)
lt = time.mktime(cdate.timetuple())
#
# XXX the timzone currently defaults to the host's timezone
# (i.e. assuming the import is being done on a machine in the
# same timezone as the original SCCS source server lived)
#
# With the addition of the AuthorMap file ala git-sccsimport
# then we could also adjust timestamps on a per-author basis,
# though that would also probably require use of the magical
# third-party "pytz" module.
#
epoch_offset = time.mktime(time.gmtime(lt)) # convert to UTC
#
# Maybe there could also be some option to change the timezone
# at some date (or list of dates), in order to handle cases
# where the SCCS files moved location. (mostly a special case
# for me, but perhaps others have moved between timezones too)
#
# On 2010/11/04 I arrived in Kelowna from Toronto, so since then
# local timestamps are three hours less than they were, so if
# the timestamp is from before that date, then add three hours.
#
if MoveDate is not None:
mvd = time.mktime(MoveDate.timetuple())
if lt < mvd:
lt += MoveOffset
# We subtract UNIX_EPOCH to take account of the fact
# that the system epoch may in fact not be the same as the Unix
# epoch.
#
# git fast-import requires the timestamp to be measured in
# seconds since the Unix epoch.
#
self._timestamp = epoch_offset - UNIX_EPOCH
def GitTimestamp(self):
n = int(self._timestamp)
# We also pass timezone information from the AuthorMap (or local
# timezone) by setting the appropriate <offutc> value here.
# N.B. the timestamp must still be in UTC -- <offutc> is only
# used to advise formatting of timestamps in log reports and
# such.
return "%d %s" % (n, self._ui.tz,)
def GitComment(self):
"""Format a comment, noting any MRs as 'Issue' numbers"""
comment = "" # commit comment is mandatory
if self._comment:
comment = self._comment
if self._mrs:
comment += "\n"
comment += "Issue"
if len(self._mrs) > 1:
comment += "s"
comment += ": "
comment += ", ".join(map(lambda mr: '#' + mr, self._mrs))
return comment
def SidLevel(self):
return int(self._sid.split(".")[0])
def SidRev(self):
return int(self._sid.split(".")[1])
class SccsFile(object):
def __init__(self, name, *args, **kwargs):
super(SccsFile, self).__init__(*args, **kwargs)
self._filename = name
qif = SccsFileQuery()
revisions = filter(self.GoodRevision, qif.GetRevisionList(name))
self._deltas = [Delta(self, sid, qif) for sid in revisions]
self._gitname = self.GitFriendlyName(self._GottenName())
if FileMode(self._filename) & 0111:
self._gitmode = "755"
else:
self._gitmode = "644"
gitname = property(lambda self: self._gitname)
gitmode = property(lambda self: self._gitmode)
filename = property(lambda self: self._filename)
@staticmethod
def IsValidSccsFile(filename):
qif = SccsFileQuery()
return qif.IsValidSccsFile(filename)
def __repr__(self):
return "SccsFile(r'%s')" % (self._filename,)
@staticmethod
def GitFriendlyName(name):
"""Clean up filenames.
git-fastimport does not like leading or trailing slashes, or
. or .. in file names. This method removes such things.
"""
if os.path.isabs(name):
raise ImportFailure, "%s is an absolute path name" % (name,)
drive, path = os.path.splitdrive(name)
return os.path.normpath(path)
def _GottenName(self):
"""Map SCCS filename to Makefile name.
Convert the name of an SCCS file to the name of the working file
as would be assumed by make.
Specifically, the s. prefix is stripped, and if the s.file is in
a directory called SCCS, that directory is stripped out of the
path also.
"""
head, tail = os.path.split(self._filename)
if tail.startswith("s."):
tail = tail[2:]
dirhead, dirtail = os.path.split(head)
if dirtail == "SCCS":
head = dirhead
return os.path.join(head, tail)
def GoodRevision(self, sid):
comps = sid.split(".")
if len(comps) > 1 and all(int(x) > 0 for x in comps):
return True
else:
NotImporting(self._filename, sid,
"Invalid SID")
return False
class GitImporter(object):
"""Handles communications with git-fast-import."""
def __init__(self, *args, **kwargs):
super(GitImporter, self).__init__(*args, **kwargs)
self._next_mark = 1
self._command = None
self._importer = None
self._write_to_stdout = False
self._used_tags = {}
def StartImporter(self):
args = ["git","fast-import"]
self._command = " ".join(args)
self._importer = subprocess.Popen(args,
close_fds=True,
stdin=subprocess.PIPE)
def SendToStdout(self):
self._command = None
self._importer = None
self._write_to_stdout = True
def GetNextMark(self):
"""Get the next unused idnum for a mark statement."""
result = self._next_mark
self._next_mark += 1
return result
def Write(self, s):
"""Write some data to the importer."""
if self._write_to_stdout:
sys.stdout.write(s)
else:
assert self._importer
self._importer.stdin.write(s)
def Done(self):
if self._importer:
self._importer.stdin.close()
returncode = self._importer.wait()
if returncode != 0:
ReportCommandFailure(self._command, returncode, None)
else:
print >>sys.stderr, ("%s completed successfully"
% (self._command,))
output = RunCommand(["git",
"--git-dir=%s" % (GitDir,),
"--work-tree=%s" % (os.path.dirname(GitDir),),
"gc", "--aggressive"]) # n.b. no --progress option!
if output and verbose:
print >>sys.stderr, ("git gc: %s" % (output,))
output = RunCommand(["git",
"--git-dir=%s" % (GitDir,),
"--work-tree=%s" % (os.path.dirname(GitDir),),
"checkout", "--progress",
IMPORT_REF.rsplit('/', 1)[1], "--", "."])
if output and verbose:
print >>sys.stderr, ("git checkout: %s" % (output,))
def ProgressMsg(self, msg):
"""Emit a progress message for the user."""
sys.stderr.write(msg)
def Progress(self, done, items):
"""Inform the user of our current progress."""
percent = (100.0 * float(done)) / float(items)
if done == items:
tail = " done\n"
else:
tail = ""
msg = "\r %3.0f%% (%d/%d)%s" % (percent, done, items, tail,)
self.ProgressMsg(msg)
def WriteData(self, data):
"""Emit a data command followd by a blob of data."""
self.Write("data %d\n" % (len(data),))
self.Write(data)
self.Write("\n")
def BeginCommit(self, delta, parent):
"""Start a new commit (having the indicated parent)."""
mark = self.GetNextMark()
self.Write("commit %s\nmark :%d\n" % (IMPORT_REF, mark,))
ts = delta.GitTimestamp()
self.Write("committer %s %s\n"
% (delta._ui.email, ts))
# Git's commit a965bb31166d04f3e5c8f7a93569fb73f9a9d749 added
# support for # original-oid in git-fast-import, and "git tag
# --contains a965bb31" tells me this will be v2.21.0 or newer:
#
if LooseVersion(GitVer) >= LooseVersion("v2.21.0"):
self.Write("original-oid %s-%s\n"
% (delta._sccsfile._filename, delta._seqno))
self.WriteData(delta.GitComment())
if parent:
self.Write("from :%d\n" % (parent,))
return mark
def WriteTag(self, pdelta, parent):
"""Write a new Tag for the new SID level."""
# we're tagging the previous release each time we see a new one
relno = pdelta.SidLevel() - 1
tag = ("v%d" % (relno,))
trev = 0
# add a tag "revision" number to avoid cases of "error: multiple
# updates for ref 'refs/tags/v18' not allowed" when release
# levels are not consistently incremented at release time....
if self._used_tags.has_key(tag):
self._used_tags[tag] += 1
trev = self._used_tags[tag]
tag = ("v%d.%d" % (pdelta.SidLevel(), trev,))
else:
self._used_tags[tag] = trev
if verbose:
self.ProgressMsg("\nNEW Tag: %s (for %s: %s)\n"
% (tag, pdelta._sid, pdelta._comment.rstrip(),))
self.Write("tag %s\n" % (tag,))
self.Write("from :%d\n" % (parent,))
ts = pdelta.GitTimestamp()
self.Write("tagger %s %s\n"
% (pdelta._ui.email, ts))
self.WriteData(pdelta.GitComment())
def Filedelete(self, sfile):
"""Write a filedelete section of a commit."""
self.Write("D %s\n" % (sfile.gitname,))
def Filemodify(self, sfile, body):
"""Write a filemodify section of a commit."""
self.Write("M %s inline %s\n" % (sfile.gitmode, sfile.gitname,))
self.WriteData(body)
def CompleteCommit(self):
"""Write the final part of a commit."""
self.Write("\n")
# TODO: if the fuzzy commit logic puts subsequent deltas into the same
# commit, the timestamp of the commit is that of the first delta.
# One could argue that the timestamp of the last one would be a better choice.
def ImportDeltas(imp, deltas):
if not deltas:
raise ImportFailure, "No deltas to import"
first_delta_in_commit = None
done = 0
imp.ProgressMsg("\nCreating commits...\n")
plevel = None
parent = None
pdelta = None
commit_count = 0
write_tag_next = False
for d in deltas:
imp.Progress(done, len(deltas))
done += 1
# Figure out if we need to start a new commit.
if first_delta_in_commit:
if not first_delta_in_commit.SameFuzzyCommit(d):
imp.CompleteCommit()
first_delta_in_commit = None
if DoTags and write_tag_next:
imp.WriteTag(plevel, current - 1)
write_tag_next = False
if plevel and d.SidLevel() > plevel.SidLevel() and d.SidRev() == 1:
write_tag_next = True
if first_delta_in_commit is None:
first_delta_in_commit = d
current = imp.BeginCommit(d, parent)
commit_count += 1
parent = current
if pdelta:
plevel = d
pdelta = d
# We're now in a commit. Emit the body for this delta.
body = GetBody(d._sccsfile._filename, d._seqno, EXPAND_KEYWORDS)
if len(body) == 0:
imp.Filedelete(d._sccsfile)
else:
imp.Filemodify(d._sccsfile, body)
# Finished looping over deltas
if parent:
imp.CompleteCommit()
imp.Progress(done, len(deltas))
imp.ProgressMsg("\nDone.\n")
print >>sys.stderr, ("%d SCCS deltas in %d git commits"
% (len(deltas), commit_count))
def Import(filenames, stdout):
"""Import the indicated SCCS files into git."""
for filename in filenames:
if not os.access(filename, os.R_OK):
msg = "%s is not readable" % (filename,)
raise ImportFailure, msg
if not os.path.isfile(filename):
msg = "%s is not a file" % (filename,)
raise ImportFailure, msg
sccsfiles = []
done = 0
imp = GitImporter()
imp.ProgressMsg("Reading metadata from SCCS files...\n")
for filename in filenames:
try:
imp.Progress(done, len(filenames))
if SccsFile.IsValidSccsFile(filename):
sf = SccsFile(filename)
sccsfiles.append(sf)
else:
NotImporting(filename, None, "not a valid SCCS file")
done += 1
except ImportFailure:
msg = ("\nAn import failure occurred while processing %s"
% (filename,))
print >>sys.stderr, msg
raise
imp.Progress(done, len(filenames))
# Now we have all the metadata; sort the deltas by timestamp
# and import the deltas in time order.
#
delta_list = []
for sfile in sccsfiles:
for delta in sfile._deltas:
ts = "%020d" % (delta._timestamp,)
t = (ts, delta)
delta_list.append(t)
delta_list.sort()
if stdout:
imp.SendToStdout()
else:
imp.StartImporter()
try:
ImportDeltas(imp, [d[1] for d in delta_list])
finally:
imp.Done()
def IsValidGitDir(path):
"""Returns True IFF path is a valid git repo.
Copied from git-p4.
"""
if (os.path.exists(path + "/HEAD")
and os.path.exists(path + "/refs")
and os.path.exists(path + "/objects")):
return True;
return False
def FindGitDir(gitdir, init):
"""Locate the git repository."""
if not gitdir:
gitdir = RunCommand(["git", "rev-parse", "--git-dir"])
if gitdir:
gitdir = gitdir.strip()
else:
cdup = RunCommand(["git", "rev-parse", "--show-cdup"])
if cdup:
gitdir = os.path.abspath(cdup.strip())
else:
gitdir = "."
if init:
# Do a sanity check that we're not about to create /.git.
assert gitdir
if not os.path.exists(gitdir):
try:
os.mkdir(gitdir)
except:
raise ImportFailure ("%s: Unable to create directory"
% (gitdir,))
if not gitdir.endswith("/.git"):
gitdir += "/.git"
if IsValidGitDir(gitdir):
raise ImportFailure, ("Git repository %s was already initialised"
% (gitdir,))
else:
msg = ("Initializing repository: git --git-dir=%s init"
% (gitdir,))
print >>sys.stderr, msg
output = RunCommand(["git", "--git-dir=%s" % (gitdir,), "init"])
if output and verbose:
print >>sys.stderr, ("git init: %s" % (output,))
if not IsValidGitDir(gitdir):
gitdir += "/.git"
if not IsValidGitDir(gitdir):
raise ImportFailure, ("cannot locate git repository at %s"
% (gitdir,))
print >>sys.stderr, ("git repository: %s"
% (gitdir,))
return gitdir
def MakeDirWorklist(dirs):
result = []
for dirname in dirs:
# XXX it would be good to be able to report errors herein,
# especially permission denied, etc....
for root, subdirs, files in os.walk(dirname):
for f in files:
if f.startswith("s."):
physpath = os.path.join(root, f)
if os.access(physpath, os.R_OK):
result.append(physpath)
if not result:
print >>sys.stderr, ("Warning: No SCCS files were found in %s"
% (" ".join(dirs)))
return result
# The author map should match the format of git-cvsimport:
#
# XXX currently the [time/zone] option requires the ISO8601 basic format,
# i.e. "[+-]hhmm", e.g. "-0800".
#
# <username>=Full Name <email@addre.ss> [time/zone]
#
# e.g.:
#
# exon=Andreas Ericsson <ae@op5.se>
# spawn=Simon Pawn <spawn@frog-pond.org> -0400
#
# Comment lines, beginning with a '#', are ignored.
#
class UserInfo():
def __init__(self, login, email, tz):
self.login = login
self.email = email
self.tz = tz
def GetAuthorMap(filename):
map = {}
with open(filename, 'r') as fd:
for line in fd:
if line[0] == '#':
continue
(k, v) = line.split('=')
v = v.strip()
if not v:
# ignore usernames with no info
continue
sp = v.rsplit(None, 1)
tz = DEFAULT_USER_TZ
if sp[-1].find('/') > -1:
tz = FindUTCOffset(sp[-1]) # XXX ToDo ???
v = sp[0]
elif sp[-1][0] == '+' or sp[-1][0] == '-':
assert int(sp[-1])
tz = sp[-1]
v = sp[0]
map[k.strip()] = UserInfo(k, v, tz)
return map
def GitUser(username, login_name, mail_domain):
# xxx actually username is optional to git-fast-import too!
if mail_domain:
return "%s <%s@%s>" % (username, login_name, mail_domain,)
return "%s <%s>" % (username, login_name,)
def GetUserInfo(login_name, mail_domain, tz):
"""Get a user's info corresponding to the given login name."""
if AuthorMap:
return AuthorMap.get(login_name,
UserInfo(login_name,
GitUser(login_name, login_name, mail_domain),