-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathdeploy.go
More file actions
387 lines (327 loc) · 12.2 KB
/
deploy.go
File metadata and controls
387 lines (327 loc) · 12.2 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
package deploy
import (
"fmt"
"os"
"path/filepath"
rt "runtime"
"strings"
"github.com/go-openapi/strfmt"
"github.com/ActiveState/cli/internal/analytics"
"github.com/ActiveState/cli/internal/assets"
"github.com/ActiveState/cli/internal/config"
"github.com/ActiveState/cli/internal/errs"
"github.com/ActiveState/cli/internal/exeutils"
"github.com/ActiveState/cli/internal/fileutils"
"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/rtutils"
"github.com/ActiveState/cli/internal/runbits"
"github.com/ActiveState/cli/internal/runbits/rtusage"
"github.com/ActiveState/cli/internal/subshell"
"github.com/ActiveState/cli/internal/subshell/sscommon"
"github.com/ActiveState/cli/pkg/platform/authentication"
"github.com/ActiveState/cli/pkg/platform/model"
"github.com/ActiveState/cli/pkg/platform/runtime"
"github.com/ActiveState/cli/pkg/platform/runtime/setup"
"github.com/ActiveState/cli/pkg/platform/runtime/target"
"github.com/ActiveState/cli/pkg/project"
)
type Params struct {
Namespace project.Namespaced
Path string
Force bool
UserScope bool
}
// RequiresAdministratorRights checks if the requested deploy command requires administrator privileges.
func RequiresAdministratorRights(step Step, userScope bool) bool {
if rt.GOOS != "windows" {
return false
}
return (step == UnsetStep || step == ConfigureStep) && !userScope
}
type Deploy struct {
auth *authentication.Auth
output output.Outputer
subshell subshell.SubShell
step Step
cfg *config.Instance
analytics analytics.Dispatcher
svcModel *model.SvcModel
}
type primeable interface {
primer.Auther
primer.Outputer
primer.Subsheller
primer.Configurer
primer.Analyticer
primer.SvcModeler
}
func NewDeploy(step Step, prime primeable) *Deploy {
return &Deploy{
prime.Auth(),
prime.Output(),
prime.Subshell(),
step,
prime.Config(),
prime.Analytics(),
prime.SvcModel(),
}
}
func (d *Deploy) Run(params *Params) error {
if RequiresAdministratorRights(d.step, params.UserScope) {
isAdmin, err := osutils.IsAdmin()
if err != nil {
multilog.Error("Could not check for windows administrator privileges: %v", err)
}
if !isAdmin {
return locale.NewError("err_deploy_admin_privileges_required", "Administrator rights are required for this command to modify the system PATH. If you want to deploy to the user environment, please adjust the command line flags.")
}
}
commitID, err := d.commitID(params.Namespace)
if err != nil {
return locale.WrapError(err, "err_deploy_commitid", "Could not grab commit ID for project: {{.V0}}.", params.Namespace.String())
}
// Headless argument is simply false here as you cannot deploy a headless project
rtTarget := target.NewCustomTarget(params.Namespace.Owner, params.Namespace.Project, commitID, params.Path, target.TriggerDeploy, false) /* TODO: handle empty path */
logging.Debug("runSteps: %s", d.step.String())
if d.step == UnsetStep || d.step == InstallStep {
logging.Debug("Running install step")
if err := d.install(rtTarget); err != nil {
return err
}
}
if d.step == UnsetStep || d.step == ConfigureStep {
logging.Debug("Running configure step")
if err := d.configure(params.Namespace, rtTarget, params.UserScope); err != nil {
return err
}
}
if d.step == UnsetStep || d.step == SymlinkStep {
logging.Debug("Running symlink step")
if err := d.symlink(rtTarget, params.Force); err != nil {
return err
}
}
if d.step == UnsetStep || d.step == ReportStep {
logging.Debug("Running report step")
if err := d.report(rtTarget); err != nil {
return err
}
}
return nil
}
func (d *Deploy) commitID(namespace project.Namespaced) (strfmt.UUID, error) {
commitID := namespace.CommitID
if commitID == nil {
branch, err := model.DefaultBranchForProjectName(namespace.Owner, namespace.Project)
if err != nil {
return "", errs.Wrap(err, "Could not detect default branch")
}
if branch.CommitID == nil {
return "", locale.NewInputError(
"err_deploy_no_commits",
"The project '{{.V0}}' does not have any packages configured, please add add some packages first.", namespace.String())
}
commitID = branch.CommitID
}
if commitID == nil {
return "", errs.New("commitID is nil")
}
return *commitID, nil
}
func (d *Deploy) install(rtTarget setup.Targeter) (rerr error) {
d.output.Notice(output.Title(locale.T("deploy_install")))
rtusage.PrintRuntimeUsage(d.svcModel, d.output, rtTarget.Owner())
rti, err := runtime.New(rtTarget, d.analytics, d.svcModel)
if err == nil {
d.output.Notice(locale.Tl("deploy_already_installed", "Already installed"))
return nil
}
if !runtime.IsNeedsUpdateError(err) {
return locale.WrapError(err, "deploy_runtime_err", "Could not initialize runtime")
}
pg := runbits.NewRuntimeProgressIndicator(d.output)
defer rtutils.Closer(pg.Close, &rerr)
if err := rti.Update(d.auth, pg); err != nil {
return locale.WrapError(err, "deploy_install_failed", "Installation failed.")
}
// Todo Remove with https://www.pivotaltracker.com/story/show/178161240
// call rti.Environ as this completes the runtime activation cycle:
// It ensures that the analytics event for failure / success are sent
_, _ = rti.Env(false, false)
if rt.GOOS == "windows" {
contents, err := assets.ReadFile("scripts/setenv.bat")
if err != nil {
return err
}
err = fileutils.WriteFile(filepath.Join(rtTarget.Dir(), "setenv.bat"), contents)
if err != nil {
return locale.WrapError(err, "err_deploy_write_setenv", "Could not create setenv batch scriptfile at path: %s", rtTarget.Dir())
}
}
d.output.Print(locale.Tl("deploy_install_done", "Installation completed"))
return nil
}
func (d *Deploy) configure(namespace project.Namespaced, rtTarget setup.Targeter, userScope bool) error {
rti, err := runtime.New(rtTarget, d.analytics, d.svcModel)
if err != nil {
if runtime.IsNeedsUpdateError(err) {
return locale.NewInputError("err_deploy_run_install")
}
return locale.WrapError(err, "deploy_runtime_err", "Could not initialize runtime")
}
env, err := rti.Env(false, false)
if err != nil {
return err
}
d.output.Notice(output.Title(locale.Tr("deploy_configure_shell", d.subshell.Shell())))
// Configure available shells
err = subshell.ConfigureAvailableShells(d.subshell, d.cfg, env, sscommon.DeployID, userScope)
if err != nil {
return locale.WrapError(err, "err_deploy_subshell_write", "Could not write environment information to your shell configuration.")
}
binPath := filepath.Join(rtTarget.Dir(), "bin")
if err := fileutils.MkdirUnlessExists(binPath); err != nil {
return locale.WrapError(err, "err_deploy_binpath", "Could not create bin directory.")
}
// Write global env file
d.output.Notice(fmt.Sprintf("Writing shell env file to %s\n", filepath.Join(rtTarget.Dir(), "bin")))
err = d.subshell.SetupShellRcFile(binPath, env, &namespace)
if err != nil {
return locale.WrapError(err, "err_deploy_subshell_rc_file", "Could not create environment script.")
}
return nil
}
func (d *Deploy) symlink(rtTarget setup.Targeter, overwrite bool) error {
rti, err := runtime.New(rtTarget, d.analytics, d.svcModel)
if err != nil {
if runtime.IsNeedsUpdateError(err) {
return locale.NewInputError("err_deploy_run_install")
}
return locale.WrapError(err, "deploy_runtime_err", "Could not initialize runtime")
}
var path string
if rt.GOOS != "windows" {
// Retrieve path to write symlinks to
path, err = usablePath()
if err != nil {
return locale.WrapError(err, "err_usablepath", "Could not retrieve a usable PATH")
}
}
// Retrieve artifact binary directories
bins, err := rti.ExecutablePaths()
if err != nil {
return locale.WrapError(err, "err_symlink_exes", "Could not detect executable paths")
}
exes, err := exeutils.Executables(bins)
if err != nil {
return locale.WrapError(err, "err_symlink_exes", "Could not detect executables")
}
// Remove duplicate executables as per PATH and PATHEXT
exes, err = exeutils.UniqueExes(exes, os.Getenv("PATHEXT"))
if err != nil {
return locale.WrapError(err, "err_unique_exes", "Could not detect unique executables, make sure your PATH and PATHEXT environment variables are properly configured.")
}
if rt.GOOS != "windows" {
// Symlink to PATH (eg. /usr/local/bin)
if err := symlinkWithTarget(overwrite, path, exes, d.output); err != nil {
return locale.WrapError(err, "err_symlink", "Could not create symlinks to {{.V0}}.", path)
}
} else {
d.output.Notice(locale.Tl("deploy_symlink_skip", "Skipped on Windows"))
}
return nil
}
// SymlinkTargetPath adds the .lnk file ending on windows
func symlinkTargetPath(targetDir string, path string) string {
target := filepath.Clean(filepath.Join(targetDir, filepath.Base(path)))
if rt.GOOS != "windows" {
return target
}
oldExt := filepath.Ext(target)
return target[0:len(target)-len(oldExt)] + ".lnk"
}
// symlinkWithTarget creates symlinks in the target path of all executables found in the bins dir
// It overwrites existing files, if the overwrite flag is set.
// On Windows the same executable name can have several file extensions,
// therefore executables are only symlinked if it has not been symlinked to a
// target (with the same or a different extension) from a different directory.
// Also: Only the executable with the highest priority according to pathExt is symlinked.
func symlinkWithTarget(overwrite bool, symlinkPath string, exePaths []string, out output.Outputer) error {
out.Notice(output.Title(locale.Tr("deploy_symlink", symlinkPath)))
if err := fileutils.MkdirUnlessExists(symlinkPath); err != nil {
return locale.WrapInputError(
err, "err_deploy_mkdir",
"Could not create directory at {{.V0}}, make sure you have permissions to write to {{.V1}}.", symlinkPath, filepath.Dir(symlinkPath))
}
for _, exePath := range exePaths {
symlink := symlinkTargetPath(symlinkPath, exePath)
// If the link already exists we may have to overwrite it, skip it, or fail..
if fileutils.TargetExists(symlink) {
// If the existing symlink already matches the one we want to create, skip it
skip, err := shouldSkipSymlink(symlink, exePath)
if err != nil {
return locale.WrapError(err, "err_deploy_shouldskip", "Could not determine if link already exists.")
}
if skip {
continue
}
// If we're trying to overwrite a link not owned by us but overwrite=false then we should fail
if !overwrite {
return locale.NewInputError(
"err_deploy_symlink_target_exists",
"Cannot create symlink as the target already exists: {{.V0}}. Use '--force' to overwrite any existing files.", symlink)
}
// We're about to overwrite, so if this link isn't owned by us we should let the user know
out.Notice(locale.Tr("deploy_overwrite_target", symlink))
// to overwrite the existing file, we have to remove it first, or the link command will fail
if err := os.Remove(symlink); err != nil {
return locale.WrapInputError(
err, "err_deploy_overwrite",
"Could not overwrite {{.V0}}, make sure you have permissions to write to this file.", symlink)
}
}
if err := link(exePath, symlink); err != nil {
return err
}
}
return nil
}
type Report struct {
BinaryDirectories []string
Environment map[string]string
}
func (d *Deploy) report(rtTarget setup.Targeter) error {
rti, err := runtime.New(rtTarget, d.analytics, d.svcModel)
if err != nil {
if runtime.IsNeedsUpdateError(err) {
return locale.NewInputError("err_deploy_run_install")
}
return locale.WrapError(err, "deploy_runtime_err", "Could not initialize runtime")
}
env, err := rti.Env(false, false)
if err != nil {
return err
}
var bins []string
if path, ok := env["PATH"]; ok {
delete(env, "PATH")
bins = strings.Split(path, string(os.PathListSeparator))
}
d.output.Notice(output.Title(locale.T("deploy_info")))
d.output.Print(Report{
BinaryDirectories: bins,
Environment: env,
})
d.output.Notice(output.Title(locale.T("deploy_restart")))
if rt.GOOS == "windows" {
d.output.Notice(locale.Tr("deploy_restart_cmd", filepath.Join(rtTarget.Dir(), "setenv.bat")))
} else {
d.output.Notice(locale.T("deploy_restart_shell"))
}
return nil
}