-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
529 lines (484 loc) · 12.1 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
package main
import (
"archive/zip"
"bytes"
"context"
"encoding/json"
"flag"
"fmt"
"github.com/inconshreveable/log15"
git "github.com/lhchavez/git2go"
"github.com/omegaup/githttp"
"github.com/omegaup/gitserver"
"github.com/omegaup/gitserver/request"
base "github.com/omegaup/go-base"
"github.com/omegaup/quark/common"
"github.com/pkg/errors"
"io"
"io/ioutil"
"os"
"path"
"path/filepath"
"time"
)
var (
author = flag.String("author", "", "Author of the commit")
commitMessage = flag.String("commit-message", "", "Commit message")
repositoryPath = flag.String("repository-path", "", "Path of the git repository")
problemSettingsJSON = flag.String("problem-settings", "", "(Optional) JSON-encoded ProblemSettings")
// Flags that are used when updating a repository with a .zip.
zipPath = flag.String("zip-path", "", "Path of the .zip file")
mergeStrategyName = flag.String("merge-strategy", "theirs", "Merge strategy to use. Valid values are 'ours', 'theirs', 'statement-ours', and 'recursive-theirs'")
acceptsSubmissions = flag.Bool("accepts-submissions", true, "Problem accepts submissions")
libinteractivePath = flag.String("libinteractive-path", "/usr/share/java/libinteractive.jar", "Path of libinteractive.jar")
// Flags that are used when updating a repository with a []BlobUpdate.
blobUpdateJSON = flag.String("blob-update", "", "Update a subset of the blobs")
// An empty .zip file.
emptyZipFile = []byte{
0x50, 0x4b, 0x05, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
}
)
// BlobUpdate represents updating a single blob in the repository.
type BlobUpdate struct {
Path string `json:"path"`
ContentsPath string `json:"contents_path"`
}
func commitZipFile(
zipReader *zip.Reader,
repo *git.Repository,
lockfile *githttp.Lockfile,
authorUsername string,
commitMessage string,
problemSettings *common.ProblemSettings,
zipMergeStrategy gitserver.ZipMergeStrategy,
acceptsSubmissions bool,
log log15.Logger,
) (*gitserver.UpdateResult, error) {
ctx := request.NewContext(context.Background())
requestContext := request.FromContext(ctx)
requestContext.IsAdmin = true
requestContext.CanView = true
requestContext.CanEdit = true
protocol := gitserver.NewGitProtocol(
nil,
nil,
true,
gitserver.OverallWallTimeHardLimit,
&gitserver.LibinteractiveCompiler{
LibinteractiveJarPath: *libinteractivePath,
Log: log,
},
log,
)
return gitserver.PushZip(
ctx,
zipReader,
githttp.AuthorizationAllowed,
repo,
lockfile,
authorUsername,
commitMessage,
problemSettings,
zipMergeStrategy,
acceptsSubmissions,
protocol,
log,
)
}
func convertBlobsToPackfile(
contents map[string]io.Reader,
repo *git.Repository,
parent *git.Oid,
author, committer *git.Signature,
commitMessage string,
w io.Writer,
log log15.Logger,
) (*git.Oid, error) {
headCommit, err := repo.LookupCommit(parent)
if err != nil {
return nil, errors.Wrap(
err,
"failed to get the repository's HEAD's commit",
)
}
defer headCommit.Free()
headTree, err := headCommit.Tree()
if err != nil {
return nil, errors.Wrap(
err,
"failed to get the repository's HEAD's commit's tree",
)
}
defer headTree.Free()
odb, err := repo.Odb()
if err != nil {
return nil, errors.Wrap(
err,
"failed to open odb",
)
}
defer odb.Free()
looseObjectsDir, err := ioutil.TempDir("", 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, errors.Wrap(
err,
"failed to create new loose object backend",
)
}
if err := odb.AddBackend(looseObjectsBackend, 999); err != nil {
looseObjectsBackend.Free()
return nil, errors.Wrap(
err,
"failed to register loose object backend",
)
}
tree, err := githttp.BuildTree(
repo,
contents,
log,
)
if err != nil {
return nil, errors.Wrap(
err,
"failed to create new tree",
)
}
defer tree.Free()
mergedTree, err := githttp.MergeTrees(
repo,
log,
tree,
headTree,
)
if err != nil {
return nil, errors.Wrap(
err,
"failed to merge tree",
)
}
defer mergedTree.Free()
newCommitID, err := repo.CreateCommit(
"",
author,
committer,
commitMessage,
mergedTree,
headCommit,
)
if err != nil {
return nil, errors.Wrap(
err,
"failed to create commit",
)
}
walk, err := repo.Walk()
if err != nil {
return nil, errors.Wrap(
err,
"failed to create revwalk",
)
}
defer walk.Free()
if err := walk.Hide(headCommit.Id()); err != nil {
return nil, errors.Wrapf(
err,
"failed to hide commit %s", headCommit.Id().String(),
)
}
if err := walk.Push(newCommitID); err != nil {
return nil, errors.Wrapf(
err,
"failed to add commit %s", newCommitID.String(),
)
}
pb, err := repo.NewPackbuilder()
if err != nil {
return nil, errors.Wrap(
err,
"failed to create packbuilder",
)
}
defer pb.Free()
if err := pb.InsertWalk(walk); err != nil {
return nil, errors.Wrap(
err,
"failed to insert walk into packbuilder",
)
}
if err := pb.Write(w); err != nil {
return nil, errors.Wrap(
err,
"failed to write packfile",
)
}
return newCommitID, nil
}
func commitBlobs(
repo *git.Repository,
lockfile *githttp.Lockfile,
authorUsername string,
commitMessage string,
contents map[string]io.Reader,
log log15.Logger,
) (*gitserver.UpdateResult, error) {
reference, err := repo.Head()
if err != nil {
log.Error("Failed to get the repository's HEAD", "err", err)
return nil, err
}
defer reference.Free()
oldOid := reference.Target()
signature := git.Signature{
Name: authorUsername,
Email: fmt.Sprintf("%s@omegaup", authorUsername),
When: time.Now(),
}
var pack bytes.Buffer
newOid, err := convertBlobsToPackfile(
contents,
repo,
oldOid,
&signature,
&signature,
commitMessage,
&pack,
log,
)
if err != nil {
return nil, err
}
ctx := request.NewContext(context.Background())
requestContext := request.FromContext(ctx)
requestContext.IsAdmin = true
requestContext.CanView = true
requestContext.CanEdit = true
protocol := gitserver.NewGitProtocol(
nil,
nil,
true,
gitserver.OverallWallTimeHardLimit,
&gitserver.LibinteractiveCompiler{
LibinteractiveJarPath: *libinteractivePath,
},
log,
)
updatedRefs, err, unpackErr := protocol.PushPackfile(
ctx,
repo,
lockfile,
githttp.AuthorizationAllowed,
[]*githttp.GitCommand{
{
Old: oldOid,
New: newOid,
ReferenceName: "refs/heads/master",
Reference: reference,
},
},
&pack,
)
if err != nil {
log.Error("Failed to push blobs", "err", err)
return nil, err
}
if unpackErr != nil {
log.Error("Failed to unpack packfile", "err", unpackErr)
return nil, err
}
updatedFiles, err := gitserver.GetUpdatedFiles(repo, updatedRefs)
if err != nil {
log.Error("failed to get updated files", "err", err)
}
return &gitserver.UpdateResult{
Status: "ok",
UpdatedRefs: updatedRefs,
UpdatedFiles: updatedFiles,
}, nil
}
func main() {
flag.Parse()
log := base.StderrLog()
if *author == "" {
log.Crit("author cannot be empty. Please specify one with -author")
os.Exit(1)
}
if *commitMessage == "" {
log.Crit("commit message cannot be empty. Please specify one with -commit-message")
os.Exit(1)
}
if *repositoryPath == "" {
log.Crit("repository path cannot be empty. Please specify one with -repository-path")
os.Exit(1)
}
var repo *git.Repository
commitCallback := func() error { return nil }
if _, err := os.Stat(*repositoryPath); os.IsNotExist(err) {
dir, err := ioutil.TempDir(filepath.Dir(*repositoryPath), "repository")
if err != nil {
log.Crit("Failed to create temporary directory", "err", err)
os.Exit(1)
}
defer os.RemoveAll(dir)
if err := os.Chmod(dir, 0755); err != nil {
log.Crit("Failed to chmod temporary directory", "err", err)
os.Exit(1)
}
repo, err = gitserver.InitRepository(dir)
if err != nil {
log.Crit("Failed to init bare repository", "err", err)
os.Exit(1)
}
commitCallback = func() error {
return os.Rename(dir, *repositoryPath)
}
} else {
if _, err := os.Stat(path.Join(*repositoryPath, "omegaup/version")); os.IsNotExist(err) {
encoder := json.NewEncoder(os.Stdout)
encoder.SetIndent("", "\t")
encoder.Encode(&gitserver.UpdateResult{
Status: "error",
Error: "omegaup-update-problem-old-version",
})
os.Exit(1)
}
repo, err = git.OpenRepository(*repositoryPath)
if err != nil {
log.Crit("failed to open existing repository", "err", err)
os.Exit(1)
}
}
defer repo.Free()
lockfile := githttp.NewLockfile(repo.Path())
if ok, err := lockfile.TryLock(); !ok {
log.Info("Waiting for the lockfile", "err", err)
if err := lockfile.Lock(); err != nil {
log.Crit("Failed to acquire the lockfile", "err", err)
os.Exit(1)
}
}
defer lockfile.Unlock()
var problemSettings *common.ProblemSettings
if *problemSettingsJSON != "" {
problemSettings = &common.ProblemSettings{}
if err := json.Unmarshal([]byte(*problemSettingsJSON), problemSettings); err != nil {
log.Crit("Failed to parse -problem-settings", "err", err)
os.Exit(1)
}
}
var updateResult *gitserver.UpdateResult
if *zipPath != "" {
zipMergeStrategy, err := gitserver.ParseZipMergeStrategy(*mergeStrategyName)
if err != nil {
log.Crit("Invalid value for -merge-strategy: %q", *mergeStrategyName)
os.Exit(1)
}
zipReader, err := zip.OpenReader(*zipPath)
if err != nil {
log.Crit("Failed to open the zip file", "err", err)
os.Exit(1)
}
defer zipReader.Close()
updateResult, err = commitZipFile(
&zipReader.Reader,
repo,
lockfile,
*author,
*commitMessage,
problemSettings,
zipMergeStrategy,
*acceptsSubmissions,
log,
)
if err != nil {
log.Error("Failed update the repository", "path", *repositoryPath, "err", err)
updateResult = &gitserver.UpdateResult{
Status: "error",
Error: err.Error(),
}
} else if err := commitCallback(); err != nil {
log.Error("Failed to commit the write to the repository", "err", err)
updateResult = &gitserver.UpdateResult{
Status: "error",
Error: err.Error(),
}
}
} else if *blobUpdateJSON != "" {
var blobUpdates []BlobUpdate
if err := json.Unmarshal([]byte(*blobUpdateJSON), &blobUpdates); err != nil {
log.Crit("Failed to parse -blob-update", "err", err)
os.Exit(1)
}
contents := make(map[string]io.Reader)
for _, blobUpdate := range blobUpdates {
f, err := os.Open(blobUpdate.ContentsPath)
if err != nil {
log.Crit("failed to open blob contents",
"contents path", blobUpdate.ContentsPath,
"path", blobUpdate.Path,
)
os.Exit(1)
}
defer f.Close()
contents[blobUpdate.Path] = f
}
var err error
updateResult, err = commitBlobs(
repo,
lockfile,
*author,
*commitMessage,
contents,
log,
)
if err != nil {
log.Error("Failed update the repository", "path", *repositoryPath, "err", err)
updateResult = &gitserver.UpdateResult{
Status: "error",
Error: err.Error(),
}
}
} else if *problemSettingsJSON != "" {
var err error
zipReader, err := zip.NewReader(bytes.NewReader(emptyZipFile), int64(len(emptyZipFile)))
if err != nil {
log.Crit("Failed to open the empty zip file", "err", err)
os.Exit(1)
}
updateResult, err = commitZipFile(
zipReader,
repo,
lockfile,
*author,
*commitMessage,
problemSettings,
gitserver.ZipMergeStrategyOurs,
*acceptsSubmissions,
log,
)
if err != nil {
log.Error("Failed update the repository", "path", *repositoryPath, "err", err)
updateResult = &gitserver.UpdateResult{
Status: "error",
Error: err.Error(),
}
}
} else {
log.Error("-zip-path, -blob-update, and -problem-settings cannot be simultaneously empty.")
os.Exit(1)
}
encoder := json.NewEncoder(os.Stdout)
encoder.SetIndent("", "\t")
encoder.Encode(&updateResult)
if updateResult.Status != "ok" {
os.Exit(1)
}
}