cli/pkg/cmd/codespace/select.go
Caleb Brose 57c73e8239
Add --repo filter to more gh codespaces commands (#6669)
* Add --repo flag to commands

* Example of using common args

* Add -r to stop

* Add validation to the add helper

* Skip prompt for single option

* Migrate (mostly) everything to addGetOrChooseCodespaceCommandArgs

* Fix typo in logsCmd

* Use R instead of r

* Update a couple -r usages

* Refactor to codespace_selector

* Clean up selector, apply it in a couple examples

* Use apiClient instead in constructor

* Restore addDeprecatedRepoShorthand

* Finish implementing the commands

* Update existing tests to use the selector

* Add tests for selector

* linter

* Catch case where there's no conflict

* Make the flag persistent for ports

* Add support to stop
2023-02-22 17:16:36 -06:00

83 lines
1.6 KiB
Go

package codespace
import (
"context"
"fmt"
"os"
"github.com/spf13/cobra"
)
type selectOptions struct {
filePath string
selector *CodespaceSelector
}
func newSelectCmd(app *App) *cobra.Command {
var (
opts selectOptions
)
selectCmd := &cobra.Command{
Use: "select",
Short: "Select a Codespace",
Hidden: true,
Args: noArgsConstraint,
RunE: func(cmd *cobra.Command, args []string) error {
return app.Select(cmd.Context(), opts)
},
}
opts.selector = AddCodespaceSelector(selectCmd, app.apiClient)
selectCmd.Flags().StringVarP(&opts.filePath, "file", "f", "", "Output file path")
return selectCmd
}
// Hidden codespace `select` command allows to reuse existing codespace selection
// dialog by external GH CLI extensions. By default output selected codespace name
// into `stdout`. Pass `--file`(`-f`) flag along with a file path to output selected
// codespace name into a file instead.
//
// ## Examples
//
// With `stdout` output:
//
// ```shell
//
// gh codespace select
//
// ```
//
// With `into-a-file` output:
//
// ```shell
//
// gh codespace select --file /tmp/selected_codespace.txt
//
// ```
func (a *App) Select(ctx context.Context, opts selectOptions) (err error) {
codespace, err := opts.selector.Select(ctx)
if err != nil {
return err
}
if opts.filePath != "" {
f, err := os.Create(opts.filePath)
if err != nil {
return fmt.Errorf("failed to create output file: %w", err)
}
defer safeClose(f, &err)
_, err = f.WriteString(codespace.Name)
if err != nil {
return fmt.Errorf("failed to write codespace name to output file: %w", err)
}
return nil
}
fmt.Fprintln(a.io.Out, codespace.Name)
return nil
}