-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathmain.go
More file actions
308 lines (264 loc) · 9.58 KB
/
main.go
File metadata and controls
308 lines (264 loc) · 9.58 KB
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
299
300
301
302
303
304
305
306
307
308
package main
import (
"context"
"errors"
"fmt"
"os"
"runtime/debug"
"strings"
"time"
"github.com/ActiveState/cli/cmd/state/internal/cmdtree"
"github.com/ActiveState/cli/cmd/state/internal/cmdtree/exechandlers/notifier"
anAsync "github.com/ActiveState/cli/internal/analytics/client/async"
anaConst "github.com/ActiveState/cli/internal/analytics/constants"
"github.com/ActiveState/cli/internal/captain"
"github.com/ActiveState/cli/internal/config"
"github.com/ActiveState/cli/internal/constants"
"github.com/ActiveState/cli/internal/constraints"
"github.com/ActiveState/cli/internal/errs"
"github.com/ActiveState/cli/internal/events"
"github.com/ActiveState/cli/internal/installation"
"github.com/ActiveState/cli/internal/installation/storage"
"github.com/ActiveState/cli/internal/locale"
"github.com/ActiveState/cli/internal/logging"
configMediator "github.com/ActiveState/cli/internal/mediators/config"
"github.com/ActiveState/cli/internal/migrator"
"github.com/ActiveState/cli/internal/multilog"
"github.com/ActiveState/cli/internal/output"
"github.com/ActiveState/cli/internal/primer"
"github.com/ActiveState/cli/internal/profile"
"github.com/ActiveState/cli/internal/prompt"
_ "github.com/ActiveState/cli/internal/prompt" // Sets up survey defaults
"github.com/ActiveState/cli/internal/rollbar"
"github.com/ActiveState/cli/internal/rtutils"
runbits_errors "github.com/ActiveState/cli/internal/runbits/errors"
"github.com/ActiveState/cli/internal/runbits/panics"
"github.com/ActiveState/cli/internal/subshell"
"github.com/ActiveState/cli/internal/svcctl"
"github.com/ActiveState/cli/pkg/platform/api"
secretsapi "github.com/ActiveState/cli/pkg/platform/api/secrets"
"github.com/ActiveState/cli/pkg/platform/authentication"
"github.com/ActiveState/cli/pkg/platform/model"
"github.com/ActiveState/cli/pkg/project"
"github.com/ActiveState/cli/pkg/projectfile"
)
func main() {
startTime := time.Now()
var exitCode int
// Set up logging
rollbar.SetupRollbar(constants.StateToolRollbarToken)
// We have to disable mouse trap as without it the state:// protocol cannot work
captain.DisableMousetrap()
var cfg *config.Instance
defer func() {
// Handle panics gracefully, and ensure that we exit with non-zero code
if panics.HandlePanics(recover(), debug.Stack()) {
exitCode = 1
}
// ensure rollbar messages are called
if err := events.WaitForEvents(5*time.Second, rollbar.Wait, authentication.LegacyClose, logging.Close); err != nil {
logging.Warning("Failed waiting for events: %v", err)
}
if cfg != nil {
events.Close("config", cfg.Close)
}
profile.Measure("main", startTime)
// exit with exitCode
os.Exit(exitCode)
}()
var err error
cfg, err = config.New()
if err != nil {
if !locale.IsInputError(err) {
multilog.Critical("Could not initialize config: %v", errs.JoinMessage(err))
fmt.Fprintf(os.Stderr, "Could not load config, if this problem persists please reinstall the State Tool. Error: %s\n", errs.JoinMessage(err))
} else {
for _, err2 := range locale.UnpackError(err) {
fmt.Fprintf(os.Stderr, err2.Error())
}
}
exitCode = 1
return
}
rollbar.SetConfig(cfg)
api.SetConfig(cfg)
// Configuration options
// This should only be used if the config option is not exclusive to one package.
configMediator.RegisterOption(constants.OptinBuildscriptsConfig, configMediator.Bool, false)
// Set up our output formatter/writer
outFlags := parseOutputFlags(os.Args)
shellName, _ := subshell.DetectShell(cfg)
out, err := initOutput(outFlags, "", shellName)
if err != nil {
multilog.Critical("Could not initialize outputer: %s", errs.JoinMessage(err))
os.Stderr.WriteString(locale.Tr("err_main_outputer", err.Error()))
exitCode = 1
return
}
// Set up our legacy outputer
setPrinterColors(outFlags)
// Run our main command logic, which is logic that defers to the error handling logic below
err = run(os.Args, cfg, out)
if err != nil {
exitCode, err = runbits_errors.ParseUserFacing(err)
if err != nil {
out.Error(err)
}
}
}
func run(args []string, cfg *config.Instance, out output.Outputer) (rerr error) {
defer profile.Measure("main:run", time.Now())
// Set up profiling
if os.Getenv(constants.CPUProfileEnvVarName) != "" {
cleanup, err := profile.CPU()
if err != nil {
return err
}
defer rtutils.Closer(cleanup, &rerr)
}
logging.CurrentHandler().SetVerbose(os.Getenv("VERBOSE") != "" || argsHaveVerbose(args))
logging.Debug("ConfigPath: %s", cfg.ConfigPath())
logging.Debug("CachePath: %s", storage.CachePath())
svcExec, err := installation.ServiceExec()
if err != nil {
return errs.Wrap(err, "Could not get service info")
}
ipcClient := svcctl.NewDefaultIPCClient()
argText := strings.Join(args, " ")
svcPort, err := svcctl.EnsureExecStartedAndLocateHTTP(ipcClient, svcExec, argText, out)
if err != nil {
return locale.WrapError(err, "start_svc_failed", "Failed to start state-svc at state tool invocation")
}
svcmodel := model.NewSvcModel(svcPort)
// Amend Rollbar data to also send the state-svc log tail. This cannot be done inside the rollbar
// package itself because importing pkg/platform/model creates an import cycle.
rollbar.AddLogDataAmender(func(logData string) string {
ctx, cancel := context.WithTimeout(context.Background(), model.SvcTimeoutMinimal)
defer cancel()
svcLogData, err := svcmodel.FetchLogTail(ctx)
if err != nil {
svcLogData = fmt.Sprintf("Could not fetch state-svc log: %v", err)
}
logData += "\nstate-svc log:\n"
if len(svcLogData) == logging.TailSize {
logData += "<truncated>\n"
}
logData += svcLogData
return logData
})
auth := authentication.New(cfg)
defer events.Close("auth", auth.Close)
if auth.AvailableAPIToken() != "" {
jwt, err := svcmodel.GetJWT(context.Background())
if err != nil {
multilog.Critical("Could not get JWT: %v", errs.JoinMessage(err))
}
if err != nil || jwt == nil {
// Could not authenticate; user got logged out
auth.Logout()
} else {
auth.UpdateSession(jwt)
}
}
projectfile.RegisterMigrator(migrator.NewMigrator(auth, cfg, svcmodel))
// Retrieve project file
if os.Getenv("ACTIVESTATE_PROJECT") != "" {
out.Notice(locale.T("warning_activestate_project_env_var"))
}
pjPath, err := projectfile.GetProjectFilePath()
var errNoProjectFromEnv *projectfile.ErrorNoProjectFromEnv
if err != nil && errors.As(err, &errNoProjectFromEnv) {
// Fail if we are meant to inherit the projectfile from the environment, but the file doesn't exist
return err
}
// Set up project (if we have a valid path)
var pj *project.Project
if pjPath != "" {
pjf, err := projectfile.FromPath(pjPath)
if err != nil {
return err
}
pj, err = project.New(pjf, out)
if err != nil {
return err
}
}
pjNamespace := ""
if pj != nil {
pjNamespace = pj.Namespace().String()
}
an := anAsync.New(anaConst.SrcStateTool, svcmodel, cfg, auth, out, pjNamespace)
defer func() {
if err := events.WaitForEvents(time.Second, an.Wait); err != nil {
logging.Warning("Failed waiting for events: %v", err)
}
}()
// Set up prompter
prompter := prompt.New(out, an)
// Set up conditional, which accesses a lot of primer data
sshell := subshell.New(cfg)
conditional := constraints.NewPrimeConditional(auth, pj, sshell.Shell())
project.RegisterConditional(conditional)
if err := project.RegisterExpander("mixin", project.NewMixin(auth).Expander); err != nil {
logging.Debug("Could not register mixin expander: %v", err)
}
if err := project.RegisterExpander("secrets", project.NewSecretPromptingExpander(secretsapi.Get(auth), prompter, cfg, auth)); err != nil {
logging.Debug("Could not register secrets expander: %v", err)
}
// Run the actual command
cmds := cmdtree.New(primer.New(pj, out, auth, prompter, sshell, conditional, cfg, ipcClient, svcmodel, an), args...)
childCmd, err := cmds.Command().FindChild(args[1:])
if err != nil {
logging.Debug("Could not find child command, error: %v", err)
}
notifier := notifier.New(out, svcmodel)
cmds.OnExecStart(notifier.OnExecStart)
cmds.OnExecStop(notifier.OnExecStop)
// Auto update to latest state tool version if possible.
if updated, err := autoUpdate(svcmodel, args, childCmd, cfg, an, out); err == nil && updated {
return nil // command will be run by updated exe
} else if err != nil {
multilog.Error("Failed to autoupdate: %v", err)
}
// Check to see if this state tool version is different from the lock version.
if (childCmd == nil || !childCmd.SkipChecks()) && pj != nil && pj.IsLocked() {
if (pj.Version() != "" && pj.Version() != constants.Version) ||
(pj.Channel() != "" && pj.Channel() != constants.ChannelName) {
return errs.AddTips(
locale.NewInputError("lock_version_mismatch", "", pj.Source().Lock, constants.ChannelName, constants.Version),
locale.Tr("lock_update_legacy_version", constants.DocumentationURLLocking),
locale.T("lock_update_lock"),
)
}
}
err = cmds.Execute(args[1:])
if err != nil {
cmdName := ""
if childCmd != nil {
cmdName = childCmd.JoinedSubCommandNames() + " "
}
if !out.Type().IsStructured() {
err = errs.AddTips(err, locale.Tl("err_tip_run_help", "Run → '[ACTIONABLE]state {{.V0}}--help[/RESET]' for general help", cmdName))
}
runbits_errors.ReportError(err, cmds.Command(), an)
}
return err
}
func argsHaveVerbose(args []string) bool {
var isRunOrExec bool
nextArg := 0
for i, arg := range args {
if arg == "run" || arg == "exec" {
isRunOrExec = true
nextArg = i + 1
}
// Skip looking for verbose args after --, eg. for `state shim -- perl -v`
if arg == "--" {
return false
}
if (arg == "--verbose" || arg == "-v") && (!isRunOrExec || i == nextArg) {
return true
}
}
return false
}