/
runr.go
90 lines (77 loc) · 1.9 KB
/
runr.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
package state
import (
"context"
"log/slog"
"os"
"os/signal"
"syscall"
"time"
"github.com/buyoio/goodies/streams"
"gopkg.in/yaml.v2"
)
func (l *Runr) State(file ...bool) *State {
if len(file) > 0 && file[0] {
return l.fileState
}
return l.aggrState
}
func (l *Runr) Path() string {
return getDefaultConfigPath()
}
func (l *Runr) Marshal() error {
yamlFile, err := yaml.Marshal(l.fileState)
if err != nil {
return err
}
return os.WriteFile(l.Path(), yamlFile, 0644)
}
func (runr *Runr) Logger() *slog.Logger {
if runr.logger != nil {
return runr.logger
}
// ensure logs path is correct
// and reset it after logger creation
if runr.fileState.Logs.Path == nil {
runr.logger, _ = runr.fileState.Logs.Logger()
return runr.logger
}
// todo don't like this at all
p := runr.fileState.Logs.Path
*runr.fileState.Logs.Path = resolvePath(*runr.fileState.Logs.Path)
runr.logger, runr.closer = runr.fileState.Logs.Logger()
runr.fileState.Logs.Path = p
return runr.logger
}
func (runr *Runr) IO() *streams.IO {
return runr.io
}
// https://github.com/tilt-dev/tilt/blob/master/internal/cli/cli.go#L115C6-L155
func (runr *Runr) GetContext() context.Context {
// logger := runr.Logger()
var ctx context.Context
if runr.cmd != nil {
ctx = runr.cmd.Context()
} else {
ctx = context.Background()
// logger.Debug("No context found; using background context.")
}
// SIGNAL TRAPPING
ctx, cancel := context.WithCancel(ctx)
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
go func() {
<-sigs
cancel()
// If we get another signal, OR it takes too long
// to exit after canceling context, just exit
select {
case <-sigs:
runr.Logger().Debug("force quitting...")
os.Exit(1)
case <-time.After(2 * time.Second):
runr.Logger().Debug("Context canceled but app still running; forcibly exiting.")
os.Exit(1)
}
}()
return ctx
}