-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
107 lines (100 loc) · 2.43 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
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"os"
"os/signal"
"github.com/urfave/cli/v2"
"marwan.io/gowatch/watcher"
)
func main() {
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, os.Kill)
defer cancel()
app := &cli.App{
Name: "gowatch",
Usage: "Automatically restart Go processes on file changes",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "cwd",
Usage: "set the current working directoy for the Go process",
},
&cli.StringSliceFlag{
Name: "additiona-files",
Usage: "Comma separated directories or files to watch",
},
&cli.BoolFlag{
Name: "vendor",
Usage: "Also watch the vendor directory",
},
&cli.StringSliceFlag{
Name: "build-flags",
Usage: "flags to send to the 'go build'",
},
&cli.BoolFlag{
Name: "print-files",
Aliases: []string{"p"},
Usage: "print all watched files",
},
},
Commands: []*cli.Command{
{
Name: "init",
Usage: "creates a gowatch.json file in the current working directory",
Action: func(*cli.Context) error {
f, err := os.Create("gowatch.json")
if err != nil {
return err
}
defer f.Close()
enc := json.NewEncoder(f)
enc.SetIndent("", "\t")
return enc.Encode(watcher.Config{})
},
},
},
Action: run,
}
err := app.RunContext(ctx, os.Args)
if err != nil && !errors.Is(err, context.Canceled) {
log.Fatal(err)
}
}
const configFile = "gowatch.json"
func run(c *cli.Context) error {
if _, err := os.Stat(configFile); err == nil {
return runFile(c)
}
return runCLI(c)
}
func runFile(ctx *cli.Context) error {
return watcher.RunAndWatchConfig(ctx.Context, configFile, func() (watcher.Config, error) {
f, err := os.Open(configFile)
if err != nil {
return watcher.Config{}, fmt.Errorf("configFile: %w", err)
}
defer f.Close()
var c watcher.Config
err = json.NewDecoder(f).Decode(&c)
if err != nil {
return watcher.Config{}, fmt.Errorf("json.Decode: %w", err)
}
if len(c.RuntimeArgs) == 0 {
c.RuntimeArgs = ctx.Args().Slice()
}
return c, nil
})
}
func runCLI(c *cli.Context) error {
cfg := watcher.Config{
Dir: c.String("cwd"),
AdditionalFiles: c.StringSlice("additional-files"),
BuildFlags: c.StringSlice("build-flag"),
RuntimeArgs: c.Args().Slice(),
Vendor: c.Bool("vendor"),
PrintFiles: c.Bool("print-files"),
}
return watcher.Run(c.Context, cfg)
}