-
Notifications
You must be signed in to change notification settings - Fork 52
/
branch.go
53 lines (43 loc) · 1.32 KB
/
branch.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package promptutil
import (
"context"
"fmt"
"github.com/AlecAivazis/survey/v2"
ps "github.com/planetscale/planetscale-go/planetscale"
"github.com/planetscale/cli/internal/cmdutil"
"github.com/planetscale/cli/internal/printer"
)
// GetBranch returns the database branch. If there is only one branch, it
// returns the branch immediately. Otherwise the user is prompted to select the
// branch from a list of existing branches.
func GetBranch(ctx context.Context, client *ps.Client, org, db string) (string, error) {
branches, err := client.DatabaseBranches.List(ctx, &ps.ListDatabaseBranchesRequest{
Organization: org,
Database: db,
})
if err != nil {
return "", cmdutil.HandleError(err)
}
if len(branches) == 0 {
return "", fmt.Errorf("no branch exist for database: %q", db)
}
// if there is only one branch, just return it
if len(branches) == 1 {
return branches[0].Name, nil
}
if printer.IsTTY {
branchNames := make([]string, 0, len(branches)-1)
for _, b := range branches {
branchNames = append(branchNames, b.Name)
}
prompt := &survey.Select{
Message: "Select a branch to connect to:",
Options: branchNames,
VimMode: true,
}
var branch string
err = survey.AskOne(prompt, &branch)
return branch, err
}
return "", fmt.Errorf("more than one branch exists for database %q", db)
}