-
Notifications
You must be signed in to change notification settings - Fork 1
/
ziphandler.go
1827 lines (1688 loc) · 41.5 KB
/
ziphandler.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 gitserver
import (
"archive/zip"
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"io/fs"
"math/big"
"mime/multipart"
"net/http"
"os"
"path"
"path/filepath"
"regexp"
"sort"
"strings"
"time"
"github.com/omegaup/githttp/v2"
"github.com/omegaup/gitserver/request"
base "github.com/omegaup/go-base/v3"
"github.com/omegaup/go-base/v3/logging"
"github.com/omegaup/go-base/v3/tracing"
"github.com/omegaup/quark/common"
git "github.com/libgit2/git2go/v33"
"github.com/pkg/errors"
)
const (
maxAllowedZipSize = 200 * base.Mebibyte
slowQueueThresholdDuration = base.Duration(time.Duration(30) * time.Second)
// OverallWallTimeHardLimit is the absolute maximum wall time that problems
// are allowed to have.
OverallWallTimeHardLimit = base.Duration(time.Duration(60) * time.Second)
)
// A ZipMergeStrategy represents the strategy to use when merging the trees of
// a .zip upload and its parent.
type ZipMergeStrategy int
const (
// ZipMergeStrategyOurs will use the parent commit's tree as-is without even
// looking at the contents of the .zip or doing any kind of merge. This is
// exactly what what git-merge does with '-s ours'.
ZipMergeStrategyOurs ZipMergeStrategy = iota
// ZipMergeStrategyTheirs will use the tree that was contained in the .zip
// as-is without even looking at the parent tree or doing any kind of merge.
// This the opposite of ZipMergeStrategyOurs, and has no equivalent in
// git-merge.
ZipMergeStrategyTheirs
// ZipMergeStrategyStatementsOurs will keep the statements/ subtree from the
// parent commit as-is, and replace the rest of the tree with the contents of
// the .zip file.
ZipMergeStrategyStatementsOurs
// ZipMergeStrategyRecursiveTheirs will merge the contents of the .zip file
// with the parent commit's tree, preferring whatever is present in the .zip
// file. This is similar to what git-merge does with `-srecursive -Xtheirs`.
ZipMergeStrategyRecursiveTheirs
)
var (
defaultGitfiles = map[string]string{
".gitignore": `# OS-specific resources
.DS_Store
Thumbs.db
# Backup files
*~
*.bak
*.swp
*.orig
# Packaged files
*.zip
*.bz2
# Karel
*.kx
# Python
*.pyc
# IDE files
*.cbp
*.depend
*.layout
# Compiled Object files
*.slo
*.lo
*.o
*.obj
*.hi
# Precompiled Headers
*.gch
*.pch
# Compiled Dynamic libraries
*.so
*.dylib
*.dll
# Fortran module files
*.mod
# Compiled Static libraries
*.lai
*.la
*.a
*.lib
# Executables
*.exe
*.app
# libinteractive files
Makefile
libinteractive/
libinteractive.jar
`,
".gitattributes": GitAttributesContents,
}
casesRegexp = regexp.MustCompile("^cases/([^/]+)\\.in$")
)
func (z ZipMergeStrategy) String() string {
switch z {
case ZipMergeStrategyOurs:
return "ours"
case ZipMergeStrategyTheirs:
return "theirs"
case ZipMergeStrategyStatementsOurs:
return "statement-ours"
case ZipMergeStrategyRecursiveTheirs:
return "recursive-theirs"
}
return ""
}
// ParseZipMergeStrategy returns the corresponding ZipMergeStrategy for the provided name.
func ParseZipMergeStrategy(name string) (ZipMergeStrategy, error) {
switch name {
case "ours":
return ZipMergeStrategyOurs, nil
case "theirs":
return ZipMergeStrategyTheirs, nil
case "statement-ours":
return ZipMergeStrategyStatementsOurs, nil
case "recursive-theirs":
return ZipMergeStrategyRecursiveTheirs, nil
}
return ZipMergeStrategyOurs, errors.Errorf("invalid value for ZipMergeStrategy: %q", name)
}
// UpdatedFile represents an updated file. Type is either "added", "deleted",
// or "modified".
type UpdatedFile struct {
Path string `json:"path"`
Type string `json:"type"`
}
type byPath []UpdatedFile
func (p byPath) Len() int { return len(p) }
func (p byPath) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func (p byPath) Less(i, j int) bool { return p[i].Path < p[j].Path }
// UpdateResult represents the result of running this command.
type UpdateResult struct {
Status string `json:"status"`
Error string `json:"error,omitempty"`
UpdatedRefs []githttp.UpdatedRef `json:"updated_refs,omitempty"`
UpdatedFiles []UpdatedFile `json:"updated_files"`
}
func getAllFilesForCommit(
ctx context.Context,
repo *git.Repository,
commitID *git.Oid,
) (map[string]*git.Oid, error) {
defer tracing.FromContext(ctx).StartSegment("getAllFilesForCommit").End()
if commitID.IsZero() {
return map[string]*git.Oid{}, nil
}
commit, err := repo.LookupCommit(commitID)
if err != nil {
return nil, base.ErrorWithCategory(
ErrInternalGit,
errors.Wrapf(
err,
"failed to lookup commit %s",
commitID.String(),
),
)
}
defer commit.Free()
tree, err := commit.Tree()
if err != nil {
return nil, base.ErrorWithCategory(
ErrInternalGit,
errors.Wrapf(
err,
"failed to lookup commit %s",
commitID.String(),
),
)
}
defer tree.Free()
commitFiles := make(map[string]*git.Oid)
err = tree.Walk(func(name string, entry *git.TreeEntry) error {
if entry.Type != git.ObjectBlob {
return nil
}
filename := path.Join(name, entry.Name)
commitFiles[filename] = entry.Id
return nil
})
if err != nil {
return nil, base.ErrorWithCategory(
ErrInternalGit,
errors.Wrapf(
err,
"failed to traverse tree for commit %s",
commitID.String(),
),
)
}
return commitFiles, nil
}
// GetUpdatedFiles returns the files that were updated in the master branch.
func GetUpdatedFiles(
ctx context.Context,
repo *git.Repository,
updatedRefs []githttp.UpdatedRef,
) ([]UpdatedFile, error) {
defer tracing.FromContext(ctx).StartSegment("GetUpdatedFiles").End()
var masterUpdatedRef *githttp.UpdatedRef
for _, updatedRef := range updatedRefs {
if updatedRef.Name != "refs/heads/master" {
continue
}
masterUpdatedRef = &updatedRef
break
}
if masterUpdatedRef == nil {
return nil, base.ErrorWithCategory(
ErrInternalGit,
errors.New("failed to find the updated master ref"),
)
}
fromCommitID, err := git.NewOid(masterUpdatedRef.From)
if err != nil {
return nil, base.ErrorWithCategory(
ErrInternalGit,
errors.Wrapf(
err,
"failed to parse the old OID '%s'",
masterUpdatedRef.From,
),
)
}
toCommitID, err := git.NewOid(masterUpdatedRef.To)
if err != nil {
return nil, base.ErrorWithCategory(
ErrInternalGit,
errors.Wrapf(
err,
"failed to parse the new OID '%s'",
masterUpdatedRef.To,
),
)
}
fromIDs, err := getAllFilesForCommit(ctx, repo, fromCommitID)
if err != nil {
return nil, base.ErrorWithCategory(
ErrInternalGit,
errors.Wrapf(
err,
"failed to get the old files for commit %s",
fromCommitID.String(),
),
)
}
toIDs, err := getAllFilesForCommit(ctx, repo, toCommitID)
if err != nil {
return nil, base.ErrorWithCategory(
ErrInternalGit,
errors.Wrapf(
err,
"failed to get the new files for commit %s",
toCommitID.String(),
),
)
}
var updatedFiles []UpdatedFile
// Deleted files.
for filename := range fromIDs {
if _, ok := toIDs[filename]; !ok {
updatedFiles = append(updatedFiles, UpdatedFile{
Path: filename,
Type: "deleted",
})
}
}
// Added / modified files.
for filename, toID := range toIDs {
if fromID, ok := fromIDs[filename]; ok {
if !fromID.Equal(toID) {
updatedFiles = append(updatedFiles, UpdatedFile{
Path: filename,
Type: "modified",
})
}
} else {
updatedFiles = append(updatedFiles, UpdatedFile{
Path: filename,
Type: "added",
})
}
}
sort.Sort(byPath(updatedFiles))
return updatedFiles, nil
}
// isValidProblemFile returns whether a file is considered to be part of a
// problem layout.
func isValidProblemFile(filename string) bool {
for _, commitDescription := range DefaultCommitDescriptions {
for _, pathRegexp := range commitDescription.PathRegexps {
if pathRegexp.MatchString(filename) {
return true
}
}
}
return false
}
// CreatePackfile creates a packfile that contains a commit that contains the
// specified contents plus a subset of the parent commit's tree, depending of
// the value of zipMergeStrategy.
func CreatePackfile(
ctx context.Context,
contents map[string]io.Reader,
settings *common.ProblemSettings,
zipMergeStrategy ZipMergeStrategy,
repo *git.Repository,
parent *git.Oid,
author, committer *git.Signature,
commitMessage string,
w io.Writer,
log logging.Logger,
) (*git.Oid, error) {
defer tracing.FromContext(ctx).StartSegment("CreatePackfile").End()
odb, err := repo.Odb()
if err != nil {
return nil, base.ErrorWithCategory(
ErrInternalGit,
errors.Wrap(
err,
"failed to create a new object database",
),
)
}
defer odb.Free()
looseObjectsDir, err := os.MkdirTemp("", fmt.Sprintf("loose_objects_%s", path.Base(repo.Path())))
if err != nil {
return nil, errors.Wrap(
err,
"failed to create temporary directory for loose objects",
)
}
defer os.RemoveAll(looseObjectsDir)
looseObjectsBackend, err := git.NewOdbBackendLoose(looseObjectsDir, -1, false, 0, 0)
if err != nil {
return nil, base.ErrorWithCategory(
ErrInternalGit,
errors.Wrap(
err,
"failed to create a new loose object backend",
),
)
}
if err := odb.AddBackend(looseObjectsBackend, 999); err != nil {
looseObjectsBackend.Free()
return nil, base.ErrorWithCategory(
ErrInternalGit,
errors.Wrap(
err,
"failed to register loose object backend",
),
)
}
// trees will contain a map of top-level entries (strings) to a map of full
// pathnames to io.Readers. This will be used to create individual trees that
// will then be spliced using a git.TreeBuilder.
trees := make(map[string]map[string]io.Reader)
topLevelEntries := make(map[string]*git.Oid)
// .gitattributes is always overwritten.
delete(contents, ".gitattributes")
if zipMergeStrategy != ZipMergeStrategyOurs &&
zipMergeStrategy != ZipMergeStrategyRecursiveTheirs {
if settings != nil {
// If we were given an explicit settings object, that takes
// precedence over whatever was bundled in the .zip.
} else if r, ok := contents["settings.json"]; ok {
settings = &common.ProblemSettings{}
if err := json.NewDecoder(r).Decode(settings); err != nil {
return nil, base.ErrorWithCategory(
ErrJSONParseError,
errors.Wrap(
err,
"failed to parse settings.json",
),
)
}
} else {
settings = &common.ProblemSettings{
Limits: common.DefaultLimits,
Slow: false,
Validator: common.ValidatorSettings{
Name: common.ValidatorNameTokenCaseless,
},
}
}
delete(contents, "settings.json")
// Information needed to build ProblemSettings.Cases.
caseWeightMapping := common.NewCaseWeightMapping()
for filename := range contents {
casesMatches := casesRegexp.FindStringSubmatch(filename)
if casesMatches == nil {
continue
}
caseName := casesMatches[1]
caseWeightMapping.AddCaseName(caseName, big.NewRat(1, 1), false)
}
if r, ok := contents["testplan"]; ok {
zipGroupSettings := caseWeightMapping
caseWeightMapping, err = common.NewCaseWeightMappingFromTestplan(r)
if err != nil {
return nil, base.ErrorWithCategory(
ErrInvalidTestplan,
err,
)
}
// Validate that the files in the testplan are all present in the .zip file.
if err := zipGroupSettings.SymmetricDiff(caseWeightMapping, ".zip"); err != nil {
return nil, base.ErrorWithCategory(
ErrInvalidTestplan,
err,
)
}
// ... and viceversa.
if err := caseWeightMapping.SymmetricDiff(zipGroupSettings, "testplan"); err != nil {
return nil, base.ErrorWithCategory(
ErrInvalidTestplan,
err,
)
}
}
// Remove this file since it's redundant with settings.json.
delete(contents, "testplan")
// Update the problem settings.
settings.Cases = caseWeightMapping.ToGroupSettings()
}
// libinteractive samples don't require an .out file. Generate one just for
// validation's sake.
for filename := range contents {
if !strings.HasPrefix(filename, "interactive/examples/") || !strings.HasSuffix(filename, ".in") {
continue
}
filename = strings.TrimSuffix(filename, ".in") + ".out"
if _, ok := contents[filename]; !ok {
contents[filename] = bytes.NewReader([]byte{})
}
}
for filename, r := range contents {
if !isValidProblemFile(filename) {
continue
}
if strings.HasPrefix(filename, "interactive/examples/") {
// we move the libinteractive examples to the examples/ directory.
filename = strings.TrimPrefix(filename, "interactive/")
}
if strings.HasPrefix(filename, "examples/") || strings.HasPrefix(filename, "cases/") {
normalizedReader, err := NormalizeCase(r)
if err != nil {
// removeBOM already wrapped the error correctly.
return nil, err
}
r = normalizedReader
} else if (strings.HasPrefix(filename, "statements/") || strings.HasPrefix(filename, "solutions/")) &&
(strings.HasSuffix(filename, ".markdown") || strings.HasSuffix(filename, ".md")) {
utfReader, err := ConvertMarkdownToUTF8(r)
if err != nil {
return nil, base.ErrorWithCategory(
ErrInvalidMarkup,
errors.Wrapf(
err,
"failed to convert %s to UTF-8",
filename,
),
)
}
r = utfReader
}
if !strings.Contains(filename, "/") {
blobContents, err := io.ReadAll(r)
if err != nil {
return nil, base.ErrorWithCategory(
ErrInternalGit,
errors.Wrapf(
err,
"failed to read file %s",
filename,
),
)
}
oid, err := repo.CreateBlobFromBuffer(blobContents)
if err != nil {
return nil, base.ErrorWithCategory(
ErrInternalGit,
errors.Wrapf(
err,
"failed to create blob for %s",
filename,
),
)
}
topLevelEntries[filename] = oid
} else {
components := strings.SplitN(filename, "/", 2)
topLevelComponent := components[0]
componentSubpath := components[1]
if _, ok := trees[topLevelComponent]; !ok {
trees[topLevelComponent] = make(map[string]io.Reader)
}
trees[topLevelComponent][componentSubpath] = r
}
}
if settings != nil {
var buf bytes.Buffer
encoder := json.NewEncoder(&buf)
encoder.SetIndent("", "\t")
if err := encoder.Encode(settings); err != nil {
return nil, base.ErrorWithCategory(
ErrInternal,
errors.Wrap(
err,
"failed to marshal settings.json",
),
)
}
oid, err := repo.CreateBlobFromBuffer(buf.Bytes())
if err != nil {
return nil, base.ErrorWithCategory(
ErrInternalGit,
errors.Wrap(
err,
"failed to create blob for settings.json",
),
)
}
topLevelEntries["settings.json"] = oid
}
// Some default, useful files to have.
for filename, contents := range defaultGitfiles {
if _, ok := topLevelEntries[filename]; ok {
continue
}
oid, err := repo.CreateBlobFromBuffer([]byte(contents))
if err != nil {
return nil, base.ErrorWithCategory(
ErrInternalGit,
errors.Wrapf(
err,
"failed to create blob for %s",
filename,
),
)
}
topLevelEntries[filename] = oid
}
treebuilder, err := repo.TreeBuilder()
if err != nil {
return nil, base.ErrorWithCategory(
ErrInternalGit,
errors.Wrap(
err,
"failed to create treebuilder",
),
)
}
defer treebuilder.Free()
for topLevelComponent, files := range trees {
log.Debug(
"Building top-level tree",
map[string]any{
"name": topLevelComponent,
"files": files,
},
)
tree, err := githttp.BuildTree(repo, files, log)
if err != nil {
return nil, base.ErrorWithCategory(
ErrInternalGit,
errors.Wrapf(
err,
"failed to build tree for %s",
topLevelComponent,
),
)
}
treeID := tree.Id()
tree.Free()
if err = treebuilder.Insert(topLevelComponent, treeID, 040000); err != nil {
return nil, base.ErrorWithCategory(
ErrInternalGit,
errors.Wrapf(
err,
"failed to insert tree %s into treebuilder",
topLevelComponent,
),
)
}
}
for topLevelComponent, oid := range topLevelEntries {
log.Debug(
"Adding top-level file",
map[string]any{
"name": topLevelComponent,
"id": oid.String(),
},
)
if err = treebuilder.Insert(topLevelComponent, oid, 0100644); err != nil {
return nil, base.ErrorWithCategory(
ErrInternalGit,
errors.Wrapf(
err,
"failed to insert file %s into treebuilder",
topLevelComponent,
),
)
}
}
var parentCommits []*git.Commit
var parentTree *git.Tree
if !parent.IsZero() {
parentCommit, err := repo.LookupCommit(parent)
if err != nil {
return nil, base.ErrorWithCategory(
ErrInternalGit,
errors.Wrapf(
err,
"failed to find parent commit %s",
parent,
),
)
}
defer parentCommit.Free()
parentCommits = append(parentCommits, parentCommit)
parentTree, err = parentCommit.Tree()
if err != nil {
return nil, base.ErrorWithCategory(
ErrInternalGit,
errors.Wrapf(
err,
"failed to find tree for parent commit %s",
parent,
),
)
}
defer parentTree.Free()
if zipMergeStrategy == ZipMergeStrategyStatementsOurs {
// This merge strategy takes the whole statements subtree as-is, so we
// avoid performing an actual tree merge.
for i := uint64(0); i < parentTree.EntryCount(); i++ {
entry := parentTree.EntryByIndex(i)
if entry.Name != "statements" {
continue
}
if err = treebuilder.Insert(entry.Name, entry.Id, entry.Filemode); err != nil {
return nil, base.ErrorWithCategory(
ErrInternalGit,
errors.Wrapf(
err,
"failed to insert file %s into treebuilder",
entry.Name,
),
)
}
}
}
}
treeID, err := treebuilder.Write()
if err != nil {
return nil, base.ErrorWithCategory(
ErrInternalGit,
errors.Wrap(
err,
"failed to create merged tree",
),
)
}
if parentTree != nil && (zipMergeStrategy == ZipMergeStrategyOurs ||
zipMergeStrategy == ZipMergeStrategyRecursiveTheirs) {
// If we could not do the easy merge strategies (theirs and
// statement-ours), we need to perform an actual merge of the trees.
// Regardless of which of the two merge strategies was chosen, we will be
// choosing the files in the recently created tree because we have already
// filtered out all of the files that should not have been in the tree.
tree, err := repo.LookupTree(treeID)
if err != nil {
return nil, base.ErrorWithCategory(
ErrInternalGit,
errors.Wrap(
err,
"failed to lookup recently-created tree",
),
)
}
defer tree.Free()
mergedTree, err := githttp.MergeTrees(
repo,
tree,
parentTree,
)
if err != nil {
return nil, base.ErrorWithCategory(
ErrInternalGit,
errors.Wrap(
err,
"failed to merge tree",
),
)
}
defer mergedTree.Free()
treeID = mergedTree.Id()
}
log.Debug(
"Final tree created",
map[string]any{
"id": treeID.String(),
},
)
tree, err := repo.LookupTree(treeID)
if err != nil {
return nil, base.ErrorWithCategory(
ErrInternalGit,
errors.Wrap(
err,
"failed to find newly merged tree",
),
)
}
defer tree.Free()
newCommitID, err := repo.CreateCommit(
"",
author,
committer,
commitMessage,
tree,
parentCommits...,
)
if err != nil {
return nil, base.ErrorWithCategory(
ErrInternalGit,
errors.Wrap(
err,
"failed to create merged commit",
),
)
}
walk, err := repo.Walk()
if err != nil {
return nil, base.ErrorWithCategory(
ErrInternalGit,
errors.Wrap(
err,
"failed to create revwalk",
),
)
}
defer walk.Free()
for _, parentCommit := range parentCommits {
if err := walk.Hide(parentCommit.Id()); err != nil {
return nil, base.ErrorWithCategory(
ErrInternalGit,
errors.Wrapf(
err,
"failed to hide commit %s", parentCommit.Id().String(),
),
)
}
}
if err := walk.Push(newCommitID); err != nil {
return nil, base.ErrorWithCategory(
ErrInternalGit,
errors.Wrapf(
err,
"failed to add commit %s", newCommitID.String(),
),
)
}
pb, err := repo.NewPackbuilder()
if err != nil {
return nil, base.ErrorWithCategory(
ErrInternalGit,
errors.Wrap(
err,
"failed to create packbuilder",
),
)
}
defer pb.Free()
if err := pb.InsertWalk(walk); err != nil {
return nil, base.ErrorWithCategory(
ErrInternalGit,
errors.Wrap(
err,
"failed to insert walk into packbuilder",
),
)
}
if err := pb.Write(w); err != nil {
return nil, base.ErrorWithCategory(
ErrInternalGit,
errors.Wrap(
err,
"failed to write packfile",
),
)
}
return newCommitID, nil
}
func getUpdatedProblemSettings(
ctx context.Context,
problemSettings *common.ProblemSettings,
repo *git.Repository,
parent *git.Oid,
) (*common.ProblemSettings, error) {
defer tracing.FromContext(ctx).StartSegment("getUpdatedProblemSettings").End()
parentCommit, err := repo.LookupCommit(parent)
if err != nil {
return nil, base.ErrorWithCategory(
ErrInternalGit,
errors.Wrapf(
err,
"failed to find parent commit %s",
parent.String(),
),
)
}
defer parentCommit.Free()
parentTree, err := parentCommit.Tree()
if err != nil {
return nil, base.ErrorWithCategory(
ErrInternalGit,
errors.Wrapf(
err,
"failed to find tree for parent commit %s",
parentCommit.Id(),
),
)
}
defer parentTree.Free()
var updatedProblemSettings common.ProblemSettings
entry := parentTree.EntryByName("settings.json")
if entry == nil {
return nil, base.ErrorWithCategory(
ErrInternalGit,
errors.New("failed to find settings.json"),
)
}
blob, err := repo.LookupBlob(entry.Id)
if err != nil {
return nil, base.ErrorWithCategory(
ErrInternalGit,
errors.Wrap(
err,
"failed to lookup settings.json",
),
)
}
defer blob.Free()
if err := json.Unmarshal(blob.Contents(), &updatedProblemSettings); err != nil {
return nil, base.ErrorWithCategory(
ErrJSONParseError,
errors.Wrap(
err,
"settings.json",
),
)
}
updatedProblemSettings.Limits = problemSettings.Limits
updatedProblemSettings.Validator.Name = problemSettings.Validator.Name
updatedProblemSettings.Validator.GroupScorePolicy = problemSettings.Validator.GroupScorePolicy
updatedProblemSettings.Validator.Tolerance = problemSettings.Validator.Tolerance
updatedProblemSettings.Validator.Limits = problemSettings.Validator.Limits
return &updatedProblemSettings, nil
}
// ConvertZipToPackfile receives a .zip file from the caller and converts it
// into a git packfile that can be used to update the repository.
func ConvertZipToPackfile(
ctx context.Context,
problemFiles common.ProblemFiles,
settings *common.ProblemSettings,
zipMergeStrategy ZipMergeStrategy,
repo *git.Repository,
parent *git.Oid,
author, committer *git.Signature,
commitMessage string,
acceptsSubmissions bool,
w io.Writer,
log logging.Logger,
) (*git.Oid, error) {
defer tracing.FromContext(ctx).StartSegment("ConvertZipToPackfile").End()
contents := make(map[string]io.Reader)
inCases := make(map[string]struct{})
outCases := make(map[string]struct{})
hasStatements := false
hasEsStatement := false
if zipMergeStrategy != ZipMergeStrategyOurs {
for _, zipfilePath := range problemFiles.Files() {
components := strings.Split(zipfilePath, "/")
topLevelComponent := components[0]
if zipMergeStrategy == ZipMergeStrategyStatementsOurs &&
topLevelComponent == "statements" {
continue
}
isValidFile := false
for _, description := range DefaultCommitDescriptions {
if description.ContainsPath(zipfilePath) {
isValidFile = true
break