-
Notifications
You must be signed in to change notification settings - Fork 51
/
main.go
298 lines (267 loc) · 7.98 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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
package app
import (
"bufio"
"log"
"net"
"net/http"
"os"
"runtime"
"runtime/pprof"
"time"
"github.com/alecthomas/kong"
"github.com/mattn/go-isatty"
"github.com/posener/complete"
"github.com/willabides/kongplete"
"github.com/cashapp/hermit"
"github.com/cashapp/hermit/cache"
"github.com/cashapp/hermit/github"
"github.com/cashapp/hermit/state"
"github.com/cashapp/hermit/ui"
"github.com/cashapp/hermit/util/debug"
)
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
// SHA256 checksums for all known versions of per-environment scripts.
// If empty shell.ScriptSHAs will be used.
SHA256Sums []string
HTTP func(HTTPTransportConfig) *http.Client
State state.Config
KongOptions []kong.Option
KongPlugins kong.Plugins
// Defaults to cache.GetSource if nil.
PackageSourceSelector cache.PackageSourceSelector
// True if we're running in CI - disables progress bar.
CI bool
}
type loggingHTTPTransport struct {
logger ui.Logger
next http.RoundTripper
}
func (l *loggingHTTPTransport) RoundTrip(r *http.Request) (*http.Response, error) {
l.logger.Tracef("%s %s", r.Method, r.URL)
return l.next.RoundTrip(r)
}
// Make a HTTP client.
func (c Config) makeHTTPClient(logger ui.Logger, config HTTPTransportConfig) *http.Client {
client := c.HTTP(config)
if debug.Flags.FailHTTP {
client.Timeout = time.Millisecond
}
client.Transport = &loggingHTTPTransport{logger, client.Transport}
return client
}
// Make a HTTP client with very short timeouts for issuing optional requests.
func (c Config) fastHTTPClient(logger ui.Logger) *http.Client {
return c.makeHTTPClient(logger, HTTPTransportConfig{
ResponseHeaderTimeout: time.Second * 5,
DialTimeout: time.Second,
KeepAlive: 30 * time.Second,
})
}
func (c Config) defaultHTTPClient(logger ui.Logger) *http.Client {
return c.makeHTTPClient(logger, HTTPTransportConfig{})
}
// Main runs the Hermit command-line application with the given config.
func Main(config Config) {
config.LogLevel = ui.AutoLevel(config.LogLevel)
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}
}
}
if len(config.SHA256Sums) == 0 {
config.SHA256Sums = hermit.ScriptSHAs
}
var (
err error
p *ui.UI
stdoutIsTTY = isatty.IsTerminal(os.Stdout.Fd())
stderrIsTTY = isatty.IsTerminal(os.Stderr.Fd())
)
if stdoutIsTTY {
// 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)
}
p.SetProgressBarEnabled(!config.CI)
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{unactivated: unactivated{Plugins: config.KongPlugins}}
} else {
envPath, err = os.Getwd()
if err != nil {
log.Fatalf("couldn't get working directory: %s", err)
}
cli = &unactivated{Plugins: config.KongPlugins}
}
userConfig, err := LoadUserConfig()
if err != nil {
log.Printf("%s: %s", userConfigPath, err)
}
githubToken := os.Getenv("HERMIT_GITHUB_TOKEN")
if githubToken == "" {
githubToken = os.Getenv("GITHUB_TOKEN")
p.Tracef("GitHub token set from GITHUB_TOKEN")
} else {
p.Tracef("GitHub token set from HERMIT_GITHUB_TOKEN")
}
kongOptions := []kong.Option{
kong.Groups{
"env": "Environment:\nCommands for creating and managing environments.",
"global": "Global:\nCommands for interacting with the shared global Hermit state.",
},
kong.Resolvers(UserConfigResolver(userConfig)),
kong.UsageOnError(),
kong.Description(help),
kong.BindTo(cli, (*cliCommon)(nil)),
kong.Bind(userConfig, config),
kong.Vars{
"version": config.Version,
"env": envPath,
},
kong.HelpOptions{
Compact: true,
},
}
kongOptions = append(kongOptions, config.KongOptions...)
parser, err := kong.New(cli, kongOptions...)
if err != nil {
log.Fatalf("failed to initialise CLI: %s", err)
}
getSource := config.PackageSourceSelector
if config.PackageSourceSelector == nil {
getSource = cache.GetSource
}
defaultHTTPClient := config.defaultHTTPClient(p)
ghClient := github.New(defaultHTTPClient, githubToken)
cache, err := cache.Open(hermit.UserStateDir, getSource, defaultHTTPClient, config.fastHTTPClient(p))
if err != nil {
log.Fatalf("failed to open cache: %s", err)
}
sta, err = state.Open(hermit.UserStateDir, config.State, cache)
if err != nil {
log.Fatalf("failed to open state: %s", err)
}
if isActivated {
env, err = hermit.OpenEnv(envPath, sta, cache.GetSource, cli.getGlobalState().Env, defaultHTTPClient, config.SHA256Sums)
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),
kongplete.WithPredictor("dir", complete.PredictDirs("*")),
kongplete.WithPredictor("hclfile", complete.PredictFiles("*.hcl")),
)
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(), ghClient, defaultHTTPClient, cache)
if err != nil && p.WillLog(ui.LevelDebug) {
p.Fatalf("%+v", err)
} else {
fatalIfError(p, err)
}
}
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)
}
}