-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathmain.go
More file actions
264 lines (223 loc) · 8.07 KB
/
main.go
File metadata and controls
264 lines (223 loc) · 8.07 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
package main
import (
"bufio"
"context"
"errors"
"fmt"
"os"
"os/exec"
"runtime/debug"
"strings"
"time"
"github.com/ActiveState/cli/cmd/state/internal/cmdtree"
"github.com/ActiveState/cli/cmd/state/internal/cmdtree/exechandlers/messenger"
anAsync "github.com/ActiveState/cli/internal/analytics/client/async"
"github.com/ActiveState/cli/internal/captain"
"github.com/ActiveState/cli/internal/config"
"github.com/ActiveState/cli/internal/constants"
"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"
"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/runbits/panics"
"github.com/ActiveState/cli/internal/subshell"
"github.com/ActiveState/cli/internal/svcctl"
cmdletErrors "github.com/ActiveState/cli/pkg/cmdlets/errors"
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"
)
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 {
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))
exitCode = 1
return
}
rollbar.SetConfig(cfg)
// 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)
isInteractive := strings.ToLower(os.Getenv(constants.NonInteractiveEnvVarName)) != "true" && out.Config().Interactive
// Run our main command logic, which is logic that defers to the error handling logic below
err = run(os.Args, isInteractive, cfg, out)
if err != nil {
exitCode, err = cmdletErrors.ParseUserFacing(err)
if err != nil {
out.Error(err)
}
// If a state tool error occurs in a VSCode integrated terminal, we want
// to pause and give time to the user to read the error message.
// But not, if we exit, because the last command in the activated sub-shell failed.
var eerr *exec.ExitError
isExitError := errors.As(err, &eerr)
if !isExitError && outFlags.ConfirmExit {
out.Print(locale.T("confirm_exit_on_error_prompt"))
br := bufio.NewReader(os.Stdin)
br.ReadLine()
}
}
}
func run(args []string, isInteractive bool, 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 cleanup()
}
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)
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)
sshell := subshell.New(cfg)
pj, err := project.NewWithVars(out, auth, sshell.Shell())
if err != nil {
return err
}
pjNamespace := ""
if pj != nil {
pjNamespace = pj.Namespace().String()
}
if err := auth.Sync(); err != nil {
logging.Warning("Could not sync authenticated state: %s", err.Error())
}
an := anAsync.New(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(isInteractive, an)
project.RegisterExpander("secrets", project.NewSecretPromptingExpander(secretsapi.Get(), prompter, cfg, auth))
// Run the actual command
cmds := cmdtree.New(primer.New(pj, out, auth, prompter, sshell, cfg, ipcClient, svcmodel, an), args...)
childCmd, err := cmds.Command().Find(args[1:])
if err != nil {
logging.Debug("Could not find child command, error: %v", err)
}
msger := messenger.New(out, svcmodel)
cmds.OnExecStart(msger.OnExecStart)
cmds.OnExecStop(msger.OnExecStop)
if childCmd != nil && !childCmd.SkipChecks() {
// Auto update to latest state tool version
if updated, err := autoUpdate(args, 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)
}
if childCmd.Name() != "update" && pj != nil && pj.IsLocked() {
if (pj.Version() != "" && pj.Version() != constants.Version) ||
(pj.VersionBranch() != "" && pj.VersionBranch() != constants.BranchName) {
return errs.AddTips(
locale.NewInputError("lock_version_mismatch", "", pj.Source().Lock, constants.BranchName, constants.Version),
locale.Tl("lock_update_legacy_version", "", constants.DocumentationURLLocking),
locale.T("lock_update_lock"),
)
}
}
}
err = cmds.Execute(args[1:])
if err != nil && !errs.IsSilent(err) {
cmdName := ""
if childCmd != nil {
cmdName = childCmd.JoinedSubCommandNames() + " "
}
err = errs.AddTips(err, locale.Tl("err_tip_run_help", "Run → [ACTIONABLE]`state {{.V0}}--help`[/RESET] for general help", cmdName))
cmdletErrors.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
}