-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathexec.go
More file actions
86 lines (72 loc) · 2.34 KB
/
exec.go
File metadata and controls
86 lines (72 loc) · 2.34 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
// Copyright (c) Codesphere Inc.
// SPDX-License-Identifier: Apache-2.0
package cmd
import (
"fmt"
"os"
"strings"
"github.com/codesphere-cloud/cs-go/pkg/cs"
"github.com/codesphere-cloud/cs-go/pkg/io"
"github.com/spf13/cobra"
)
type ExecCmd struct {
cmd *cobra.Command
Opts ExecOptions
}
type ExecOptions struct {
GlobalOptions
EnvVar *[]string
WorkDir *string
}
func (c *ExecCmd) RunE(_ *cobra.Command, args []string) error {
command := strings.Join(args, " ")
fmt.Printf("running command %s\n", command)
client, err := NewClient(c.Opts.GlobalOptions)
if err != nil {
return fmt.Errorf("failed to create Codesphere client: %w", err)
}
return c.ExecCommand(client, command)
}
func AddExecCmd(rootCmd *cobra.Command, opts GlobalOptions) {
exec := ExecCmd{
cmd: &cobra.Command{
Use: "exec",
Args: cobra.MinimumNArgs(1),
Short: "Run a command in Codesphere workspace",
Long: io.Long(`Run a command in a Codesphere workspace.
Output will be printed to STDOUT, errors to STDERR.`),
Example: io.FormatExampleCommands("exec", []io.Example{
{Cmd: "-- echo hello world", Desc: "Print `hello world`"},
{Cmd: "-- find .", Desc: "List all files in workspace"},
{Cmd: "-d user -- find .", Desc: "List all files in the user directory"},
{Cmd: "-e FOO=bar -- 'echo $FOO'", Desc: "Set custom environment variables for this command"},
}),
},
Opts: ExecOptions{GlobalOptions: opts},
}
exec.Opts.EnvVar = exec.cmd.Flags().StringArrayP("env", "e", []string{}, "Additional environment variables to pass to the command in the form key=val")
exec.Opts.WorkDir = exec.cmd.Flags().StringP("workdir", "d", ".", "Working directory for the command")
rootCmd.AddCommand(exec.cmd)
exec.cmd.RunE = exec.RunE
}
func (c *ExecCmd) ExecCommand(client Client, command string) error {
wsId, err := c.Opts.GetWorkspaceId()
if err != nil {
return fmt.Errorf("failed to get workspace ID: %w", err)
}
envVarMap, err := cs.ArgToEnvVarMap(*c.Opts.EnvVar)
if err != nil {
return fmt.Errorf("failed to parse environment variables: %w", err)
}
stdout, stderr, err := client.ExecCommand(wsId, command, *c.Opts.WorkDir, envVarMap)
if err != nil {
return fmt.Errorf("failed to exec command: %w", err)
}
fmt.Println("STDOUT:")
fmt.Println(stdout)
if stderr != "" {
fmt.Println("STDERR:")
fmt.Fprintln(os.Stderr, stderr)
}
return nil
}