-
Notifications
You must be signed in to change notification settings - Fork 227
/
test.go
209 lines (191 loc) · 4.65 KB
/
test.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
package cmd
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strings"
"unicode"
"github.com/fatih/color"
ansi "github.com/k0kubun/go-ansi"
"github.com/sergi/go-diff/diffmatchpatch"
"github.com/shirou/gopsutil/process"
"github.com/xalanq/cf-tool/config"
"github.com/xalanq/cf-tool/util"
)
func splitCmd(s string) (res []string) {
// https://github.com/vrischmann/shlex/blob/master/shlex.go
var buf bytes.Buffer
insideQuotes := false
for _, r := range s {
switch {
case unicode.IsSpace(r) && !insideQuotes:
if buf.Len() > 0 {
res = append(res, buf.String())
buf.Reset()
}
case r == '"' || r == '\'':
if insideQuotes {
res = append(res, buf.String())
buf.Reset()
insideQuotes = false
continue
}
insideQuotes = true
default:
buf.WriteRune(r)
}
}
if buf.Len() > 0 {
res = append(res, buf.String())
}
return
}
func plain(raw []byte) string {
buf := bufio.NewScanner(bytes.NewReader(raw))
var b bytes.Buffer
newline := []byte{'\n'}
for buf.Scan() {
b.Write(bytes.TrimSpace(buf.Bytes()))
b.Write(newline)
}
return b.String()
}
func judge(sampleID, command string) error {
inPath := fmt.Sprintf("in%v.txt", sampleID)
ansPath := fmt.Sprintf("ans%v.txt", sampleID)
input, err := os.Open(inPath)
if err != nil {
return err
}
var o bytes.Buffer
output := io.Writer(&o)
cmds := splitCmd(command)
cmd := exec.Command(cmds[0], cmds[1:]...)
cmd.Stdin = input
cmd.Stdout = output
cmd.Stderr = os.Stderr
if err := cmd.Start(); err != nil {
return fmt.Errorf("Runtime Error #%v ... %v", sampleID, err.Error())
}
pid := int32(cmd.Process.Pid)
maxMemory := uint64(0)
ch := make(chan error)
go func() {
ch <- cmd.Wait()
}()
running := true
for running {
select {
case err := <-ch:
if err != nil {
return fmt.Errorf("Runtime Error #%v ... %v", sampleID, err.Error())
}
running = false
default:
p, err := process.NewProcess(pid)
if err == nil {
m, err := p.MemoryInfo()
if err == nil && m.RSS > maxMemory {
maxMemory = m.RSS
}
}
}
}
b, err := ioutil.ReadFile(ansPath)
if err != nil {
b = []byte{}
}
ans := plain(b)
out := plain(o.Bytes())
state := ""
diff := ""
if out == ans {
state = color.New(color.FgGreen).Sprintf("Passed #%v", sampleID)
} else {
input, err := ioutil.ReadFile(inPath)
if err != nil {
return err
}
state = color.New(color.FgRed).Sprintf("Failed #%v", sampleID)
dmp := diffmatchpatch.New()
d := dmp.DiffMain(out, ans, true)
diff += color.New(color.FgCyan).Sprintf("-----Input-----\n")
diff += string(input) + "\n"
diff += color.New(color.FgCyan).Sprintf("-----Output-----\n")
diff += dmp.DiffText1(d) + "\n"
diff += color.New(color.FgCyan).Sprintf("-----Answer-----\n")
diff += dmp.DiffText2(d) + "\n"
diff += color.New(color.FgCyan).Sprintf("-----Diff-----\n")
diff += dmp.DiffPrettyText(d) + "\n"
}
parseMemory := func(memory uint64) string {
if memory > 1024*1024 {
return fmt.Sprintf("%.3fMB", float64(memory)/1024.0/1024.0)
} else if memory > 1024 {
return fmt.Sprintf("%.3fKB", float64(memory)/1024.0)
}
return fmt.Sprintf("%vB", memory)
}
ansi.Printf("%v ... %.3fs %v\n%v", state, cmd.ProcessState.UserTime().Seconds(), parseMemory(maxMemory), diff)
return nil
}
// Test command
func Test(args map[string]interface{}) error {
cfg := config.Instance
if len(cfg.Template) == 0 {
return errors.New("You have to add at least one code template by `cf config`")
}
samples := getSampleID()
if len(samples) == 0 {
color.Red("There is no sample data")
return nil
}
filename, index, err := getOneCode(args, cfg.Template)
if err != nil {
return err
}
template := cfg.Template[index]
path, full := filepath.Split(filename)
ext := filepath.Ext(filename)
file := full[:len(full)-len(ext)]
rand := util.RandString(8)
filter := func(cmd string) string {
cmd = strings.ReplaceAll(cmd, "$%rand%$", rand)
cmd = strings.ReplaceAll(cmd, "$%path%$", path)
cmd = strings.ReplaceAll(cmd, "$%full%$", full)
cmd = strings.ReplaceAll(cmd, "$%file%$", file)
return cmd
}
run := func(script string) error {
if s := filter(script); len(s) > 0 {
fmt.Println(s)
cmds := splitCmd(s)
cmd := exec.Command(cmds[0], cmds[1:]...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
return nil
}
if err := run(template.BeforeScript); err != nil {
return err
}
if s := filter(template.Script); len(s) > 0 {
for _, i := range samples {
err := judge(i, s)
if err != nil {
color.Red(err.Error())
}
}
} else {
color.Red("Invalid script command. Please check config file")
return nil
}
return run(template.AfterScript)
}