Merge remote-tracking branch 'origin' into docs
This commit is contained in:
commit
517aae2805
13 changed files with 263 additions and 83 deletions
|
|
@ -44,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)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
)
|
||||
|
||||
|
|
@ -40,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 {
|
||||
|
|
@ -70,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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,6 +6,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"
|
||||
)
|
||||
|
|
@ -54,6 +55,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 {
|
||||
|
|
@ -69,14 +71,15 @@ func Delete(codespaceName string) error {
|
|||
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 {
|
||||
|
|
@ -98,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 {
|
||||
|
|
@ -134,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{})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,22 +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 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
|
||||
}
|
||||
|
||||
|
|
@ -28,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()
|
||||
|
||||
|
|
@ -42,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{
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
)
|
||||
|
|
@ -39,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 {
|
||||
|
|
@ -50,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)
|
||||
}
|
||||
|
|
|
|||
55
cmd/ghcs/output/format_json.go
Normal file
55
cmd/ghcs/output/format_json.go
Normal file
|
|
@ -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()
|
||||
}
|
||||
31
cmd/ghcs/output/format_table.go
Normal file
31
cmd/ghcs/output/format_table.go
Normal file
|
|
@ -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()))
|
||||
}
|
||||
25
cmd/ghcs/output/format_tsv.go
Normal file
25
cmd/ghcs/output/format_tsv.go
Normal file
|
|
@ -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() {}
|
||||
45
cmd/ghcs/output/logger.go
Normal file
45
cmd/ghcs/output/logger.go
Normal file
|
|
@ -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...)
|
||||
}
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
|
|
@ -10,26 +11,37 @@ 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: "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 +49,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 +107,6 @@ func Ports() error {
|
|||
table.Render()
|
||||
|
||||
return nil
|
||||
|
||||
}
|
||||
|
||||
func getPorts(ctx context.Context, lsclient *liveshare.Client) (liveshare.Ports, error) {
|
||||
|
|
@ -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
|
||||
|
|
@ -172,7 +173,8 @@ func NewPortsPublicCmd() *cobra.Command {
|
|||
Short: "Mark port as public",
|
||||
Args: cobra.ExactArgs(2),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
return updatePortVisibility(args[0], args[1], true)
|
||||
log := output.NewLogger(os.Stdout, os.Stderr, false)
|
||||
return updatePortVisibility(log, args[0], args[1], true)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
|
@ -183,12 +185,13 @@ func NewPortsPrivateCmd() *cobra.Command {
|
|||
Short: "Mark port as private",
|
||||
Args: cobra.ExactArgs(2),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
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"))
|
||||
|
||||
|
|
@ -207,7 +210,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)
|
||||
}
|
||||
|
|
@ -227,11 +230,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
|
||||
}
|
||||
|
|
@ -242,12 +244,13 @@ func NewPortsForwardCmd() *cobra.Command {
|
|||
Short: "Forward port",
|
||||
Args: cobra.ExactArgs(3),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
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"))
|
||||
|
||||
|
|
@ -266,7 +269,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)
|
||||
}
|
||||
|
|
@ -290,7 +293,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)
|
||||
|
|
@ -298,3 +301,8 @@ func forwardPort(codespaceName, sourcePort, destPort string) error {
|
|||
|
||||
return nil
|
||||
}
|
||||
|
||||
func normalizeJSON(j []byte) []byte {
|
||||
// remove trailing commas
|
||||
return bytes.ReplaceAll(j, []byte("},}"), []byte("}}"))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
|
|
@ -29,7 +30,7 @@ func NewSSHCmd() *cobra.Command {
|
|||
|
||||
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", "", "Codespace Name")
|
||||
sshCmd.Flags().StringVarP(&codespaceName, "codespace", "c", "", "The `name` of the Codespace to use")
|
||||
|
||||
return sshCmd
|
||||
}
|
||||
|
|
@ -41,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 {
|
||||
|
|
@ -52,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)
|
||||
}
|
||||
|
|
@ -62,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)
|
||||
|
|
@ -87,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 {
|
||||
|
|
@ -104,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)
|
||||
}
|
||||
|
|
@ -133,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(
|
||||
"/",
|
||||
|
|
@ -147,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)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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...)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue