Skip to content

Commit

Permalink
cmd/run: users can select and run any runbook
Browse files Browse the repository at this point in the history
  • Loading branch information
joshi4 committed Apr 28, 2024
1 parent 84f722b commit 37fe893
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 2 deletions.
2 changes: 1 addition & 1 deletion client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ func (c *client) RunbookByID(ctx context.Context, id string) (*Runbook, error) {

func (c *client) Runbooks(ctx context.Context) ([]RunbookInfo, error) {
cl := c.cl
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.apiURL("/api/v1/runbooks"), nil)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.apiURL("/api/v1/runbooks/"), nil)
if err != nil {
return nil, err
}
Expand Down
56 changes: 55 additions & 1 deletion cmd/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@ import (
"fmt"
"io"
"log"
"log/slog"
"os"
"os/signal"
"sync"
"syscall"

"github.com/charmbracelet/huh"
huhSpinner "github.com/charmbracelet/huh/spinner"
"github.com/creack/pty"
"github.com/getsavvyinc/savvy-cli/client"
Expand Down Expand Up @@ -59,7 +61,18 @@ func savvyRun(cmd *cobra.Command, args []string) {
cl = client.NewGuest()
}

runbookID := args[0]
var runbookID string

if len(args) == 0 {
runbookID, err = allowUserToSelectRunbook(ctx, logger, cl)
if err != nil {
display.ErrorWithSupportCTA(err)
os.Exit(1)
}
} else {
runbookID = args[0]
}

rb, err := fetchRunbook(ctx, cl, runbookID)
if err != nil {
logger.Error("failed to fetch runbook", "runbook_id", runbookID, "error", err)
Expand Down Expand Up @@ -164,3 +177,44 @@ func fetchRunbook(ctx context.Context, cl client.Client, runbookID string) (*cli
}
return rb, err
}

type selectableRunbook struct {
Key int `json:"key"`
RunbookID string `json:"runbook_id"`
}

func allowUserToSelectRunbook(ctx context.Context, logger *slog.Logger, cl client.Client) (string, error) {
l := logger.With("func", "allowsUserToSelectRunbook")
runbooks, err := cl.Runbooks(ctx)
if err != nil {
l.Debug("failed to fetch runbooks", "error", err)
return "", err
}

var options []huh.Option[selectableRunbook]
var selectedRunbook selectableRunbook

for i, rb := range runbooks {
options = append(options, huh.NewOption(
fmt.Sprintf("%d. %s", i+1, rb.Title),
selectableRunbook{Key: i, RunbookID: rb.RunbookID},
))
}

form := huh.NewForm(
huh.NewGroup(
huh.NewSelect[selectableRunbook]().
Title("Select a runbook").
Options(options...).
Description("Press x to select the runbook you want to run").
Height(33).
Value(&selectedRunbook),
),
)

if err := form.Run(); err != nil {
logger.Debug("failed to run form", "error", err)
return "", err
}
return selectedRunbook.RunbookID, nil
}

0 comments on commit 37fe893

Please sign in to comment.