-
Notifications
You must be signed in to change notification settings - Fork 0
/
module.go
97 lines (78 loc) · 1.57 KB
/
module.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
package gocc
import (
"fmt"
"go/parser"
"go/printer"
"go/token"
"io"
"os"
"os/exec"
"path/filepath"
"golang.org/x/tools/go/ast/astutil"
)
type Module struct {
Name string
SourceCode string
}
func NewModule(root string, pkg string) (*Module, error) {
return &Module{
Name: pkg,
SourceCode: root,
}, nil
}
func (mod *Module) CopyFrom(file string) (*Suite, error) {
switch {
case filepath.Ext(file) == ".go":
return mod.copyFromGo(file)
default:
return nil, fmt.Errorf("not supported %s", file)
}
}
func (mod *Module) copyFromGo(file string) (*Suite, error) {
return NewSuite(file)
}
func (mod *Module) CreateRunner(tests []*Suite) error {
run := filepath.Join(mod.SourceCode, "runner.go")
err := os.WriteFile(run, []byte(`
package main
import (
"os"
"github.com/fogfish/gurl/v2/http"
)
func main(){}
`), 0644)
if err != nil {
return err
}
fset := token.NewFileSet()
code, err := parser.ParseFile(fset, run, nil, parser.ParseComments)
if err != nil {
return err
}
astReWrite(code, tests)
for _, test := range tests {
if test.Pkg != "main" {
astutil.AddNamedImport(fset, code, test.Pkg, test.PkgPath)
}
}
f, err := os.Create(run)
if err != nil {
return err
}
defer f.Close()
err = printer.Fprint(f, fset, code)
if err != nil {
return err
}
return nil
}
func (mod *Module) Run(stdout io.Writer, defaultHost string) error {
run := exec.Command("go", "run", "runner.go", defaultHost)
run.Dir = mod.SourceCode
run.Stderr, run.Stdout = stdout, stdout
err := run.Run()
if err != nil {
return err
}
return nil
}