-
Notifications
You must be signed in to change notification settings - Fork 1
/
handler.go
1956 lines (1810 loc) · 51 KB
/
handler.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 (
"bytes"
"context"
"encoding/json"
stderrors "errors"
"fmt"
"math"
"math/big"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"regexp"
"strings"
"time"
"unicode/utf8"
"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 (
iterationLabel = "Iteration: "
objectLimit = 10000
// GitAttributesContents is what the .gitattributes and info/attributes files
// contain.
GitAttributesContents = "cases/* -diff -delta -merge -text -crlf\n"
)
var (
// ErrNotAReview is returned if a merge to master is attempted and does not
// come from a review commit.
ErrNotAReview = stderrors.New("not-a-review")
// ErrJSONParseError is returned if one of the JSON files fails to be parsed.
ErrJSONParseError = stderrors.New("json-parse-error")
// ErrChangeMissingSettingsJSON is returned if the settings.json file is missing.
ErrChangeMissingSettingsJSON = stderrors.New("change-missing-settings-json")
// ErrPublishedNotFromMaster is returned if an update to the published branch
// is attempted and the new reference does not point to a commit in the
// master branch.
ErrPublishedNotFromMaster = stderrors.New("published-must-point-to-commit-in-master")
// ErrConfigSubdirectoryMissingTarget is returned if a 'subdirectory'
// publishing config is missing a 'target' entry.
ErrConfigSubdirectoryMissingTarget = stderrors.New("config-subdirectory-missing-target")
// ErrConfigInvalidPublishingMode is returned if a publishing config is not
// 'subdirectory' or 'mirror'.
ErrConfigInvalidPublishingMode = stderrors.New("config-invalid-publishing-mode")
// ErrConfigRepositoryNotAbsoluteURL is returned if a publishing config does
// not have a valid, absolute URL for 'repository'.
ErrConfigRepositoryNotAbsoluteURL = stderrors.New("config-repository-not-absolute-url")
// ErrConfigBadLayout is returned if the refs/meta/config structure does not
// contain the correct layout.
ErrConfigBadLayout = stderrors.New("config-bad-layout")
// ErrTestsBadLayout is returned if the tests/ directory does not contain the
// correct layout.
ErrTestsBadLayout = stderrors.New("tests-bad-layout")
// ErrInteractiveBadLayout is returned if the interactive/ directory does not
// contain the correct layout.
ErrInteractiveBadLayout = stderrors.New("interactive-bad-layout")
// ErrProblemBadLayout is returned if the problem structure does not contain the
// correct layout.
ErrProblemBadLayout = stderrors.New("problem-bad-layout")
// ErrReviewBadLayout is returned if the review structure does not contain
// the correct layout.
ErrReviewBadLayout = stderrors.New("review-bad-layout")
// ErrMismatchedInputFile is returned if there is an .in without an .out.
ErrMismatchedInputFile = stderrors.New("mismatched-input-file")
// ErrInternalGit is returned if there is a problem with the git structure.
ErrInternalGit = stderrors.New("internal-git-error")
// ErrInternal is returned if there is an internal error.
ErrInternal = stderrors.New("internal-error")
// ErrTooManyObjects is returned if the packfile has too many objects.
ErrTooManyObjects = stderrors.New("too-many-objects-in-packfile")
// ErrInvalidZipFilename is returned if a path in the .zip is invalid.
ErrInvalidZipFilename = stderrors.New("invalid-zip-filename")
// ErrNoStatements is returned if the problem does not have any statements.
ErrNoStatements = stderrors.New("no-statements")
// ErrNoEsStatement is returned if the problem does not have the default
// Spanish statement.
ErrNoEsStatement = stderrors.New("no-es-statement")
// ErrSlowRejected is returned if the maximum runtime would exceed the hard
// limit.
ErrSlowRejected = stderrors.New("slow-rejected")
// ErrInvalidTestplan is returned if the testplan file is not valid.
ErrInvalidTestplan = stderrors.New("invalid-testplan")
// ErrInvalidMarkup is returned if the markup file is not valid.
ErrInvalidMarkup = stderrors.New("invalid-markup")
// DefaultCommitDescriptions describes which files go to which branches.
DefaultCommitDescriptions = []githttp.SplitCommitDescription{
{
ReferenceName: "refs/heads/public",
PathRegexps: []*regexp.Regexp{
regexp.MustCompile("^.gitattributes$"),
regexp.MustCompile("^.gitignore$"),
regexp.MustCompile(`^statements(/[^/]+\.(md|markdown|gif|jpe?g|png|svg|py[23]?|cpp\w*|c|java|kp|kj|in|out))?$`),
regexp.MustCompile("^examples(/[^/]+\\.(in|out))?$"),
regexp.MustCompile("^interactive/Main\\.distrib\\.[a-z0-9]+$"),
regexp.MustCompile("^interactive/examples(/[^/]+\\.(in|out))?$"),
regexp.MustCompile("^validator\\.distrib\\.[a-z]+$"),
regexp.MustCompile("^settings\\.distrib\\.json$"),
},
},
{
ReferenceName: "refs/heads/protected",
PathRegexps: []*regexp.Regexp{
regexp.MustCompile(`^solutions(/[^/]+\.(md|markdown|gif|jpe?g|png|svg|py[23]?|cpp\w*|c|java|kp|kj|in|out))?$`),
regexp.MustCompile("^tests(/.*)?$"),
},
},
{
ReferenceName: "refs/heads/private",
PathRegexps: []*regexp.Regexp{
regexp.MustCompile("^cases(/[^/]+\\.(in|out))?$"),
regexp.MustCompile("^interactive/Main\\.[a-z0-9]+$"),
regexp.MustCompile("^interactive/[^/]+\\.idl$"),
regexp.MustCompile("^validator\\.[a-z0-9]+$"),
regexp.MustCompile("^settings\\.json$"),
},
},
}
// statementExampleBoundaryRegexp is the regular expression that finds all
// example boundary tokens.
statementExampleBoundaryRegexp = regexp.MustCompile(
`(?:\n|^)\s*\|\|(input|output|description|end)\s*(?:\n|$)`,
)
)
// LedgerIteration is an entry in the iteration ledger.
type LedgerIteration struct {
Author string `json:"author"`
Date int64 `json:"date"`
Summary string `json:"summary"`
UUID string `json:"uuid"`
Vote string `json:"vote"`
}
// Range is a range in the source code that is associated with a Comment.
type Range struct {
LineStart int `json:"lineStart"`
LineEnd int `json:"lineEnd"`
ColStart int `json:"colStart"`
ColEnd int `json:"colEnd"`
}
// Comment is a comment in the code review.
type Comment struct {
Author string `json:"author"`
Date int64 `json:"date"`
Done bool `json:"done"`
Filename string `json:"filename"`
IterationUUID string `json:"iterationUuid"`
Message string `json:"message"`
ParentUUID *string `json:"parentUuid"`
Range *Range `json:"range"`
ReplacementSuggestion bool `json:"replacementSuggestion"`
UUID string `json:"uuid"`
}
// PublishingConfig represents the publishing section of config.json in
// refs/meta/config.
type PublishingConfig struct {
Mode string `json:"mode"`
Repository string `json:"repository"`
Target string `json:"target,omitempty"`
Branch string `json:"branch,omitempty"`
}
// MetaConfig represents the contents of config.json in refs/meta/config.
type MetaConfig struct {
Publishing PublishingConfig `json:"publishing"`
}
type gitProtocol struct {
allowDirectPushToMaster bool
hardOverallWallTimeLimit base.Duration
interactiveSettingsCompiler InteractiveSettingsCompiler
log logging.Logger
lockfileManager *githttp.LockfileManager
}
// GitProtocolOpts contains all the possible options to initialize the git protocol.
type GitProtocolOpts struct {
githttp.GitProtocolOpts
AllowDirectPushToMaster bool
HardOverallWallTimeLimit base.Duration
InteractiveSettingsCompiler InteractiveSettingsCompiler
LockfileManager *githttp.LockfileManager
}
// NewGitProtocol creates a new GitProtocol with the provided authorization
// callback.
func NewGitProtocol(opts GitProtocolOpts) *githttp.GitProtocol {
protocol := &gitProtocol{
allowDirectPushToMaster: opts.AllowDirectPushToMaster,
hardOverallWallTimeLimit: opts.HardOverallWallTimeLimit,
interactiveSettingsCompiler: opts.InteractiveSettingsCompiler,
log: opts.Log,
lockfileManager: opts.LockfileManager,
}
opts.AllowNonFastForward = true
opts.UpdateCallback = protocol.validateUpdate
opts.PreprocessCallback = protocol.preprocess
return githttp.NewGitProtocol(opts.GitProtocolOpts)
}
func getProblemSettings(
ctx context.Context,
repo *git.Repository,
tree *git.Tree,
) (*common.ProblemSettings, error) {
defer tracing.FromContext(ctx).StartSegment("getProblemSettings").End()
settingsJSONEntry, err := tree.EntryByPath("settings.json")
if err != nil {
return nil, base.ErrorWithCategory(
ErrChangeMissingSettingsJSON,
err,
)
}
settingsJSONBlob, err := repo.LookupBlob(settingsJSONEntry.Id)
if err != nil {
return nil, base.ErrorWithCategory(
ErrInternalGit,
errors.Wrap(
err,
"failed to lookup blob for settings.json",
),
)
}
defer settingsJSONBlob.Free()
var settings common.ProblemSettings
if err := json.Unmarshal(settingsJSONBlob.Contents(), &settings); err != nil {
return nil, base.ErrorWithCategory(
ErrJSONParseError,
errors.Wrap(
err,
settingsJSONEntry.Name,
),
)
}
return &settings, nil
}
func isSlow(
settings *common.ProblemSettings,
hardOverallWallTimeLimit base.Duration,
) (bool, error) {
if settings.Limits.OverallWallTimeLimit <= slowQueueThresholdDuration {
return false, nil
}
inputCount := 0
for _, group := range settings.Cases {
inputCount += len(group.Cases)
}
maxRunDuration := settings.Limits.TimeLimit + settings.Limits.ExtraWallTime
if settings.Validator.Limits != nil && settings.Validator.Name == common.ValidatorNameCustom {
maxRunDuration += settings.Validator.Limits.TimeLimit + settings.Validator.Limits.ExtraWallTime
}
maxRuntime := base.Duration(
time.Duration(math.Ceil(maxRunDuration.Seconds())*float64(inputCount)) * time.Second,
)
if settings.Limits.OverallWallTimeLimit > hardOverallWallTimeLimit &&
maxRuntime > hardOverallWallTimeLimit {
return false, base.ErrorWithCategory(
ErrSlowRejected,
errors.Errorf(
"rejecting problem: overall wall time limit %s, max runtime %s",
settings.Limits.OverallWallTimeLimit,
maxRuntime,
),
)
}
return maxRuntime >= slowQueueThresholdDuration, nil
}
func extractExampleCasesFromStatement(
statementContents string,
) map[string]*common.LiteralCaseSettings {
examples := make(map[string]*common.LiteralCaseSettings)
lastLabel := ""
lastIndex := 0
var labelMapping []struct {
label, chunk string
}
for _, boundaryIndices := range statementExampleBoundaryRegexp.FindAllStringSubmatchIndex(
statementContents,
-1,
) {
currentLabel := statementContents[boundaryIndices[2]:boundaryIndices[3]]
lastChunk := statementContents[lastIndex:boundaryIndices[0]]
if lastLabel != "" {
labelMapping = append(
labelMapping,
struct {
label, chunk string
}{
label: lastLabel,
chunk: lastChunk,
},
)
}
lastLabel = currentLabel
lastIndex = boundaryIndices[1]
}
for i := 0; i < len(labelMapping)-1; i++ {
if labelMapping[i].label != "input" || labelMapping[i+1].label != "output" {
continue
}
examples[fmt.Sprintf("statement_%03d", len(examples)+1)] = &common.LiteralCaseSettings{
Input: labelMapping[i].chunk,
ExpectedOutput: labelMapping[i+1].chunk,
Weight: big.NewRat(1, 1),
}
}
return examples
}
func extractExampleCases(
ctx context.Context,
repo *git.Repository,
tree *git.Tree,
) (map[string]*common.LiteralCaseSettings, error) {
defer tracing.FromContext(ctx).StartSegment("preprocessMaster").End()
exampleCases := make(map[string]*common.LiteralCaseSettings)
for _, examplesDirectory := range []string{"examples", "interactive/examples"} {
entry, err := tree.EntryByPath(examplesDirectory)
if err != nil {
if git.IsErrorCode(err, git.ErrorCodeNotFound) {
continue
}
return nil, base.ErrorWithCategory(
ErrInternalGit,
errors.Wrapf(
err,
"failed to find the %s directory",
examplesDirectory,
),
)
}
examplesTree, err := repo.LookupTree(entry.Id)
if err != nil {
return nil, base.ErrorWithCategory(
ErrInternalGit,
errors.Wrapf(
err,
"failed to lookup the %s directory",
examplesDirectory,
),
)
}
defer examplesTree.Free()
for i := uint64(0); i < examplesTree.EntryCount(); i++ {
inputEntry := examplesTree.EntryByIndex(i)
if !strings.HasSuffix(inputEntry.Name, ".in") {
continue
}
inputName := inputEntry.Name[:len(inputEntry.Name)-3]
outputEntry := examplesTree.EntryByName(
fmt.Sprintf("%s.out", inputName),
)
if outputEntry == nil {
return nil, base.ErrorWithCategory(
ErrMismatchedInputFile,
errors.Errorf(
"failed to find the output file for %s/%s",
examplesDirectory,
inputEntry.Name,
),
)
}
inputBlob, err := repo.LookupBlob(inputEntry.Id)
if err != nil {
return nil, base.ErrorWithCategory(
ErrInternalGit,
errors.Wrapf(
err,
"failed to lookup input file %s/%s",
examplesDirectory,
inputEntry.Name,
),
)
}
defer inputBlob.Free()
outputBlob, err := repo.LookupBlob(outputEntry.Id)
if err != nil {
return nil, base.ErrorWithCategory(
ErrInternalGit,
errors.Wrapf(
err,
"failed to lookup output file %s/%s",
examplesDirectory,
inputEntry.Name,
),
)
}
defer outputBlob.Free()
exampleCases[inputName] = &common.LiteralCaseSettings{
Input: string(inputBlob.Contents()),
ExpectedOutput: string(outputBlob.Contents()),
Weight: big.NewRat(1, 1),
}
}
}
if len(exampleCases) == 0 {
// If the problem author did not explicitly specify some sample cases,
// let's try to extract them from the statements.
entry, err := tree.EntryByPath("statements")
if err != nil {
return nil, base.ErrorWithCategory(
ErrInternalGit,
errors.Wrap(
err,
"failed to find the statements directory",
),
)
}
statementsTree, err := repo.LookupTree(entry.Id)
if err != nil {
return nil, base.ErrorWithCategory(
ErrInternalGit,
errors.Wrap(
err,
"failed to lookup the statements directory",
),
)
}
defer statementsTree.Free()
for _, statementLanguage := range []string{"es", "en", "pt"} {
statementEntry := statementsTree.EntryByName(
fmt.Sprintf("%s.markdown", statementLanguage),
)
if statementEntry == nil {
continue
}
statementBlob, err := repo.LookupBlob(statementEntry.Id)
if err != nil {
if git.IsErrorCode(err, git.ErrorCodeNotFound) {
continue
}
return nil, base.ErrorWithCategory(
ErrInternalGit,
errors.Wrapf(
err,
"failed to lookup statements/%s.markdown",
statementLanguage,
),
)
}
defer statementBlob.Free()
exampleCases = extractExampleCasesFromStatement(string(statementBlob.Contents()))
if len(exampleCases) > 0 {
break
}
}
}
return exampleCases, nil
}
func validateUpdateMaster(
ctx context.Context,
repo *git.Repository,
newCommit *git.Commit,
allowDirectPush bool,
hardOverallWallTimeLimit base.Duration,
interactiveSettingsCompiler InteractiveSettingsCompiler,
log logging.Logger,
) error {
defer tracing.FromContext(ctx).StartSegment("validateUpdateMaster").End()
it, err := repo.NewReferenceIteratorGlob("refs/changes/*")
if err != nil {
return base.ErrorWithCategory(
ErrInternalGit,
errors.Wrap(
err,
"failed to iterate over refs/changes/* references",
),
)
}
defer it.Free()
var sourceReview string
for {
ref, err := it.Next()
if err != nil {
if git.IsErrorCode(err, git.ErrorCodeIterOver) {
break
}
return base.ErrorWithCategory(
ErrInternalGit,
errors.Wrapf(
err,
"failed to iterate over refs/changes/* references",
),
)
}
defer ref.Free()
if newCommit.Id().Equal(ref.Target()) {
sourceReview = ref.Name()
}
}
if sourceReview == "" && !allowDirectPush {
return ErrNotAReview
}
requestContext := request.FromContext(ctx)
requestContext.Request.ReviewRef = sourceReview
tree, err := newCommit.Tree()
if err != nil {
return base.ErrorWithCategory(
ErrInternalGit,
errors.Wrapf(
err,
"failed to get tree for new commit %s",
newCommit.Id(),
),
)
}
defer tree.Free()
// Statements.
statementsTreeEntry := tree.EntryByName("statements")
if statementsTreeEntry == nil {
return ErrNoStatements
}
if statementsTreeEntry.Type != git.ObjectTree {
return base.ErrorWithCategory(
ErrNoStatements,
errors.New("statements/ directory is not a tree"),
)
}
statementsTree, err := repo.LookupTree(statementsTreeEntry.Id)
if err != nil {
return base.ErrorWithCategory(
ErrInternalGit,
errors.Wrap(
err,
"failed to lookup the statements/ tree",
),
)
}
defer statementsTree.Free()
statementsEsMarkdownEntry := statementsTree.EntryByName("es.markdown")
if statementsEsMarkdownEntry == nil {
return ErrNoEsStatement
}
if statementsEsMarkdownEntry.Type != git.ObjectBlob {
return base.ErrorWithCategory(
ErrNoEsStatement,
errors.New("statements/es.markdown is not a file"),
)
}
// Validate and re-generate the problem settings.
problemSettings, err := getProblemSettings(ctx, repo, tree)
if err != nil {
// getProblemSettings already wrapped the error correctly.
return err
}
// Tests.
testsTreeEntry := tree.EntryByName("tests")
if testsTreeEntry != nil {
if testsTreeEntry.Type != git.ObjectTree {
return base.ErrorWithCategory(
ErrTestsBadLayout,
errors.New("tests/ directory is not a tree"),
)
}
testsTree, err := repo.LookupTree(testsTreeEntry.Id)
if err != nil {
return base.ErrorWithCategory(
ErrInternalGit,
errors.Wrap(
err,
"failed to lookup the tests/ tree",
),
)
}
defer testsTree.Free()
testSettingsJSONEntry := testsTree.EntryByName("tests.json")
if testSettingsJSONEntry == nil {
return base.ErrorWithCategory(
ErrTestsBadLayout,
errors.New("tests/tests.json is missing"),
)
}
testSettingsJSONBlob, err := repo.LookupBlob(testSettingsJSONEntry.Id)
if err != nil {
return base.ErrorWithCategory(
ErrInternalGit,
errors.Wrap(
err,
"failed to lookup tests/tests.json",
),
)
}
defer testSettingsJSONBlob.Free()
var testsSettings common.TestsSettings
{
decoder := json.NewDecoder(bytes.NewReader(testSettingsJSONBlob.Contents()))
decoder.DisallowUnknownFields()
if err := decoder.Decode(&testsSettings); err != nil {
return base.ErrorWithCategory(
ErrJSONParseError,
errors.Wrap(
err,
"tests/tests.json",
),
)
}
}
for _, solutionSettings := range testsSettings.Solutions {
if _, err := testsTree.EntryByPath(solutionSettings.Filename); err != nil {
return base.ErrorWithCategory(
ErrTestsBadLayout,
errors.Wrapf(
err,
"tests/%s is missing",
solutionSettings.Filename,
),
)
}
if solutionSettings.ScoreRange == nil && solutionSettings.Verdict == "" {
return base.ErrorWithCategory(
ErrTestsBadLayout,
errors.Errorf(
"score_range or validator for %s in tests/tests.json should be set",
solutionSettings.Filename,
),
)
}
if solutionSettings.Verdict != "" {
foundVerdict := false
for _, verdict := range common.VerdictList {
if verdict == solutionSettings.Verdict {
foundVerdict = true
break
}
}
if !foundVerdict {
return base.ErrorWithCategory(
ErrTestsBadLayout,
errors.Errorf(
"verdict for %s in tests/tests.json is not valid",
solutionSettings.Filename,
),
)
}
}
}
if testsSettings.InputsValidator != nil {
if _, err := testsTree.EntryByPath(testsSettings.InputsValidator.Filename); err != nil {
return base.ErrorWithCategory(
ErrTestsBadLayout,
errors.Wrapf(
err,
"tests/%s is missing",
testsSettings.InputsValidator.Filename,
),
)
}
}
}
// Interactive settings.
interactiveTreeEntry := tree.EntryByName("interactive")
var mainDistribSourceContents, idlFileContents []byte
if interactiveTreeEntry == nil {
problemSettings.Interactive = nil
} else {
if interactiveTreeEntry.Type != git.ObjectTree {
return base.ErrorWithCategory(
ErrInteractiveBadLayout,
errors.New("interactive/ directory is not a tree"),
)
}
interactiveTree, err := repo.LookupTree(interactiveTreeEntry.Id)
if err != nil {
return base.ErrorWithCategory(
ErrInternalGit,
errors.Wrap(
err,
"failed to lookup the interactive/ tree",
),
)
}
defer interactiveTree.Free()
var moduleName, parentLang, distribLang string
var idlFileOid, mainDistribSourceOid, mainSourceOid *git.Oid
for i := uint64(0); i < interactiveTree.EntryCount(); i++ {
entry := interactiveTree.EntryByIndex(i)
if strings.HasPrefix(entry.Name, "Main.distrib.") {
if distribLang != "" {
return base.ErrorWithCategory(
ErrInteractiveBadLayout,
errors.Errorf(
"multiple Main.distrib sources: Main.distrib.%s and %s",
distribLang,
entry.Name,
),
)
}
distribLang = path.Ext(entry.Name)[1:]
mainDistribSourceOid = entry.Id
} else if strings.HasPrefix(entry.Name, "Main.") {
if parentLang != "" {
return base.ErrorWithCategory(
ErrInteractiveBadLayout,
errors.Errorf(
"multiple Main sources: Main.distrib.%s and %s",
parentLang,
entry.Name,
),
)
}
parentLang = path.Ext(entry.Name)[1:]
mainSourceOid = entry.Id
} else if strings.HasSuffix(entry.Name, ".idl") {
if moduleName != "" {
return base.ErrorWithCategory(
ErrInteractiveBadLayout,
errors.Errorf(
"multiple .idl files: %s.idl and %s",
moduleName,
entry.Name,
),
)
}
moduleName = entry.Name[:len(entry.Name)-4]
idlFileOid = entry.Id
}
}
if moduleName == "" {
return base.ErrorWithCategory(
ErrInteractiveBadLayout,
errors.New("missing .idl file"),
)
}
if parentLang == "" {
return base.ErrorWithCategory(
ErrInteractiveBadLayout,
errors.New("missing Main source file"),
)
}
if distribLang == "" {
mainSourceBlob, err := repo.LookupBlob(mainSourceOid)
if err != nil {
return base.ErrorWithCategory(
ErrInteractiveBadLayout,
errors.Wrapf(
err,
"failed to lookup blob for the main source file: interactive/Main.%s",
parentLang,
),
)
}
defer mainSourceBlob.Free()
mainDistribSourceContents = mainSourceBlob.Contents()
distribPath := fmt.Sprintf("interactive/Main.distrib.%s", parentLang)
requestContext.UpdatedFiles[distribPath] = bytes.NewReader(
mainDistribSourceContents,
)
} else if parentLang != distribLang {
return base.ErrorWithCategory(
ErrInteractiveBadLayout,
errors.Errorf(
"mismatched parent language: Main.%s and Main.distrib.%s",
parentLang,
distribLang,
),
)
} else {
mainDistribSourceBlob, err := repo.LookupBlob(mainDistribSourceOid)
if err != nil {
return base.ErrorWithCategory(
ErrInternalGit,
errors.Wrapf(
err,
"failed to lookup blob for the main distrib source file interactive/Main.distrib.%s",
parentLang,
),
)
}
defer mainDistribSourceBlob.Free()
mainDistribSourceContents = mainDistribSourceBlob.Contents()
}
idlFileBlob, err := repo.LookupBlob(idlFileOid)
if err != nil {
return base.ErrorWithCategory(
ErrInternalGit,
errors.Wrapf(
err,
"failed to lookup blob for the idl file interactive/%s.idl",
moduleName,
),
)
}
defer idlFileBlob.Free()
idlFileContents = idlFileBlob.Contents()
problemSettings.Interactive, err = interactiveSettingsCompiler.GetInteractiveSettings(
bytes.NewReader(idlFileContents),
moduleName,
parentLang,
)
if err != nil {
return base.ErrorWithCategory(
ErrInteractiveBadLayout,
errors.Wrap(
err,
"failed to get the interactive settings",
),
)
}
}
// Validator settings.
var validatorLang string
for i := uint64(0); i < tree.EntryCount(); i++ {
entry := tree.EntryByIndex(i)
if entry.Type != git.ObjectBlob {
continue
}
if !strings.HasPrefix(entry.Name, "validator.") {
continue
}
if validatorLang != "" {
return base.ErrorWithCategory(
ErrProblemBadLayout,
errors.Errorf(
"multiple validator sources: validator.%s and %s",
validatorLang,
entry.Name,
),
)
}
validatorLang = filepath.Ext(entry.Name)[1:]
}
if problemSettings.Validator.Name == common.ValidatorNameCustom {
if validatorLang == "" {
return base.ErrorWithCategory(
ErrProblemBadLayout,
errors.Errorf(
"problem with custom validator missing a validator",
),
)
}
problemSettings.Validator.Lang = &validatorLang
problemSettings.Validator.Name = common.ValidatorNameCustom
} else if validatorLang != "" {
return base.ErrorWithCategory(
ErrProblemBadLayout,
errors.Errorf(
"problem requested using validator %s, but has an unused validator.%s file",
problemSettings.Validator.Name,
validatorLang,
),
)
}
// Slowness.
if problemSettings.Slow, err = isSlow(problemSettings, hardOverallWallTimeLimit); err != nil {
// isSlow already wrapped the error correctly.
return err
}
problemSettingsBytes, err := json.MarshalIndent(problemSettings, "", " ")
if err != nil {
return base.ErrorWithCategory(
ErrInteractiveBadLayout,
errors.Wrap(
err,
"failed to marshal the new interactive settings",
),
)
}
requestContext.UpdatedFiles["settings.json"] = bytes.NewReader(problemSettingsBytes)
// Generate the distributable problem settings (that can be used by the
// ephemeral grader).
problemDistribSettings := common.LiteralInput{
Cases: make(map[string]*common.LiteralCaseSettings),
Limits: &problemSettings.Limits,
Validator: &common.LiteralValidatorSettings{
Name: problemSettings.Validator.Name,
GroupScorePolicy: problemSettings.Validator.GroupScorePolicy,
Tolerance: problemSettings.Validator.Tolerance,
},
}
if problemDistribSettings.Cases, err = extractExampleCases(ctx, repo, tree); err != nil {
// extractExampleCases already wrapped the error correctly.
return err
}
if problemSettings.Validator.Name == common.ValidatorNameCustom {
problemDistribSettings.Validator.CustomValidator = &common.LiteralCustomValidatorSettings{
Source: "",
Language: *problemSettings.Validator.Lang,
Limits: problemSettings.Validator.Limits,
}
validatorDistribTreeEntry := tree.EntryByName(
fmt.Sprintf("validator.distrib.%s", *problemSettings.Validator.Lang),
)
if validatorDistribTreeEntry != nil {
validatorDistribBlob, err := repo.LookupBlob(validatorDistribTreeEntry.Id)
if err != nil {
return base.ErrorWithCategory(
ErrInternalGit,
errors.Wrap(
err,
"failed to lookup the distributable validator",
),
)
}
defer validatorDistribBlob.Free()
problemDistribSettings.Validator.CustomValidator.Source = string(validatorDistribBlob.Contents())
}
}
if problemSettings.Interactive != nil {
problemDistribSettings.Interactive = &common.LiteralInteractiveSettings{
IDLSource: string(idlFileContents),
Templates: problemSettings.Interactive.Templates,
ModuleName: problemSettings.Interactive.ModuleName,
ParentLang: problemSettings.Interactive.ParentLang,
MainSource: string(mainDistribSourceContents),
}
}
problemDistribSettingsBytes, err := json.MarshalIndent(problemDistribSettings, "", " ")
if err != nil {
return base.ErrorWithCategory(
ErrInternal,
errors.Wrap(