-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
111 lines (92 loc) · 1.75 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
package main
import (
"bufio"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strings"
)
var (
exitCode = 0
defaultTmpl = []byte(`package main
import (
"fmt"
)
func main() {
fmt.Println("Hello, gomain")
}
`)
)
func reportError(err error) {
exitCode = 2
fmt.Fprintln(os.Stderr, err.Error())
}
func main() {
defer os.Exit(exitCode)
if err := doMain(nil); err != nil {
reportError(err)
return
}
}
func doMain(tmpl []byte) error {
out := bufio.NewWriter(os.Stdout)
tempDir, err := ioutil.TempDir("", "gomain")
if err != nil {
return err
}
defer os.RemoveAll(tempDir)
// write template contents to main.go
f, err := os.Create(filepath.Join(tempDir, "main.go"))
if err != nil {
return err
}
defer os.Remove(f.Name())
if tmpl == nil {
f.Write([]byte(defaultTmpl))
} else {
f.Write([]byte(tmpl))
}
f.Close()
err = launchEditor(f.Name())
if err != nil {
return err
}
// show contents of main.go
writtenCode, err := ioutil.ReadFile(f.Name())
if err != nil {
return err
}
out.Write(writtenCode)
// go run main.go && show result
out.WriteRune('\n')
out.WriteString("--- Output ---")
out.WriteRune('\n')
cmd := exec.Command("go", "run", f.Name())
cmd.Stdout = out
cmd.Stderr = out
cmd.Run()
out.Write([]byte("\nre-edit? y/[N]"))
out.Flush()
s, _ := bufio.NewReader(os.Stdin).ReadString('\n')
if isYes(s) {
return doMain(writtenCode)
}
return nil
}
func launchEditor(filename string) error {
editor := os.Getenv("EDITOR")
if editor == "" {
editor = "vim"
}
cmd := exec.Command(editor, filename)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
func isYes(txt string) bool {
txt = strings.Trim(strings.ToUpper(txt), " \n")
return txt == "Y" || txt == "YES"
}