-
Notifications
You must be signed in to change notification settings - Fork 0
/
autocompile.go
76 lines (65 loc) · 1.96 KB
/
autocompile.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
package cpp
import (
"bytes"
"context"
"errors"
"fmt"
"github.com/mraron/njudge/pkg/language/sandbox"
"io"
"os"
"path/filepath"
"github.com/spf13/afero"
)
func AutoCompile(ctx context.Context, fs afero.Fs, s sandbox.Sandbox, workDir, src, dst string) error {
if src == "" {
return nil
}
if st, err := fs.Stat(dst); os.IsNotExist(err) || st.Size() == 0 || st.Mode()&0100 != 0100 {
if binary, err := fs.Create(dst); err == nil {
if file, err := fs.Open(src); err == nil {
var errorStream bytes.Buffer
if err := s.Init(ctx); err != nil {
return errors.Join(err, binary.Close(), file.Close())
}
defer func(s sandbox.Sandbox, ctx context.Context) {
_ = s.Cleanup(ctx)
}(s, ctx)
contents, err := afero.ReadFile(fs, src)
if err != nil {
return errors.Join(err, file.Close(), binary.Close())
}
var headers []sandbox.File
for _, header := range ExtractHeaderNames(fs, workDir, contents) {
headerContents, err := afero.ReadFile(fs, filepath.Join(workDir, header))
if err != nil {
return errors.Join(err, file.Close(), binary.Close())
}
headers = append(headers, sandbox.File{
Name: header,
Source: io.NopCloser(bytes.NewReader(headerContents)),
})
}
var resBinary *sandbox.File
if resBinary, err = Std17.Compile(context.TODO(), s, sandbox.File{
Name: filepath.Base(src),
Source: file,
}, &errorStream, headers); err != nil {
return errors.Join(err, binary.Close(), file.Close(), fmt.Errorf("compile error: %v", errorStream.String()))
}
if _, err = io.Copy(binary, resBinary.Source); err != nil {
return errors.Join(err, binary.Close(), file.Close())
}
if err := fs.Chmod(dst, 0755); err != nil {
return errors.Join(err, binary.Close(), file.Close())
}
return errors.Join(binary.Close(), file.Close())
} else {
return errors.Join(err, binary.Close())
}
} else {
return err
}
} else {
return err
}
}