-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathset_env_vars.go
More file actions
73 lines (61 loc) · 1.94 KB
/
set_env_vars.go
File metadata and controls
73 lines (61 loc) · 1.94 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
// Copyright (c) Codesphere Inc.
// SPDX-License-Identifier: Apache-2.0
package cmd
import (
"fmt"
"log"
"github.com/codesphere-cloud/cs-go/pkg/cs"
"github.com/codesphere-cloud/cs-go/pkg/io"
"github.com/spf13/cobra"
)
type SetEnvVarCmd struct {
Opts SetEnvVarOptions
cmd *cobra.Command
}
type SetEnvVarOptions struct {
GlobalOptions
EnvVar *[]string
}
func AddSetEnvVarCmd(p *cobra.Command, opts GlobalOptions) {
l := SetEnvVarCmd{
cmd: &cobra.Command{
Use: "set-env",
Short: "Set environment variables",
Long: `Set environment variables in a workspace`,
Example: io.FormatExampleCommands("set-env", []io.Example{
{Cmd: "--workspace <workspace-id> --env-var foo=bar", Desc: "Set single environment variable"},
{Cmd: "--workspace <workspace-id> --env-var foo=bar --env-var hello=world", Desc: "Set multiple environment variables"},
}),
},
Opts: SetEnvVarOptions{GlobalOptions: opts},
}
l.cmd.RunE = l.RunE
l.parseFlags()
p.AddCommand(l.cmd)
}
func (l *SetEnvVarCmd) parseFlags() {
l.Opts.EnvVar = l.cmd.Flags().StringArrayP("env-var", "e", []string{}, "env vars to set in form key=val")
}
func (l *SetEnvVarCmd) RunE(_ *cobra.Command, args []string) (err error) {
client, err := NewClient(l.Opts.GlobalOptions)
if err != nil {
return fmt.Errorf("failed to create Codesphere client: %w", err)
}
return l.SetEnvironmentVariables(client)
}
func (l *SetEnvVarCmd) SetEnvironmentVariables(client Client) (err error) {
envVarMap, err := cs.ArgToEnvVarMap(*l.Opts.EnvVar)
if err != nil {
return fmt.Errorf("failed to parse environment variables: %w", err)
}
wsId, err := l.Opts.GetWorkspaceId()
if err != nil {
return fmt.Errorf("failed to get workspace ID: %w", err)
}
err = client.SetEnvVarOnWorkspace(wsId, envVarMap)
if err != nil {
return fmt.Errorf("failed to set environment variables %v: %w", envVarMap, err)
}
log.Printf("Environment variables set successfully on workspace %d\n", wsId)
return nil
}