From 140a54a009b27c41fe7d602b5fbada129fcacd4d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Wed, 4 Aug 2021 15:56:10 +0200 Subject: [PATCH 1/7] Add machine-readable output formats - Default table output (when stdout is attached to a terminal) stays the same; - When stdout is redirected, output tab-separated values and no header line; - With `--json` flag, output structured JSON data. Example: $ ghcs list --json [ { "Branch": "main", "Created At": "2021-06-10T15:04:46+02:00", "Name": "mislav-playground-jvqj", "Repository": "mislav/playground", "State": "Shutdown" }, { "Branch": "master", "Created At": "2021-07-15T15:51:08+02:00", "Name": "mislav-github-github-pwgg365xv", "Repository": "github/github", "State": "Shutdown" } ] --- cmd/ghcs/delete.go | 6 +++--- cmd/ghcs/list.go | 17 ++++++++++++----- cmd/ghcs/output/format_json.go | 33 +++++++++++++++++++++++++++++++++ cmd/ghcs/output/format_table.go | 28 ++++++++++++++++++++++++++++ cmd/ghcs/output/format_tsv.go | 25 +++++++++++++++++++++++++ 5 files changed, 101 insertions(+), 8 deletions(-) create mode 100644 cmd/ghcs/output/format_json.go create mode 100644 cmd/ghcs/output/format_table.go create mode 100644 cmd/ghcs/output/format_tsv.go diff --git a/cmd/ghcs/delete.go b/cmd/ghcs/delete.go index 2694e9cdf..5cec0f80b 100644 --- a/cmd/ghcs/delete.go +++ b/cmd/ghcs/delete.go @@ -73,7 +73,7 @@ func Delete(codespaceName string) error { fmt.Println("Codespace deleted.") - return List() + return List(&ListOptions{}) } func DeleteAll() error { @@ -103,7 +103,7 @@ func DeleteAll() error { fmt.Printf("Codespace deleted: %s\n", c.Name) } - return List() + return List(&ListOptions{}) } func DeleteByRepo(repo string) error { @@ -143,5 +143,5 @@ func DeleteByRepo(repo string) error { fmt.Printf("No codespace was found for repository: %s\n", repo) } - return List() + return List(&ListOptions{}) } diff --git a/cmd/ghcs/list.go b/cmd/ghcs/list.go index 6db79af97..bbee2aae8 100644 --- a/cmd/ghcs/list.go +++ b/cmd/ghcs/list.go @@ -5,21 +5,28 @@ 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.", 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 +34,7 @@ func init() { rootCmd.AddCommand(NewListCmd()) } -func List() error { +func List(opts *ListOptions) error { apiClient := api.New(os.Getenv("GITHUB_TOKEN")) ctx := context.Background() @@ -46,7 +53,7 @@ func List() error { 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/output/format_json.go b/cmd/ghcs/output/format_json.go new file mode 100644 index 000000000..37208629c --- /dev/null +++ b/cmd/ghcs/output/format_json.go @@ -0,0 +1,33 @@ +package output + +import ( + "encoding/json" + "io" +) + +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[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) +} diff --git a/cmd/ghcs/output/format_table.go b/cmd/ghcs/output/format_table.go new file mode 100644 index 000000000..97e7cab58 --- /dev/null +++ b/cmd/ghcs/output/format_table.go @@ -0,0 +1,28 @@ +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 { + f, ok := w.(*os.File) + isTTY := ok && term.IsTerminal(int(f.Fd())) + + if asJSON { + return &jsonwriter{w: w, pretty: isTTY} + } + if isTTY { + return tablewriter.NewWriter(w) + } + return &tabwriter{w: w} +} 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() {} From db95f2f71f5c390dac86811f120a193074dffbb6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Thu, 12 Aug 2021 14:35:49 +0200 Subject: [PATCH 2/7] Add machine-readable output functionality to `ports` command --- cmd/ghcs/output/format_json.go | 24 +++++++++++++++++- cmd/ghcs/output/format_table.go | 9 ++++--- cmd/ghcs/output/logger.go | 45 +++++++++++++++++++++++++++++++++ cmd/ghcs/ports.go | 37 ++++++++++++++------------- 4 files changed, 93 insertions(+), 22 deletions(-) create mode 100644 cmd/ghcs/output/logger.go diff --git a/cmd/ghcs/output/format_json.go b/cmd/ghcs/output/format_json.go index 37208629c..8488e8dfa 100644 --- a/cmd/ghcs/output/format_json.go +++ b/cmd/ghcs/output/format_json.go @@ -3,6 +3,8 @@ package output import ( "encoding/json" "io" + "strings" + "unicode" ) type jsonwriter struct { @@ -19,7 +21,7 @@ func (j *jsonwriter) SetHeader(cols []string) { func (j *jsonwriter) Append(values []string) { row := make(map[string]string) for i, v := range values { - row[j.cols[i]] = v + row[camelize(j.cols[i])] = v } j.data = append(j.data, row) } @@ -31,3 +33,23 @@ func (j *jsonwriter) Render() { } _ = 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 index 97e7cab58..e0345672d 100644 --- a/cmd/ghcs/output/format_table.go +++ b/cmd/ghcs/output/format_table.go @@ -15,9 +15,7 @@ type Table interface { } func NewTable(w io.Writer, asJSON bool) Table { - f, ok := w.(*os.File) - isTTY := ok && term.IsTerminal(int(f.Fd())) - + isTTY := isTTY(w) if asJSON { return &jsonwriter{w: w, pretty: isTTY} } @@ -26,3 +24,8 @@ func NewTable(w io.Writer, asJSON bool) Table { } 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/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 77d1b00f7..fbbffcf1d 100644 --- a/cmd/ghcs/ports.go +++ b/cmd/ghcs/ports.go @@ -10,25 +10,36 @@ 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" ) +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.", RunE: func(cmd *cobra.Command, args []string) error { - return Ports() + return Ports(opts) }, } + portsCmd.Flags().StringVarP(&opts.CodespaceName, "name", "n", "", "Name of Codespace to use") + portsCmd.Flags().BoolVar(&opts.AsJSON, "json", false, "Output as JSON") + portsCmd.AddCommand(NewPortsPublicCmd()) portsCmd.AddCommand(NewPortsPrivateCmd()) portsCmd.AddCommand(NewPortsForwardCmd()) + return portsCmd } @@ -36,16 +47,17 @@ 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()) @@ -56,33 +68,23 @@ func Ports() error { 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) 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) @@ -104,7 +106,6 @@ func Ports() error { table.Render() return nil - } func getPorts(ctx context.Context, lsclient *liveshare.Client) (liveshare.Ports, error) { From 41e223869e0d8e0c96f79eb6801875b3b39f1109 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Thu, 12 Aug 2021 14:37:06 +0200 Subject: [PATCH 3/7] Fix mapping port numbers to labels --- cmd/ghcs/ports.go | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/cmd/ghcs/ports.go b/cmd/ghcs/ports.go index fbbffcf1d..27b4e0614 100644 --- a/cmd/ghcs/ports.go +++ b/cmd/ghcs/ports.go @@ -1,6 +1,7 @@ package main import ( + "bytes" "context" "encoding/json" "errors" @@ -149,7 +150,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 @@ -309,3 +310,8 @@ func forwardPort(codespaceName, sourcePort, destPort string) error { return nil } + +func normalizeJSON(j []byte) []byte { + // remove trailing commas + return bytes.ReplaceAll(j, []byte("},}"), []byte("}}")) +} From 20d75f0ff9198f952311a8aa21bf648df6147767 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Thu, 12 Aug 2021 14:37:23 +0200 Subject: [PATCH 4/7] Normalize logging, output, and error reporting - Return errors as errors, not print to stdout and return nil - Ensure errors and warnings are always written to stderr, not stout - Do not print progress to stdout unless stdout is a terminal --- cmd/ghcs/code.go | 3 +-- cmd/ghcs/create.go | 12 +++++++----- cmd/ghcs/delete.go | 12 ++++++++---- cmd/ghcs/list.go | 5 ----- cmd/ghcs/logs.go | 4 +++- cmd/ghcs/main.go | 2 +- cmd/ghcs/ports.go | 30 ++++++++++++++++-------------- cmd/ghcs/ssh.go | 16 +++++----------- internal/codespaces/codespaces.go | 19 +++++++++++-------- 9 files changed, 52 insertions(+), 51 deletions(-) diff --git a/cmd/ghcs/code.go b/cmd/ghcs/code.go index ccb4788ee..4880436ed 100644 --- a/cmd/ghcs/code.go +++ b/cmd/ghcs/code.go @@ -43,8 +43,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..b4a4fcb1f 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,7 @@ var repo, branch, machine string func newCreateCmd() *cobra.Command { createCmd := &cobra.Command{ Use: "create", - Short: "Create a GitHub Codespace.", + Short: "Create a GitHub Codespace.", RunE: func(cmd *cobra.Command, args []string) error { return Create() }, @@ -39,6 +41,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 +72,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 df7a3f1be..d625a1ca3 100644 --- a/cmd/ghcs/delete.go +++ b/cmd/ghcs/delete.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" ) @@ -58,6 +59,7 @@ 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 { @@ -73,7 +75,7 @@ func Delete(codespaceName string) error { return fmt.Errorf("error deleting codespace: %v", err) } - fmt.Println("Codespace deleted.") + log.Println("Codespace deleted.") return List(&ListOptions{}) } @@ -81,6 +83,7 @@ func Delete(codespaceName string) error { 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 { @@ -102,7 +105,7 @@ 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(&ListOptions{}) @@ -111,6 +114,7 @@ func DeleteAll() error { 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 { @@ -138,11 +142,11 @@ 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(&ListOptions{}) diff --git a/cmd/ghcs/list.go b/cmd/ghcs/list.go index bbee2aae8..acc01b7ad 100644 --- a/cmd/ghcs/list.go +++ b/cmd/ghcs/list.go @@ -48,11 +48,6 @@ func List(opts *ListOptions) error { return fmt.Errorf("error getting codespaces: %v", err) } - if len(codespaces) == 0 { - fmt.Println("You have no codespaces.") - return nil - } - table := output.NewTable(os.Stdout, opts.AsJSON) table.SetHeader([]string{"Name", "Repository", "Branch", "State", "Created At"}) for _, codespace := range codespaces { diff --git a/cmd/ghcs/logs.go b/cmd/ghcs/logs.go index 03a7c963a..45fd8bca8 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" ) @@ -38,6 +39,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 +51,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..a2617788a 100644 --- a/cmd/ghcs/main.go +++ b/cmd/ghcs/main.go @@ -22,7 +22,7 @@ var rootCmd = &cobra.Command{ 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.") + fmt.Fprintln(os.Stderr, "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) } diff --git a/cmd/ghcs/ports.go b/cmd/ghcs/ports.go index 27b4e0614..613a1834b 100644 --- a/cmd/ghcs/ports.go +++ b/cmd/ghcs/ports.go @@ -61,15 +61,14 @@ func Ports(opts *PortsOptions) error { 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) - 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) } @@ -177,7 +176,8 @@ func NewPortsPublicCmd() *cobra.Command { 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) }, } } @@ -192,12 +192,13 @@ func NewPortsPrivateCmd() *cobra.Command { 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")) @@ -216,7 +217,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) } @@ -236,11 +237,10 @@ 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 } @@ -254,12 +254,14 @@ func NewPortsForwardCmd() *cobra.Command { if len(args) < 3 { return errors.New("[codespace_name] [source] [dst] port number are required.") } - return forwardPort(args[0], args[1], args[2]) + + log := output.NewLogger(os.Stdout, os.Stderr, false) + return forwardPort(log, args[0], args[1], args[2]) }, } } -func forwardPort(codespaceName, sourcePort, destPort string) error { +func forwardPort(log *output.Logger, codespaceName, sourcePort, destPort string) error { ctx := context.Background() apiClient := api.New(os.Getenv("GITHUB_TOKEN")) @@ -278,7 +280,7 @@ func forwardPort(codespaceName, sourcePort, destPort 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 +304,7 @@ func forwardPort(codespaceName, sourcePort, destPort string) error { return fmt.Errorf("error sharing source port: %v", err) } - fmt.Println("Forwarding port: " + sourcePort + " -> " + destPort) + log.Println("Forwarding port: " + sourcePort + " -> " + destPort) portForwarder := liveshare.NewPortForwarder(lsclient, server, dstPortInt) if err := portForwarder.Start(ctx); err != nil { return fmt.Errorf("error forwarding port: %v", err) diff --git a/cmd/ghcs/ssh.go b/cmd/ghcs/ssh.go index 60fdee498..372061c55 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" @@ -40,6 +41,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 +53,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,7 +63,7 @@ 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) if err != nil { @@ -71,8 +73,6 @@ func SSH(sshProfile, codespaceName string, sshServerPort int) error { if err := setupSSH(ctx, terminal, containerID, codespace.RepositoryName); err != nil { return fmt.Errorf("error creating ssh server: %v", err) } - - fmt.Printf("\n") } tunnelPort, tunnelClosed, err := codespaces.MakeSSHTunnel(ctx, lsclient, sshServerPort) @@ -88,7 +88,7 @@ func SSH(sshProfile, codespaceName string, sshServerPort int) error { usingCustomPort := tunnelPort == sshServerPort connClosed := codespaces.ConnectToTunnel(ctx, tunnelPort, connectDestination, usingCustomPort) - fmt.Println("Ready...") + log.Println("Ready...") select { case err := <-tunnelClosed: if err != nil { @@ -104,7 +104,6 @@ func SSH(sshProfile, codespaceName string, sshServerPort int) error { } func getContainerID(ctx context.Context, terminal *liveshare.Terminal) (string, error) { - fmt.Print(".") cmd := terminal.NewCommand( "/", "/usr/bin/docker ps -aq --filter label=Type=codespaces --filter status=running", @@ -114,17 +113,14 @@ func getContainerID(ctx context.Context, terminal *liveshare.Terminal) (string, return "", fmt.Errorf("error running command: %v", err) } - fmt.Print(".") scanner := bufio.NewScanner(stream) scanner.Scan() - fmt.Print(".") containerID := scanner.Text() if err := scanner.Err(); err != nil { return "", fmt.Errorf("error scanning stream: %v", err) } - fmt.Print(".") if err := stream.Close(); err != nil { return "", fmt.Errorf("error closing stream: %v", err) } @@ -135,7 +131,6 @@ func getContainerID(ctx context.Context, terminal *liveshare.Terminal) (string, func setupSSH(ctx context.Context, 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(".") compositeCommand := []string{setupBashProfileCmd} cmd := terminal.NewCommand( "/", @@ -146,7 +141,6 @@ func setupSSH(ctx context.Context, terminal *liveshare.Terminal, containerID, re return fmt.Errorf("error running command: %v", err) } - fmt.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 From c9c1ff8dacdee9fae5d386d8f084890b6c6147a8 Mon Sep 17 00:00:00 2001 From: Jose Garcia Date: Mon, 16 Aug 2021 20:16:50 +0000 Subject: [PATCH 5/7] add back . indicators & update ConnectToTunnel --- cmd/ghcs/logs.go | 2 +- cmd/ghcs/ssh.go | 20 +++++++++++++++----- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/cmd/ghcs/logs.go b/cmd/ghcs/logs.go index 45fd8bca8..d9422d49d 100644 --- a/cmd/ghcs/logs.go +++ b/cmd/ghcs/logs.go @@ -78,7 +78,7 @@ func Logs(tail bool, codespaceName string) error { go func() { scanner := bufio.NewScanner(stdout) for scanner.Scan() { - fmt.Println(scanner.Text()) + log.Println(scanner.Text()) } if err := scanner.Err(); err != nil { diff --git a/cmd/ghcs/ssh.go b/cmd/ghcs/ssh.go index 372061c55..40f8fbc18 100644 --- a/cmd/ghcs/ssh.go +++ b/cmd/ghcs/ssh.go @@ -65,14 +65,16 @@ func SSH(sshProfile, codespaceName string, sshServerPort int) error { 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) } + + log.Print("\n") } tunnelPort, tunnelClosed, err := codespaces.MakeSSHTunnel(ctx, lsclient, sshServerPort) @@ -86,7 +88,7 @@ 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) log.Println("Ready...") select { @@ -103,24 +105,30 @@ func SSH(sshProfile, codespaceName string, sshServerPort int) error { return nil } -func getContainerID(ctx context.Context, terminal *liveshare.Terminal) (string, error) { +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) } + logger.Print(".") scanner := bufio.NewScanner(stream) scanner.Scan() + logger.Print(".") containerID := scanner.Text() if err := scanner.Err(); err != nil { return "", fmt.Errorf("error scanning stream: %v", err) } + logger.Print(".") if err := stream.Close(); err != nil { return "", fmt.Errorf("error closing stream: %v", err) } @@ -128,9 +136,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) + logger.Print(".") compositeCommand := []string{setupBashProfileCmd} cmd := terminal.NewCommand( "/", @@ -141,6 +150,7 @@ func setupSSH(ctx context.Context, terminal *liveshare.Terminal, containerID, re return fmt.Errorf("error running command: %v", err) } + logger.Print(".") if err := stream.Close(); err != nil { return fmt.Errorf("error closing stream: %v", err) } From 22be26431e918fa10142ddb471ffaf151d9877a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Mon, 16 Aug 2021 22:28:39 +0200 Subject: [PATCH 6/7] Have `--codespace ` flag be consistent across commands --- cmd/ghcs/ports.go | 2 +- cmd/ghcs/ssh.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/cmd/ghcs/ports.go b/cmd/ghcs/ports.go index 613a1834b..1d5d5ff9f 100644 --- a/cmd/ghcs/ports.go +++ b/cmd/ghcs/ports.go @@ -34,7 +34,7 @@ func NewPortsCmd() *cobra.Command { }, } - portsCmd.Flags().StringVarP(&opts.CodespaceName, "name", "n", "", "Name of Codespace to use") + 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()) diff --git a/cmd/ghcs/ssh.go b/cmd/ghcs/ssh.go index 372061c55..b6bbe254d 100644 --- a/cmd/ghcs/ssh.go +++ b/cmd/ghcs/ssh.go @@ -29,7 +29,7 @@ func NewSSHCmd() *cobra.Command { 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(&codespaceName, "codespace", "c", "", "The `name` of the Codespace to use") return sshCmd } From b47686163a2d06ce4e1b46d480f34133df611f2f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Tue, 17 Aug 2021 13:04:55 +0200 Subject: [PATCH 7/7] Fixes for log/output streams --- cmd/ghcs/logs.go | 2 +- internal/codespaces/ssh.go | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/cmd/ghcs/logs.go b/cmd/ghcs/logs.go index d9422d49d..45fd8bca8 100644 --- a/cmd/ghcs/logs.go +++ b/cmd/ghcs/logs.go @@ -78,7 +78,7 @@ func Logs(tail bool, codespaceName string) error { go func() { scanner := bufio.NewScanner(stdout) for scanner.Scan() { - log.Println(scanner.Text()) + fmt.Println(scanner.Text()) } if err := scanner.Err(); err != nil { 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...)