-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
2309 lines (2205 loc) · 79.3 KB
/
main.go
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
package main
// gitp4transfer program
// This processes a git fast-export file and writes the following:
// * a journal file with p4 records (written in 2004.2 format for simplicity)
// * accompanying archive/depot files per revision.
// Note that the latter use CText filetype (compressed) rather than RCS
//
// Design:
// The main loop GitParse():
// Reads the next record from the git file using libfastimport
// Blobs are sent to a channel to be compressed and saved using their Mark (ID) as a filename
// The idea is to write them to disk ASAP and later on to rename the files to their final
// name and then release the file to GC - we want to avoid using up too much memory!
// Other commands are processed and collected per GitCommit (e.g. File Modify/Delete/Rename/Copy records
// are attached to the Commit).
// As each Commit is processed, journal records are written.
//
// Global data structures:
// * Hash of GitCommit records
// * Hash of Blob records (without actual data)
// * Hash of GitFile action records
//
// Notes:
// * Plastic SCM writes git fast-export files that are invalid for git! Thus we have to filter records
// and handle anomalies, e.g.
// - rename of a file already renamed
// - delete of a file which has been renamed already
// - etc.
import (
"bufio"
"compress/gzip"
"errors"
"fmt"
"io" // profiling only
_ "net/http/pprof" // profiling only
"os"
"path"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"sync"
"time"
"github.com/alitto/pond"
"github.com/emicklei/dot"
"github.com/h2non/filetype"
"github.com/h2non/filetype/types"
"github.com/rcowham/gitp4transfer/config"
journal "github.com/rcowham/gitp4transfer/journal"
node "github.com/rcowham/gitp4transfer/node"
libfastimport "github.com/rcowham/go-libgitfastimport"
"github.com/perforce/p4prometheus/version"
"github.com/sirupsen/logrus"
"gopkg.in/alecthomas/kingpin.v2"
)
var defaultP4user = "git-user" // Default user if non found
func Humanize(b int) string {
const unit = 1000
if b < unit {
return fmt.Sprintf("%d B", b)
}
div, exp := int(unit), 0
for n := b / unit; n >= unit; n /= unit {
div *= unit
exp++
}
return fmt.Sprintf("%.1f %cB",
float64(b)/float64(div), "kMGTPE"[exp])
}
type GitParserOptions struct {
config *config.Config
gitImportFile string
archiveRoot string
dryRun bool
dummyArchives bool
caseInsensitive bool // If true then create case insensitive checkpoint for Linux and lowercase archive files
convertCRLF bool // If true then convert CRLF to just LF
graphFile string
maxCommits int
debugCommit int // For debug breakpoint
}
type GitAction int
const (
unknown GitAction = iota
modify
delete
copy
rename
)
func (a GitAction) String() string {
return [...]string{"Unknown", "Modify", "Delete", "Copy", "Rename"}[a]
}
// Performs simple hash
func getBlobIDPath(rootDir string, blobID int) (dir string, name string) {
n := fmt.Sprintf("%08d", blobID)
d := path.Join(rootDir, n[0:2], n[2:5], n[5:8])
n = path.Join(d, n)
return d, n
}
func writeBlob(rootDir string, blobID int, data *string) error {
dir, name := getBlobIDPath(rootDir, blobID)
err := os.MkdirAll(dir, 0777)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to create1 %s: %v", dir, err)
return err
}
f, err := os.Create(name)
if err != nil {
return err
}
defer f.Close()
fmt.Fprint(f, *data)
if err != nil {
return err
}
return nil
}
var gitFileID = 0 // Unique ID - set by newGitFile
// GitBlob - wrapper around CmdBlob
type GitBlob struct {
blob *libfastimport.CmdBlob
compressed bool
baseFileType journal.FileType // Base type when file is only known as a Blob
hasData bool
dataRemoved bool
saved bool
lock sync.RWMutex
blobDirPath string
blobFileName string // Temporary storage location once read
gitFileIDs []int // list of gitfiles referring to this blob
}
func newGitBlob(blob *libfastimport.CmdBlob) *GitBlob {
b := &GitBlob{blob: blob, hasData: true, gitFileIDs: make([]int, 0), baseFileType: journal.CText}
if blob != nil { // Construct a suitable filename
filename := fmt.Sprintf("%07d", b.blob.Mark)
b.blobFileName = filename
b.blobDirPath = path.Join(filename[:1], filename[1:4])
}
return b
}
type GitFileMap map[int]*GitFile // Maps Gitfile ID to *GF
type BlobMap map[int]*GitBlob // Maps Blob ID to *blob
// BlobFileMatcher - maps blobs to files and vice versa
type BlobFileMatcher struct {
logger *logrus.Logger
gitFileMap GitFileMap
blobMap BlobMap
}
func newBlobFileMatcher(logger *logrus.Logger) *BlobFileMatcher {
return &BlobFileMatcher{logger: logger, gitFileMap: GitFileMap{}, blobMap: BlobMap{}}
}
func (m *BlobFileMatcher) addBlob(b *GitBlob) {
if _, ok := m.blobMap[b.blob.Mark]; !ok {
m.blobMap[b.blob.Mark] = b
} else {
m.logger.Errorf("Found duplicate blob: %d", b.blob.Mark)
}
}
func (m *BlobFileMatcher) addGitFile(gf *GitFile) {
if _, ok := m.gitFileMap[gf.ID]; !ok {
m.gitFileMap[gf.ID] = gf
} else {
m.logger.Errorf("Found duplicate gitfile: %d", gf.ID)
}
found := false
for _, id := range gf.blob.gitFileIDs {
if id == gf.ID {
found = true
break
}
}
if found {
return
}
gf.blob.gitFileIDs = append(gf.blob.gitFileIDs, gf.ID) // Multiple gitFiles can reference same blob
if len(gf.blob.gitFileIDs) > 1 {
gf.duplicateArchive = true
}
}
func (m *BlobFileMatcher) removeGitFile(gf *GitFile) {
if gf.blob == nil {
return
}
oldIDs := gf.blob.gitFileIDs
gf.blob.gitFileIDs = make([]int, 0)
for _, id := range oldIDs {
if id != gf.ID {
gf.blob.gitFileIDs = append(gf.blob.gitFileIDs, id) // Multiple gitFiles can reference same blob
}
}
}
func (m *BlobFileMatcher) getBlob(blobID int) *GitBlob {
if b, ok := m.blobMap[blobID]; ok {
return b
} else {
m.logger.Errorf("Failed to find blob: %d", blobID)
return nil
}
}
// For a GitFile which is a duplicate, copies the original lbrFile/lbrRev
func (m *BlobFileMatcher) updateDuplicateGitFile(gf *GitFile) {
b, ok := m.blobMap[gf.blob.blob.Mark]
if !ok {
gf.logger.Errorf("Failed to find GitFile ID1: %d %s", gf.blob.blob.Mark, gf.p4.depotFile)
return
}
if len(b.gitFileIDs) == 0 {
gf.logger.Errorf("Failed to find GitFile ID2: %d %s", gf.blob.blob.Mark, gf.p4.depotFile)
return
}
origGF, ok := m.gitFileMap[b.gitFileIDs[0]]
if !ok {
gf.logger.Errorf("Failed to find GitFile ID: %d %s", b.gitFileIDs[0], gf.p4.depotFile)
return
}
gf.p4.lbrFile = origGF.p4.lbrFile
gf.p4.lbrRev = origGF.p4.lbrRev
gf.logger.Debugf("Duplicate file %s %d of: %s %d", gf.p4.depotFile, gf.p4.rev, gf.p4.lbrFile, gf.p4.lbrRev)
if gf.p4.lbrFile == "" {
gf.logger.Errorf("Invalid referenced lbrFile in duplicate %s %d", gf.p4.depotFile, gf.p4.rev)
}
}
// GitFile - A git file record - modify/delete/copy/move
type GitFile struct {
name string // Git filename (target for rename/copy)
srcName string // Name of git source file for rename/copy
ID int
size int
p4 *P4File
duplicateArchive bool
action GitAction
actionInvalid bool // Set to true if this is overriden by a later action in same commit
isBranch bool
isMerge bool
isDirtyRename bool // Rename where content changed in same commit
isPseudoRename bool // Rename where source file should not be deleted as updated in same commit
baseFileType journal.FileType // baseFileType means Text or Binary
fileType journal.FileType // fileType includes typemap matching
compressed bool
blob *GitBlob
logger *logrus.Logger
commit *GitCommit
}
// Information for a P4File
type P4File struct {
depotFile string // Full depot path
rev int // Depot rev
lbrRev int // Lbr rev - usually same as Depot rev
lbrFile string // Lbr file - usually same as Depot file
srcDepotFile string // Depot path of source for a rename or a branched file
srcRev int // Rev of source for a rename or a branched file
origTargDepotFile string // For branched/merged rename - Depot path of original target of the rename
origTargDepotRev int // For branched/merged rename - rev of original target of the rename
origSrcDepotFile string // For branched/merged rename - Depot path of original source of the rename
origSrcDepotRev int // For branched/merged rename - rev of original target of the rename
archiveFile string
p4action journal.FileAction
}
func newGitFile(gf *GitFile) *GitFile {
gitFileID += 1
gf.ID = gitFileID
if gf.baseFileType == 0 {
gf.baseFileType = journal.CText // Default - may be overwritten later
}
gf.p4 = &P4File{}
gf.updateFileDetails()
return gf
}
// GitCommit - A git commit
type GitCommit struct {
commit *libfastimport.CmdCommit
user string
branch string // branch name
prevBranch string // set if first commit on new branch
parentBranch string // set to ancestor of current branch
mergeBranch string // set if commit is a merge - assumes only 1 merge candidate!
commitSize int // Size of all files in this commit - useful for memory sizing
gNode dot.Node // Optional link to GraphizNode
files []*GitFile
}
// HasPrefix tests whether the string s begins with prefix (or is prefix)
func hasPrefix(s, prefix string) bool {
return len(s) >= len(prefix) && s[0:len(prefix)] == prefix
}
// This expands on above to require original is longer!
func hasDirPrefix(s, prefix string, caseInsensitive bool) bool {
if caseInsensitive {
return len(s) > len(prefix) && strings.EqualFold(s[0:len(prefix)], prefix)
}
return len(s) > len(prefix) && s[0:len(prefix)] == prefix
}
func getUserFromEmail(email string) string {
if email == "" {
return defaultP4user
}
parts := strings.Split(email, "@")
if len(parts) > 0 && parts[0] != "" {
return parts[0]
}
return defaultP4user
}
func newGitCommit(commit *libfastimport.CmdCommit, commitSize int) *GitCommit {
user := getUserFromEmail(commit.Author.Email)
gc := &GitCommit{commit: commit, user: user, commitSize: commitSize, files: make([]*GitFile, 0)}
gc.branch = strings.Replace(commit.Ref, "refs/heads/", "", 1)
if hasPrefix(gc.branch, "refs/tags") || hasPrefix(gc.branch, "refs/remote") {
gc.branch = ""
}
return gc
}
func (gc *GitCommit) findGitFile(name string) *GitFile {
for _, gf := range gc.files {
if gf.name == name {
return gf
}
}
return nil
}
func (gc *GitCommit) ref() string {
return fmt.Sprintf("%s:%d", gc.branch, gc.commit.Mark)
}
type CommitMap map[int]*GitCommit
type RevChange struct { // Struct to remember revs and changes per depotFile
rev int
chgNo int
lbrRev int // Normally same as chgNo but not for renames/copies, and for deletes is of previous version
lbrFile string // Normally same as depotFile byt not for renames/copies
action GitAction
}
type BranchRegex struct {
nameRegex *regexp.Regexp
prefix string
}
// BranchNameMapper - maps blobs to files and vice versa
type BranchNameMapper struct {
branchMaps []BranchRegex
}
func newBranchNameMapper(config *config.Config) *BranchNameMapper {
bm := &BranchNameMapper{
branchMaps: make([]BranchRegex, 0),
}
if config == nil {
return bm
}
for _, m := range config.BranchMappings {
br := BranchRegex{
nameRegex: regexp.MustCompile(m.Name),
prefix: m.Prefix,
}
bm.branchMaps = append(bm.branchMaps, br)
}
return bm
}
func (bm *BranchNameMapper) branchName(name string) string {
for _, m := range bm.branchMaps {
if m.nameRegex.MatchString(name) {
return m.prefix + name
}
}
return name
}
// GitP4Transfer - Transfer via git fast-export file
type GitP4Transfer struct {
logger *logrus.Logger
gitChan chan GitCommit
opts GitParserOptions
depotFileRevs map[string]*RevChange // Map depotFile to latest rev/chg
depotFileTypes map[string]journal.FileType // Map depotFile#rev to filetype (for renames/branching)
blobFileMatcher *BlobFileMatcher // Map between gitfile ID and record
commits map[int]*GitCommit
testInput string // For testing only
graph *dot.Graph // If outputting a graph
filesOnBranch map[string]*node.Node // Records current state of git tree per branch
branchNameMapper *BranchNameMapper
}
func NewGitP4Transfer(logger *logrus.Logger, opts *GitParserOptions) (*GitP4Transfer, error) {
g := &GitP4Transfer{logger: logger,
opts: *opts,
depotFileRevs: make(map[string]*RevChange),
blobFileMatcher: newBlobFileMatcher(logger),
depotFileTypes: make(map[string]journal.FileType),
commits: make(map[int]*GitCommit),
filesOnBranch: make(map[string]*node.Node),
branchNameMapper: newBranchNameMapper(opts.config)}
return g, nil
}
// Convert a branch name to a full depot path (using global options)
func (gf *GitFile) getDepotPath(opts GitParserOptions, mapper *BranchNameMapper, branch string, name string) string {
bname := mapper.branchName(branch)
if len(opts.config.ImportPath) == 0 {
return fmt.Sprintf("//%s/%s/%s", opts.config.ImportDepot, bname, name)
} else {
return fmt.Sprintf("//%s/%s/%s/%s", opts.config.ImportDepot, opts.config.ImportPath, bname, name)
}
}
// Sets the depot path according to branch name and whether this is a branched file
func (gf *GitFile) setDepotPaths(opts GitParserOptions, mapper *BranchNameMapper, fileRevs *map[string]*RevChange, gc *GitCommit) {
gf.commit = gc
gf.p4.depotFile = gf.getDepotPath(opts, mapper, gc.branch, gf.name)
if gf.srcName != "" {
gf.p4.srcDepotFile = gf.getDepotPath(opts, mapper, gc.branch, gf.srcName)
} else if gc.prevBranch != "" {
gf.srcName = gf.name
gf.isBranch = true
gf.p4.srcDepotFile = gf.getDepotPath(opts, mapper, gc.prevBranch, gf.srcName)
}
if gc.mergeBranch != "" && gc.mergeBranch != gc.branch {
if gf.srcName == "" {
srcDepotFile := gf.getDepotPath(opts, mapper, gc.mergeBranch, gf.name)
if fr, ok := (*fileRevs)[srcDepotFile]; ok {
if gf.action == delete {
if fr.action == delete {
gf.isMerge = true
}
} else if fr.action != delete {
gf.isMerge = true
}
}
if gf.isMerge {
gf.srcName = gf.name
gf.p4.srcDepotFile = srcDepotFile
}
} else {
gf.isMerge = true
}
}
}
// Sets compression option and distinguishes binary/text according to mimetype or extension
func (b *GitBlob) setCompressionDetails() types.Type {
b.baseFileType = journal.CText
b.compressed = true
l := len(b.blob.Data)
if l > 261 {
l = 261
}
head := []byte(b.blob.Data[:l])
kind, _ := filetype.Match(head)
if filetype.IsImage(head) || filetype.IsVideo(head) || filetype.IsArchive(head) || filetype.IsAudio(head) {
b.baseFileType = journal.UBinary
b.compressed = false
return kind
}
if filetype.IsDocument(head) {
b.baseFileType = journal.Binary
kind, _ := filetype.Match(head)
switch kind.Extension {
case "docx", "dotx", "potx", "ppsx", "pptx", "vsdx", "vstx", "xlsx", "xltx":
b.compressed = false
}
}
return kind
}
// Sets p4 action
func (gf *GitFile) updateFileDetails() {
switch gf.action {
case delete:
gf.p4.p4action = journal.Delete
return
case rename:
gf.p4.p4action = journal.Rename
return
case modify:
gf.p4.p4action = journal.Edit
}
}
func getOID(dataref string) (int, error) {
if !strings.HasPrefix(dataref, ":") {
return 0, errors.New("invalid dataref")
}
return strconv.Atoi(dataref[1:])
}
// SaveBlob will save it to a temp dir, e.g. 1234567 -> 1/234/1234567[.gz]
// Later the file will be moved to the required depot location
// Uses a provided pool to get concurrency
// Allow for dummy data to be saved (used to speed up large conversions to check structure)
func (b *GitBlob) SaveBlob(pool *pond.WorkerPool, opts GitParserOptions, matcher *BlobFileMatcher) error {
if b.blob == nil || !b.hasData {
matcher.logger.Debugf("NoBlobToSave")
return nil
}
b.lock.Lock()
kind := b.setCompressionDetails()
matcher.logger.Debugf("BlobFileType: %d: %s MIME:%s", b.blob.Mark, b.baseFileType, kind.MIME.Value)
// Do the work in pool worker threads for concurrency, especially with compression
rootDir := path.Join(opts.archiveRoot, b.blobDirPath)
if b.compressed {
fname := path.Join(rootDir, fmt.Sprintf("%s.gz", b.blobFileName))
matcher.logger.Debugf("SavingBlobCompressed: %s", fname)
var data string
data = b.blob.Data
if opts.dummyArchives {
data = fmt.Sprintf("%d", b.blob.Mark)
}
b.lock.Unlock()
pool.Submit(
func(b *GitBlob, rootDir string, fname string, data string) func() {
return func() {
err := os.MkdirAll(rootDir, 0755)
if err != nil {
matcher.logger.Errorf("failed mkdir: %s %v", rootDir, err)
return
}
f, err := os.Create(fname)
if err != nil {
matcher.logger.Errorf("failed create: %s %v", fname, err)
return
}
zw := gzip.NewWriter(f)
b.lock.Lock()
defer b.lock.Unlock()
_, err = zw.Write([]byte(data))
if err != nil {
matcher.logger.Errorf("failed write: %s %v", fname, err)
return
}
err = zw.Close()
if err != nil {
matcher.logger.Errorf("failed zipclose: %s %v", fname, err)
}
err = f.Close()
if err != nil {
matcher.logger.Errorf("failed close: %s %v", fname, err)
return
}
b.saved = true
b.blob.Data = "" // Allow contents to be GC'ed
b.dataRemoved = true
}
}(b, rootDir, fname, data))
} else {
fname := path.Join(rootDir, b.blobFileName)
matcher.logger.Debugf("SavingBlobNotCompressed: %s", fname)
data := b.blob.Data
b.lock.Unlock()
if opts.dummyArchives {
data = fmt.Sprintf("%d", b.blob.Mark)
}
pool.Submit(
func(b *GitBlob, rootDir string, fname string, data string) func() {
return func() {
err := os.MkdirAll(rootDir, 0755)
if err != nil {
matcher.logger.Errorf("failed mkdir: %s %v", rootDir, err)
return
}
f, err := os.Create(fname)
if err != nil {
matcher.logger.Errorf("failed create: %s %v", fname, err)
return
}
b.lock.Lock()
defer b.lock.Unlock()
fmt.Fprint(f, data)
if err != nil {
matcher.logger.Errorf("failed write: %s %v", fname, err)
return
}
err = f.Close()
if err != nil {
matcher.logger.Errorf("failed close: %s %v", fname, err)
return
}
b.saved = true
b.blob.Data = "" // Allow contents to be GC'ed
b.dataRemoved = true
}
}(b, rootDir, fname, data))
}
return nil
}
// readZipFile - used when converting CRLF->LF - assume text files small enough to be read into memory
func readZipFile(fname string) (string, error) {
f, err := os.Open(fname)
if err != nil {
return "", err
}
defer f.Close()
gz, err := gzip.NewReader(f)
if err != nil {
return "", err
}
buf, err := io.ReadAll(gz)
if err != nil {
return "", err
}
if err := gz.Close(); err != nil {
return "", err
}
return string(buf), err
}
// writeToFile - write contents to file
func writeToFile(fname, contents string) error {
f, err := os.Create(fname)
if err != nil {
return err
}
_, err = fmt.Fprint(f, contents)
if err != nil {
_ = f.Close()
return err
}
err = f.Close()
return err
}
// readFile - assume text files small enough to be read into memory
func readFile(fname string) (string, error) {
f, err := os.Open(fname)
if err != nil {
return "", err
}
buf, err := io.ReadAll(f)
if err != nil {
return "", err
}
if err := f.Close(); err != nil {
return "", err
}
return string(buf), nil
}
// CreateArchiveFile - Rename the saved blob to appropriate archive file as required
func (gf *GitFile) CreateArchiveFile(pool *pond.WorkerPool, opts *GitParserOptions, matcher *BlobFileMatcher, changeNo int) {
if gf.action == delete || (gf.action == rename && !gf.isDirtyRename && !gf.isPseudoRename) ||
gf.blob == nil || !gf.blob.hasData {
return
}
// Fix wildcards
depotFile := journal.ReplaceWildcards(gf.p4.depotFile[2:])
if opts.caseInsensitive {
depotFile = strings.ToLower(depotFile)
}
depotRoot := opts.archiveRoot
rootDir := path.Join(depotRoot, fmt.Sprintf("%s,d", depotFile))
if gf.blob.blobFileName == "" {
gf.logger.Errorf("NoBlobFound: %s", depotFile)
return
}
bname := path.Join(depotRoot, gf.blob.blobDirPath, gf.blob.blobFileName)
fname := path.Join(rootDir, fmt.Sprintf("1.%d", changeNo))
if gf.compressed {
bname = path.Join(depotRoot, gf.blob.blobDirPath, fmt.Sprintf("%s.gz", gf.blob.blobFileName))
fname = path.Join(rootDir, fmt.Sprintf("1.%d.gz", changeNo))
}
convertCRLF := false
if opts.convertCRLF && (gf.fileType == journal.UText || gf.fileType == journal.CText) {
convertCRLF = true
}
gf.logger.Debugf("CreateArchiveFile: %s -> %s, %v", bname, fname, convertCRLF)
err := os.MkdirAll(rootDir, 0755)
if err != nil {
gf.logger.Errorf("Failed to Mkdir: %s - %v", rootDir, err)
return
}
// Rename the archive file for first copy, expect a duplicate otherwise and save references to it
// By submitting to the pool we allow files to be written first (we hope!)
if !gf.duplicateArchive {
if pool != nil {
pool.Submit(
func(gf *GitFile, bname string, fname string, convertCRLF bool) func() {
return func() {
for {
loopCount := 0
gf.blob.lock.RLock()
if !gf.blob.saved {
gf.logger.Warnf("Waiting for blob to be saved: %d", gf.blob.blob.Mark)
gf.blob.lock.RUnlock()
time.Sleep(1 * time.Second)
loopCount += 1
if loopCount > 60 {
gf.logger.Errorf("Rename wait failed: %d seconds", loopCount)
break
}
} else {
gf.blob.lock.RUnlock()
break
}
}
if !convertCRLF {
err = os.Rename(bname, fname)
if err != nil {
gf.logger.Errorf("Failed to Rename after waiting: %v", err)
} else {
gf.logger.Debugf("CreateArchiveFile1 - renamed: %s", fname)
}
} else {
// Instead of renaming them we have to rewrite the CRLF, optionally unzipping and zipping again
if gf.compressed {
data, err := readZipFile(bname)
if err != nil {
gf.logger.Errorf("Failed to readZipFile: %s %v", bname, err)
return
}
f, err := os.Create(fname)
if err != nil {
gf.logger.Errorf("Failed to create2: %s %v", fname, err)
return
}
zw := gzip.NewWriter(f)
_, err = zw.Write([]byte(strings.ReplaceAll(data, "\r\n", "\n")))
if err != nil {
gf.logger.Errorf("Failed to write1: %s %v", fname, err)
}
err = zw.Close()
if err != nil {
gf.logger.Errorf("Failed to zipclose: %s %v", fname, err)
}
err = f.Close()
if err != nil {
gf.logger.Errorf("Failed to close: %s %v", fname, err)
} else {
gf.logger.Debugf("CreateArchiveFile2 - renamed zip: %s", fname)
}
} else {
data, err := readFile(bname)
if err != nil {
gf.logger.Errorf("Failed to read: %s %v", fname, err)
} else {
err = writeToFile(fname, strings.ReplaceAll(data, "\r\n", "\n"))
if err != nil {
gf.logger.Errorf("Failed to write2: %s %v", fname, err)
} else {
gf.logger.Debugf("CreateArchiveFile3 - renamed: %s", fname)
}
}
}
// As we copied the file, lets's delete the original
err = os.Remove(bname)
if err != nil {
gf.logger.Errorf("Failed to remove: %v", err)
}
}
}
}(gf, bname, fname, convertCRLF))
} else {
if !convertCRLF {
err = os.Rename(bname, fname)
if err != nil {
gf.logger.Errorf("Failed to Rename: %v", err)
} else {
gf.logger.Debugf("CreateArchiveFile4 - renamed: %s", fname)
}
} else {
// Instead of renaming them we have to rewrite the CRLF, optionally unzipping and zipping again
if gf.compressed {
data, err := readZipFile(bname)
if err != nil {
gf.logger.Errorf("Failed to readZipFile: %s %v", bname, err)
return
}
f, err := os.Create(fname)
if err != nil {
gf.logger.Errorf("Failed to create3: %s %v", fname, err)
return
}
zw := gzip.NewWriter(f)
_, err = zw.Write([]byte(strings.ReplaceAll(data, "\r\n", "\n")))
if err != nil {
gf.logger.Errorf("Failed to write3: %s %v", fname, err)
}
err = zw.Close()
if err != nil {
gf.logger.Errorf("Failed to zipclose: %s %v", fname, err)
}
err = f.Close()
if err != nil {
gf.logger.Errorf("Failed to close: %s %v", fname, err)
} else {
gf.logger.Debugf("CreateArchiveFile5 - renamed zip: %s", fname)
}
} else {
data, err := readFile(bname)
if err != nil {
gf.logger.Errorf("Failed to readFile: %s %v", bname, err)
return
}
err = writeToFile(fname, strings.ReplaceAll(data, "\r\n", "\n"))
if err != nil {
gf.logger.Errorf("Failed to write4: %s %v", fname, err)
} else {
gf.logger.Debugf("CreateArchiveFile6 - renamed: %s", fname)
}
}
// As we copied the file, lets's delete the original
err = os.Remove(bname)
if err != nil {
gf.logger.Errorf("Failed to remove: %v", err)
}
}
}
}
}
func minval(val, min int) int { // Minimum of specified val or min
if val < min {
return min
}
return val
}
// WriteJournal writes journal record for a GitFile
func (gf *GitFile) WriteJournal(j *journal.Journal, c *GitCommit) {
dt := int(c.commit.Author.Time.Unix())
chgNo := c.commit.Mark
fileType := gf.fileType
if fileType == 0 {
fileType = gf.baseFileType
if fileType == 0 {
gf.logger.Errorf("Unexpected filetype text: %s#%d", gf.p4.depotFile, gf.p4.rev)
fileType = journal.CText
}
}
if gf.action == modify {
if gf.isBranch || gf.isMerge {
// we write rev for newly branched depot file, with link to old version
action := journal.Add
if gf.p4.rev > 1 { // TODO
action = journal.Edit
}
j.WriteRev(gf.p4.depotFile, gf.p4.rev, action, fileType, chgNo, gf.p4.lbrFile, gf.p4.lbrRev, dt)
startFromRev := gf.p4.srcRev - 1
endFromRev := gf.p4.srcRev
startToRev := gf.p4.rev - 1
endToRev := gf.p4.rev
j.WriteInteg(gf.p4.depotFile, gf.p4.srcDepotFile, startFromRev, endFromRev, startToRev, endToRev, journal.BranchFrom, journal.DirtyBranchInto, c.commit.Mark)
} else {
j.WriteRev(gf.p4.depotFile, gf.p4.rev, gf.p4.p4action, fileType, chgNo, gf.p4.lbrFile, gf.p4.lbrRev, dt)
}
} else if gf.action == delete {
if gf.isMerge {
j.WriteRev(gf.p4.depotFile, gf.p4.rev, gf.p4.p4action, fileType, chgNo, gf.p4.lbrFile, gf.p4.lbrRev, dt)
startFromRev := gf.p4.srcRev - 1
endFromRev := gf.p4.srcRev
startToRev := gf.p4.rev - 1
endToRev := gf.p4.rev
j.WriteInteg(gf.p4.depotFile, gf.p4.srcDepotFile, startFromRev, endFromRev, startToRev, endToRev, journal.DeleteFrom, journal.DeleteInto, c.commit.Mark)
} else {
j.WriteRev(gf.p4.depotFile, gf.p4.rev, gf.p4.p4action, fileType, chgNo, gf.p4.lbrFile, gf.p4.lbrRev, dt)
}
} else if gf.action == rename {
if gf.isBranch { // Rename of a branched file - create integ records from parent
if !gf.isPseudoRename {
// Branched rename from dev -> main
// Original file was dev/src
// Branched as main/src -> main/targ
// Create a delete rev for main/src
j.WriteRev(gf.p4.srcDepotFile, gf.p4.srcRev, journal.Delete, fileType, chgNo, gf.p4.lbrFile, gf.p4.lbrRev, dt)
// WriteInteg(toFile string, fromFile string, startFromRev int, endFromRev int, startToRev int, endToRev int,
// how IntegHow, reverseHow IntegHow, chgNo int)
startFromRev := 0
endFromRev := gf.p4.origSrcDepotRev
startToRev := 0
endToRev := gf.p4.rev
// We create DeleteFrom integ between dev/src and main/src
j.WriteInteg(gf.p4.srcDepotFile, gf.p4.origSrcDepotFile, startFromRev, endFromRev, startToRev, endToRev, journal.DeleteFrom, journal.DeleteInto, c.commit.Mark)
}
j.WriteRev(gf.p4.depotFile, gf.p4.rev, journal.Add, fileType, chgNo, gf.p4.lbrFile, gf.p4.lbrRev, dt)
startFromRev := gf.p4.origSrcDepotRev - 1
endFromRev := gf.p4.origSrcDepotRev
startToRev := gf.p4.rev - 1
endToRev := gf.p4.rev
// We create BranchFrom integ between dev/targ and main/targ
j.WriteInteg(gf.p4.depotFile, gf.p4.origSrcDepotFile, startFromRev, endFromRev, startToRev, endToRev, journal.BranchFrom, journal.BranchInto, c.commit.Mark)
} else if gf.isMerge { // Merging a rename
// Merge rename from dev -> main
// Original rename was dev/src -> dev/targ
// Merged as main/src -> main/targ
// Setup integ BranchFrom dev/targ -> main/targ
startFromRev := 0
endFromRev := gf.p4.origTargDepotRev
startToRev := minval(gf.p4.rev-1, 0)
endToRev := gf.p4.rev
if gf.isPseudoRename {
endFromRev = gf.p4.srcRev // Not deleted for pseudo rename
} else {
j.WriteRev(gf.p4.srcDepotFile, gf.p4.srcRev, journal.Delete, fileType, chgNo, gf.p4.lbrFile, gf.p4.lbrRev, dt)
// Integ DeleteFrom dev/src -> main/src, otherwise just do a normal rename
if gf.p4.origSrcDepotFile != "" {
startFromRev := 0
endFromRev := gf.p4.origSrcDepotRev
startToRev := gf.p4.srcRev - 1
endToRev := gf.p4.srcRev
j.WriteInteg(gf.p4.srcDepotFile, gf.p4.origSrcDepotFile, startFromRev, endFromRev, startToRev, endToRev, journal.DeleteFrom, journal.DeleteInto, c.commit.Mark)
}
}
j.WriteRev(gf.p4.depotFile, gf.p4.rev, journal.Add, fileType, chgNo, gf.p4.lbrFile, gf.p4.lbrRev, dt)
if gf.p4.origTargDepotFile != "" { // Merged rename
j.WriteInteg(gf.p4.depotFile, gf.p4.origTargDepotFile, startFromRev, endFromRev, startToRev, endToRev, journal.BranchFrom, journal.BranchInto, c.commit.Mark)
} else { // Simple rename
startFromRev := minval(gf.p4.srcRev-2, 0)
endFromRev := gf.p4.srcRev - 1
startToRev := gf.p4.rev - 1
endToRev := gf.p4.rev
j.WriteInteg(gf.p4.depotFile, gf.p4.srcDepotFile, startFromRev, endFromRev, startToRev, endToRev, journal.BranchFrom, journal.BranchInto, c.commit.Mark)
}
} else { // Simple renamed file
startFromRev := minval(gf.p4.srcRev-2, 0)
endFromRev := gf.p4.srcRev - 1
startToRev := gf.p4.rev - 1
endToRev := gf.p4.rev
if gf.isPseudoRename {
// The src is not deleted for pseudo/double renames
endFromRev = gf.p4.srcRev
} else {
// Delete src record
j.WriteRev(gf.p4.srcDepotFile, gf.p4.srcRev, journal.Delete, fileType, chgNo, gf.p4.lbrFile, gf.p4.lbrRev, dt)
}
j.WriteRev(gf.p4.depotFile, gf.p4.rev, journal.Add, fileType, chgNo, gf.p4.lbrFile, gf.p4.lbrRev, dt)
j.WriteInteg(gf.p4.depotFile, gf.p4.srcDepotFile, startFromRev, endFromRev, startToRev, endToRev, journal.BranchFrom, journal.BranchInto, c.commit.Mark)
}
} else {
gf.logger.Errorf("Unexpected action: %s", gf.action.String())
}
}
// DumpGit - incrementally parse the git file, collecting stats and optionally saving archives as we go
// Useful for parsing very large git fast-export files without loading too much into memory!
func (g *GitP4Transfer) DumpGit(saveFiles bool) {
var buf io.Reader
if g.testInput != "" {
buf = strings.NewReader(g.testInput)
} else {
file, err := os.Open(g.opts.gitImportFile)
if err != nil {
fmt.Printf("ERROR: Failed to open file '%s': %v\n", g.opts.gitImportFile, err)
os.Exit(1)
}
defer file.Close()
buf = bufio.NewReader(file)
}
commits := make(map[int]*GitCommit, 0)
files := make(map[int]*GitFile, 0)
extSizes := make(map[string]int)
var currCommit *GitCommit
var commitSize = 0
f := libfastimport.NewFrontend(buf, nil, nil)
for {
cmd, err := f.ReadCmd()
if err != nil {
if err != io.EOF {
g.logger.Errorf("Failed to read cmd1: %v", err)
panic("Unrecoverable error")
} else {
break
}