|
| 1 | +// Copyright (c) Codesphere Inc. |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +package cmd |
| 5 | + |
| 6 | +import ( |
| 7 | + "fmt" |
| 8 | + |
| 9 | + "github.com/codesphere-cloud/cs-go/api" |
| 10 | + "github.com/codesphere-cloud/cs-go/pkg/out" |
| 11 | + "github.com/jedib0t/go-pretty/v6/table" |
| 12 | + |
| 13 | + "github.com/spf13/cobra" |
| 14 | +) |
| 15 | + |
| 16 | +type SetEnvVarCmd struct { |
| 17 | + opts SetEnvVarOptions |
| 18 | + cmd *cobra.Command |
| 19 | +} |
| 20 | + |
| 21 | +type SetEnvVarOptions struct { |
| 22 | + GlobalOptions |
| 23 | + WorkspaceId *int |
| 24 | + EnvVar map[string]string |
| 25 | +} |
| 26 | + |
| 27 | +func addSetEnvVarCmd(p *cobra.Command, opts GlobalOptions) { |
| 28 | + l := ListTeamsCmd{ |
| 29 | + cmd: &cobra.Command{ |
| 30 | + Use: "env vars", |
| 31 | + Short: "set env vars", |
| 32 | + Long: `set an environment variable for your workspace`, |
| 33 | + Example: ` |
| 34 | +Set environment variable: |
| 35 | +
|
| 36 | +$ cs set env var --workspace-id <workspace-id> --name <env-var-name> --value <env-var-value> |
| 37 | + `, |
| 38 | + }, |
| 39 | + opts: opts, |
| 40 | + } |
| 41 | + l.cmd.RunE = l.RunE |
| 42 | + p.AddCommand(l.cmd) |
| 43 | +} |
| 44 | + |
| 45 | +func (l *SetEnvVarCmd) RunE(_ *cobra.Command, args []string) (err error) { |
| 46 | + client, err := NewClient(l.opts) |
| 47 | + if err != nil { |
| 48 | + return fmt.Errorf("Failed to create Codesphere client: %w", err) |
| 49 | + } |
| 50 | + workspaceId, err := l.getWorkspaceId(client.workspaceId) |
| 51 | + if (err !== nil) { |
| 52 | + return nil, fmt.Errorf("Failed to get workspaceId (%s): %w", client, err) |
| 53 | + } |
| 54 | + err := client.SetEnvVarOnWorkspace(workspaceId, *l.Opts.EnvVar) |
| 55 | + if (err != nil) { |
| 56 | + return nil, fmt.Errorf("Failed to set environment variable: %s", *l.Opts.EnvVar) |
| 57 | + } |
| 58 | + |
| 59 | + return nil |
| 60 | +} |
| 61 | + |
| 62 | +func (l *SetEnvVarCmd) getWorkspaceId(client Client) (workspaceId int, err error) { |
| 63 | + if l.Opts.WorkspaceId != nil && *l.Opts.WorkspaceId >= 0 { |
| 64 | + workspaceId := *l.Opts.WorkspaceId |
| 65 | + return |
| 66 | + } |
| 67 | + var allWorkspaces []api.Workspace{} |
| 68 | + allWorkspaces, err = client.ListWorkspaces() |
| 69 | + if err != nil { |
| 70 | + return |
| 71 | + } |
| 72 | + for _, w := range allWorkspaces { |
| 73 | + if int(w.id) == *l.Opts.WorkspaceId |
| 74 | + workspaceId := int(w.id) |
| 75 | + return |
| 76 | + } |
| 77 | + return |
| 78 | +} |
0 commit comments