68 lines
1.6 KiB
Go
68 lines
1.6 KiB
Go
package ghcs
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"net/url"
|
|
|
|
"github.com/github/ghcs/internal/api"
|
|
"github.com/skratchdot/open-golang/open"
|
|
"github.com/spf13/cobra"
|
|
)
|
|
|
|
func newCodeCmd() *cobra.Command {
|
|
var (
|
|
codespace string
|
|
useInsiders bool
|
|
)
|
|
|
|
codeCmd := &cobra.Command{
|
|
Use: "code",
|
|
Short: "Open a codespace in VS Code",
|
|
Args: cobra.MaximumNArgs(1),
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
return code(codespace, useInsiders)
|
|
},
|
|
}
|
|
|
|
codeCmd.Flags().StringVarP(&codespace, "codespace", "c", "", "Name of the codespace")
|
|
codeCmd.Flags().BoolVar(&useInsiders, "insiders", false, "Use the insiders version of VS Code")
|
|
|
|
return codeCmd
|
|
}
|
|
|
|
func code(codespaceName string, useInsiders bool) error {
|
|
apiClient := api.New(GithubToken)
|
|
ctx := context.Background()
|
|
|
|
user, err := apiClient.GetUser(ctx)
|
|
if err != nil {
|
|
return fmt.Errorf("error getting user: %w", err)
|
|
}
|
|
|
|
if codespaceName == "" {
|
|
codespace, err := chooseCodespace(ctx, apiClient, user)
|
|
if err != nil {
|
|
if err == errNoCodespaces {
|
|
return err
|
|
}
|
|
return fmt.Errorf("error choosing codespace: %w", err)
|
|
}
|
|
codespaceName = codespace.Name
|
|
}
|
|
|
|
url := vscodeProtocolURL(codespaceName, useInsiders)
|
|
if err := open.Run(url); err != nil {
|
|
return fmt.Errorf("error opening vscode URL %s: %s. (Is VS Code installed?)", url, err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func vscodeProtocolURL(codespaceName string, useInsiders bool) string {
|
|
application := "vscode"
|
|
if useInsiders {
|
|
application = "vscode-insiders"
|
|
}
|
|
return fmt.Sprintf("%s://github.codespaces/connect?name=%s", application, url.QueryEscape(codespaceName))
|
|
}
|