-
Notifications
You must be signed in to change notification settings - Fork 0
/
run_unix.go
190 lines (170 loc) · 4.3 KB
/
run_unix.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
//go:build !plan9 && !windows
// +build !plan9,!windows
package run
import (
"fmt"
"log"
"os"
"os/exec"
"os/signal"
"path/filepath"
"strings"
"syscall"
"time"
"github.com/AlecAivazis/survey/v2"
"github.com/fsnotify/fsnotify"
"github.com/spf13/cobra"
"github.com/xushuhui/goal/config"
"github.com/xushuhui/goal/internal/pkg/helper"
)
var quit = make(chan os.Signal, 1)
var excludeDir string
var includeExt string
func init() {
CmdRun.Flags().StringVarP(&excludeDir, "excludeDir", "", excludeDir, `eg: goal run --excludeDir="tmp,vendor,.git,.idea"`)
CmdRun.Flags().StringVarP(&includeExt, "includeExt", "", includeExt, `eg: goal run --includeExt="go,tpl,tmpl,html,yaml,yml,toml,ini,json"`)
if excludeDir == "" {
excludeDir = config.RunExcludeDir
}
if includeExt == "" {
includeExt = config.RunIncludeExt
}
}
var CmdRun = &cobra.Command{
Use: "run",
Short: "goal run [main.go path]",
Long: "goal run [main.go path]",
Example: "goal run cmd/server",
Run: func(cmd *cobra.Command, args []string) {
cmdArgs, programArgs := helper.SplitArgs(cmd, args)
var dir string
if len(cmdArgs) > 0 {
dir = cmdArgs[0]
}
base, err := os.Getwd()
if err != nil {
fmt.Fprintf(os.Stderr, "ERROR: %s\n", err)
return
}
if dir == "" {
cmdPath, err := helper.FindMain(base, excludeDir)
if err != nil {
fmt.Fprintf(os.Stderr, "ERROR: %s\n", err)
return
}
switch len(cmdPath) {
case 0:
fmt.Fprintf(os.Stderr, "ERROR: %s\n", "The cmd directory cannot be found in the current directory")
return
case 1:
for _, v := range cmdPath {
dir = v
}
default:
var cmdPaths []string
for k := range cmdPath {
cmdPaths = append(cmdPaths, k)
}
prompt := &survey.Select{
Message: "Which directory do you want to run?",
Options: cmdPaths,
PageSize: 10,
}
e := survey.AskOne(prompt, &dir)
if e != nil || dir == "" {
return
}
dir = cmdPath[dir]
}
}
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
fmt.Printf("Goal run %s.", dir)
fmt.Printf("Watch excludeDir %s", excludeDir)
fmt.Printf("Watch includeExt %s", includeExt)
watch(dir, programArgs)
},
}
func watch(dir string, programArgs []string) {
// Listening file path
watchPath := "./"
// Create a new file watcher
watcher, err := fsnotify.NewWatcher()
if err != nil {
fmt.Println("Error:", err)
return
}
defer watcher.Close()
excludeDirArr := strings.Split(excludeDir, ",")
includeExtArr := strings.Split(includeExt, ",")
includeExtMap := make(map[string]struct{})
for _, s := range includeExtArr {
includeExtMap[s] = struct{}{}
}
// Add files to watcher
err = filepath.Walk(watchPath, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
for _, s := range excludeDirArr {
if s == "" {
continue
}
if strings.HasPrefix(path, s) {
return nil
}
}
if !info.IsDir() {
ext := filepath.Ext(info.Name())
if _, ok := includeExtMap[strings.TrimPrefix(ext, ".")]; ok {
err = watcher.Add(path)
if err != nil {
fmt.Println("Error:", err)
}
}
}
return nil
})
if err != nil {
fmt.Println("Error:", err)
return
}
cmd := start(dir, programArgs)
// Loop listening file modification
for {
select {
case <-quit:
err = syscall.Kill(-cmd.Process.Pid, syscall.SIGINT)
if err != nil {
fmt.Print("server exiting...")
return
}
fmt.Print("server exiting...")
os.Exit(0)
case event := <-watcher.Events:
// The file has been modified or created
if event.Op&fsnotify.Create == fsnotify.Create ||
event.Op&fsnotify.Write == fsnotify.Write ||
event.Op&fsnotify.Remove == fsnotify.Remove {
fmt.Printf("file modified: %s", event.Name)
syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
cmd = start(dir, programArgs)
}
case err := <-watcher.Errors:
fmt.Println("Error:", err)
}
}
}
func start(dir string, programArgs []string) *exec.Cmd {
cmd := exec.Command("go", append([]string{"run", dir}, programArgs...)...)
// Set a new process group to kill all child processes when the program exits
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Start()
if err != nil {
log.Fatal("cmd run failed")
}
time.Sleep(time.Second)
fmt.Print("running...")
return cmd
}