-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathcmd.go
More file actions
475 lines (413 loc) · 16 KB
/
cmd.go
File metadata and controls
475 lines (413 loc) · 16 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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
package main
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"runtime"
"runtime/debug"
"strings"
"time"
"github.com/ActiveState/cli/internal/analytics"
"github.com/ActiveState/cli/internal/analytics/client/sync"
"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/exeutils"
"github.com/ActiveState/cli/internal/fileutils"
"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/osutils"
"github.com/ActiveState/cli/internal/output"
"github.com/ActiveState/cli/internal/primer"
"github.com/ActiveState/cli/internal/rollbar"
"github.com/ActiveState/cli/internal/runbits/panics"
"github.com/ActiveState/cli/internal/subshell"
"github.com/ActiveState/cli/internal/subshell/bash"
"github.com/ActiveState/cli/pkg/cmdlets/errors"
"github.com/ActiveState/cli/pkg/project"
"github.com/ActiveState/cli/pkg/sysinfo"
"golang.org/x/crypto/ssh/terminal"
)
const AnalyticsCat = "installer"
const AnalyticsFunnelCat = "installer-funnel"
type Params struct {
sourceInstaller string
path string
updateTag string
command string
force bool
isUpdate bool
activate *project.Namespaced
activateDefault *project.Namespaced
}
func newParams() *Params {
return &Params{activate: &project.Namespaced{}, activateDefault: &project.Namespaced{}}
}
func main() {
var exitCode int
var an analytics.Dispatcher
var cfg *config.Instance
// Handle things like panics, exit codes and the closing of globals
defer func() {
if panics.HandlePanics(recover(), debug.Stack()) {
exitCode = 1
}
if cfg != nil {
events.Close("config", cfg.Close)
}
if err := events.WaitForEvents(5*time.Second, rollbar.Wait, an.Wait, logging.Close); err != nil {
logging.Warning("state-installer failed to wait for events: %v", err)
}
os.Exit(exitCode)
}()
// Set up verbose logging
logging.CurrentHandler().SetVerbose(os.Getenv("VERBOSE") != "")
// Set up rollbar reporting
rollbar.SetupRollbar(constants.StateInstallerRollbarToken)
// Allow starting the installer via a double click
captain.DisableMousetrap()
// Set up configuration handler
var err error
cfg, err = config.New()
if err != nil {
multilog.Error("Could not set up configuration handler: " + errs.JoinMessage(err))
fmt.Fprintln(os.Stderr, err.Error())
exitCode = 1
}
rollbar.SetConfig(cfg)
// Set up output handler
out, err := output.New("plain", &output.Config{
OutWriter: os.Stdout,
ErrWriter: os.Stderr,
Colored: true,
Interactive: false,
})
if err != nil {
multilog.Error("Could not set up output handler: " + errs.JoinMessage(err))
fmt.Fprintln(os.Stderr, err.Error())
exitCode = 1
return
}
var garbageBool bool
var garbageString string
// We have old install one liners around that use `-activate` instead of `--activate`
processedArgs := os.Args
for x, v := range processedArgs {
if strings.HasPrefix(v, "-activate") {
processedArgs[x] = "--activate" + strings.TrimPrefix(v, "-activate")
}
}
logging.Debug("Original Args: %v", os.Args)
logging.Debug("Processed Args: %v", processedArgs)
an = sync.New(cfg, nil, out)
an.Event(AnalyticsFunnelCat, "start")
params := newParams()
cmd := captain.NewCommand(
"state-installer",
"",
"Installs or updates the State Tool",
primer.New(nil, out, nil, nil, nil, cfg, nil, nil, an),
[]*captain.Flag{ // The naming of these flags is slightly inconsistent due to backwards compatibility requirements
{
Name: "command",
Shorthand: "c",
Description: "Run any command after the install script has completed",
Value: ¶ms.command,
},
{
Name: "activate",
Description: "Activate a project when State Tool is correctly installed",
Value: params.activate,
},
{
Name: "activate-default",
Description: "Activate a project and make it always available for use",
Value: params.activateDefault,
},
{
Name: "force",
Shorthand: "f",
Description: "Force the installation, overwriting any version of the State Tool already installed",
Value: ¶ms.force,
},
{
Name: "update",
Shorthand: "u",
Description: "Force update behaviour for the installer",
Value: ¶ms.isUpdate,
},
{
Name: "source-installer",
Hidden: true, // This is internally routed in via the install frontend (eg. install.sh, etc)
Value: ¶ms.sourceInstaller,
},
{
Name: "path",
Shorthand: "t",
Hidden: true, // Since we already expose the path as an argument, let's not confuse the user
Value: ¶ms.path,
},
// The remaining flags are for backwards compatibility (ie. we don't want to error out when they're provided)
{Name: "nnn", Shorthand: "n", Hidden: true, Value: &garbageBool}, // don't prompt; useless cause we don't prompt anyway
{Name: "channel", Hidden: true, Value: &garbageString},
{Name: "bbb", Shorthand: "b", Hidden: true, Value: &garbageString},
{Name: "vvv", Shorthand: "v", Hidden: true, Value: &garbageString},
{Name: "source-path", Hidden: true, Value: &garbageString},
},
[]*captain.Argument{
{
Name: "path",
Description: "Install into target directory <path>",
Value: ¶ms.path,
},
},
func(ccmd *captain.Command, _ []string) error {
return execute(out, cfg, an, processedArgs[1:], params)
},
)
an.Event(AnalyticsFunnelCat, "pre-exec")
err = cmd.Execute(processedArgs[1:])
if err != nil {
errors.ReportError(err, cmd, an)
if locale.IsInputError(err) {
an.EventWithLabel(AnalyticsCat, "input-error", errs.JoinMessage(err))
logging.Debug("Installer input error: " + errs.JoinMessage(err))
} else {
an.EventWithLabel(AnalyticsCat, "error", errs.JoinMessage(err))
multilog.Critical("Installer error: " + errs.JoinMessage(err))
}
an.EventWithLabel(AnalyticsFunnelCat, "fail", errs.JoinMessage(err))
exitCode, err = errors.ParseUserFacing(err)
if err != nil {
out.Error(err)
}
} else {
an.Event(AnalyticsFunnelCat, "success")
}
}
func execute(out output.Outputer, cfg *config.Instance, an analytics.Dispatcher, args []string, params *Params) error {
an.Event(AnalyticsFunnelCat, "exec")
if params.path == "" {
var err error
params.path, err = installation.InstallPathForBranch(constants.BranchName)
if err != nil {
return errs.Wrap(err, "Could not detect installation path.")
}
}
// Detect installed state tool
stateToolInstalled, installPath, err := installedOnPath(params.path, constants.BranchName)
if err != nil {
return errs.Wrap(err, "Could not detect if State Tool is already installed.")
}
if stateToolInstalled && installPath != params.path {
logging.Debug("Setting path to: %s", installPath)
params.path = installPath
}
// If this is a fresh installation we ensure that the target directory is empty
if !stateToolInstalled && fileutils.DirExists(params.path) && !params.force {
empty, err := fileutils.IsEmptyDir(params.path)
if err != nil {
return errs.Wrap(err, "Could not check if install path is empty")
}
if !empty {
return locale.NewInputError("err_install_nonempty_dir", "Installation path must be an empty directory: {{.V0}}", params.path)
}
}
// We expect the installer payload to be in the same directory as the installer itself
payloadPath := filepath.Dir(osutils.Executable())
route := "install"
if params.isUpdate {
route = "update"
}
an.Event(AnalyticsFunnelCat, route)
// Check if state tool already installed
if !params.isUpdate && !params.force && stateToolInstalled {
logging.Debug("Cancelling out because State Tool is already installed")
out.Print(fmt.Sprintf("State Tool Package Manager is already installed at [NOTICE]%s[/RESET]. To reinstall use the [ACTIONABLE]--force[/RESET] flag.", installPath))
an.Event(AnalyticsFunnelCat, "already-installed")
params.isUpdate = true
return postInstallEvents(out, cfg, an, params)
}
if err := installOrUpdateFromLocalSource(out, cfg, an, payloadPath, params); err != nil {
return err
}
storeInstallSource(params.sourceInstaller)
return postInstallEvents(out, cfg, an, params)
}
// installOrUpdateFromLocalSource is invoked when we're performing an installation where the payload is already provided
func installOrUpdateFromLocalSource(out output.Outputer, cfg *config.Instance, an analytics.Dispatcher, payloadPath string, params *Params) error {
logging.Debug("Install from local source")
an.Event(AnalyticsFunnelCat, "local-source")
if !params.isUpdate {
// install.sh or install.ps1 downloaded this installer and is running it.
out.Print(output.Title("Installing State Tool Package Manager"))
out.Print(`The State Tool lets you install and manage your language runtimes.` + "\n\n" +
`ActiveState collects usage statistics and diagnostic data about failures. ` + "\n" +
`By using the State Tool Package Manager you agree to the terms of ActiveState’s Privacy Policy, ` + "\n" +
`available at: [ACTIONABLE]https://www.activestate.com/company/privacy-policy[/RESET]` + "\n")
}
if err := assertCompatibility(); err != nil {
// Don't wrap, we want the error from assertCompatibility to be returned -- installer doesn't have intelligent error handling yet
// https://activestatef.atlassian.net/browse/DX-957
return err
}
installer, err := NewInstaller(cfg, out, payloadPath, params)
if err != nil {
out.Print(fmt.Sprintf("[ERROR]Could not create installer: %s[/RESET]", errs.JoinMessage(err)))
return err
}
if params.isUpdate {
out.Fprint(os.Stdout, "• Installing Update... ")
} else {
out.Fprint(os.Stdout, fmt.Sprintf("• Installing State Tool to [NOTICE]%s[/RESET]... ", installer.InstallPath()))
}
// Run installer
an.Event(AnalyticsFunnelCat, "pre-installer")
if err := installer.Install(); err != nil {
out.Print("[ERROR]x Failed[/RESET]")
return err
}
an.Event(AnalyticsFunnelCat, "post-installer")
out.Print("[SUCCESS]✔ Done[/RESET]")
if !params.isUpdate {
out.Print("")
out.Print(output.Title("State Tool Package Manager Installation Complete"))
out.Print("State Tool Package Manager has been successfully installed.")
}
return nil
}
func postInstallEvents(out output.Outputer, cfg *config.Instance, an analytics.Dispatcher, params *Params) error {
an.Event(AnalyticsFunnelCat, "post-install-events")
installPath, err := resolveInstallPath(params.path)
if err != nil {
return errs.Wrap(err, "Could not resolve installation path")
}
binPath, err := installation.BinPathFromInstallPath(installPath)
if err != nil {
return errs.Wrap(err, "Could not detect installation bin path")
}
stateExe, err := installation.StateExecFromDir(installPath)
if err != nil {
return locale.WrapError(err, "err_state_exec")
}
ss := subshell.New(cfg)
if ss.Shell() == bash.Name && runtime.GOOS == "darwin" {
out.Print(locale.T("warning_macos_bash"))
}
// Execute requested command, these are mutually exclusive
switch {
// Execute provided --command
case params.command != "":
an.Event(AnalyticsFunnelCat, "forward-command")
out.Print(fmt.Sprintf("\nRunning `[ACTIONABLE]%s[/RESET]`\n", params.command))
cmd, args := exeutils.DecodeCmd(params.command)
if _, _, err := exeutils.ExecuteAndPipeStd(cmd, args, envSlice(binPath)); err != nil {
an.EventWithLabel(AnalyticsFunnelCat, "forward-command-err", err.Error())
return errs.Silence(errs.Wrap(err, "Running provided command failed, error returned: %s", errs.JoinMessage(err)))
}
// Activate provided --activate Namespace
case params.activate.IsValid():
an.Event(AnalyticsFunnelCat, "forward-activate")
out.Print(fmt.Sprintf("\nRunning `[ACTIONABLE]state activate %s[/RESET]`\n", params.activate.String()))
if _, _, err := exeutils.ExecuteAndPipeStd(stateExe, []string{"activate", params.activate.String()}, envSlice(binPath)); err != nil {
an.EventWithLabel(AnalyticsFunnelCat, "forward-activate-err", err.Error())
return errs.Silence(errs.Wrap(err, "Could not activate %s, error returned: %s", params.activate.String(), errs.JoinMessage(err)))
}
// Activate provided --activate-default Namespace
case params.activateDefault.IsValid():
an.Event(AnalyticsFunnelCat, "forward-activate-default")
out.Print(fmt.Sprintf("\nRunning `[ACTIONABLE]state activate --default %s[/RESET]`\n", params.activateDefault.String()))
if _, _, err := exeutils.ExecuteAndPipeStd(stateExe, []string{"activate", params.activateDefault.String(), "--default"}, envSlice(binPath)); err != nil {
an.EventWithLabel(AnalyticsFunnelCat, "forward-activate-default-err", err.Error())
return errs.Silence(errs.Wrap(err, "Could not activate %s, error returned: %s", params.activateDefault.String(), errs.JoinMessage(err)))
}
case !params.isUpdate && terminal.IsTerminal(int(os.Stdin.Fd())) && os.Getenv(constants.InstallerNoSubshell) != "true" && os.Getenv("TERM") != "dumb":
if err := ss.SetEnv(osutils.InheritEnv(envMap(binPath))); err != nil {
return locale.WrapError(err, "err_subshell_setenv")
}
if err := ss.Activate(nil, cfg, out); err != nil {
return errs.Wrap(err, "Error activating subshell: %s", errs.JoinMessage(err))
}
if err = <-ss.Errors(); err != nil {
return errs.Wrap(err, "Error during subshell execution: %s", errs.JoinMessage(err))
}
}
return nil
}
func envSlice(binPath string) []string {
return []string{
"PATH=" + binPath + string(os.PathListSeparator) + os.Getenv("PATH"),
constants.DisableErrorTipsEnvVarName + "=true",
}
}
func envMap(binPath string) map[string]string {
return map[string]string{
"PATH": binPath + string(os.PathListSeparator) + os.Getenv("PATH"),
}
}
// storeInstallSource writes the name of the install client (eg. install.sh) to the appdata dir
// this is used in analytics to give us a sense for where our users are coming from
func storeInstallSource(installSource string) {
if installSource == "" {
installSource = "state-installer"
}
appData, err := storage.AppDataPath()
if err != nil {
multilog.Error("Could not store install source due to AppDataPath error: %s", errs.JoinMessage(err))
return
}
if err := fileutils.WriteFile(filepath.Join(appData, constants.InstallSourceFile), []byte(installSource)); err != nil {
multilog.Error("Could not store install source due to WriteFile error: %s", errs.JoinMessage(err))
}
}
func resolveInstallPath(path string) (string, error) {
if path != "" {
return filepath.Abs(path)
} else {
return installation.DefaultInstallPath()
}
}
func assertCompatibility() error {
if sysinfo.OS() == sysinfo.Windows {
osv, err := sysinfo.OSVersion()
if err != nil {
return locale.WrapError(err, "windows_compatibility_warning", "", err.Error())
} else if osv.Major < 10 || (osv.Major == 10 && osv.Micro < 17134) {
return locale.WrapError(err, "windows_compatibility_error", "", osv.Name, osv.Version)
}
}
return nil
}
func noArgs() bool {
return len(os.Args[1:]) == 0
}
func shouldUpdateInstalledStateTool(stateExePath string) bool {
logging.Debug("Checking if installed state tool is an older version.")
stdout, _, err := exeutils.ExecSimple(stateExePath, []string{"--version", "--output", "json"}, os.Environ())
if err != nil {
logging.Debug("Could not determine state tool version.")
return true // probably corrupted install
}
stdout = strings.Split(stdout, "\x00")[0] // TODO: DX-328
versionData := installation.VersionData{}
err = json.Unmarshal([]byte(stdout), &versionData)
if err != nil {
logging.Debug("Could not read state tool version output")
return true
}
if versionData.Branch != constants.BranchName {
logging.Debug("State tool branch is different from installer.")
return false // do not update, require --force
}
if versionData.Version != constants.Version {
logging.Debug("State tool version is different from installer.")
return true
}
return false
}