all repos — erl @ main

Execute Reload Loop

main.go (view raw)

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
package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"log"
	"os"
	"os/signal"
	"slices"
	"strings"
	"sync"
	"syscall"
	"time"

	"github.com/fsnotify/fsnotify"
	"github.com/jessevdk/go-flags"

	"alin.ovh/erl/command"
	"alin.ovh/erl/ignore"
	"alin.ovh/erl/state"
	"alin.ovh/erl/watcher"
)

type Options struct {
	Exec    string   `short:"x" long:"exec"    description:"command to execute on file change"`
	Quiet   bool     `short:"q" long:"quiet"   description:"suppress own output"`
	Verbose bool     `short:"v" long:"verbose" description:"verbose output (print events)"`
	Watch   []string `short:"w" long:"watch"   description:"extra directories to watch"`
}

func Start(ctx context.Context, verbose *log.Logger, w watcher.Watcher, sm *state.StateMachine) {
	var wg sync.WaitGroup

	wg.Add(1)
	go func(events <-chan watcher.Event, errors <-chan error) {
		defer wg.Done()
		sm.SendEvent(state.Start)
		for {
			select {
			case <-ctx.Done():
				sm.SendEvent(state.Shutdown)

				return
			case event, ok := <-events:
				if !ok {
					return
				}

				// skip if _only_ chmod
				if event.Op == fsnotify.Chmod {
					continue
				}

				verbose.Printf("event: %s %s\n", event.Name, event.Op.String())
				if event.Op.Has(fsnotify.Create) {
					stat, err := os.Stat(event.Name)
					if err != nil {
						log.Printf("Error getting file info: %v\n", err)

						continue
					}
					if stat.IsDir() {
						err = w.AddRecursive(event.Name)
						if err != nil {
							log.Printf("Error adding directory to watcher: %v\n", err)
						}
					}
				}
				if event.Op.Has(fsnotify.Remove) {
					for _, dir := range w.WatchList() {
						if strings.HasPrefix(dir, event.Name) {
							err := w.Remove(dir)
							if err != nil {
								log.Printf("Error removing directory from watcher: %v\n", err)
							}
						}
					}
				}

				sm.SendEvent(state.Restart)

				time.Sleep(100 * time.Millisecond)

			case err, ok := <-errors:
				if !ok {
					return
				}
				log.Printf("Error: %v\n", err)
			}
		}
	}(w.Monitor())

	<-ctx.Done()
	log.Println("shutting down")

	sm.SendEvent(state.Shutdown)

	wg.Wait()
}

func main() {
	var opts Options
	log.SetFlags(log.Lmsgprefix)

	fp := flags.NewParser(&opts, flags.Default|flags.PassAfterNonOption)
	args, err := fp.Parse()
	if err != nil {
		if errors.Is(err, flags.ErrHelp) {
			os.Exit(0)
		}

		os.Exit(1)
	}

	program := opts.Exec
	if program == "" {
		program = "go"

		if len(args) == 0 {
			args = []string{"run", "."}
		} else {
			args = slices.Insert(args, 0, "run")
		}
	}

	wd, err := os.Getwd()
	if err != nil {
		log.Fatalf("failed to get working directory: %v", err)
	}

	ctx, cancel := signal.NotifyContext(
		context.Background(),
		os.Interrupt,
		syscall.SIGHUP,
		syscall.SIGTERM,
	)
	defer cancel()

	filter := ignore.New(wd)
	err = filter.ReadIgnoreFiles(ctx)
	if err != nil {
		panic(fmt.Sprintf("failed to read ignore files: %v", err))
	}

	watcher, err := watcher.New(watcher.Options{
		Filter: *filter,
	})
	if err != nil {
		panic(fmt.Sprintf("failed to create watcher: %v", err))
	}
	defer watcher.Close()

	err = watcher.AddRecursive(".")
	if err != nil {
		log.Panicf("failed to add directory to watcher: %v", err)
	}
	for _, watchPath := range opts.Watch {
		err = watcher.AddRecursive(watchPath)
		if err != nil {
			log.Panicf("failed to add directory to watcher: %v", err)
		}
	}

	copts := command.Options{}
	if opts.Quiet {
		copts.Output = io.Discard
	}

	var logger *log.Logger
	if opts.Verbose {
		logger = log.New(os.Stderr, "", 0)
	} else {
		logger = log.New(io.Discard, "", 0)
	}

	cmd := command.New(program, args, copts)
	sm := state.New(cmd, state.Options{
		Logger:  log.New(os.Stderr, "state: ", log.Lmsgprefix),
		Timeout: time.Second * 5,
	})
	Start(ctx, logger, watcher, sm)
}