-
Notifications
You must be signed in to change notification settings - Fork 49
/
main.go
232 lines (211 loc) 路 5.92 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
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
package app
import (
"bufio"
"github.com/willabides/kongplete"
"log"
"net"
"net/http"
"os"
"runtime"
"runtime/pprof"
"time"
"github.com/alecthomas/kong"
konghcl "github.com/alecthomas/kong-hcl"
"github.com/cashapp/hermit"
"github.com/cashapp/hermit/state"
"github.com/cashapp/hermit/ui"
"github.com/cashapp/hermit/util/debug"
"github.com/mattn/go-isatty"
)
const help = `馃悮 Hermit is a hermetic binary package manager.`
// HTTPTransportConfig defines the configuration for HTTP transports used by Hermit.
type HTTPTransportConfig struct {
ResponseHeaderTimeout time.Duration
DialTimeout time.Duration
KeepAlive time.Duration
}
// Config for the main Hermit application.
type Config struct {
Version string
LogLevel ui.Level
BaseDistURL string
HTTP func(HTTPTransportConfig) *http.Client
State state.Config
// True if we're running in CI.
CI bool
}
// Main runs the Hermit command-line application with the given config.
func Main(config Config) {
if config.HTTP == nil {
config.HTTP = func(config HTTPTransportConfig) *http.Client {
transport := &http.Transport{
ResponseHeaderTimeout: config.ResponseHeaderTimeout,
DialContext: (&net.Dialer{
Timeout: config.DialTimeout,
KeepAlive: config.KeepAlive,
}).DialContext,
}
return &http.Client{Transport: transport}
}
}
var (
err error
p *ui.UI
stdoutIsTTY = !config.CI && isatty.IsTerminal(os.Stdout.Fd())
stderrIsTTY = !config.CI && isatty.IsTerminal(os.Stderr.Fd())
)
if isatty.IsTerminal(os.Stdout.Fd()) && !config.CI {
// This is necessary because stdout/stderr are unbuffered and thus _very_ slow.
stdout := bufio.NewWriter(os.Stdout)
stderr := bufio.NewWriter(os.Stderr)
go func() {
for {
time.Sleep(time.Millisecond * 100)
err = stdout.Flush()
if err != nil {
break
}
err = stderr.Flush()
if err != nil {
break
}
}
}()
p = ui.New(config.LogLevel, &bufioSyncer{stdout}, &bufioSyncer{stderr}, stdoutIsTTY, stderrIsTTY)
defer stdout.Flush()
defer stderr.Flush()
} else {
p = ui.New(config.LogLevel, os.Stdout, os.Stderr, stdoutIsTTY, stderrIsTTY)
}
defer func() {
err := recover()
p.Clear()
if err != nil {
panic(err)
}
}()
var (
cli cliCommon
env *hermit.Env
sta *state.State
)
isActivated := false
envPath := os.Getenv("HERMIT_ENV")
if err != nil {
log.Fatalf("failed to open state: %s", err) // nolint: gocritic
}
if envPath != "" {
isActivated = true
cli = &activated{}
} else {
envPath, err = os.Getwd()
if err != nil {
log.Fatalf("couldn't get working directory: %s", err)
}
cli = &unactivated{}
}
parser, err := kong.New(cli,
kong.Groups{
"env": "Environment:\nCommands for creating and managing environments.",
"global": "Global:\nCommands for interacting with the shared global Hermit state.",
},
kong.Configuration(konghcl.Loader, "~/.hermit.hcl"),
kong.UsageOnError(),
kong.Description(help),
kong.BindTo(cli, (*cliCommon)(nil)),
kong.Vars{
"version": config.Version,
"env": envPath,
},
kong.HelpOptions{
Compact: true,
})
if err != nil {
log.Fatalf("failed to initialise CLI: %s", err)
}
sta, err = openState(config.State, config.HTTP)
if err != nil {
log.Fatalf("failed to open state: %s", err)
}
if isActivated {
env, err = hermit.OpenEnv(envPath, sta, cli.getGlobalState().Env)
if err != nil {
log.Fatalf("failed to open environment: %s", err)
}
}
packagePredictor := hermit.NewPackagePredictor(sta, env, p)
installedPredictor := hermit.NewInstalledPackagePredictor(env, p)
kongplete.Complete(parser,
kongplete.WithPredictor("package", packagePredictor),
kongplete.WithPredictor("installed-package", installedPredictor),
)
ctx, err := parser.Parse(os.Args[1:])
parser.FatalIfErrorf(err)
configureLogging(cli, ctx.Command(), p)
if pprofPath := cli.getCPUProfile(); pprofPath != "" {
f, err := os.Create(pprofPath)
fatalIfError(p, err)
defer f.Close() // nolint: gosec
err = pprof.StartCPUProfile(f)
fatalIfError(p, err)
defer pprof.StopCPUProfile()
}
if pprofPath := cli.getMemProfile(); pprofPath != "" {
f, err := os.Create(pprofPath)
fatalIfError(p, err)
defer f.Close() // nolint: gosec
runtime.GC() // get up-to-date statistics
err = pprof.WriteHeapProfile(f)
fatalIfError(p, err)
}
err = ctx.Run(env, p, sta, config, cli.getGlobalState())
if err != nil && p.WillLog(ui.LevelDebug) {
p.Fatalf("%+v", err)
} else {
fatalIfError(p, err)
}
}
func openState(config state.Config, newHTTPClient func(HTTPTransportConfig) *http.Client) (*state.State, error) {
client := newHTTPClient(HTTPTransportConfig{})
fastFailClient := newHTTPClient(HTTPTransportConfig{
ResponseHeaderTimeout: time.Second * 5,
DialTimeout: time.Second,
KeepAlive: 30 * time.Second,
})
if debug.Flags.FailHTTP {
client.Timeout = time.Millisecond
fastFailClient.Timeout = time.Millisecond
}
return state.Open(hermit.UserStateDir, config, client, fastFailClient)
}
func configureLogging(cli cliCommon, cmd string, p *ui.UI) {
// This is set to avoid logging in environments where quiet flag is not used
// in the "hermit" script. This is fragile, and should be removed when we know that all the
// environments are using a script with executions done with --quiet
isExecution := cmd == "exec <binary>"
switch {
case cli.getTrace():
p.SetLevel(ui.LevelTrace)
case cli.getDebug():
p.SetLevel(ui.LevelDebug)
case cli.getQuiet():
p.SetLevel(ui.LevelFatal)
default:
if isExecution {
p.SetLevel(ui.LevelFatal)
} else {
p.SetLevel(cli.getLevel())
}
}
if cli.getQuiet() {
p.SetProgressBarEnabled(false)
}
}
// Makes bufio conform to Sync() so the logger can flush it after each line.
type bufioSyncer struct{ *bufio.Writer }
func (b *bufioSyncer) Sync() error { return b.Flush() }
func fatalIfError(logger *ui.UI, err error) {
if err != nil {
logger.Task("hermit").Fatalf("%s", err)
}
}