diff --git a/cmd/ghcs/code.go b/cmd/ghcs/code.go index ccb4788ee..ac5bffe8b 100644 --- a/cmd/ghcs/code.go +++ b/cmd/ghcs/code.go @@ -14,8 +14,9 @@ import ( func NewCodeCmd() *cobra.Command { return &cobra.Command{ - Use: "code", - Short: "Open a GitHub Codespace in VSCode.", + Use: "code []", + Short: "Open a Codespace in VS Code", + Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { var codespaceName string if len(args) > 0 { @@ -43,8 +44,7 @@ func Code(codespaceName string) error { codespace, err := codespaces.ChooseCodespace(ctx, apiClient, user) if err != nil { if err == codespaces.ErrNoCodespaces { - fmt.Println(err.Error()) - return nil + return err } return fmt.Errorf("error choosing codespace: %v", err) } diff --git a/cmd/ghcs/create.go b/cmd/ghcs/create.go index 385e5d957..bb2e18eff 100644 --- a/cmd/ghcs/create.go +++ b/cmd/ghcs/create.go @@ -2,6 +2,7 @@ package main import ( "context" + "errors" "fmt" "os" "strings" @@ -9,6 +10,7 @@ import ( "github.com/AlecAivazis/survey/v2" "github.com/fatih/camelcase" "github.com/github/ghcs/api" + "github.com/github/ghcs/cmd/ghcs/output" "github.com/spf13/cobra" ) @@ -17,7 +19,8 @@ var repo, branch, machine string func newCreateCmd() *cobra.Command { createCmd := &cobra.Command{ Use: "create", - Short: "Create a GitHub Codespace.", + Short: "Create a Codespace", + Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { return Create() }, @@ -39,6 +42,7 @@ func Create() error { apiClient := api.New(os.Getenv("GITHUB_TOKEN")) locationCh := getLocation(ctx, apiClient) userCh := getUser(ctx, apiClient) + log := output.NewLogger(os.Stdout, os.Stderr, false) repo, err := getRepoName() if err != nil { @@ -69,18 +73,17 @@ func Create() error { return fmt.Errorf("error getting machine type: %v", err) } if machine == "" { - fmt.Println("There are no available machine types for this repository") - return nil + return errors.New("There are no available machine types for this repository") } - fmt.Println("Creating your codespace...") + log.Println("Creating your codespace...") codespace, err := apiClient.CreateCodespace(ctx, userResult.User, repository, machine, branch, locationResult.Location) if err != nil { return fmt.Errorf("error creating codespace: %v", err) } - fmt.Println("Codespace created: " + codespace.Name) + log.Printf("Codespace created: %s\n", codespace.Name) return nil } diff --git a/cmd/ghcs/delete.go b/cmd/ghcs/delete.go index 2694e9cdf..d79bcc448 100644 --- a/cmd/ghcs/delete.go +++ b/cmd/ghcs/delete.go @@ -2,44 +2,43 @@ package main import ( "context" - "errors" "fmt" "os" "github.com/github/ghcs/api" + "github.com/github/ghcs/cmd/ghcs/output" + "github.com/github/ghcs/internal/codespaces" "github.com/spf13/cobra" ) func NewDeleteCmd() *cobra.Command { deleteCmd := &cobra.Command{ - Use: "delete CODESPACE_NAME", - Short: "Delete a GitHub Codespace.", + Use: "delete []", + Short: "Delete a Codespace", + Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - if len(args) == 0 { - return errors.New("A Codespace name is required.") + var codespaceName string + if len(args) > 0 { + codespaceName = args[0] } - return Delete(args[0]) + return Delete(codespaceName) }, } deleteAllCmd := &cobra.Command{ Use: "all", - Short: "delete all codespaces", - Long: "delete all codespaces for the user with the current token", + Short: "Delete all Codespaces for the current user", + Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { return DeleteAll() }, } deleteByRepoCmd := &cobra.Command{ - Use: "repo REPO_NAME", - Short: "delete all codespaces for the repo", - Long: `delete all the codespaces that the user with the current token has in this repo. -This includes all codespaces in all states.`, + Use: "repo ", + Short: "Delete all Codespaces for a repository", + Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - if len(args) == 0 { - return errors.New("A Repository name is required.") - } return DeleteByRepo(args[0]) }, } @@ -56,29 +55,31 @@ func init() { func Delete(codespaceName string) error { apiClient := api.New(os.Getenv("GITHUB_TOKEN")) ctx := context.Background() + log := output.NewLogger(os.Stdout, os.Stderr, false) user, err := apiClient.GetUser(ctx) if err != nil { return fmt.Errorf("error getting user: %v", err) } - token, err := apiClient.GetCodespaceToken(ctx, user.Login, codespaceName) + codespace, token, err := codespaces.GetOrChooseCodespace(ctx, apiClient, user, codespaceName) if err != nil { - return fmt.Errorf("error getting codespace token: %v", err) + return fmt.Errorf("get or choose codespace: %v", err) } - if err := apiClient.DeleteCodespace(ctx, user, token, codespaceName); err != nil { + if err := apiClient.DeleteCodespace(ctx, user, token, codespace.Name); err != nil { return fmt.Errorf("error deleting codespace: %v", err) } - fmt.Println("Codespace deleted.") + log.Println("Codespace deleted.") - return List() + return List(&ListOptions{}) } func DeleteAll() error { apiClient := api.New(os.Getenv("GITHUB_TOKEN")) ctx := context.Background() + log := output.NewLogger(os.Stdout, os.Stderr, false) user, err := apiClient.GetUser(ctx) if err != nil { @@ -100,15 +101,16 @@ func DeleteAll() error { return fmt.Errorf("error deleting codespace: %v", err) } - fmt.Printf("Codespace deleted: %s\n", c.Name) + log.Printf("Codespace deleted: %s\n", c.Name) } - return List() + return List(&ListOptions{}) } func DeleteByRepo(repo string) error { apiClient := api.New(os.Getenv("GITHUB_TOKEN")) ctx := context.Background() + log := output.NewLogger(os.Stdout, os.Stderr, false) user, err := apiClient.GetUser(ctx) if err != nil { @@ -136,12 +138,12 @@ func DeleteByRepo(repo string) error { return fmt.Errorf("error deleting codespace: %v", err) } - fmt.Printf("Codespace deleted: %s\n", c.Name) + log.Printf("Codespace deleted: %s\n", c.Name) } if !deleted { - fmt.Printf("No codespace was found for repository: %s\n", repo) + return fmt.Errorf("No codespace was found for repository: %s", repo) } - return List() + return List(&ListOptions{}) } diff --git a/cmd/ghcs/list.go b/cmd/ghcs/list.go index 6db79af97..27b11d4fd 100644 --- a/cmd/ghcs/list.go +++ b/cmd/ghcs/list.go @@ -5,21 +5,29 @@ import ( "fmt" "os" - "github.com/olekukonko/tablewriter" - "github.com/github/ghcs/api" + "github.com/github/ghcs/cmd/ghcs/output" "github.com/spf13/cobra" ) +type ListOptions struct { + AsJSON bool +} + func NewListCmd() *cobra.Command { + opts := &ListOptions{} + listCmd := &cobra.Command{ Use: "list", - Short: "List GitHub Codespaces you have on your account.", + Short: "List your Codespaces", + Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { - return List() + return List(opts) }, } + listCmd.Flags().BoolVar(&opts.AsJSON, "json", false, "Output as JSON") + return listCmd } @@ -27,7 +35,7 @@ func init() { rootCmd.AddCommand(NewListCmd()) } -func List() error { +func List(opts *ListOptions) error { apiClient := api.New(os.Getenv("GITHUB_TOKEN")) ctx := context.Background() @@ -41,12 +49,7 @@ func List() error { return fmt.Errorf("error getting codespaces: %v", err) } - if len(codespaces) == 0 { - fmt.Println("You have no codespaces.") - return nil - } - - table := tablewriter.NewWriter(os.Stdout) + table := output.NewTable(os.Stdout, opts.AsJSON) table.SetHeader([]string{"Name", "Repository", "Branch", "State", "Created At"}) for _, codespace := range codespaces { table.Append([]string{ diff --git a/cmd/ghcs/logs.go b/cmd/ghcs/logs.go index 03a7c963a..dd8664597 100644 --- a/cmd/ghcs/logs.go +++ b/cmd/ghcs/logs.go @@ -7,6 +7,7 @@ import ( "os" "github.com/github/ghcs/api" + "github.com/github/ghcs/cmd/ghcs/output" "github.com/github/ghcs/internal/codespaces" "github.com/spf13/cobra" ) @@ -15,8 +16,9 @@ func NewLogsCmd() *cobra.Command { var tail bool logsCmd := &cobra.Command{ - Use: "logs", + Use: "logs []", Short: "Access Codespace logs", + Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { var codespaceName string if len(args) > 0 { @@ -38,6 +40,7 @@ func init() { func Logs(tail bool, codespaceName string) error { apiClient := api.New(os.Getenv("GITHUB_TOKEN")) ctx := context.Background() + log := output.NewLogger(os.Stdout, os.Stderr, false) user, err := apiClient.GetUser(ctx) if err != nil { @@ -49,7 +52,7 @@ func Logs(tail bool, codespaceName string) error { return fmt.Errorf("get or choose codespace: %v", err) } - lsclient, err := codespaces.ConnectToLiveshare(ctx, apiClient, token, codespace) + lsclient, err := codespaces.ConnectToLiveshare(ctx, log, apiClient, token, codespace) if err != nil { return fmt.Errorf("connecting to liveshare: %v", err) } diff --git a/cmd/ghcs/main.go b/cmd/ghcs/main.go index 00e8be894..58037437a 100644 --- a/cmd/ghcs/main.go +++ b/cmd/ghcs/main.go @@ -1,33 +1,46 @@ package main import ( + "errors" "fmt" + "io" "os" "github.com/spf13/cobra" ) func main() { - Execute() + if err := rootCmd.Execute(); err != nil { + explainError(os.Stderr, err) + os.Exit(1) + } } var Version = "DEV" var rootCmd = &cobra.Command{ - Use: "ghcs", - Short: "Unofficial GitHub Codespaces CLI.", - Long: "Unofficial CLI tool to manage and interact with GitHub Codespaces.", + Use: "ghcs", + Long: `Unofficial CLI tool to manage GitHub Codespaces. + +Running commands requires the GITHUB_TOKEN environment variable to be set to a +token to access the GitHub API with.`, Version: Version, + + PersistentPreRunE: func(cmd *cobra.Command, args []string) error { + if os.Getenv("GITHUB_TOKEN") == "" { + return tokenError + } + return nil + }, } -func Execute() { - if os.Getenv("GITHUB_TOKEN") == "" { - fmt.Println("The GITHUB_TOKEN environment variable is required. Create a Personal Access Token at https://github.com/settings/tokens/new?scopes=repo and make sure to enable SSO for the GitHub organization after creating the token.") - os.Exit(1) - } +var tokenError = errors.New("GITHUB_TOKEN is missing") - if err := rootCmd.Execute(); err != nil { - fmt.Fprintln(os.Stderr, err) - os.Exit(1) +func explainError(w io.Writer, err error) { + if errors.Is(err, tokenError) { + fmt.Fprintln(w, "The GITHUB_TOKEN environment variable is required. Create a Personal Access Token at https://github.com/settings/tokens/new?scopes=repo") + fmt.Fprintln(w, "Make sure to enable SSO for your organizations after creating the token.") + return } + // fmt.Fprintf(w, "%v\n", err) } diff --git a/cmd/ghcs/output/format_json.go b/cmd/ghcs/output/format_json.go new file mode 100644 index 000000000..8488e8dfa --- /dev/null +++ b/cmd/ghcs/output/format_json.go @@ -0,0 +1,55 @@ +package output + +import ( + "encoding/json" + "io" + "strings" + "unicode" +) + +type jsonwriter struct { + w io.Writer + pretty bool + cols []string + data []interface{} +} + +func (j *jsonwriter) SetHeader(cols []string) { + j.cols = cols +} + +func (j *jsonwriter) Append(values []string) { + row := make(map[string]string) + for i, v := range values { + row[camelize(j.cols[i])] = v + } + j.data = append(j.data, row) +} + +func (j *jsonwriter) Render() { + enc := json.NewEncoder(j.w) + if j.pretty { + enc.SetIndent("", " ") + } + _ = enc.Encode(j.data) +} + +func camelize(s string) string { + var b strings.Builder + capitalizeNext := false + for i, r := range s { + if r == ' ' { + capitalizeNext = true + continue + } + if capitalizeNext { + b.WriteRune(unicode.ToUpper(r)) + capitalizeNext = false + } else if i == 0 { + b.WriteRune(unicode.ToLower(r)) + } else { + b.WriteRune(r) + } + } + return b.String() +} diff --git a/cmd/ghcs/output/format_table.go b/cmd/ghcs/output/format_table.go new file mode 100644 index 000000000..e0345672d --- /dev/null +++ b/cmd/ghcs/output/format_table.go @@ -0,0 +1,31 @@ +package output + +import ( + "io" + "os" + + "github.com/olekukonko/tablewriter" + "golang.org/x/term" +) + +type Table interface { + SetHeader([]string) + Append([]string) + Render() +} + +func NewTable(w io.Writer, asJSON bool) Table { + isTTY := isTTY(w) + if asJSON { + return &jsonwriter{w: w, pretty: isTTY} + } + if isTTY { + return tablewriter.NewWriter(w) + } + return &tabwriter{w: w} +} + +func isTTY(w io.Writer) bool { + f, ok := w.(*os.File) + return ok && term.IsTerminal(int(f.Fd())) +} diff --git a/cmd/ghcs/output/format_tsv.go b/cmd/ghcs/output/format_tsv.go new file mode 100644 index 000000000..3f1d226ca --- /dev/null +++ b/cmd/ghcs/output/format_tsv.go @@ -0,0 +1,25 @@ +package output + +import ( + "fmt" + "io" +) + +type tabwriter struct { + w io.Writer +} + +func (j *tabwriter) SetHeader([]string) {} + +func (j *tabwriter) Append(values []string) { + var sep string + for i, v := range values { + if i == 1 { + sep = "\t" + } + fmt.Fprintf(j.w, "%s%s", sep, v) + } + fmt.Fprint(j.w, "\n") +} + +func (j *tabwriter) Render() {} diff --git a/cmd/ghcs/output/logger.go b/cmd/ghcs/output/logger.go new file mode 100644 index 000000000..32d05acc8 --- /dev/null +++ b/cmd/ghcs/output/logger.go @@ -0,0 +1,45 @@ +package output + +import ( + "fmt" + "io" +) + +func NewLogger(stdout, stderr io.Writer, disabled bool) *Logger { + return &Logger{ + out: stdout, + errout: stderr, + enabled: !disabled && isTTY(stdout), + } +} + +type Logger struct { + out io.Writer + errout io.Writer + enabled bool +} + +func (l *Logger) Print(v ...interface{}) (int, error) { + if !l.enabled { + return 0, nil + } + return fmt.Fprint(l.out, v...) +} + +func (l *Logger) Println(v ...interface{}) (int, error) { + if !l.enabled { + return 0, nil + } + return fmt.Fprintln(l.out, v...) +} + +func (l *Logger) Printf(f string, v ...interface{}) (int, error) { + if !l.enabled { + return 0, nil + } + return fmt.Fprintf(l.out, f, v...) +} + +func (l *Logger) Errorf(f string, v ...interface{}) (int, error) { + return fmt.Fprintf(l.errout, f, v...) +} diff --git a/cmd/ghcs/ports.go b/cmd/ghcs/ports.go index b51490ddc..9985c708a 100644 --- a/cmd/ghcs/ports.go +++ b/cmd/ghcs/ports.go @@ -1,6 +1,7 @@ package main import ( + "bytes" "context" "encoding/json" "errors" @@ -10,26 +11,38 @@ import ( "strings" "github.com/github/ghcs/api" + "github.com/github/ghcs/cmd/ghcs/output" "github.com/github/ghcs/internal/codespaces" "github.com/github/go-liveshare" "github.com/muhammadmuzzammil1998/jsonc" - "github.com/olekukonko/tablewriter" "github.com/spf13/cobra" "golang.org/x/sync/errgroup" ) +type PortsOptions struct { + CodespaceName string + AsJSON bool +} + func NewPortsCmd() *cobra.Command { + opts := &PortsOptions{} + portsCmd := &cobra.Command{ Use: "ports", - Short: "Forward ports from a GitHub Codespace.", + Short: "List ports in a Codespace", + Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { - return Ports() + return Ports(opts) }, } + portsCmd.Flags().StringVarP(&opts.CodespaceName, "codespace", "c", "", "The `name` of the Codespace to use") + portsCmd.Flags().BoolVar(&opts.AsJSON, "json", false, "Output as JSON") + portsCmd.AddCommand(NewPortsPublicCmd()) portsCmd.AddCommand(NewPortsPrivateCmd()) portsCmd.AddCommand(NewPortsForwardCmd()) + return portsCmd } @@ -37,53 +50,43 @@ func init() { rootCmd.AddCommand(NewPortsCmd()) } -func Ports() error { +func Ports(opts *PortsOptions) error { apiClient := api.New(os.Getenv("GITHUB_TOKEN")) ctx := context.Background() + log := output.NewLogger(os.Stdout, os.Stderr, opts.AsJSON) user, err := apiClient.GetUser(ctx) if err != nil { return fmt.Errorf("error getting user: %v", err) } - codespace, err := codespaces.ChooseCodespace(ctx, apiClient, user) + codespace, token, err := codespaces.GetOrChooseCodespace(ctx, apiClient, user, opts.CodespaceName) if err != nil { if err == codespaces.ErrNoCodespaces { - fmt.Println(err.Error()) - return nil + return err } return fmt.Errorf("error choosing codespace: %v", err) } devContainerCh := getDevContainer(ctx, apiClient, codespace) - token, err := apiClient.GetCodespaceToken(ctx, user.Login, codespace.Name) - if err != nil { - return fmt.Errorf("error getting codespace token: %v", err) - } - - liveShareClient, err := codespaces.ConnectToLiveshare(ctx, apiClient, token, codespace) + liveShareClient, err := codespaces.ConnectToLiveshare(ctx, log, apiClient, token, codespace) if err != nil { return fmt.Errorf("error connecting to liveshare: %v", err) } - fmt.Println("Loading ports...") + log.Println("Loading ports...") ports, err := getPorts(ctx, liveShareClient) if err != nil { return fmt.Errorf("error getting ports: %v", err) } - if len(ports) == 0 { - fmt.Println("This codespace has no open ports") - return nil - } - devContainerResult := <-devContainerCh if devContainerResult.Err != nil { - fmt.Printf("Failed to get port names: %v\n", devContainerResult.Err.Error()) + _, _ = log.Errorf("Failed to get port names: %v\n", devContainerResult.Err.Error()) } - table := tablewriter.NewWriter(os.Stdout) + table := output.NewTable(os.Stdout, opts.AsJSON) table.SetHeader([]string{"Label", "Source Port", "Destination Port", "Public", "Browse URL"}) for _, port := range ports { sourcePort := strconv.Itoa(port.SourcePort) @@ -105,7 +108,6 @@ func Ports() error { table.Render() return nil - } func getPorts(ctx context.Context, lsclient *liveshare.Client) (liveshare.Ports, error) { @@ -149,7 +151,7 @@ func getDevContainer(ctx context.Context, apiClient *api.API, codespace *api.Cod return } - convertedJSON := jsonc.ToJSON(contents) + convertedJSON := normalizeJSON(jsonc.ToJSON(contents)) if !jsonc.Valid(convertedJSON) { ch <- devContainerResult{nil, errors.New("failed to convert json to standard json")} return @@ -168,35 +170,29 @@ func getDevContainer(ctx context.Context, apiClient *api.API, codespace *api.Cod func NewPortsPublicCmd() *cobra.Command { return &cobra.Command{ - Use: "public", - Short: "public", - Long: "public", + Use: "public ", + Short: "Mark port as public", + Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { - if len(args) < 2 { - return errors.New("[codespace_name] [source] port number are required.") - } - - return updatePortVisibility(args[0], args[1], true) + log := output.NewLogger(os.Stdout, os.Stderr, false) + return updatePortVisibility(log, args[0], args[1], true) }, } } func NewPortsPrivateCmd() *cobra.Command { return &cobra.Command{ - Use: "private", - Short: "private", - Long: "private", + Use: "private ", + Short: "Mark port as private", + Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { - if len(args) < 2 { - return errors.New("[codespace_name] [source] port number are required.") - } - - return updatePortVisibility(args[0], args[1], false) + log := output.NewLogger(os.Stdout, os.Stderr, false) + return updatePortVisibility(log, args[0], args[1], false) }, } } -func updatePortVisibility(codespaceName, sourcePort string, public bool) error { +func updatePortVisibility(log *output.Logger, codespaceName, sourcePort string, public bool) error { ctx := context.Background() apiClient := api.New(os.Getenv("GITHUB_TOKEN")) @@ -215,7 +211,7 @@ func updatePortVisibility(codespaceName, sourcePort string, public bool) error { return fmt.Errorf("error getting codespace: %v", err) } - lsclient, err := codespaces.ConnectToLiveshare(ctx, apiClient, token, codespace) + lsclient, err := codespaces.ConnectToLiveshare(ctx, log, apiClient, token, codespace) if err != nil { return fmt.Errorf("error connecting to liveshare: %v", err) } @@ -235,30 +231,27 @@ func updatePortVisibility(codespaceName, sourcePort string, public bool) error { } state := "PUBLIC" - if public == false { + if !public { state = "PRIVATE" } - - fmt.Println(fmt.Sprintf("Port %s is now %s.", sourcePort, state)) + log.Printf("Port %s is now %s.\n", sourcePort, state) return nil } func NewPortsForwardCmd() *cobra.Command { return &cobra.Command{ - Use: "forward", - Short: "forward", - Long: "forward", + Use: "forward ", + Short: "Forward port", + Args: cobra.MinimumNArgs(2), RunE: func(cmd *cobra.Command, args []string) error { - if len(args) < 2 { - return errors.New("[codespace_name] [source]:[dst] port number are required.") - } - return forwardPort(args[0], args[1:]) + log := output.NewLogger(os.Stdout, os.Stderr, false) + return forwardPorts(log, args[0], args[1:]) }, } } -func forwardPort(codespaceName string, ports []string) error { +func forwardPorts(log *output.Logger, codespaceName string, ports []string) error { ctx := context.Background() apiClient := api.New(os.Getenv("GITHUB_TOKEN")) @@ -282,7 +275,7 @@ func forwardPort(codespaceName string, ports []string) error { return fmt.Errorf("error getting codespace: %v", err) } - lsclient, err := codespaces.ConnectToLiveshare(ctx, apiClient, token, codespace) + lsclient, err := codespaces.ConnectToLiveshare(ctx, log, apiClient, token, codespace) if err != nil { return fmt.Errorf("error connecting to liveshare: %v", err) } @@ -302,7 +295,7 @@ func forwardPort(codespaceName string, ports []string) error { } g.Go(func() error { - fmt.Println("Forwarding port: " + srcstr + " ==> " + strconv.Itoa(portPair.Dst)) + log.Println("Forwarding port: " + srcstr + " ==> " + strconv.Itoa(portPair.Dst)) portForwarder := liveshare.NewPortForwarder(lsclient, server, portPair.Dst) if err := portForwarder.Start(gctx); err != nil { return fmt.Errorf("error forwarding port: %v", err) @@ -347,3 +340,8 @@ func getPortPairs(ports []string) ([]portPair, error) { return pp, nil } + +func normalizeJSON(j []byte) []byte { + // remove trailing commas + return bytes.ReplaceAll(j, []byte("},}"), []byte("}}")) +} diff --git a/cmd/ghcs/ssh.go b/cmd/ghcs/ssh.go index 60fdee498..1754f968a 100644 --- a/cmd/ghcs/ssh.go +++ b/cmd/ghcs/ssh.go @@ -9,6 +9,7 @@ import ( "time" "github.com/github/ghcs/api" + "github.com/github/ghcs/cmd/ghcs/output" "github.com/github/ghcs/internal/codespaces" "github.com/github/go-liveshare" "github.com/spf13/cobra" @@ -20,15 +21,16 @@ func NewSSHCmd() *cobra.Command { sshCmd := &cobra.Command{ Use: "ssh", - Short: "SSH into a GitHub Codespace, for use with running tests/editing in vim, etc.", + Short: "SSH into a Codespace", + Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { return SSH(sshProfile, codespaceName, sshServerPort) }, } - sshCmd.Flags().StringVarP(&sshProfile, "profile", "", "", "SSH Profile") - sshCmd.Flags().IntVarP(&sshServerPort, "server-port", "", 0, "SSH Server Port") - sshCmd.Flags().StringVarP(&codespaceName, "codespace", "c", "", "Codespace Name") + sshCmd.Flags().StringVarP(&sshProfile, "profile", "", "", "The `name` of the SSH profile to use") + sshCmd.Flags().IntVarP(&sshServerPort, "server-port", "", 0, "SSH server port number") + sshCmd.Flags().StringVarP(&codespaceName, "codespace", "c", "", "The `name` of the Codespace to use") return sshCmd } @@ -40,6 +42,7 @@ func init() { func SSH(sshProfile, codespaceName string, sshServerPort int) error { apiClient := api.New(os.Getenv("GITHUB_TOKEN")) ctx := context.Background() + log := output.NewLogger(os.Stdout, os.Stderr, false) user, err := apiClient.GetUser(ctx) if err != nil { @@ -51,7 +54,7 @@ func SSH(sshProfile, codespaceName string, sshServerPort int) error { return fmt.Errorf("get or choose codespace: %v", err) } - lsclient, err := codespaces.ConnectToLiveshare(ctx, apiClient, token, codespace) + lsclient, err := codespaces.ConnectToLiveshare(ctx, log, apiClient, token, codespace) if err != nil { return fmt.Errorf("error connecting to liveshare: %v", err) } @@ -61,18 +64,18 @@ func SSH(sshProfile, codespaceName string, sshServerPort int) error { return fmt.Errorf("error creating liveshare terminal: %v", err) } - fmt.Println("Preparing SSH...") + log.Println("Preparing SSH...") if sshProfile == "" { - containerID, err := getContainerID(ctx, terminal) + containerID, err := getContainerID(ctx, log, terminal) if err != nil { return fmt.Errorf("error getting container id: %v", err) } - if err := setupSSH(ctx, terminal, containerID, codespace.RepositoryName); err != nil { + if err := setupSSH(ctx, log, terminal, containerID, codespace.RepositoryName); err != nil { return fmt.Errorf("error creating ssh server: %v", err) } - fmt.Printf("\n") + log.Print("\n") } tunnelPort, tunnelClosed, err := codespaces.MakeSSHTunnel(ctx, lsclient, sshServerPort) @@ -86,9 +89,9 @@ func SSH(sshProfile, codespaceName string, sshServerPort int) error { } usingCustomPort := tunnelPort == sshServerPort - connClosed := codespaces.ConnectToTunnel(ctx, tunnelPort, connectDestination, usingCustomPort) + connClosed := codespaces.ConnectToTunnel(ctx, log, tunnelPort, connectDestination, usingCustomPort) - fmt.Println("Ready...") + log.Println("Ready...") select { case err := <-tunnelClosed: if err != nil { @@ -103,28 +106,30 @@ func SSH(sshProfile, codespaceName string, sshServerPort int) error { return nil } -func getContainerID(ctx context.Context, terminal *liveshare.Terminal) (string, error) { - fmt.Print(".") +func getContainerID(ctx context.Context, logger *output.Logger, terminal *liveshare.Terminal) (string, error) { + logger.Print(".") + cmd := terminal.NewCommand( "/", "/usr/bin/docker ps -aq --filter label=Type=codespaces --filter status=running", ) + stream, err := cmd.Run(ctx) if err != nil { return "", fmt.Errorf("error running command: %v", err) } - fmt.Print(".") + logger.Print(".") scanner := bufio.NewScanner(stream) scanner.Scan() - fmt.Print(".") + logger.Print(".") containerID := scanner.Text() if err := scanner.Err(); err != nil { return "", fmt.Errorf("error scanning stream: %v", err) } - fmt.Print(".") + logger.Print(".") if err := stream.Close(); err != nil { return "", fmt.Errorf("error closing stream: %v", err) } @@ -132,10 +137,10 @@ func getContainerID(ctx context.Context, terminal *liveshare.Terminal) (string, return containerID, nil } -func setupSSH(ctx context.Context, terminal *liveshare.Terminal, containerID, repositoryName string) error { +func setupSSH(ctx context.Context, logger *output.Logger, terminal *liveshare.Terminal, containerID, repositoryName string) error { setupBashProfileCmd := fmt.Sprintf(`echo "cd /workspaces/%v; export $(cat /workspaces/.codespaces/shared/.env | xargs); exec /bin/zsh;" > /home/codespace/.bash_profile`, repositoryName) - fmt.Print(".") + logger.Print(".") compositeCommand := []string{setupBashProfileCmd} cmd := terminal.NewCommand( "/", @@ -146,7 +151,7 @@ func setupSSH(ctx context.Context, terminal *liveshare.Terminal, containerID, re return fmt.Errorf("error running command: %v", err) } - fmt.Print(".") + logger.Print(".") if err := stream.Close(); err != nil { return fmt.Errorf("error closing stream: %v", err) } diff --git a/internal/codespaces/codespaces.go b/internal/codespaces/codespaces.go index 4c62d9aff..48369cfa0 100644 --- a/internal/codespaces/codespaces.go +++ b/internal/codespaces/codespaces.go @@ -57,9 +57,14 @@ func ChooseCodespace(ctx context.Context, apiClient *api.API, user *api.User) (* return codespace, nil } -func ConnectToLiveshare(ctx context.Context, apiClient *api.API, token string, codespace *api.Codespace) (client *liveshare.Client, err error) { +type logger interface { + Print(v ...interface{}) (int, error) + Println(v ...interface{}) (int, error) +} + +func ConnectToLiveshare(ctx context.Context, log logger, apiClient *api.API, token string, codespace *api.Codespace) (client *liveshare.Client, err error) { if codespace.Environment.State != api.CodespaceEnvironmentStateAvailable { - fmt.Println("Starting your codespace...") // TODO(josebalius): better way of notifying of events + log.Println("Starting your codespace...") if err := apiClient.StartCodespace(ctx, token, codespace); err != nil { return nil, fmt.Errorf("error starting codespace: %v", err) } @@ -69,7 +74,7 @@ func ConnectToLiveshare(ctx context.Context, apiClient *api.API, token string, c for codespace.Environment.Connection.SessionID == "" || codespace.Environment.State != api.CodespaceEnvironmentStateAvailable { if retries > 1 { if retries%2 == 0 { - fmt.Print(".") + log.Print(".") } time.Sleep(1 * time.Second) @@ -88,10 +93,10 @@ func ConnectToLiveshare(ctx context.Context, apiClient *api.API, token string, c } if retries >= 2 { - fmt.Print("\n") + log.Print("\n") } - fmt.Println("Connecting to your codespace...") + log.Println("Connecting to your codespace...") lsclient, err := liveshare.NewClient( liveshare.WithConnection(liveshare.Connection{ @@ -117,10 +122,8 @@ func GetOrChooseCodespace(ctx context.Context, apiClient *api.API, user *api.Use codespace, err = ChooseCodespace(ctx, apiClient, user) if err != nil { if err == ErrNoCodespaces { - fmt.Println(err.Error()) - return nil, "", nil + return nil, "", err } - return nil, "", fmt.Errorf("choosing codespace: %v", err) } codespaceName = codespace.Name diff --git a/internal/codespaces/ssh.go b/internal/codespaces/ssh.go index 2bb661086..672ba3b7b 100644 --- a/internal/codespaces/ssh.go +++ b/internal/codespaces/ssh.go @@ -56,12 +56,12 @@ func makeSSHArgs(port int, dst, cmd string) ([]string, []string) { return cmdArgs, connArgs } -func ConnectToTunnel(ctx context.Context, port int, destination string, usingCustomPort bool) <-chan error { +func ConnectToTunnel(ctx context.Context, log logger, port int, destination string, usingCustomPort bool) <-chan error { connClosed := make(chan error) args, connArgs := makeSSHArgs(port, destination, "") if usingCustomPort { - fmt.Println("Connection Details: ssh " + destination + " " + strings.Join(connArgs, " ")) + log.Println("Connection Details: ssh " + destination + " " + strings.Join(connArgs, " ")) } cmd := exec.CommandContext(ctx, "ssh", args...)