-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathrun.go
87 lines (73 loc) · 1.91 KB
/
run.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
package cli
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"github.com/nevalang/neva/internal/compiler"
cli "github.com/urfave/cli/v2"
)
func newRunCmd(workdir string, nativec compiler.Compiler) *cli.Command {
return &cli.Command{
Name: "run",
Usage: "Build and run neva program from source code",
Args: true,
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "trace",
Usage: "Write trace information to file",
},
&cli.BoolFlag{
Name: "emit-ir",
Usage: "Emit intermediate representation to ir.yml file",
},
},
ArgsUsage: "Provide path to main package",
Action: func(cliCtx *cli.Context) error {
mainPkg, err := mainPkgPathFromArgs(cliCtx)
if err != nil {
return err
}
trace := cliCtx.IsSet("trace")
emitIR := cliCtx.IsSet("emit-ir")
// we need to always set GOOS for compiler backend
prevGOOS := os.Getenv("GOOS")
if err := os.Setenv("GOOS", runtime.GOOS); err != nil {
return fmt.Errorf("set GOOS: %w", err)
}
defer func() {
if err := os.Setenv("GOOS", prevGOOS); err != nil {
panic(err)
}
}()
expectedOutputFileName := "output"
if runtime.GOOS == "windows" { // assumption that on windows compiler generates .exe
expectedOutputFileName += ".exe"
}
input := compiler.CompilerInput{
Main: mainPkg,
Output: workdir,
Trace: trace,
EmitIR: emitIR,
}
if err := nativec.Compile(cliCtx.Context, input); err != nil {
return err
}
execPath := filepath.Join(workdir, expectedOutputFileName)
defer func() {
if err := os.Remove(execPath); err != nil {
fmt.Println("failed to remove output file:", err)
}
}()
cmd := exec.CommandContext(cliCtx.Context, execPath)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return fmt.Errorf("failed to run generated executable: %w", err)
}
return nil
},
}
}